Files
magpie/internal/gateway/mistral_extra_fields_test.go
T
yetone 0ad0f42411 gateway: Ollama's options reach no Chat upstream, so Hermes Agent's requests to Mistral are not turned away (lijiho96940561 on X)
Hermes Agent pointed at magpie (provider "custom", base URL on this
machine) probes the server as Ollama: detect_local_server_type GETs
/api/tags, which magpie answers in Ollama's shape for VS Code's Copilot,
and the body has "models", so it is "ollama". agent_init_ollama.py then
asks /api/show for the model's context and the custom profile sends it as
extra_body {"options": {"num_ctx": N}} on every chat request
(plugins/model-providers/custom/__init__.py, NousResearch/hermes-agent
90d6b98f). magpie relayed that top-level options to Mistral as it came,
and Mistral's chat API forbids extra fields: 422 extra_forbidden on
["body","options"] for every request. Mistral's own request model
(mistralai/client-python d3da3bd, ChatCompletionRequest) has no options;
it does take reasoning_effort "medium", the other field Hermes adds.

9a4eaab82 (#3097) left options out for Gemini's OpenAI-compatible API
only and kept it for every other vendor. No Chat API reads it, Ollama's
own /v1 included (openai.ChatCompletionRequest has no Options), so every
relayed Chat body now goes without its top-level options
(withoutOllamaOptions), as the Ollama route's own builder already leaves
the runner settings out (ollamaChatBody). The cut is withoutTopMember's,
every other byte as it came: the old withoutFields re-encoded the whole
body through a map, which would have reordered every tool schema of any
request whose text says "options". A body without the word is not
parsed. Groq, which Hermes' own comment names as strict too, and every
other vendor get the same body. /api/tags and /api/show are left
answering in Ollama's shape: VS Code's and Visual Studio's Copilot need
them, and a client can't be told from Hermes there.

Run (mote, at this commit): go test ./internal/gateway -timeout 45m:
ok (812.7s). go vet ./internal/gateway, GOOS=linux GOARCH=amd64
-tags nogui and GOOS=windows GOARCH=amd64 go vet ./internal/gateway
clean; gofmt -l clean.
Red without the fix: with the withoutOllamaOptions line taken out,
TestHermesOllamaOptionsNeverReachMistral fails with Mistral's fake 422
extra_forbidden on options, and TestChatRelayLeavesOutOllamaOptions with
options reaching both Gemini and Kimi. With withoutFields(body,
"options") in its place, the new test fails on the tools not going
byte for byte.
Not tried: a real Mistral key (none at hand; api.mistral.ai answers 401
before it validates the body) and a real Hermes run (it rewrites the live
~/.hermes launcher under a temp HERMES_HOME); the field and the refusal
are from Hermes' and Mistral's own source, the 422 shape from #494/#393.
2026-11-06 16:03:41 +08:00

109 lines
4.8 KiB
Go

package gateway
import (
"encoding/json"
"fmt"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// mistralRefuse answers as Mistral's chat completions do a body with a
// field it doesn't know: 422 extra_forbidden, every such field listed.
func mistralRefuse(body []byte) (int, string) {
known := []string{"model", "messages", "stream", "stream_options", "max_tokens", "temperature", "top_p", "tools", "tool_choice",
"parallel_tool_calls", "response_format", "stop", "random_seed", "presence_penalty", "frequency_penalty", "n", "reasoning_effort"}
var m map[string]json.RawMessage
json.Unmarshal(body, &m)
var detail []string
for k, v := range m {
if !slices.Contains(known, k) {
detail = append(detail, fmt.Sprintf(`{"type":"extra_forbidden","loc":["body",%q],"msg":"Extra inputs are not permitted","input":%s}`, k, v))
}
}
if len(detail) == 0 {
return 0, ""
}
return 422, `{"object":"error","message":{"detail":[` + strings.Join(detail, ",") + `]},"type":"invalid_request_error","param":null,"code":null,"raw_status_code":422}`
}
// Hermes Agent took the gateway for an Ollama server (/api/tags lists its
// models, so detect_local_server_type says "ollama") and sends the context
// /api/show tells as Ollama's options.num_ctx (agent_init_ollama.py,
// plugins/model-providers/custom), beside the reasoning_effort it sends any
// custom endpoint. Mistral turned every such request away with 422
// extra_forbidden on options (lijiho96940561 on X): it goes without
// options, in one call, and a tool's own "options" parameter and the
// rest of the body go byte for byte.
func TestHermesOllamaOptionsNeverReachMistral(t *testing.T) {
f := &fake{t: t, reply: sse(
`data: {"id":"c1","model":"m1","choices":[{"delta":{"content":"ok"}}]}`,
`data: {"id":"c1","choices":[{"delta":{},"finish_reason":"stop"}]}`,
`data: [DONE]`), refuse: mistralRefuse}
setup(t, provider.Chat, f)
srv := New()
tools := `[{"type":"function","function":{"name":"clarify","description":"Ask with \"options\"","parameters":{"type":"object","properties":{"question":{"type":"string"},"options":{"type":"array","items":{"type":"string"}}}}}}]`
body := `{"model":"m1","messages":[{"role":"user","content":"pick one of the \"options\""}],"tools":` + tools +
`,"stream":true,"reasoning_effort":"medium","options":{"num_ctx":131072}}`
code, reply := postTo(t, srv, "/v1/chat/completions", body)
if code != 200 || !strings.Contains(reply, `"ok"`) {
t.Fatalf("Hermes' request: %d %s", code, reply)
}
if f.calls != 1 {
t.Errorf("%d upstream calls, want 1", f.calls)
}
var sent map[string]json.RawMessage
if err := json.Unmarshal(f.got, &sent); err != nil {
t.Fatalf("Mistral was sent %s", f.got)
}
if _, ok := sent["options"]; ok {
t.Errorf("Ollama's options reached Mistral: %s", f.got)
}
if string(sent["tools"]) != tools {
t.Errorf("the tools didn't go as sent:\n%s\nwant\n%s", sent["tools"], tools)
}
if string(sent["reasoning_effort"]) != `"medium"` || !strings.Contains(string(sent["messages"]), `the \"options\"`) {
t.Errorf("the rest of the request didn't go as asked: %s", f.got)
}
}
// OpenCode's store:false (and Kimi Code's thinking switch) to Mistral, which
// turns away fields it doesn't know (#393): asked again without them, and
// not sent them again.
func TestMistralRefusesStore(t *testing.T) {
f := &fake{t: t, reply: sse(
`data: {"id":"c1","model":"m1","choices":[{"delta":{"content":"ok"}}]}`,
`data: {"id":"c1","choices":[{"delta":{},"finish_reason":"stop"}]}`,
`data: [DONE]`), refuse: mistralRefuse}
setup(t, provider.Chat, f)
srv := New()
for _, c := range []struct {
body string
calls int
}{
{`{"model":"m1","stream":true,"store":false,"messages":[{"role":"user","content":"hi"}],"max_tokens":20}`, 2},
{`{"model":"m1","stream":true,"store":false,"messages":[{"role":"user","content":"hi"}],"max_tokens":20}`, 1},
{`{"model":"m1","stream":true,"thinking":{"type":"enabled","keep":"all"},"messages":[{"role":"user","content":"hi"}]}`, 2},
{`{"model":"m1","stream":true,"store":false,"thinking":{"type":"enabled"},"messages":[{"role":"user","content":"hi"}]}`, 1},
} {
calls := f.calls
code, body := postTo(t, srv, "/v1/chat/completions", c.body)
if code != 200 || !strings.Contains(body, `"ok"`) {
t.Fatalf("%s: %d %s", c.body, code, body)
}
if n := f.calls - calls; n != c.calls {
t.Errorf("%s: %d upstream calls, want %d", c.body, n, c.calls)
}
}
// anything else refused goes back to the client as it came
f.refuse = func([]byte) (int, string) {
return 422, `{"object":"error","message":{"detail":[{"type":"missing","loc":["body","messages"],"msg":"Field required"}]}}`
}
calls := f.calls
if code, body := postTo(t, srv, "/v1/chat/completions", `{"model":"m1","store":false,"messages":[]}`); code != 422 || f.calls-calls != 1 {
t.Errorf("other refusal: %d after %d calls %s", code, f.calls-calls, body)
}
}