gateway: DSML calls Alma relays from a group's DeepSeek are guarded on the Responses route

wishSeikouudoku on X (tweet 2117056042001719807, 11-02 08:47 +0800): Alma,
through a magpie group to DeepSeek, got <||DSML|| calls>, invoke
name="…" and parameter as its reply's text, and no tool ran.

Cause, already fixed on main: Alma's magpie provider is of type openai,
which the AI SDK sends to /v1/responses (the owner's usage log: 4365
Alma rows with ep /v1/responses). DeepSeek's preset speaks Responses
too, so the reply was relayed as it came, and before 20f27f514 (#4743,
first in v0.1.2652, published 11-01 22:36Z, about 2h before the tweet)
a relayed Responses reply's text was never read for calls. The DSML
parser itself already read these exact bytes (observedPipes, #2623).
No code change here: this commit adds the reporter's route to the tests
and fixes the subsystem doc, which still said a relayed Responses reply
"is not read for calls yet".

- textcalls_alma_test.go: TestDSMLAlmaResponsesThroughGroup sends
  Alma's AI-SDK-shaped request (streamed and whole) to a group of two
  Responses members, the first answering or refusing with a 500. The
  reply is DeepSeek-shaped: a reasoning item, then a message whose text
  is "我先搜一下。\n\n" + observedPipes, one character to a delta.
  TestDSMLAlmaResponsesPlugin does the same to a plugin's model, alone
  and as a group's only member (the plugin is asked Chat, so the
  translation reads it).
- gateway-routing.md: the text-calls paragraph names responsesTextCalls
  and this report.

Run (mote; the full package at 4d55a0a02 + this change, then the DSML,
TestTextWritten and Responses passthrough tests again at ca1fc43fc +
this change, which touched no gateway file: ok):
- go test -timeout 45m ./internal/gateway/ ./ : root ok; gateway red on
  TestCodexPoolSaysTheClientsVersion only, a file this change doesn't
  touch, which is #4807 (red in a full package run on mote, passes
  alone); alone with TestDSMLAlma it is ok. A full ./... run wasn't
  made: this change is a test file and a doc.
- -run 'TestDSMLAlma|TestDSMLThroughGroup|TestInvokeReportedResponsesPassthrough': ok

Broken by hand:
- the responsesTextCalls branch in passthrough turned off (as before
  v0.1.2652): TestDSMLAlmaResponsesThroughGroup red, the DSML in
  output_text and in response.completed's output, no function_call.
- textCallSee turned off in both translated paths (gateway.go written,
  continuation.go): TestDSMLAlmaResponsesPlugin red. With only
  gateway.go's off it stayed green: the plugin's reply goes through
  continuation.go's.

Real request: an Alma-shaped streamed /v1/responses request through a
sandboxed magpie (sandbox HOME on mote, port 3591) to a group of
deepseek/deepseek-flash, opencode-go/deepseek-v4.1-flash and
volcengine-2/deepseek-v4-1-flash-260910. DeepSeek's own API answered
Insufficient Balance and OpenCode Go's key has expired, so Volcengine's
DeepSeek V4.1 Flash served it: a native web_search function_call, no
DSML. The model didn't write its call as text on that try.

