gateway: any model's 8.0 in a call's arguments reaches the agent as 8, not only Grok's (#3152)
1024MrL's Codex, on opencode-go/muse-spark-1.3-contributor through the
gateway, had every tool_search turned away before it ran ("failed to
parse tool_search arguments: invalid number" over {"limit": 8.0}), and
exec_command the same ("floating point `2000.0`, expected usize").
grok_integral.go's whole-number rewrite (#1431) already fixes exactly
this, but it ran only when the model was Grok's.
Decision (delegated by the owner): the rewrite runs for every model,
not narrowed to Grok. Why:
- The defect is the model's, not a vendor's: Grok (#1431) and muse-spark
(#3152) both write it, and no list of models would stay complete.
- The rewrite changes only a number written with a fraction of zeros and
no exponent, to the same JSON number. Strict parsers break on 8.0
(Codex's serde u64/usize/i32, Go's json into an int), while every
float-typed field takes 8 (serde f64, Go float64, JS). The one visible
difference is a Python client's json.loads giving int 8 for float 8.0,
which any `number` schema allows.
- Strings, keys, other fractions (2.5, 2.50) and exponents (1.0e3) stay
as written, held by integralCases' edges case.
- The reporter ran it end to end on Windows with real Codex 0.163 and
muse-spark: 6 of 7 and 20 of 21 calls refused without it, 0 with it in
two runs (thread, 10-23).
Gemini routes are left as they were: their call arguments are an object
the client decodes itself, and no report shows the shape there.
What changed:
- passthrough installs intTidy on every Responses, Chat and Messages
reply; translate's Request.Grok and grokServed are gone, encoder wraps
every reply in wholeEncoder and render runs wholeResult. grokModel
stays for grok_schema.go.
- crTidy (glm-5.3-flash*'s stitched CR, #4256) now runs before intTidy,
in the stream, the held-tail chain and the drain. With intTidy on every
route, a whole reply it held went from its flush past crArgs, so the
CR cure never saw it (added in this port: the patch's comment gave a
different reason).
- intTidy's flush says a whole reply with no call marker as it came,
without decoding it (added in this port), since every model's whole
reply now reaches it.
- TestOnlyGrokCallsGetIntegers (which held the old scope) became
TestOtherModelsCallsGetCodexIntegers; TestGrokCallsByUpstreamName is
gone; TestToolSearchWholeFloatLimitGivesCodexIntegers is the report's
shape; TestStitchedCRAndWholeFloatsBothGo (added in this port) holds
both cures on a glm-5.3-flash route, whole and streamed. Its whole
case reads the input's fields as written, not through a decode and
encode, which would print 8.0 as 8 and pass on the old code.
Run at this head (rebased on 2c5d9101b, after #2580's held line in
passthrough's write), on mote:
- go test -tags nogui -count=1 -run 'TestWholeNums|TestGrok|
TestOtherModelsCallsGetCodexIntegers|TestToolSearchWholeFloat|
TestStitchedCRAndWholeFloatsBothGo|StitchedCR|TestCRLeavesHealthy|
TestCRDropper|TestPluginStreamLargeReplies|TestQuietWholeReplyStreamed|
TestTextWritten|TestChatStreamCut|TestPassthroughStream|TestNameless'
./internal/gateway: ok (61s).
- go vet -tags nogui ./internal/gateway on darwin, GOOS=linux and
GOOS=windows: clean. gofmt -l: clean.
- At the review tree: the -run family above (without the last three)
with -race -count=2: ok.
- Not run before the push: the whole gateway package and ./... (the
package runs in the background after).
Broken by hand:
- gateway.go, grok_integral.go and ir.go back at origin/main, tests
kept: TestToolSearchWholeFloatLimitGivesCodexIntegers fails "deltas:
limit is 8.0 in {"query":"exa web search","limit":8.0}, want 8";
TestOtherModelsCallsGetCodexIntegers fails "deltas: yield_time_ms is
2500.0 ..., want 2500"; TestStitchedCRAndWholeFloatsBothGo fails in
both subtests ("limit":8.0).
- the rewrite on every route but the old order (ints before crArgs):
TestStitchedCRAndWholeFloatsBothGo/whole, TestChatReplyToolArgsLoseStitchedCR
and TestAnthropicWholeRelayedToolArgsLoseStitchedCR fail with the
stitched \r kept.
Not tried: a real muse-spark or Codex run by this port (the reporter's
runs stand in); a Gemini client. Risk not covered: a vendor that streams
SSE labelled Content-Type application/json. eventStream reads that as a
whole reply, and intTidy, now on every Responses, Chat and Messages
route, holds a whole reply to its flush, so such a stream would reach
the client only at its end, on every route rather than Grok's alone
(crTidy and chatWhole already hold such bodies on theirs). No vendor was
checked for it; a report of a stream arriving all at once points here.
Co-authored-by: ggbdpq <ggbdpq@gmail.com>
This commit is contained in:
@@ -261,7 +261,7 @@ recorded as a prediction failure (`noPrediction`).
|
||||
- A Responses upstream that wants a turn's reasoning back (`replaysReasoning` in [`responses.go`](../../internal/gateway/responses.go): a model with `deepseek` in its name, on any host but OpenAI's, xAI's, Copilot's and Azure's) gets every reasoning item with a `reasoning_text` and every tool call after one, relayed (`withReasoningText` in `passthrough`) or translated (`buildResponses`). DeepSeek's `/v1/responses` turns the whole request away ("The `reasoning_text` in the thinking mode must be passed back to the API") over a reasoning item without text, one with an empty text, and a `function_call` whose step (since the last user message or tool output) has no reasoning item. Codex sends all three in a routing group that falls to DeepSeek after ChatGPT: the backend's sealed items (`encrypted_content` only), magpie's summary-only items, and another member's calls with none (#1104, #1592). DeepSeek reads a step (a run of reasoning, assistant messages and calls) as one assistant message whose thinking is the item it starts with: in the current turn, a step with a call or after a tool output must lead with a reasoning item, so [message, reasoning, call] and [output, message] are refused while [reasoning, message, call] and [output, reasoning, message] are taken (checked against api.deepseek.com on 2026-10-12). Codex sends a step that said something before its call with no reasoning for another model's turn, which magpie used to send [message, reasoning " ", call] and DeepSeek refused intermittently, only while the turn lasted (#1822, through OpenCode Go). An item's own text is kept; one without gets its summary, else a space (`noReasoning`); each such step leads with its reasoning (`reasonFirst`): its own first reasoning item moved ahead, else one holding a space. A sealed item keeps its id and `encrypted_content`; a body already in that shape goes byte for byte.
|
||||
- A Messages upstream that wants a turn's thinking back (`anthropicReplaysThinking` in [`anthropic.go`](../../internal/gateway/anthropic.go): a host or a model with `deepseek` in it, never `api.anthropic.com` or a Claude model) gets a thinking block on every assistant message with a `tool_use` or right after tool results alone (refused the same way, checked 2026-10-12, #1822), relayed (`withThinkingOnToolTurns` in `passthrough`) or translated (`build`, which also keeps unsigned thinking as its text there). DeepSeek's `/anthropic/v1/messages`, thinking (its default, or asked for), turns the whole request away with 400 "The `content[].thinking` in the thinking mode must be passed back to the API" when such a message has none, and answers any `redacted_thinking` with 422, a block it can't read. Claude Code sends both in a routing group that falls to DeepSeek after Claude (#1611). A message with no thinking gets one holding a space (`noReasoning`) first; Claude's `redacted_thinking` becomes that block, or is left out beside thinking of the message's own. Signed thinking, DeepSeek's own and every other message go as they came. Checked against the real endpoint on 2026-10-11: it takes Claude's signed thinking, unsigned thinking and a space, anywhere in the message. A thinking block magpie sends unsigned (the space, or a turn's reasoning kept as its text) says `"signature": ""`, as `aBlock` writes `thinking` even when empty: OpenRouter's `/api/v1/messages` holds a block's signature to a string and turns a DeepSeek request with none away, 400 "Invalid Anthropic Messages API request" (#2883, #3696), and DeepSeek's own endpoint takes the empty one (checked 2026-10-19). `TestOpenRouterDeepSeekThinkingHasASignature`.
|
||||
- Every thinking block a Messages client gets says a `signature`, a string, as Anthropic's own do (its stream starts each block with `"signature": ""`): Grok Build reads `ContentBlock::Thinking` as `{thinking, signature}`, both required, and turned a whole reply away, "missing field `signature`" (uk.jent on Discord, on the MiniMax Code plugin). The encoder starts a thinking block signed empty (`anthropicEncoder.thinking`), `renderAnthropic` and `whole_stream.go` write the field too, and a reply relayed from a Messages endpoint that wrote none, streamed or whole, gets an empty one (`sigFieldTidy` in [`thinking_signature.go`](../../internal/gateway/thinking_signature.go), in `passthrough`); a block already signed goes byte for byte, and `redacted_thinking` is untouched. magpie never makes a signature up: an empty one is none to every path that sends history on (`anthropicBody` leaves it out for Anthropic, keeps its text where reasoning is replayed), and a relay sends it back to the vendor that wrote the block. `TestMessagesThinkingIsSigned`, `TestSignedThinkingRelayedAsItCame`.
|
||||
- A Grok model writes a whole number in a call's arguments with a fraction of zeros (`2500.0`, `17277.0`), whoever serves it: the Grok subscription or its plugin, xAI, OpenRouter or a relay. Codex reads its integer fields as u64, usize or i32 even though their schemas say `number`, so serde turns away the whole call (#1431). In a reply to a request whose model, as magpie names it or as it is sent upstream, has a last `/` segment beginning with `grok` (`grokModel`, `grokServed`), every number in a call's arguments written with a fraction of zeros and no exponent loses the fraction: `2500.0` becomes `2500`, `-3.00` becomes `-3`. Strings, keys, other fractions (`2.5`, `2.50`) and exponents (`1.0e3`) stay as written. No tool schema is consulted, since JSON has one number type. The rule runs over the arguments as a stream of text (`wholeNums`), holding back only a fraction of zeros until the next byte. This gives the same arguments whether they come whole or in deltas cut anywhere, so what a call's deltas add up to is what its done events say. Relayed replies are rewritten in `passthrough` by `intTidy`: Responses' function_call items, argument deltas and done events and the completed response; Chat's `tool_calls` deltas and messages; Messages' `tool_use` input and `input_json_delta`, streamed or whole. Translated replies are rewritten at the encoder (`wholeEncoder`, outside `usageEncoder`) and at `render` (`wholeResult`) when `Request.Grok` is set. Any other model's reply is relayed byte for byte ([`grok_integral.go`](../../internal/gateway/grok_integral.go)).
|
||||
- A model writes a whole number in a call's arguments with a fraction of zeros (`2500.0`, `17277.0`, tool_search's `limit: 8.0`): Grok's on every turn, whoever serves it (#1431), and muse-spark through the gateway (#3152). Codex reads the integer fields it parses as u64, usize or i32 even though their schemas say `number`, so serde turns away the whole call ("invalid number" for tool_search's arguments). In every reply, every number in a call's arguments written with a fraction of zeros and no exponent loses the fraction: `2500.0` becomes `2500`, `-3.00` becomes `-3`. Strings, keys, other fractions (`2.5`, `2.50`) and exponents (`1.0e3`) stay as written. No tool schema is consulted, since JSON has one number type and one that took `2500.0` takes `2500`. The rule runs over the arguments as a stream of text (`wholeNums`), holding back only a fraction of zeros until the next byte. This gives the same arguments whether they come whole or in deltas cut anywhere, so what a call's deltas add up to is what its done events say. Relayed replies are rewritten in `passthrough` by `intTidy`: Responses' function_call items, argument deltas and done events and the completed response; Chat's `tool_calls` deltas and messages; Messages' `tool_use` input and `input_json_delta`, streamed or whole; a whole reply with no call in it is said as it came, undecoded. A glm-5.3-flash* route's stitched CR (`crTidy`, #4256) is dropped before `intTidy` sees the reply, since `intTidy` holds a whole one to its flush (`TestStitchedCRAndWholeFloatsBothGo`). Translated replies are rewritten at the encoder (`wholeEncoder`, outside `usageEncoder`) and at `render` (`wholeResult`). Grok's schema quirks stay `grokModel`'s ([`grok_integral.go`](../../internal/gateway/grok_integral.go)).
|
||||
- A tool call a model writes into its reply's text, when the request offered tools, is made the call it is ([`textcalls.go`](../../internal/gateway/textcalls.go), #823): Hermes' `<tool_call>{…}</tool_call>`, DeepSeek's DSML (`<|DSML|invoke name=…>` with its parameters; its mark found as the parse regexes read it, by `dsmlMark`, not from a list of spellings: any run of pipes, ASCII or full-width or mixed, spaces after `<` and around `/`, `<||DSML||` too, #2623), DeepSeek's half-Hermes `<parameter>` form (#917) and GLM's `<arg_key>`/`<arg_value>` (#906), read by `parseTextCalls`. Each block must name an offered tool and have arguments that can be read; else the text goes on as it came. The text before the first block is kept, what is left of the tags goes, and the reply ends as one that called tools (`finish_reason` `tool_calls`, `stop_reason` `tool_use`). A DSML close with no block before it (`</||DSML|| calls>`) is held as a block is, and dropped when it is tags and nothing else. A reply whose model made a call itself has no call read out of its text, but tags and nothing else left in it after the call go, with the spaces before them (喜欢一个人 on Discord: a relay made the calls of DeepSeek's invokes and left the wrapper's close as text). Every route reads it the same way: a relayed Chat stream (`textCallTidy`), a relayed Chat reply that came whole, JSON or under `text/plain` or no type (`chatWhole` with `wholeTextCalls`, #1845: a `stream:false` request kept the markup and `finish_reason` `stop`), which also covers a vendor that answered a streamed request whole (`wholeAsStream`), and every translation, which magpie always asks streamed, a plugin's included, whatever the client asked (`textCallSee`). A relayed Responses or Messages upstream's text is not read for calls. Covered by `TestTextWritten*`, `TestDSMLClose*`, `TestDSMLBlockClosedWithCalls`, `TestGLMTextCall*`, `TestPluginTextWrittenCall` and `TestQuietWholeReplyStreamed`.
|
||||
- Structured output is carried across every translation (`Format`, [`format.go`](../../internal/gateway/format.go)). It is read from Responses' `text.format`, Chat's `response_format`, Anthropic's `output_config.format` and Gemini's `responseMimeType` with `responseJsonSchema`/`responseSchema`: `json_schema` with its name, description, schema and strict, or `json_object`. Each upstream is asked in its own field: `text.format` on Responses, `response_format` on Chat, `output_config.format` on Messages, and `generationConfig.responseMimeType`/`responseJsonSchema` on Gemini and Code Assist. An API with no name for it gets `response`. Messages and the Claude subscription's `--json-schema` take a schema only, so `json_object` is told in the system prompt there (`inSystem`). A 400 or 422 that names the field (`refusesFormat`: DeepSeek's "This response_format type is unavailable now", a schema Anthropic can't hold) marks the provider and model (`formatRefused`), and the request is asked again with the format told in the system prompt, as are later requests to that provider and model. A relayed request keeps its format as sent. A Gemini client's format is also still told in its system prompt, as before. A model may still wrap its JSON answer in a Markdown code fence; a client that asked for structured output, in a field or told in the system prompt (`wantsJSON`), gets the JSON inside a single unlabelled or json-labelled fence when that content is a complete valid JSON value, streamed (`fenceEncoder`) or whole (`unfencedResult`), in [`format_fence.go`](../../internal/gateway/format_fence.go). Invalid or truncated JSON, other fence languages, text outside the fence, and answers to plain-text clients reach the client as they came. This normalization applies to translated replies; native protocol passthrough stays byte-preserving.
|
||||
- A tool's images reach the model on every translation (`toolOutput` in [`ir.go`](../../internal/gateway/ir.go) reads them from Anthropic's `tool_result`, Responses' `function_call_output`, such as Codex's `view_image` output `[{"type":"input_image","image_url":"data:…"}]`, and a Chat tool message). Anthropic's Messages keeps them in the `tool_result`. Chat puts them in a user message right after the results, and the result says they follow; Gemini and Code Assist after the function's response. Kiro's results hold text alone, so Kiro's plugin (from 0.1.9 on) sends them with the message that answers the call, and only the latest images go again (#369, #1861). `TestCodexToolImageReachesAnthropicPlugin` and the Kiro plugin's `tool-images.test.mjs`.
|
||||
|
||||
+31
-23
@@ -5425,10 +5425,10 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
if named != nil {
|
||||
spaces = &nsTidy{named: named, sse: sse}
|
||||
}
|
||||
// a Grok model's 2500.0 in a call's arguments, which Codex turns away
|
||||
// (grok_integral.go, #1431); any other model's reply goes as it came
|
||||
// a model's 2500.0 in a call's arguments, which Codex turns away
|
||||
// (grok_integral.go, #1431, #3152: Grok's models and muse-spark alike)
|
||||
var ints *intTidy
|
||||
if (proto == provider.Responses || proto == provider.Chat || proto == provider.Anthropic) && (grokModel(model) || grokModel(upstream)) {
|
||||
if proto == provider.Responses || proto == provider.Chat || proto == provider.Anthropic {
|
||||
ints = &intTidy{proto: proto, sse: sse}
|
||||
}
|
||||
// a glm-5.3-flash* replica's CR stitched into a call's argument
|
||||
@@ -5558,12 +5558,15 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
if spaces != nil {
|
||||
out = spaces.write(out)
|
||||
}
|
||||
if ints != nil {
|
||||
out = ints.write(out)
|
||||
}
|
||||
// crArgs before ints: ints runs on every reply now and holds
|
||||
// one that came whole to its own flush, which crArgs, after it,
|
||||
// would never see (#3152 beside #4256's glm-5.3-flash routes)
|
||||
if crArgs != nil {
|
||||
out = crArgs.write(out)
|
||||
}
|
||||
if ints != nil {
|
||||
out = ints.write(out)
|
||||
}
|
||||
if sigs != nil {
|
||||
out = sigs.write(out)
|
||||
}
|
||||
@@ -5591,12 +5594,12 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
// what's held at the end goes through the filters after the one
|
||||
// that held it
|
||||
sign := func(b []byte) []byte {
|
||||
if ints != nil {
|
||||
b = ints.write(b)
|
||||
}
|
||||
if crArgs != nil {
|
||||
b = crArgs.write(b)
|
||||
}
|
||||
if ints != nil {
|
||||
b = ints.write(b)
|
||||
}
|
||||
if sigs != nil {
|
||||
b = sigs.write(b)
|
||||
}
|
||||
@@ -5628,15 +5631,20 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
if spaces != nil {
|
||||
write(sign(spaces.flush()))
|
||||
}
|
||||
if ints != nil {
|
||||
b := ints.flush()
|
||||
if crArgs != nil {
|
||||
b := crArgs.flush()
|
||||
if ints != nil {
|
||||
// ints holds a whole reply until its own drain below, so the
|
||||
// tail ints has not seen goes through it here first
|
||||
b = ints.write(b)
|
||||
}
|
||||
if sigs != nil {
|
||||
b = sigs.write(b)
|
||||
}
|
||||
write(out(b))
|
||||
}
|
||||
if crArgs != nil {
|
||||
b := crArgs.flush()
|
||||
if ints != nil {
|
||||
b := ints.flush()
|
||||
if sigs != nil {
|
||||
b = sigs.write(b)
|
||||
}
|
||||
@@ -6849,12 +6857,12 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
|
||||
}
|
||||
}
|
||||
}
|
||||
// a Grok model's 2500.0 in a call's arguments, which Codex turns away
|
||||
// (grok_integral.go, #1431)
|
||||
request.Grok = grokServed(wiresOf(r.Context()), p, model)
|
||||
// a glm-5.3-flash* replica's CR stitched into a call's arguments
|
||||
// (tool_args_cr.go, #4256)
|
||||
request.CR = glmServed(wiresOf(r.Context()), p, model)
|
||||
// a model's 2500.0 in a call's arguments, which Codex turns away, is
|
||||
// rewritten at the encoder and at render (grok_integral.go, #1431,
|
||||
// #3152)
|
||||
if from == provider.Anthropic {
|
||||
// Claude Code's auto mode classifier, on a model that reasons
|
||||
// whatever it is told (#250)
|
||||
@@ -7332,10 +7340,10 @@ func encoder(proto provider.Protocol, w *sseWriter, r *Request, usage ...*Usage)
|
||||
if len(usage) > 0 && usage[0] != nil {
|
||||
enc = &usageEncoder{streamEncoder: enc, usage: usage[0]}
|
||||
}
|
||||
if r.Grok {
|
||||
// outside usageEncoder, which reads its encoder's reply id
|
||||
enc = &wholeEncoder{streamEncoder: enc}
|
||||
}
|
||||
// a model's whole floats in a call's arguments reach the client as
|
||||
// integers (grok_integral.go, #1431, #3152), outside usageEncoder,
|
||||
// which reads its encoder's reply id
|
||||
enc = &wholeEncoder{streamEncoder: enc}
|
||||
if r.CR {
|
||||
enc = &crEncoder{streamEncoder: enc}
|
||||
}
|
||||
@@ -7362,9 +7370,9 @@ func makeEncoder(proto provider.Protocol, w *sseWriter, r *Request) streamEncode
|
||||
|
||||
func render(proto provider.Protocol, res Result, r *Request) []byte {
|
||||
model := r.Model
|
||||
if r.Grok {
|
||||
res = wholeResult(res)
|
||||
}
|
||||
// a model's whole floats in a call's arguments reach the client as
|
||||
// integers (grok_integral.go, #1431, #3152)
|
||||
res = wholeResult(res)
|
||||
if r.CR {
|
||||
res = crResult(res)
|
||||
}
|
||||
|
||||
@@ -9,24 +9,23 @@ import (
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// Grok's models write a whole number in a tool call's arguments with a
|
||||
// fraction of zeros ("yield_time_ms":2500.0, "session_id":17277.0), whoever
|
||||
// serves them: a Grok subscription or its plugin, xAI's API, OpenRouter's
|
||||
// x-ai/grok-*, or a relay in front of any of them. Codex reads such fields
|
||||
// as u64, usize, i32 or i64 (exec_command, write_stdin, shell's timeout_ms,
|
||||
// sleep, tool_search's limit, wait), though their schemas say "number", and
|
||||
// serde turns the whole call away: "failed to parse function arguments:
|
||||
// invalid type: floating point `2500.0`, expected u64" (#1431, 11 of 11
|
||||
// turns on grok-4.6 and grok-4.7 through a relay). Any client that types
|
||||
// its arguments strictly does the same.
|
||||
// Models write a whole number in a tool call's arguments with a fraction
|
||||
// of zeros ("yield_time_ms":2500.0, "session_id":17277.0), whoever serves
|
||||
// them: Grok's do it on every turn (#1431, 11 of 11 turns on grok-4.6 and
|
||||
// grok-4.7 through a relay), and muse-spark wrote tool_search's limit as
|
||||
// 8.0 through the gateway (#3152). Codex reads such fields as u64, usize,
|
||||
// i32 or i64 (exec_command, write_stdin, shell's timeout_ms, sleep,
|
||||
// tool_search's limit, wait), though their schemas say "number", and serde
|
||||
// turns the whole call away: "failed to parse function arguments: invalid
|
||||
// type: floating point `2500.0`, expected u64". Any client that types its
|
||||
// arguments strictly does the same.
|
||||
//
|
||||
// In a reply from a Grok model, a number in a call's arguments written with
|
||||
// a fraction of zeros and no exponent loses that fraction: 2500.0 is
|
||||
// written 2500. JSON has one kind of number, so 2500 is the same value to
|
||||
// every client, and one that took 2500.0 takes 2500; a tool's schema isn't
|
||||
// asked, since Codex's own say "number" for the integers it reads. Strings,
|
||||
// keys, other fractions (2.5) and exponents (2.5e3) stay as written, and
|
||||
// so does every other model's reply.
|
||||
// In a reply, a number in a call's arguments written with a fraction of
|
||||
// zeros and no exponent loses that fraction: 2500.0 is written 2500. JSON
|
||||
// has one kind of number, so 2500 is the same value to every client, and
|
||||
// one that took 2500.0 takes 2500; a tool's schema isn't asked, since
|
||||
// Codex's own say "number" for the integers it reads. Strings, keys, other
|
||||
// fractions (2.5) and exponents (2.5e3) stay as written.
|
||||
//
|
||||
// The rule is applied to the arguments as a stream of text, so it gives
|
||||
// the same arguments whether they come whole or in deltas cut anywhere:
|
||||
@@ -34,7 +33,8 @@ import (
|
||||
|
||||
// grokModel is whether id, the model as magpie or its upstream names it, is
|
||||
// one of Grok's, under whatever vendor prefix a relay or router gives it
|
||||
// (xai/grok-4.5, x-ai/grok-4).
|
||||
// (xai/grok-4.5, x-ai/grok-4). Grok's schema quirks (grok_schema.go) are
|
||||
// still Grok's alone; whole floats in calls' arguments are every model's.
|
||||
func grokModel(id string) bool {
|
||||
if i := strings.LastIndexByte(id, '/'); i >= 0 {
|
||||
id = id[i+1:]
|
||||
@@ -42,12 +42,6 @@ func grokModel(id string) bool {
|
||||
return strings.HasPrefix(strings.ToLower(id), "grok")
|
||||
}
|
||||
|
||||
// grokServed is whether a request for model on p goes to a Grok model,
|
||||
// by magpie's id for it or the name it is sent upstream under.
|
||||
func grokServed(wires map[string]string, p provider.Provider, model string) bool {
|
||||
return grokModel(model) || grokModel(provider.UpstreamNameIn(wires, p.ID, model))
|
||||
}
|
||||
|
||||
// wholeNums drops the zero fraction of each number in a stream of JSON
|
||||
// text, fed to it a piece at a time. It holds only a fraction of zeros
|
||||
// (".0", ".00") until it knows whether the number ends there, in which
|
||||
@@ -119,8 +113,8 @@ func wholeArgs(s string) string {
|
||||
return n.feed(s)
|
||||
}
|
||||
|
||||
// wholeEncoder hands its encoder a Grok model's reply with the zero
|
||||
// fractions dropped from its calls' arguments, streamed in pieces.
|
||||
// wholeEncoder hands its encoder a reply with the zero fractions dropped
|
||||
// from its calls' arguments, streamed in pieces.
|
||||
type wholeEncoder struct {
|
||||
streamEncoder
|
||||
args wholeNums
|
||||
@@ -138,8 +132,8 @@ func (e *wholeEncoder) event(ev Event) {
|
||||
e.streamEncoder.event(ev)
|
||||
}
|
||||
|
||||
// wholeResult is a whole reply from a Grok model with its calls'
|
||||
// arguments' zero fractions dropped.
|
||||
// wholeResult is a whole reply with its calls' arguments' zero fractions
|
||||
// dropped.
|
||||
func wholeResult(res Result) Result {
|
||||
var parts []Part
|
||||
for i, p := range res.Parts {
|
||||
@@ -159,12 +153,11 @@ func wholeResult(res Result) Result {
|
||||
return res
|
||||
}
|
||||
|
||||
// intTidy drops, in a Grok model's reply relayed as it came, the zero
|
||||
// fractions of its calls' arguments: Responses' function_call items and
|
||||
// argument deltas, Chat's tool_calls, and Messages' tool_use input. A
|
||||
// stream's lines pass as they came unless one carries arguments that
|
||||
// change; a reply that isn't one is held whole and gone through at the
|
||||
// end.
|
||||
// intTidy drops, in a reply relayed as it came, the zero fractions of its
|
||||
// calls' arguments: Responses' function_call items and argument deltas,
|
||||
// Chat's tool_calls, and Messages' tool_use input. A stream's lines pass
|
||||
// as they came unless one carries arguments that change; a reply that
|
||||
// isn't one is held whole and gone through at the end.
|
||||
type intTidy struct {
|
||||
proto provider.Protocol
|
||||
sse bool
|
||||
@@ -190,6 +183,11 @@ func (t *intTidy) flush() []byte {
|
||||
b := t.buf
|
||||
t.buf = nil
|
||||
if !t.sse {
|
||||
// every model's whole reply comes here now: one with no call in
|
||||
// it is said as it came, without being decoded
|
||||
if !t.carries(b) {
|
||||
return b
|
||||
}
|
||||
if out, ok := t.event(b); ok {
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package gateway
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -623,72 +622,85 @@ func TestGrokCallsGiveIntegersOnEveryProtocol(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A model magpie names otherwise but sends upstream as a Grok model is
|
||||
// Grok's too.
|
||||
func TestGrokCallsByUpstreamName(t *testing.T) {
|
||||
c := integralCases(t)[0]
|
||||
fresh(t)
|
||||
up := httptest.NewServer(responsesCall(c.tool, c.args, []string{c.args}))
|
||||
defer up.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Models: []string{"x-ai/grok-4.6"}, Responses: up.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, stream := range []bool{true, false} {
|
||||
checkResponses(t, c, askGrok(t, "/v1/responses", codexShellTurn("relay/x-ai/grok-4.6", stream)), stream)
|
||||
// Another vendor's model writes whole floats too (#3152: muse-spark's
|
||||
// tool_search limit 8.0, which Codex turns away as "invalid number"): a
|
||||
// model nobody calls Grok reaches the client with integers, relayed on
|
||||
// every protocol and translated from Chat, deltas and done alike. The
|
||||
// edges case in integralCases holds the look-alikes that stay as written:
|
||||
// 2500.5, 2.50, 2.5e3, 1.0e3, the string "4000.0".
|
||||
func TestOtherModelsCallsGetCodexIntegers(t *testing.T) {
|
||||
for _, c := range integralCases(t) {
|
||||
pieces := someCuts(c.args)["by byte"]
|
||||
for _, stream := range []bool{true, false} {
|
||||
for _, rc := range []struct {
|
||||
path, body string
|
||||
up http.HandlerFunc
|
||||
p provider.Provider
|
||||
}{
|
||||
{"/v1/responses", codexShellTurn("relay/gpt-5.5", stream), responsesCall(c.tool, c.args, pieces), provider.Provider{Responses: "/v1"}},
|
||||
{"/v1/chat/completions", chatShellTurn("relay/gpt-5.5", stream), chatCall(c.tool, c.args, pieces), provider.Provider{Chat: "/v1"}},
|
||||
{"/v1/messages", messagesShellTurn("relay/gpt-5.5", stream), messagesCall(c.tool, c.args, pieces), provider.Provider{Anthropic: "/v1"}},
|
||||
} {
|
||||
fresh(t)
|
||||
up := httptest.NewServer(rc.up)
|
||||
p := rc.p
|
||||
p.ID, p.Name, p.Key, p.Models = "relay", "relay", "k", []string{"gpt-5.5"}
|
||||
if p.Responses != "" {
|
||||
p.Responses = up.URL + p.Responses
|
||||
}
|
||||
if p.Chat != "" {
|
||||
p.Chat = up.URL + p.Chat
|
||||
}
|
||||
if p.Anthropic != "" {
|
||||
p.Anthropic = up.URL + p.Anthropic
|
||||
}
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check := func(where string, got []byte) {
|
||||
t.Helper()
|
||||
switch rc.path {
|
||||
case "/v1/responses":
|
||||
checkResponses(t, c, got, stream)
|
||||
case "/v1/chat/completions":
|
||||
c.check(t, where, chatRead(t, got, stream))
|
||||
case "/v1/messages":
|
||||
c.check(t, where, messagesRead(t, got, stream))
|
||||
}
|
||||
}
|
||||
check(rc.path+map[bool]string{true: " stream", false: ""}[stream], askGrok(t, rc.path, rc.body))
|
||||
up.Close()
|
||||
}
|
||||
|
||||
fresh(t)
|
||||
chat := httptest.NewServer(chatCall(c.tool, c.args, pieces))
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "relay", Key: "k", Models: []string{"gpt-5.5"}, Chat: chat.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for where, got := range responsesRead(t, askGrok(t, "/v1/responses", codexShellTurn("relay/gpt-5.5", stream)), stream) {
|
||||
c.check(t, "translated "+where, got)
|
||||
}
|
||||
chat.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Another vendor's model is not Grok's: the same call reaches the client
|
||||
// as it came, relayed byte for byte, and translated with its floats.
|
||||
func TestOnlyGrokCallsGetIntegers(t *testing.T) {
|
||||
c := rollout(t, "grok_4_6_exec_command.jsonl")
|
||||
pieces := []string{c.Arguments[:60], c.Arguments[60:]}
|
||||
// #3152: a model that is not Grok's writes tool_search's limit as a whole
|
||||
// float, and Codex turns the call away before it runs ("invalid number";
|
||||
// omitting limit is the reporter's proof the MCP servers were fine).
|
||||
// Relayed Responses, streamed in deltas or whole, the client reads 8.
|
||||
func TestToolSearchWholeFloatLimitGivesCodexIntegers(t *testing.T) {
|
||||
c := integralCase{name: "tool_search limit 8.0", tool: "tool_search",
|
||||
args: `{"query":"exa web search","limit":8.0}`,
|
||||
want: map[string]string{"query": `"exa web search"`, "limit": "8"}}
|
||||
for _, stream := range []bool{true, false} {
|
||||
for _, rc := range []struct {
|
||||
path, body string
|
||||
up http.HandlerFunc
|
||||
p provider.Provider
|
||||
}{
|
||||
{"/v1/responses", codexShellTurn("relay/gpt-5.5", stream), responsesCall(c.Name, c.Arguments, pieces), provider.Provider{Responses: "/v1"}},
|
||||
{"/v1/chat/completions", chatShellTurn("relay/gpt-5.5", stream), chatCall(c.Name, c.Arguments, pieces), provider.Provider{Chat: "/v1"}},
|
||||
{"/v1/messages", messagesShellTurn("relay/gpt-5.5", stream), messagesCall(c.Name, c.Arguments, pieces), provider.Provider{Anthropic: "/v1"}},
|
||||
} {
|
||||
fresh(t)
|
||||
up := httptest.NewServer(rc.up)
|
||||
p := rc.p
|
||||
p.ID, p.Name, p.Key, p.Models = "relay", "relay", "k", []string{"gpt-5.5"}
|
||||
if p.Responses != "" {
|
||||
p.Responses = up.URL + p.Responses
|
||||
}
|
||||
if p.Chat != "" {
|
||||
p.Chat = up.URL + p.Chat
|
||||
}
|
||||
if p.Anthropic != "" {
|
||||
p.Anthropic = up.URL + p.Anthropic
|
||||
}
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// what the relay itself answers
|
||||
direct := httptest.NewRecorder()
|
||||
rc.up(direct, httptest.NewRequest("POST", rc.path, strings.NewReader(strings.Replace(rc.body, "relay/gpt-5.5", "gpt-5.5", 1))))
|
||||
if got := askGrok(t, rc.path, rc.body); !bytes.Equal(got, direct.Body.Bytes()) {
|
||||
t.Fatalf("%s stream %v:\n%s\nwant\n%s", rc.path, stream, got, direct.Body)
|
||||
}
|
||||
up.Close()
|
||||
}
|
||||
|
||||
fresh(t)
|
||||
chat := httptest.NewServer(chatCall(c.Name, c.Arguments, pieces))
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "relay", Key: "k", Models: []string{"gpt-5.5"}, Chat: chat.URL + "/v1"}); err != nil {
|
||||
up := httptest.NewServer(responsesCall(c.tool, c.args, someCuts(c.args)["by byte"]))
|
||||
defer up.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Models: []string{"muse-spark-1.3-contributor"}, Responses: up.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for where, got := range responsesRead(t, askGrok(t, "/v1/responses", codexShellTurn("relay/gpt-5.5", stream)), stream) {
|
||||
if got != c.Arguments {
|
||||
t.Fatalf("stream %v: %s translated %q, want %q", stream, where, got, c.Arguments)
|
||||
}
|
||||
}
|
||||
chat.Close()
|
||||
checkResponses(t, c, askGrok(t, "/v1/responses", codexShellTurn("relay/muse-spark-1.3-contributor", stream)), stream)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -704,3 +716,58 @@ func TestGrokModel(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A glm-5.3-flash* route gets both cures now: its stitched CR goes
|
||||
// (tool_args_cr.go, #4256) and its whole floats lose their zeros. The CR
|
||||
// cure reads the arguments as the upstream wrote them, then the whole
|
||||
// floats go, in a reply that came whole (both filters hold it to the end)
|
||||
// and in a stream.
|
||||
func TestStitchedCRAndWholeFloatsBothGo(t *testing.T) {
|
||||
const want = `{"a":"xy\r\nz","limit":8}`
|
||||
t.Run("whole", func(t *testing.T) {
|
||||
fresh(t)
|
||||
f := &fake{t: t, ctype: "application/json", reply: `{"id":"msg_1","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"toolu_1","name":"tool_search","input":{"a":"x\ry\r\nz","limit":8.0}}],"stop_reason":"tool_use","usage":{"input_tokens":1,"output_tokens":3}}`}
|
||||
crModel(t, provider.Anthropic, setup(t, provider.Anthropic, f), "glm-5.3-flash")
|
||||
code, body := post(t, "/v1/messages", `{"model":"glm-5.3-flash","max_tokens":100,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("status %d: %s", code, body)
|
||||
}
|
||||
// read field by field, as written: a decode and encode of the
|
||||
// whole input would say 8.0 as 8 itself
|
||||
got := messagesRead(t, []byte(body), false)
|
||||
if f := fieldsOf(t, got); len(f) != 2 || f["a"] != `"xy\r\nz"` || f["limit"] != "8" {
|
||||
t.Fatalf("client read %s, want %s", got, want)
|
||||
}
|
||||
})
|
||||
t.Run("stream", func(t *testing.T) {
|
||||
fresh(t)
|
||||
f := &fake{t: t, reply: sse(
|
||||
`data: {"type":"response.created","response":{"id":"resp_1"}}`,
|
||||
`data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"tool_search","arguments":""}}`,
|
||||
`data: {"type":"response.function_call_arguments.delta","item_id":"fc_1","output_index":0,"delta":"{\"a\":\"x\\ry\\r\\nz\",\"limit\":8."}`,
|
||||
`data: {"type":"response.function_call_arguments.delta","item_id":"fc_1","output_index":0,"delta":"0}"}`,
|
||||
`data: {"type":"response.function_call_arguments.done","item_id":"fc_1","output_index":0,"arguments":"{\"a\":\"x\\ry\\r\\nz\",\"limit\":8.0}"}`,
|
||||
`data: {"type":"response.completed"}`,
|
||||
)}
|
||||
crModel(t, provider.Responses, setup(t, provider.Responses, f), "glm-5.3-flash")
|
||||
code, body := post(t, "/v1/responses", `{"model":"glm-5.3-flash","stream":true,"input":"hi"}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("status %d: %s", code, body)
|
||||
}
|
||||
if got := responsesArgs(t, body); got != want {
|
||||
t.Fatalf("deltas add up to %s, want %s", got, want)
|
||||
}
|
||||
var done int
|
||||
for _, ev := range events(body) {
|
||||
if ev["type"] == "response.function_call_arguments.done" {
|
||||
done++
|
||||
if a, _ := ev["arguments"].(string); a != want {
|
||||
t.Fatalf("done said %s, want %s", a, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
if done != 1 {
|
||||
t.Fatalf("%d done events in %s", done, body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -318,10 +318,6 @@ type Request struct {
|
||||
// and the conversation sent before stay as they were, so its prompt
|
||||
// cache does (#2660). Every other upstream gets them in tools.
|
||||
LoadedInPlace bool
|
||||
// Grok is set when the model asked is one of Grok's, whose calls'
|
||||
// arguments reach the client with their zero fractions dropped
|
||||
// (grok_integral.go).
|
||||
Grok bool
|
||||
// CR is set when the model asked is one of the glm-5.3-flash* routes
|
||||
// whose replicas stitch CR into a call's arguments (#4256): the
|
||||
// arguments reach the client with the stitched CR dropped
|
||||
|
||||
Reference in New Issue
Block a user