Skip to content

feat(js/plugins/compat-oai): add Responses streaming, tool calling, and reasoning round-trip - #6148

Open
cabljac wants to merge 19 commits into
feat/compat-oai-responses-slice1from
feat/compat-oai-responses-slice2
Open

cabljac wants to merge 19 commits into
feat/compat-oai-responses-slice1from
feat/compat-oai-responses-slice2

Conversation

@cabljac

@cabljac cabljac commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Part of #6002, closes #6004. Stacked on #6006; review the top commit.

Streaming, tool calling and the encrypted reasoning round-trip land together because they interact - the shared failure mode is reasoning items dropped on tool-call turns.

  • Streaming: client.responses.stream() + finalResponse(), replacing the single-chunk fallback from [JS] compat-oai: transport boundary + non-streaming Responses runner #6003. Text and reasoning-summary deltas map to parts; function-call argument deltas accumulate into partial tool requests; chunk.index carries output_index. Annotations attach to the final text part's metadata.annotations rather than streaming.
  • Tool calling: flat FunctionTool converter (strict: null), ref = call_id with the item id riding part.metadata.itemId for stateless replay, tool responses as function_call_output items, config.tools passthrough merged. Conversion is order-preserving in both directions - text around tool calls survives. supports.tools/toolChoice flip to true.
  • Encrypted reasoning: stateless requests (the pinned store: false default) always send include: ['reasoning.encrypted_content']; reasoning items round-trip through part metadata so reasoning models keep their context across tool-call boundaries.

Review hardening: edge-case request inputs (truncated JSON, unexplained failures) no longer degrade silently, truncated and failed streams are reported, models that reject streaming are not streamed to, and chunk.index no longer reports output_index.

Testing: 214 tests passing; unit + fake-server wire assertions, SSE streaming through the real SDK ResponseStream, end-to-end ai.generate tool loop. Live smoke tests extended (streaming; multi-turn tool call asserting the encrypted payload survives) but not yet run - draft until then, same as #6006.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds support for tool calling and streaming to the OpenAI Responses API transport within the compat-oai plugin. It updates model capabilities, implements serialization for tool requests, tool responses, and encrypted reasoning round-trips, and adds streaming event parsing. The review feedback highlights several critical safety improvements, including handling undefined tool outputs to prevent API errors, defensively validating configuration arrays before spreading them, and using optional chaining instead of non-null assertions for the streaming chunk callback.

Comment thread js/plugins/compat-oai/src/responses.ts Resolved
Comment thread js/plugins/compat-oai/src/responses.ts Resolved
Comment thread js/plugins/compat-oai/src/responses.ts Resolved
Comment thread js/plugins/compat-oai/src/responses.ts Resolved
// would come back as a stale in-progress response with the truncation
// or failure erased. Capture the terminal event's response instead.
let terminalResponse: OpenAIResponse | undefined;
for await (const event of stream) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Responses streams can also terminate with an error event. The SDK currently rejects with that event object, which passes through as a plain object rather than a GenkitError. Could we handle event.type === "error" here and add an SSE error test?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Turns out the SDK never lets an error event reach this loop - it throws an APIError as soon as it sees event: error, which rejects the for await and falls into the catch below, where rethrowOpenAIError turns it into a GenkitError. I checked with a synthetic SSE stream to be sure, so a branch here would be dead code. Added a test pinning that path though, good shout: 31e33b3

… API

Prepares the plugin to route some models over /v1/responses without
changing anything about the models it serves today.

A `transport` config key joins the plugin-level keys that the shared Chat
Completions body builder destructures away, so it can never reach a wire
that 400s on unrecognised arguments. Asking a Chat Completions model for
`transport: 'responses'` is rejected outright rather than silently ignored,
since opting a dual-transport model onto Responses is not available yet.
The OpenAI APIError to GenkitError mapping and the media-part helpers move
to utils.ts so a second runner can share them rather than fork them.

`UNSUPPORTED_MODEL_MATCHERS` matched 'codex' as a bare substring, which hid
gpt-5-codex, gpt-5.1-codex-max and codex-mini-latest from the model list
along with the legacy code-* completion models it was aimed at. The
matchers are now anchored patterns.
Eight OpenAI models - gpt-5-pro, the gpt-5/gpt-5.1 codex family,
codex-mini-latest, o1-pro and o3-pro - are served only over /v1/responses
and so cannot be reached through this plugin at all today.
`RESPONSES_ONLY_MODELS` names them, and a single predicate over that const
drives both the runtime routing and the `openAI.model()` type union. Any
suffixed form of a curated name matches, so o3-pro-2025-06-10 and
gpt-5-pro-preview route like their base rather than failing with an opaque
OpenAI 400; unknown suffixes fail toward the transport that works.

The runner mirrors the Chat Completions one: genkit messages become `input`
items with system messages hoisted into `instructions`, output formats map
onto `text.format`, unrecognised config keys pass through, and the response
`output` items become parts. Prior model turns are serialized part by part
rather than flattened to their text, so a structured-output turn replays as
its JSON instead of as an empty assistant message. The models declare
`constrained: 'all'` so genkit sends the output schema through
`text.format` instead of simulating it in the prompt. `store` is pinned to
false unless the caller sets it, so this transport retains no more data than
the existing one. All eight models register through it, and the resolver,
listActions and `openAI.model()` all route by the same predicate.

