Repository navigation
Conversation
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Every Stream handler now resolves pending approvals at stream start and, when client-executed or approval-required tool calls are encountered, yields ToolApprovalRequestEvents and ends the stream with FinishReason::ToolCalls instead of looping — DeepSeek, Gemini, Groq, Mistral, Ollama, OpenRouter, Qwen, Requesty, Vertex, xAI, Z, and OpenAI ChatCompletions join Anthropic + OpenAI Responses. Completes the streaming item on fork issue #4. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…rism-php#965) Covers both paths of the tools + response_format split: a tool call followed by the tool-less json_schema re-send, and the discard + re-send path when the model stops without calling the offered tools. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…ls (prism-php#1004) Replaces the unrunnable test dropped in 5c08d92: this one ships a real two-response SSE fixture and consumes the stream before asserting the request payload omits the parameters key for a parameterless tool. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
… and OpenRouter parameterless streaming Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…d Gemini These handlers reported cacheReadInputTokens while leaving the cached tokens inside promptTokens, so promptTokens + cacheReadInputTokens overstated input (double counting; upstream prism-php#1017). They now follow the convention already used by Anthropic, OpenAI (Responses) and DeepSeek: promptTokens holds the non-cached portion, guarded at zero. Gemini previously subtracted only when an explicit cachedContentName was set, missing implicit caching. Regression tests added for all three. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…ders Extends the v0.108.1 usage convention (promptTokens = non-cached input) to every provider whose API reports prompt_tokens_details.cached_tokens: - OpenAI chat_completions path (Text/Structured/Stream) now has parity with the Responses path: cacheReadInputTokens populated, cached tokens excluded from promptTokens. Also applies to vLLM/LiteLLM-style backends used via api_format. - Azure, Groq, Qwen (native DashScope fields), xAI: cached-token visibility wired up (previously ignored entirely). - Z.AI and Requesty streams: fixed genuine double counting - they reported cacheReadInputTokens while leaving those tokens inside promptTokens. Their Text/Structured paths gain cache visibility. Regression tests for all seven providers (Text path), stream-level SSE fixture tests for Z.AI and Requesty, and the first Azure provider tests. Z.AI fixture-based expectations updated: the real captures contain large cached_tokens values, confirming the double counting in production responses. Removes a leftover unused providerOptions() read in the Gemini Text handler flagged by Rector. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…checker composer-require-checker surfaced undeclared direct dependencies, now declared: ext-mbstring, ext-openssl, psr/http-message, and symfony/http-foundation (all already installed transitively via laravel/framework, so this changes nothing for consumers). laravel/mcp moves to suggest for the optional LaravelMcpTool integration; its symbols plus the PHPUnit assertion used by the testing fakes are whitelisted in composer-require-checker.json. The custom ReorderMethodsRector was dev tooling shipping inside src/ (the source of phantom PhpParser/Rector symbols) - moved to dev/ under a Prism\Dev namespace, autoloaded only in autoload-dev and export-ignored from the dist package. New Require Checker CI workflow runs the tool on every push/PR. This is the proper guard for the goal upstream prism-php#1025 aimed at (catching use of undeclared symbols) without splitting laravel/framework into illuminate/* packages. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…penAI verbosity Three bug fixes from the upstream issue tracker plus one found in review: - DeepSeek and Qwen streaming handlers sent `stream: true` in the request body but never set the Guzzle `stream` transport option, so the full response body was buffered before the first event yielded — matching the other 14 providers now (upstream prism-php#990; Qwen found in review). - OpenRouter ToolCallMap eagerly ran json_decode() and passed the result to the ToolCall constructor, so malformed model JSON produced a raw TypeError (json_decode returns null) instead of a handled error. The map now stores the raw argument string; ToolCall::arguments() decodes lazily and wraps a decode failure in PrismException::malformedToolCallArguments(), which the tool-execution loop already converts into a tool result the model sees. The loop's error path is hardened to not re-throw while building that result (upstream prism-php#1006). Also adds OpenAI text_verbosity support to the structured (Responses) path and both chat/completions paths — it was previously only wired on the Responses text path (upstream prism-php#1015). Tests: OpenRouter ToolCallMap mapping + lazy-decode behavior, verbosity pass-through for structured + chat/completions, updated the ToolCall value object test to assert the handled PrismException. 1,891 passing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…stency Per upstream prism-php#1017: promptTokens is normalized to exclude cached tokens everywhere, but completionTokens is inclusive of reasoning tokens on OpenAI/Anthropic/OpenAI-compatible providers and exclusive on Gemini/Vertex. Documents the difference rather than changing billing-relevant numbers. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…s-vertex feat(vertex): added support for multi region endpoints
Introduce the Tier-1 telemetry substrate for observability (upstream prism-php#935): a provider-agnostic set of plain Laravel events emitted across the generation lifecycle, decoupled from the existing ShouldBroadcast streaming events so telemetry never forces websocket delivery. - TelemetryContext: correlation VO carrying a stable traceId plus explicit stepIndex/toolIndex ordinals, so a consumer can rebuild the span tree deterministically without ambient context surviving the tool loop. - ContextStack: container-bound ambient stack; tolerates out-of-order removal so an abandoned streaming generator cannot corrupt later calls. - Telemetry: static emission helper; a complete no-op when disabled. - Events: GenerationStarted/Completed/Failed, StepCompleted, ToolInvoked. - config: prism.telemetry.{enabled,capture_content}, both off by default (capture_content gates prompt/completion/tool-arg payloads — PII). - Bind ContextStack as a singleton. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…ion paths Wire the neutral telemetry events into the provider-agnostic chokepoints so instrumentation lives in one place per path, touching no provider handler. - asText / asStructured / asEmbeddings / generate (images): start on entry, completed on success (with per-step StepCompleted for text/structured), failed on RequestException, context popped in finally. - asStream: wrap the provider generator via Telemetry::instrumentStream, which emits StepCompleted per StepFinishEvent and GenerationCompleted on StreamEndEvent while passing every event through untouched. - CallsTools: executeToolCall now measures and returns its own duration; ToolInvoked is dispatched from the in-process parent (executeToolsWithConcurrency and the approval-resume path) so listeners never fire in a forked child. - Tests: disabled no-op, started/completed, content-capture gating, per-step events, failure, streaming pass-through, and tool-invocation ordinals. Full suite green (1909 passed), PHPStan level 8 clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Security review found the capture_content privacy control was applied to GenerationStarted, StepCompleted, and GenerationCompleted but NOT to ToolInvoked, so tool arguments and tool results (which can carry user PII) were placed into the event payload even when capture_content was disabled — contradicting the documented opt-out and leaking content to whatever sink the operator wired. Fix: ToolInvoked now carries always-present scalar `toolName`/`toolCallId` (safe span metadata) while the content-bearing `toolCall`/`toolResult` are nullable and populated only when capture_content is enabled — matching the nullable-content pattern of the other three events. Added a regression test asserting content is withheld by default and present only when enabled. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…ceof) The security-fix commit ran Pint but not Rector; the Formatting CI job runs `rector` + `git diff --exit-code`, which flagged the `=== null` assertions. FlipTypeControlToUseExclusiveTypeRector rewrites them to `! $e->toolCall instanceof ToolCall`, matching the repo's enforced style. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The Anthropic streaming and Groq/Mistral/OpenAI audio handlers call json_validate(), a PHP 8.3 built-in, while composer.json declares "php": "^8.2" and the test matrix runs 8.2. Without a polyfill this fatals on real 8.2 in those paths, and composer-require-checker (run on 8.2) flagged json_validate as an unknown symbol — a red check on every push since the checker was added. Add symfony/polyfill-php83 to require: it defines json_validate() on 8.2, fixing the latent runtime bug and satisfying the require-checker while keeping 8.2 support (vs. a whitelist entry, which would only silence the checker). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
fix: polyfill json_validate() for PHP 8.2 support
docs: point README to the ai.particle.academy docs site
The recursive tool loop runs step N's tools before step N is recorded, so ToolInvoked carried no step ordinal and a consumer could not nest a tool span under its step. Track a per-generation step cursor on the ContextStack, advance it once per executed tool batch, and stamp it onto every ToolInvoked. No-op when telemetry is disabled.
…s + bounded content capture Adopts upstream issue prism-php#935: neutral Laravel telemetry events across the generation lifecycle (context/stack, step/tool ordinals, user/session ids), bounded opt-in content capture, and a step cursor so tool events are tagged with their owning step. Off by default and a complete no-op when disabled. Validated end-to-end (real multi-step tool generation -> OpenTelemetry bridge -> Phoenix) and security-reviewed (PASS WITH WARNINGS).
Pairs with the "main protection" branch ruleset: outside contributions now need a pull request with an approving review from a code owner before they can land on main.
The Gemini API specifies `tools` as `Tool[]`, but four handlers built it in ways
that break that contract once more than one kind of tool is in play.
**Mixed keys → JSON object.** Gemini/Text, Gemini/Stream and Vertex/Text map
provider tools into a numerically keyed list and then assign
`$tools['function_declarations'] = …` on top. The result is a mixed-key array,
which `json_encode` emits as an object:
"tools": {"0": {"google_search": {}}, "function_declarations": [...]}
Gemini and Vertex both reject that, so combining Google Search grounding with
any custom tool fails outright.
**Silent overwrite.** Vertex/Structured reassigns `$tools` instead of appending,
so provider tools vanish whenever custom tools are present.
**Mutual exclusion.** Vertex/Stream chained `elseif`, so custom tools were only
ever sent when there were neither provider tools nor `searchGrounding` — the
combination was impossible rather than merely malformed.
All four now append a separate Tool entry, matching Gemini/Structured, which
already had it right and serves as the reference:
"tools": [{"google_search": {}}, {"function_declarations": [...]}]
Provider-tool precedence in Vertex/Stream (explicit provider tools over the
legacy `searchGrounding` option) is preserved; only the custom-tool branch
becomes additive.
Adds a regression test asserting `array_is_list($data['tools'])` plus both
entries. Verified it fails on the current code and passes with the fix; the 169
Gemini + Vertex tests and Pint stay green.
Extends the fix with runnable coverage for the previously untested paths: Gemini/Text custom-tools-only, Gemini/Stream grounding + custom tools, and Vertex/Text custom-tools-only — each asserting `tools` serializes as a JSON array (array_is_list), the shape Gemini and Vertex require.
Covers enabling telemetry, the config block, the five lifecycle events and their payloads, listening, TelemetryContext, user/session metadata via withTelemetryMetadata(), the content-capture PII bounds, and exporting to OpenTelemetry / Arize Phoenix via prism-opentelemetry. Adds it under Advanced.
fix: refuse a null api key again
A client-executed tool has no server handler, including an __invoke on a class-based tool.
One classifier decides, and it checks the same decode and encode the replay uses. Numbers without a finite value, keys an object cannot hold, and nesting past 500 levels are refused. Control characters are repaired only inside strings. A provider value that is neither text nor a map is refused rather than read as no arguments.
Nested values are walked a level at a time, scalars are checked in place, a call found usable is not worked out again, and the replay path reuses the message's own calls.
Stored content blocks are sent back as received, so tool input the decoder accepted but the encoder refuses stopped the follow-up request. Non-streaming text and structured turns now replay it empty, as streaming does, and a test covers every provider's non-streaming paths.
…ments Refuse unusable tool arguments and report them as a tool error
…er-runs Never execute a client-executed tool on the server
The arguments section still said argumentsAsObject() serves numeric property names. Since #166 a top-level numeric name is refused, so the sentence now limits that to nested names and lists what is refused and what reads as no arguments.
…used docs: say which tool arguments are refused
Before 0.152, a tool call whose arguments could not be parsed was stored as one string under `raw` or `input`. On a tool with a parameter of that name, a stored call in that form looks the same as a real one. Approval requests issued by Prism now carry `arguments_format`. On resume, an approved call whose request has no marker, on a tool that names `raw` or `input`, with only that one string argument, does not run. Its result says the approval expired and asks the model to call again, so the new call needs a new approval. The result, the stream event and telemetry record it without the arguments. ToolApprovalRequest gains `argumentsFormat`, `issue()`, `fromArray()` and `argumentsAreAsSent()`; ToolApprovalRequestEvent gains `approvalRequest()`. Consumers that store requests must keep the marker.
ToolApprovalRequestEvent carries `argumentsFormat`, set only where core yields it after parsing the call. approvalRequest() copies it, so an event rebuilt from storage without it, and the messages StreamedMessages::fromEvents() builds from such an event, stay unmarked, and the legacy call still expires. ToolApprovalRequest::issue() is removed. The docs tell applications that build requests themselves how to keep the marker.
…us-approvals Expire unmarked approvals that cannot be told apart from a real call
…r (red) G-352. Through Prism::text() and Prism::structured() over faked HTTP, with stray requests refused: ask for approval, approve or deny, resume, and count the runs. 36 of 44 fail on main, every one on the missing approval request: 13 text handlers and 5 structured handlers, both decisions each. Anthropic and OpenAI Responses are the reference and pass.
G-352. Only the Anthropic and OpenAI Responses handlers put the approval requests on their Step. The other 18 non-streaming handlers (13 text, 5 structured) left them off, so the documented resume found no request, denied every approval by default, and the approved tool never ran. callToolsWithPending() now keeps the requests it issued, and each handler's Step takes them with approvalRequestsForStep(), which clears them so a later step cannot carry them again. The requests are the ones core issues, with the arguments_format marker already set. Structured handlers follow the Anthropic shape: Mistral, OpenRouter and Requesty record the step after the assistant message and its results, so a resume can start from the step's messages. Mistral structured now stops on a pending call instead of requesting the structured answer without its result. A guard test fails if a handler that can stop for an approval does not hand it back. The human-in-the-loop page shows the structured resume.
…pprovals G-352: hand back pending approvals from every non-streaming handler
…ge twice (red) G-355. Through Prism::text() over faked HTTP: a resumed approval or a follow-up turn built from $response->messages carries the tool call twice on Azure and Z, and Replicate's reply appears twice in the messages.
G-355. A text Step's messages are the conversation the request carried, and the response builder appends the step's assistant message (and tool results) to them. Azure and Z added the assistant message and tool results to the request before recording the step, so $response->messages held the tool-call message twice, and a resume or follow-up turn built from it sent the call twice. Replicate did the same with its reply. The three handlers now record the step first and add the assistant message (with any approval requests) and results to the request afterwards, as every other text handler does. Their Step->messages no longer end with the step's own reply, matching the other providers. Checked every non-streaming text handler: the other providers already record the step first. Structured responses have no message list and keep their G-352 shape; streaming handlers add messages only for the follow-up request.
…-call-message Store each assistant message once on Azure, Z and Replicate text
37 of 41 fail on main: a providers.<name> entry with driver openai-compatible is not supported, so nothing resolves, refuses or reaches the wire.
A prism.providers.<name> entry with driver openai-compatible builds an OpenAI-shaped provider that authenticates with that entry's api_key, organization and project only: never the openai provider's, never an OPENAI_* variable, and no Authorization header when it has no key. The entry is held to the registration rules before anything is built: a readable name, no built-in taken over in any case, no second entry or custom creator under the same name (extend() needs replace: true). Its url passes the existing clean-url check and must be an absolute http or https url; private and loopback addresses are allowed because the url is operator configuration. api_format is chat_completions by default, or responses. Telemetry tags the entry name.
…oviders Named openai-compatible providers from config (G-321 A)
When the last tool-call fragment and finish_reason "tool_calls" arrived in one chunk, the stream skipped the finish handling, dropped the calls and ended as Stop. A fragment chunk that also carries a finish reason now goes on to the finish handling, as the Groq, Mistral and DeepSeek handlers and prism-ts already do.
…-tool-calls fix(openai): keep chat completions tool calls sent in the finish chunk
…rigin (red) Real loopback servers: the provider endpoint answers 301/302/303/307/308 with a Location on another host or port, and those servers record every request they receive. Covers text and stream for every provider that has them, embeddings for VoyageAI, speech for ElevenLabs, every provider's client directly, and files/batch listing. Same-origin redirects are still followed.
Every provider client is built by InitializesClient::baseClient(), which now adds a middleware that refuses a redirect whose target differs from the request in scheme, host or effective port. The refused response is never followed, so the target receives no request; the call throws PrismUrlRefused with code redirect_refused, and the message names only the two origins. Redirects within the origin are followed as before, and the rule holds whatever allow_redirects options a caller passes.
fix: follow a provider redirect only within the request's origin
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Upstream has been quiet since March 2026 (v0.100.1), so particle-academy/prism — a drop-in fork,
Prism\Prismnamespace unchanged — has been absorbing the open backlog and shipping releases (context: discussion #1027). This PR offers all of that work back upstream in one piece: 166 commits, nine releases (v0.101.0–v0.109.0), gated throughout by Pest + PHPStan + Pint/Rector.If maintainership resumes, merge wholesale or tell us how you'd like it split — we're happy to break it into reviewable chunks. Either way the fork remains active.
Community PRs from this repo merged into the fork (48)
v0.101.0 — correctness fixes (17): #952, #958, #964, #971, #977, #985, #986, #987, #989, #991, #996, #1001, #1004, #1009, #1012, #1013, #1024
v0.103.0 — provider correctness / API drift (16): #949, #954, #961, #965, #975, #976, #980, #992, #993, #995, #997, #1000, #1002, #1008, #1020, #1021
v0.104.0 — features (9): #951 (batches + files APIs), #960 (xAI images), #978 (Vertex AI provider, answers #795), #988 (fine-grained tool streaming), #998 (Anthropic adaptive thinking), #1003 (pause_turn/refusal), #1014 (Mistral FIM), #1018 (provider-agnostic withReasoning()), #1026 (Requesty provider)
v0.105.0 — features + providers (6): #757 (Replicate provider), #810 (async STT interface), #835 (Azure OpenAI provider), #898 (Qwen provider), #907 (OpenAI chat/completions api_format + streaming citations, answers #900), #920 (cost tracking in Usage)
Reimplemented rather than rebased: #932 (client-executed tools + human-in-the-loop approval, answers #921) — clean-room implementation across all providers including streaming; docs at https://ai.particle.academy/docs/core-concepts/human-in-the-loop
Adjudicated, not merged (rationale posted): #950 (duplicate of #977), #937 and #1005 (superseded by an escape-based control-character fix), #999 (superseded), #1025 (rejected — a composer-require-checker CI gate solves the underlying goal properly; analysis in Particle-Academy/prism#3)
Fork-original changes
laravel/framework ^12.61.1|^13.12.0).Tool::requiresApproval(bool|Closure)/Tool::clientExecuted(), deny-by-default resume from message history, streaming approval events — text/structured/stream on all 18 providers.promptTokens= non-cached input everywhere;cacheReadInputTokenspopulated wherever the provider exposes it. Fixed silent double counting in Gemini, Vertex, OpenRouter (v0.108.1) and Z.AI + Requesty streams (v0.109.0); added cache visibility for OpenAI chat/completions, Azure, Groq, Qwen, xAI.anthropic_betaprovider option.src/.Full release notes: https://github.com/Particle-Academy/prism/releases
🤖 Generated with Claude Code