Not tried: DeepSeek's own Responses stream (no balance), so the
reasoning-then-message shape in the fixture is modelled on OpenAI's
events, not DeepSeek's bytes; the reporter's magpie version is not
known.
This commit is contained in:
yetone
2026-11-02 09:12:14 +08:00
parent ca1fc43fc9
commit 18c3976234
2 changed files with 171 additions and 2 deletions
+2 -2
View File
@@ -275,7 +275,7 @@ recorded as a prediction failure (`noPrediction`).
- 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 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), GLM's `<arg_key>`/`<arg_value>` (#906), and the plain `<invoke name=…><parameter name=…>…</parameter></invoke>` of Claude's and MiniMax's calls, bare or in `<function_calls>` or `<minimax:tool_call>` (packinggoodsllc_07668 on Discord: Claude Code through a routing group was shown the invokes as text), read by `parseTextCalls`. Text after a call read out, other than tags, ends the calls, and it and all after it go: the model went on as if its call had run ("*Result: Tool loaded.*", then the next call, then "done"), and the agent runs the call and gives it the real result. 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`), a relayed Messages reply, streamed or whole (`anthropicTextCalls`: the held text's block start and stop are held with it, the calls become `tool_use` blocks after it, or in its place when none of its text went), and every translation, which magpie always asks streamed, a plugin's included, whatever the client asked (`textCallSee`). A relayed Responses or Gemini upstream's text is not read for calls yet (#4743). Covered by `TestTextWritten*`, `TestInvokeReported*`, `TestDSMLClose*`, `TestDSMLBlockClosedWithCalls`, `TestGLMTextCall*`, `TestPluginTextWrittenCall` and `TestQuietWholeReplyStreamed`.
- 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), GLM's `<arg_key>`/`<arg_value>` (#906), and the plain `<invoke name=…><parameter name=…>…</parameter></invoke>` of Claude's and MiniMax's calls, bare or in `<function_calls>` or `<minimax:tool_call>` (packinggoodsllc_07668 on Discord: Claude Code through a routing group was shown the invokes as text), read by `parseTextCalls`. Text after a call read out, other than tags, ends the calls, and it and all after it go: the model went on as if its call had run ("*Result: Tool loaded.*", then the next call, then "done"), and the agent runs the call and gives it the real result. 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`), a relayed Messages reply, streamed or whole (`anthropicTextCalls`: the held text's block start and stop are held with it, the calls become `tool_use` blocks after it, or in its place when none of its text went), and every translation, which magpie always asks streamed, a plugin's included, whatever the client asked (`textCallSee`). A relayed Responses reply, streamed or whole, is read too (`responsesTextCalls` in [`textcalls_relay.go`](../../internal/gateway/textcalls_relay.go), #4743, from v0.1.2652): the held text's `output_text.done`, `content_part.done` and `output_item.done` wait with it, and the calls become `function_call` items after it, in the events and in `response.completed`'s output. Before it, Alma (whose provider of type openai speaks Responses) through a group to DeepSeek, whose preset speaks Responses too, had the reply relayed as it came and got DeepSeek's `<||DSML|| calls>` as text with nothing run (wishSeikouudoku on X). A relayed Gemini reply the same (`geminiTextCalls`). Covered by `TestTextWritten*`, `TestInvokeReported*`, `TestDSMLAlma*` (a group of Responses members and a plugin's DeepSeek, from a Responses client, one character to a delta), `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`.
- An image's `detail` (`Part.Detail`, read from a Responses `input_image` and a Chat `image_url`, in a message or a tool's output) is carried on a translation to Chat and Responses (`chatImage`, `chatDetail`, `responsesDetail` in [`chat.go`](../../internal/gateway/chat.go)). Chat takes `low`, `high` and `auto` as they came, and Responses' `original`, which Chat lacks, as `high`; an image without one goes without. Responses takes the four as they came, and anything else, none included, as `auto` (#1474). Messages and Gemini have no such field, so it isn't sent there (mysterious_dove on Discord, Codex: `high` and `original` were dropped on the way to Chat; `TestResponsesImageDetailReachesChat`, `TestChatImageDetailReachesResponses`).
@@ -1823,7 +1823,7 @@ go test -tags nogui ./internal/gateway ./internal/provider ./internal/cli ./inte
node --test internal/gui/tests/disabled-models.test.cjs
go test -tags nogui ./internal/gateway ./internal/gui -run 'TestBareModelIDs'
node --test internal/gui/tests/bare-ids.test.cjs
go test -tags nogui ./internal/gateway -run 'TestTextWritten|TestGLMTextCall|TestPluginTextWrittenCall|TestQuietWholeReplyStreamed'
go test -tags nogui ./internal/gateway -run 'TestTextWritten|TestGLMTextCall|TestPluginTextWrittenCall|TestQuietWholeReplyStreamed|TestDSMLAlma'
go test -tags nogui ./internal/gateway -run 'TestAutoMode|TestClaudeBridgeSafeguard|TestSafeguardsRefused'
go test -tags nogui ./internal/gateway -run 'TestCreditsExhaustedIsOutOfCredit|TestOutOfCreditLeavesFreeModels'
go test -tags nogui ./internal/gateway ./internal/usage -run 'TestRetriedRequestCountsOnce|TestRequestsCountedOnceWithTheirRetries'
+169
View File
@@ -0,0 +1,169 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// wishSeikouudoku on X (2026-11-02): Alma, through a magpie group that
// sends it on to DeepSeek, got <||DSML|| calls>, invoke name="…" and
// parameter as its reply's text, and no tool ran. Alma's provider of type
// openai speaks Responses (/v1/responses, streamed), and DeepSeek's preset
// speaks Responses too, so the reply is relayed as it came: the route
// #4743's responsesTextCalls reads. The stream here is DeepSeek-shaped: a
// reasoning item first, then the message whose text is observedPipes
// (the double-pipe calls DeepSeek wrote in real use), one character to a
// delta so every mark is cut across events. The group's first member
// answers, or refuses and the second does.
func TestDSMLAlmaResponsesThroughGroup(t *testing.T) {
stream := dsmlResponsesSSE("我先搜一下。\n\n" + observedPipes)
part := map[string]any{"type": "output_text", "text": "我先搜一下。\n\n" + observedPipes, "annotations": []any{}}
whole, _ := json.Marshal(map[string]any{"id": "r1", "object": "response", "model": "deepseek-flash", "status": "completed",
"output": []any{
map[string]any{"type": "reasoning", "id": "rs_1", "summary": []any{map[string]any{"type": "summary_text", "text": "need a search"}}},
map[string]any{"type": "message", "role": "assistant", "id": "msg_1", "status": "completed", "content": []any{part}}}})
refused := reply{500, "application/json", `{"error":{"message":"upstream overloaded"}}`}
// Alma's request as the AI SDK's openai provider writes it
body := func(stream bool) string {
s := "false"
if stream {
s = "true"
}
return `{"model":"group/ds","stream":` + s + `,"input":[{"role":"system","content":"You are Alma."},{"role":"user","content":[{"type":"input_text","text":"What is the latest Python?"}]}],` +
`"tools":[{"type":"function","name":"web_search","description":"Search the web","parameters":{"type":"object","properties":{"query":{"type":"string"}},"required":["query"],"additionalProperties":false},"strict":false}],"tool_choice":"auto"}`
}
const wantArgs = `{"query":"current Python version latest stable release"}`
for _, streamed := range []bool{true, false} {
for _, first := range []bool{true, false} {
fresh(t)
ok := reply{200, "text/event-stream", stream}
if !streamed {
ok = reply{200, "application/json", string(whole)}
}
a, b := &scripted{replies: []reply{ok}}, &scripted{replies: []reply{ok}}
if !first {
a.replies = []reply{refused}
}
scriptedOn(t, "a", provider.Responses, a)
scriptedOn(t, "b", provider.Responses, b)
if err := provider.SaveGroup(provider.Group{ID: "ds", Name: "DeepSeek", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body(streamed))))
raw := rec.Body.String()
var text string
var names, args []string
if streamed {
text, names, args, _, _ = responsesStreamRead(t, raw)
} else {
var got struct {
Output []struct {
Type string `json:"type"`
Name string `json:"name"`
Args string `json:"arguments"`
Content []struct {
Text string `json:"text"`
} `json:"content"`
} `json:"output"`
}
if err := json.Unmarshal([]byte(raw), &got); err != nil {
t.Fatalf("%v: %s", err, raw)
}
for _, o := range got.Output {
switch o.Type {
case "message":
for _, c := range o.Content {
text += c.Text
}
case "function_call":
names, args = append(names, o.Name), append(args, o.Args)
}
}
}
if rec.Code != 200 || strings.Contains(raw, "DSML") || text != "我先搜一下。\n\n" ||
len(names) != 1 || names[0] != "web_search" || args[0] != wantArgs || strings.Contains(raw, "overloaded") {
t.Fatalf("streamed %v, first answers %v: %d text %q calls %v %v\n%s", streamed, first, rec.Code, text, names, args, raw)
}
}
}
}
// dsmlResponsesSSE is a Responses stream as DeepSeek's reads: a reasoning
// item, then a message item whose text is text, one character to a delta.
func dsmlResponsesSSE(text string) string {
ev := func(typ string, v map[string]any) string {
v["type"] = typ
b, _ := json.Marshal(v)
return "event: " + typ + "\ndata: " + string(b)
}
seq := 0
n := func(v map[string]any) map[string]any { v["sequence_number"] = seq; seq++; return v }
reasoning := map[string]any{"type": "reasoning", "id": "rs_1", "summary": []any{map[string]any{"type": "summary_text", "text": "need a search"}}}
part := map[string]any{"type": "output_text", "text": text, "annotations": []any{}}
msg := map[string]any{"type": "message", "role": "assistant", "id": "msg_1", "status": "completed", "content": []any{part}}
lines := []string{
ev("response.created", n(map[string]any{"response": map[string]any{"id": "r1", "model": "deepseek-flash", "status": "in_progress", "output": []any{}}})),
ev("response.output_item.added", n(map[string]any{"output_index": 0, "item": map[string]any{"type": "reasoning", "id": "rs_1", "summary": []any{}}})),
ev("response.reasoning_summary_text.delta", n(map[string]any{"item_id": "rs_1", "output_index": 0, "summary_index": 0, "delta": "need a search"})),
ev("response.output_item.done", n(map[string]any{"output_index": 0, "item": reasoning})),
ev("response.output_item.added", n(map[string]any{"output_index": 1,
"item": map[string]any{"type": "message", "role": "assistant", "id": "msg_1", "status": "in_progress", "content": []any{}}})),
ev("response.content_part.added", n(map[string]any{"item_id": "msg_1", "output_index": 1, "content_index": 0,
"part": map[string]any{"type": "output_text", "text": "", "annotations": []any{}}})),
}
for _, r := range text {
lines = append(lines, ev("response.output_text.delta", n(map[string]any{"item_id": "msg_1", "output_index": 1, "content_index": 0, "delta": string(r)})))
}
lines = append(lines,
ev("response.output_text.done", n(map[string]any{"item_id": "msg_1", "output_index": 1, "content_index": 0, "text": text})),
ev("response.content_part.done", n(map[string]any{"item_id": "msg_1", "output_index": 1, "content_index": 0, "part": part})),
ev("response.output_item.done", n(map[string]any{"output_index": 1, "item": msg})),
ev("response.completed", n(map[string]any{"response": map[string]any{"id": "r1", "model": "deepseek-flash", "status": "completed",
"output": []any{reasoning, msg}, "usage": map[string]any{"input_tokens": 900, "output_tokens": 120, "total_tokens": 1020}}})))
return sse(lines...)
}
// The same from Alma to a plugin's DeepSeek (Trae CN, WorkBuddy), alone or
// as a group's member: the plugin's reply, Responses or Chat, whichever the
// plugin was asked, is read the same way.
func TestDSMLAlmaResponsesPlugin(t *testing.T) {
text := "我先搜一下。\n\n" + observedPipes
var paths []string
pid := besideFake(t, "trae-cn", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
paths = append(paths, r.URL.Path)
w.Header().Set("Content-Type", "text/event-stream")
if strings.HasSuffix(r.URL.Path, "/responses") {
io.WriteString(w, dsmlResponsesSSE(text))
return
}
for _, r := range text {
b, _ := json.Marshal(map[string]any{"id": "c1", "object": "chat.completion.chunk", "choices": []any{map[string]any{"index": 0, "delta": map[string]any{"content": string(r)}, "finish_reason": nil}}})
io.WriteString(w, "data: "+string(b)+"\n\n")
}
io.WriteString(w, `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n")
}))
if err := provider.SaveGroup(provider.Group{ID: "ds", Name: "DeepSeek", Members: []string{pid + "/fake-1"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
h := New().Handler()
for _, model := range []string{pid + "/fake-1", "group/ds"} {
req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(`{"model":"`+model+`","stream":true,"input":[{"role":"user","content":[{"type":"input_text","text":"What is the latest Python?"}]}],`+
`"tools":[{"type":"function","name":"web_search","parameters":{"type":"object","properties":{"query":{"type":"string"}}},"strict":false}],"tool_choice":"auto"}`))
req.Header.Set("Authorization", "Bearer magpie")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
raw := rec.Body.String()
got, names, args, _, _ := responsesStreamRead(t, raw)
if rec.Code != 200 || strings.Contains(raw, "DSML") || got != "我先搜一下。\n\n" || len(names) != 1 || names[0] != "web_search" ||
args[0] != `{"query":"current Python version latest stable release"}` {
t.Fatalf("%s (upstream asked at %v): %d text %q calls %v %v\n%s", model, paths, rec.Code, got, names, args, raw)
}
}
}