Streaming, tool calling and the encrypted reasoning round-trip are not
implemented yet. A streaming caller gets the completed response delivered
as a single chunk; a request carrying tools, a response asking for a tool
call, and a failed response carrying an `error` are all raised rather than
quietly returned as an ordinary answer.
… json and unexplained failures

Json-mode output truncated by max_output_tokens or a content filter left
partial JSON in output_text; JSON.parse threw a raw SyntaxError instead
of letting the finish reason report the truncation. Parse is now
best-effort (JSON.parse, then parsePartialJson, then a text part).

A failed response with a null error slipped past the status/error guard
and surfaced as a successful empty completion; failed responses now
always throw, with a generic message when the API omits the payload.
…d system messages

config.instructions rode the passthrough spread, which lands after the
instructions built from system messages - setting both silently dropped
the system prompt. The two sources are now joined in order.
… output

The Responses API validates json_schema formats under strict mode unless
strict: false is sent - unlike Chat Completions, where strict defaults
off. Genkit output schemas carry no additionalProperties: false, so
every schema-bearing request 400ed with invalid_json_schema. Found by
live smoke against gpt-5-pro; the fix was verified the same way.
cabljac and others added 14 commits November 19, 2026 12:18
… config

Either key through the passthrough changes the response envelope out from
under the non-streaming runner: the SDK hands back a Stream or a queued
response, which fromOpenAIResponse reads as an empty message with a clean
stop finish. Streaming belongs to Genkit's own streaming API and
background responses are not supported yet, so both are rejected.
…sponses usage

The Responses usage payload details reasoning and cached prompt tokens,
and genkit's usage schema has thoughtsTokens and cachedContentTokens for
them; a reasoning model's dominant token cost was reported nowhere.
… config

Assigning body.text wholesale silently discarded a passthrough text
object, so structured output could not be combined with e.g. verbosity;
the reasoning and instructions fields already compose for the same
reason.
…l lineup

Adds gpt-5.2-pro, gpt-5.5-pro, gpt-5.2-codex and gpt-5.3-codex, all
served exclusively over /v1/responses; the suffix bias cannot catch them
from the existing bases (gpt-5.2-codex does not extend gpt-5-codex-), so
without listing they routed to Chat Completions and failed with an
opaque 400.
…nd reasoning round-trip

Maps the Responses event protocol onto genkit chunks (text, reasoning
summaries, accumulating partial tool requests), replacing the
single-chunk streaming fallback. Adds a flat function-tool converter
(strict: null), order-preserving history conversion in both directions,
and function_call/function_call_output round-trip with call_id as the
part ref and item identity in part metadata. Stateless requests now pin
include: ['reasoning.encrypted_content'] and replay encrypted reasoning
items from part metadata, so reasoning models keep their context under
store: false.
… edge-case inputs

A void tool's undefined output serialized to nothing, dropping the
required function_call_output.output key from the request JSON. A
bare-string include from the passthrough config would be spread into
single characters. Serialize undefined as 'null' and normalize a string
include to a one-element array.
…ses streams

The SDK's finalResponse() snapshot only folds in response.completed, so
a stream ending in response.incomplete or response.failed came back as
a stale in-progress response: truncation surfaced as finishReason
'unknown' with no usage, and a mid-stream failure was swallowed into an
apparently successful response. The runner now captures the terminal
event's response and converts that.

Relatedly, a function_call item truncated by max_output_tokens carries
partial JSON in arguments; parse is now best-effort (JSON.parse, then
parsePartialJson, then the raw string) so the caller sees finishReason
'length' instead of a raw SyntaxError.
…eject it

o1-pro and o3-pro reject stream: true, and genkit's default paths (Dev
UI, generateStream) always request streaming, so both registered models
failed every default-path invocation. Curated non-streaming names now
route to a non-streaming request whose completed response is delivered
to the streaming caller as a single chunk.
…a GenkitError

The SDK throws an APIError on an 'event: error' frame before it can
reach the stream loop; the fake server gains raw SSE frames to express
the field line that json chunks cannot.
… as the chunk index

Chunk index is the message's position in the conversation, so labelling
text chunks with the reasoning item's sibling output_index split one
message into several and collided with the tool-loop message index.
Omit it and let core fill in the message index, matching the
non-streaming fallback and the Chat Completions runner.
…soning models

The stateless default asked every model for reasoning.encrypted_content,
and non-reasoning models reject that include with a 400 rather than
ignoring it, which broke the dual-transport opt-in for models like
gpt-4o. Gate the automatic include on a hand-curated reasoning-family
predicate; callers can still request it explicitly through include.
@adesinah
adesinah force-pushed the feat/compat-oai-responses-slice2 branch from b26cf22 to aa5c4f9 Compare November 19, 2026 12:19
@adesinah
adesinah marked this pull request as ready for review November 19, 2026 12:31

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[JS] compat-oai: Responses streaming, tool calling, reasoning round-trip

2 participants