Files
magpie/internal/gateway/search_ark_test.go
T
yetone a0cb8b6466 gateway: Volcengine Ark's Responses API runs Codex's web_search itself
axelburks on Discord: Ark (火山方舟) runs the web_search tool on its
Responses API, but magpie took Codex's web_search out of the body and
gave the model magpie's web_search function instead, so the model said
the tool wasn't there. ark.cn-beijing.volces.com wasn't in searchHosts,
so searchedForIt translated every Codex turn for magpie's search.

Ark's 联网搜索工具 page (docs.volcengine.com/docs/82379/1756990) asks
POST ark.cn-beijing.volces.com/api/v3/responses with
{"type":"web_search"} (sources, limit, max_keyword, user_location), and
its Web Search page (82379/1585128) marks the tool 支持 on Responses and
不支持 on Chat. The host serves the Coding Plan (/api/coding/v3), Agent
Plan (/api/plan/v3) and pay-as-you-go (/api/v3) alike, and the page's
billing names both plans, so the host counts on Responses for all three.

- searchHosts[Responses] gains arkHost. Chat and Anthropic are unchanged.
- forArkSearch (search_ark.go), on the Responses relay after forVendor:
  Ark's web_search keeps only the members Ark's docs name. Codex's
  external_web_access, search_context_size and filters, and a
  location's timezone, are left out; web_search_preview becomes
  web_search. Ark's own shape ({"sources":["doubao"]}) goes as it came.
  Any other host, or an account, is untouched.
- BytePlus ModelArk (ark.ap-southeast.bytepluses.com) is left out: its
  docs name no web_search tool.
- Ark's Messages API (web_search_20250305) and Chat web_search_options,
  which the same page documents, are #4448.

