Repository navigation
feat: convert between all four API formats - #36
Merged
Merged
Conversation
Any client format can now use any upstream protocol: Anthropic Messages, OpenAI Chat Completions, OpenAI Responses and Gemini generateContent. tw-dialect is rebuilt around an intermediate representation. Each format has a decoder and an encoder for requests, whole responses and streams, so the 12 cross-format directions share one implementation per format instead of one per pair. Field mappings follow the current official SDK type definitions (Anthropic adaptive thinking and output_config.effort, OpenAI reasoning effort up to max, Responses namespace and custom tools, Gemini parametersJsonSchema and thinkingLevel). Anything without a counterpart is reported as a field path of the client request. Requests that depend on server-side state (previous_response_id, conversation, item_reference, compaction, cachedContent) are refused rather than answered without their context. Reasoning signatures are carried in the client's own signature field with a tw1. prefix so the next turn can hand them back to the vendor that issued them. A 4x4 matrix test runs every pair through whole, streamed and collected responses. Gateway wiring: - the request is decoded once; routing facts come from the IR, so rules on model, tools, images and thinking work for every client format (Gemini clients used to route with an empty model) - rule `set` rewrites apply to the IR for converted requests and use each format's own field names in passthrough - outbound redaction now applies to the converted body; before, conversion started from the original body and sent secrets unredacted - dialect-specific client headers are dropped and anthropic-version is added when converting to Anthropic; path and query come from the conversion - upstream error bodies are converted to the client's error shape, a whole response is written as a stream when the client asked for one, and a broken stream ends in the client's format - calls other than generation (count_tokens, embeddings, compaction) are only sent to same-format upstreams; count_tokens used to be rewritten into a paid chat completion - passthrough strips reasoning signatures that a conversion wrote - /v1/models lists every model for every client format Usage sniffing reads Gemini usageMetadata and subtracts cached tokens from Responses and Chat inputs, so Gemini traffic is no longer unmetered and cache hits are no longer billed at the input price. The store records the conversion that served a request (schema 12), the history API returns it, and dry runs list candidates that would convert. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The tool-call firewall only understood Anthropic streams, so Chat, Responses and Gemini streams were not inspected at all, whether they were passthrough or converted. With conversion, a dangerous call from an untrusted relay reached a Chat or Codex client untouched. The wall still reads the bytes the client is about to receive, frame by frame, so the cut point is computed the same way. It now also recognizes Chat tool-call fragments, Responses function and custom tool calls (deltas, completed items, and WebSocket frames) and Gemini function calls, plus response text for the injection check. "Incomplete is harmless" holds in all four: Anthropic waits for content_block_stop, Chat for the end of the stream, Codex for output_item.done, and a Gemini call arrives in a single frame that is not forwarded. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
When a request is converted to Anthropic, max_tokens is required. If the client did not set one, the gateway used a guess by model name. The price table (LiteLLM's dataset) already carries max_output_tokens for each model; it is now parsed, kept through price sheets, and used first. The name-based guess remains only for models the table does not know. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
fylorn
force-pushed
the
feat/any-to-any
branch
from
September 17, 2026 13:54
4f46845 to
75d1ca7
Compare
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.
Why
Ships in 0.4.0 together with #35.
ThinkWatch Lite should let any client use any upstream: Claude Code on an OpenAI or Gemini account, Codex CLI on Claude, Gemini CLI on a Chat-compatible relay. Until now the gateway converted exactly one direction (Anthropic client → OpenAI Chat upstream), and everything else was passthrough only.
The enterprise gateway was the planned source, but its inbound converters keep plain text only (tools, images and thinking are dropped silently), it has no Gemini inbound and no stream conversion toward clients. Core's own converter was the most complete one, so this change generalizes it rather than porting.
What changes
tw-dialect: one intermediate representation, four formatsir.rs: request, response and stream-event types shared by all formats, plusDropped(field paths in the client's own request) andRejection.anthropic/,chat/,responses/,gemini/: each has request decode/encode, whole-response decode/encode, and a stream parser and writer.convert.rs:decodeonce,encodeper target;Sessionconverts whole responses, streams (StreamConverter), stream-to-whole (Collector), whole-to-stream, and upstream error bodies.strip_carriedremoves signatures a conversion wrote before a passthrough hop.thinking: adaptive+output_config.effort; older Claude and Anthropic-compatible endpoints getenabled+budget_tokens(the two are mutually exclusive by model). The official endpoint gets notemperature/top_p/top_k.strict: falseon function tools,store: false, andinclude: ["reasoning.encrypted_content"]when reasoning is on. Custom (freeform) tools and namespace tools round-trip for Codex.parametersJsonSchema,thinkingLevelon Gemini 3, and the documented syntheticthoughtSignatureon function calls from foreign history.previous_response_id,conversation,item_reference,compaction,cachedContent) are refused with an explanation.tw1.prefix, so they return to the vendor that issued them.tests/matrix.rs: 4 × 4 clients × upstreams, each through whole, streamed (cut into 7-byte pieces) and collected responses, checking text, tool calls, stop reason and usage including cache hits.Gateway
client_api::readdecodes the request once; routing facts come from the IR (RequestFacts::from_request), so rules work for every client format. Gemini clients previously routed with an empty model.setapplies to the IR for conversions and uses each format's field names in passthrough; outbound redaction now runs on the converted body (it used to start from the original body, so converted requests went out unredacted).anthropic-versionis added for Anthropic targets, path and query come from the conversion.max_tokens. When the client did not set one, the model's output limit from the price table is used;tw-pricingnow parsesmax_output_tokensfrom the LiteLLM dataset and keeps it through price sheets. A name-based guess remains for models the table does not know.count_tokens, embeddings and compaction go to same-format upstreams only;count_tokensused to be rewritten into a paid chat completion./v1/modelslists every model for every client format.usageMetadata(Gemini traffic was unmetered) and subtracts cached tokens for Responses and Chat (cache hits were billed at the input price).Store, API, dry run
requests.translated(schema 12) keeps the conversion of the hop that served the request;HistoryRow.translatedexposes it.DryRunResult.convertedlists candidates whose protocol differs from the client format.Tool-call inspection in every format
toolwallused to understand Anthropic streams only, so Chat, Responses and Gemini streams were never inspected, whether passthrough or converted. It now also reads Chat tool-call fragments, Responses function/custom tool calls (deltas, completed items, WebSocket frames) and Gemini function calls, plus response text for the injection check. The cut point is computed on the bytes the client receives, as before; a cut converted stream ends in the client's error format.Tests
cargo fmt --check,cargo clippy --workspace --all-targets -D warnings,cargo test --workspaceand./scripts/smoke.shpass locally. New:tw-dialectunit tests per format,tests/matrix.rs,tw-gateway/tests/conversion.rs(headers, Gemini paths, error conversion, count_tokens guard, signature stripping, redaction after conversion, a converted stream cut by the firewall), recorder and dry-run tests. Replay fixtures were updated by hand for the new token estimate, which no longer counts base64 image data or JSON structure strings.🤖 Generated with Claude Code