Tests (search_ark_test.go): TestArkSearchesOnResponses (every Ark
region searches on Responses, not on Chat/Anthropic; BytePlus doesn't),
TestArkGetsCodexWebSearch (a Codex body through the real handler to a
fake Ark, Zhipu and relay over a redirected dialer: Ark gets the hosted
tool in its shape, Zhipu gets Codex's as sent, a relay still gets
magpie's function), TestForArkSearchScope.

Run (mote, mote-run):
- gofmt -l on the changed files: nothing.
- go vet -tags nogui ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build: ok.
- go test -run 'TestArk|TestForArkSearch|TestZhipuSearches|
  TestDeepSeekSearches|Search' ./internal/gateway: ok.
- go test -tags nogui -count=1 -timeout 45m ./... at fa427216a + this
  change: every package ok (exit 0; internal/gateway 729s).
- Rebased on 2ec345364 (it changed internal/gateway): vet x3 and builds
  x3 again ok, and the full suite again: every package ok except
  internal/plugin's TestGatewayHookMixedPiPackage, "starting plugins:
  context deadline exceeded" at 267s, which is #2865 (output added
  there); alone at this tree it passes (139.95s). internal/gateway ok
  (807s).
- Rebased again on acdc85ac8 (internal/provider and internal/switch
  only, nothing this change reads): gofmt, vet x3, builds x3 and
  internal/gateway + internal/provider tests again: VET-BUILD-OK,
  internal/gateway ok (652s), internal/provider ok (191s).
- Rebased on 2f65a33aa (a new tools-MCP route in internal/gateway):
  vet x3 of internal/gateway, go build, and -run
  'TestArk|TestForArkSearch|Search|ToolsMCP|Readonly' ok.

Broken by hand:
- arkHost out of searchHosts: TestArkSearchesOnResponses red for all
  three regions, and TestArkGetsCodexWebSearch red with Ark sent
  magpie's web_search function, the reporter's case.
- forArkSearch call removed: TestArkGetsCodexWebSearch red, Ark sent
  external_web_access, search_context_size and the timezone.

Not tried: a real Ark key (none here), so whether Ark turns away
Codex's external_web_access is from the docs, not a reply. Ark says
either search component must be activated in its console first, or the
call errors; a user who hasn't would now get that error on a Codex turn
offering web_search instead of magpie's search. Which models take the
tool is not listed by Ark (its page links a capability table); the
docs' example is doubao-seed-2-1-pro. With no Claude/Codex account, Ark
can now be magpie's automatic searcher for other models too.
2026-10-30 22:41:00 +08:00

170 lines
7.2 KiB
Go

package gateway
import (
"context"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// Volcengine Ark's Responses API runs web_search itself, on each of its
// preset's regions (the plans and pay-as-you-go share its host): Codex's
// tool goes to it rather than to magpie's search (axelburks on Discord).
// Its Chat and Anthropic APIs are left as they were.
func TestArkSearchesOnResponses(t *testing.T) {
pre, err := provider.FromPreset("volcengine")
if err != nil {
t.Fatal(err)
}
i := slices.IndexFunc(provider.Presets(), func(d provider.PresetDef) bool { return d.ID == "volcengine" })
if i < 0 || len(provider.Presets()[i].Regions) == 0 {
t.Fatal("Volcengine Ark's preset has no regions")
}
for _, r := range provider.Presets()[i].Regions {
if r.Responses == "" {
continue
}
p := pre
p.Chat, p.Responses, p.Anthropic = r.Chat, r.Responses, r.Anthropic
if !searchesItself(p, provider.Responses) {
t.Errorf("Ark's %s doesn't search by itself on its Responses API (%s)", r.ID, r.Responses)
}
for _, proto := range []provider.Protocol{provider.Chat, provider.Anthropic} {
if searchesItself(p, proto) {
t.Errorf("Ark's %s searches by itself on %s", r.ID, proto)
}
}
}
// BytePlus ModelArk's docs name no web_search tool
if searchesItself(provider.Provider{ID: "byteplus", Responses: "https://ark.ap-southeast.bytepluses.com/api/v3"}, provider.Responses) {
t.Error("BytePlus ModelArk searches by itself")
}
}
const arkSearchReply = "event: response.created\ndata: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_1\",\"status\":\"in_progress\",\"output\":[]}}\n\n" +
"event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"item_id\":\"msg_1\",\"output_index\":0,\"content_index\":0,\"delta\":\"ok\"}\n\n" +
"event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_1\",\"status\":\"completed\",\"output\":[{\"type\":\"message\",\"id\":\"msg_1\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"ok\"}]}],\"usage\":{\"input_tokens\":3,\"output_tokens\":1,\"total_tokens\":4}}}\n\n"
// Codex's web_search reaches Ark's Responses API as a hosted web_search
// tool, in the shape Ark's docs give: external_web_access, which Ark
// doesn't name, is left out, and a location keeps Ark's members. Before,
// Ark was taken for a provider that doesn't search, and the tool was
// taken out for magpie's. Zhipu's Responses API, which searches too, is
// sent Codex's tool as it was; a relay that doesn't search is still given
// magpie's search in its place.
func TestArkGetsCodexWebSearch(t *testing.T) {
f := &fake{t: t, reply: arkSearchReply}
setup(t, provider.Responses, f)
up := httptest.NewServer(f)
t.Cleanup(up.Close)
for _, p := range []provider.Provider{
{ID: "volcengine", Preset: "volcengine", Name: "Volcengine Ark", Key: "k", Models: []string{"doubao-seed-2-1-pro"}, Responses: "http://ark.cn-beijing.volces.com/api/coding/v3"},
{ID: "zhipu", Name: "Zhipu", Key: "k", Models: []string{"glm-5"}, Responses: "http://open.bigmodel.cn/api/v1"},
{ID: "relay", Name: "Relay", Key: "k", Models: []string{"doubao-seed-2-1-pro"}, Responses: "http://relay.example.com/v1"},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
s := New()
addr := strings.TrimPrefix(up.URL, "http://")
s.client = &http.Client{Transport: &http.Transport{DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, network, addr)
}}}
const body = `{"model":"%s","stream":true,"instructions":"be brief","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"今天有什么 AI 新闻?"}]}],` +
`"tools":[{"type":"function","name":"shell","description":"run","parameters":{"type":"object","properties":{}}},` +
`{"type":"web_search","external_web_access":true,"search_context_size":"medium","user_location":{"type":"approximate","country":"CN","city":"Beijing","timezone":"Asia/Shanghai"}}]}`
tools := func(t *testing.T) []map[string]any {
var got struct {
Tools []map[string]any `json:"tools"`
}
if err := json.Unmarshal(f.got, &got); err != nil {
t.Fatalf("sent %s: %v", f.got, err)
}
return got.Tools
}
hosted := func(ts []map[string]any) map[string]any {
for _, tl := range ts {
if tl["type"] == "web_search" {
return tl
}
}
return nil
}
post := func(t *testing.T, model string) {
f.got = nil
code, reply := postTo(t, s, "/v1/responses", strings.Replace(body, "%s", model, 1))
if code != 200 {
t.Fatalf("%s: %d %s", model, code, reply)
}
}
t.Run("ark", func(t *testing.T) {
post(t, "volcengine/doubao-seed-2-1-pro")
ws := hosted(tools(t))
if ws == nil {
t.Fatalf("Ark wasn't sent web_search: %s", f.got)
}
for _, k := range []string{"external_web_access", "search_context_size"} {
if _, ok := ws[k]; ok {
t.Errorf("Ark was sent web_search's %s, which its docs don't name: %v", k, ws)
}
}
loc, _ := ws["user_location"].(map[string]any)
if loc["city"] != "Beijing" || loc["country"] != "CN" {
t.Errorf("Ark's user_location lost the city or country: %v", ws)
}
if _, ok := loc["timezone"]; ok {
t.Errorf("Ark was sent a location's timezone: %v", ws)
}
if !strings.Contains(string(f.got), `"name":"shell"`) {
t.Errorf("Ark lost the function tool: %s", f.got)
}
})
t.Run("zhipu as sent", func(t *testing.T) {
post(t, "zhipu/glm-5")
ws := hosted(tools(t))
if ws == nil || ws["external_web_access"] != true || ws["search_context_size"] != "medium" {
t.Errorf("Zhipu wasn't sent Codex's web_search as it was: %s", f.got)
}
})
t.Run("relay given magpie's", func(t *testing.T) {
post(t, "relay/doubao-seed-2-1-pro")
if ws := hosted(tools(t)); ws != nil {
t.Errorf("a relay that doesn't search was sent the hosted web_search: %s", f.got)
}
})
}
// forArkSearch leaves a body bound elsewhere, or with no search, as it came.
func TestForArkSearchScope(t *testing.T) {
in := []byte(`{"model":"m","tools":[{"type":"web_search","external_web_access":true}]}`)
for _, p := range []provider.Provider{
{ID: "openai", Responses: "https://api.openai.com/v1"},
{ID: "byteplus", Responses: "https://ark.ap-southeast.bytepluses.com/api/v3"},
{ID: "ark-acct", Responses: "https://ark.cn-beijing.volces.com/api/v3", Account: &provider.Account{Agent: "plugin"}},
} {
if out := forArkSearch(p, in); string(out) != string(in) {
t.Errorf("%s: %s, want it as it came", p.ID, out)
}
}
ark := provider.Provider{ID: "volcengine", Responses: "https://ark.cn-beijing.volces.com/api/v3"}
plain := []byte(`{"model":"m","tools":[{"type":"function","name":"f"}]}`)
if out := forArkSearch(ark, plain); string(out) != string(plain) {
t.Errorf("a body with no search changed: %s", out)
}
if out := forArkSearch(ark, []byte(`{"tools":[{"type":"web_search_preview"}]}`)); !strings.Contains(string(out), `{"type":"web_search"}`) {
t.Errorf("web_search_preview isn't web_search for Ark: %s", out)
}
doubao := []byte(`{"tools":[{"type":"web_search","sources":["doubao"]}]}`)
if out := forArkSearch(ark, doubao); string(out) != string(doubao) {
t.Errorf("Ark's own shape changed: %s", out)
}
}