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.
This commit is contained in:
yetone
2026-10-30 22:41:00 +08:00
parent 2f65a33aaf
commit a0cb8b6466
4 changed files with 282 additions and 4 deletions
+2
View File
@@ -4800,6 +4800,8 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
body, searchFn = searchAsFunction(body)
}
body = forVendor(p, body)
// Ark takes web_search in the shape its docs give (search_ark.go)
body = forArkSearch(p, body)
if replay {
// its reasoning goes back as text, never left out: DeepSeek
// refuses a request without it (#1104)
+5 -4
View File
@@ -245,13 +245,14 @@ func partSearcher(p provider.Provider) bool {
}
// searchHosts are the APIs that search by themselves: OpenAI's, xAI's,
// DeepSeek's, Zhipu's and Z.ai's web_search tool (Zhipu's on its Responses
// API only, DeepSeek's on its Responses and Anthropic APIs: their Chat APIs
// have no such tool), Anthropic's web_search_20250305 (DeepSeek's Anthropic
// DeepSeek's, Zhipu's, Z.ai's and Volcengine Ark's web_search tool
// (Zhipu's and Ark's on their Responses APIs only, DeepSeek's on its
// Responses and Anthropic APIs: their Chat APIs have no such tool; Ark's
// in the shape forArkSearch gives it), Anthropic's web_search_20250305 (DeepSeek's Anthropic
// API runs it too, answering web_search_tool_result blocks, #669),
// OpenRouter's web plugin, Gemini's googleSearch.
var searchHosts = map[provider.Protocol][]string{
provider.Responses: {"api.openai.com", "api.x.ai", "api.deepseek.com", "open.bigmodel.cn", "api.z.ai"},
provider.Responses: {"api.openai.com", "api.x.ai", "api.deepseek.com", "open.bigmodel.cn", "api.z.ai", arkHost},
provider.Anthropic: {"api.anthropic.com", "api.deepseek.com"},
provider.Chat: {"openrouter.ai"},
provider.Gemini: {"generativelanguage.googleapis.com"},
+106
View File
@@ -0,0 +1,106 @@
package gateway
import (
"bytes"
"encoding/json"
"github.com/yetone/magpie/internal/provider"
)
// arkHost is Volcengine Ark's (火山方舟) API host. Its Responses API runs
// the web_search tool itself, on pay-as-you-go (/api/v3) and the plans
// (/api/coding/v3, /api/plan/v3) alike: Ark's 联网搜索工具 page
// (docs.volcengine.com/docs/82379/1756990) asks it on
// ark.cn-beijing.volces.com/api/v3/responses with {"type":"web_search"},
// and its Web Search page marks the tool 支持 on the Responses API and 不支持
// on the Chat API (axelburks on Discord: Codex's web_search was taken from
// its body, and the model said it had no such tool). BytePlus ModelArk's
// docs name no such tool, so its host isn't counted.
const arkHost = "ark.cn-beijing.volces.com"
// arkSearchFields are the members of a web_search tool Ark's Responses API
// documents: type, sources (["doubao"] for 豆包搜索 Custom, else
// search_engine with toutiao, douyin or moji), and the content plugin's
// limit, max_keyword and user_location.
var arkSearchFields = map[string]bool{"type": true, "sources": true, "limit": true, "max_keyword": true, "user_location": true}
// arkLocationFields are the members of Ark's user_location: the city,
// region and country, beside OpenAI's type. OpenAI's timezone isn't one.
var arkLocationFields = map[string]bool{"type": true, "country": true, "region": true, "city": true}
// forArkSearch gives Ark's Responses API the web_search tool in the shape
// its docs give: OpenAI's members Ark doesn't name (Codex's
// external_web_access, search_context_size, filters, a location's
// timezone) are left out, and web_search_preview is web_search. Any other
// provider's body, or one with no such tool, goes as it came.
func forArkSearch(p provider.Provider, body []byte) []byte {
if p.Account != nil || provider.HostOf(p.Base(provider.Responses)) != arkHost || !bytes.Contains(body, []byte("web_search")) {
return body
}
q, err := rawObject(body)
if err != nil {
return body
}
tools, err := rawArray(q["tools"])
if err != nil {
return body
}
changed := false
for i, raw := range tools {
t, err := rawObject(raw)
if err != nil {
continue
}
var typ string
if json.Unmarshal(t["type"], &typ) != nil || typ != "web_search" && typ != "web_search_preview" {
continue
}
out := map[string]json.RawMessage{"type": json.RawMessage(`"web_search"`)}
drop := typ != "web_search" // a member left out, or the type renamed
for k, v := range t {
if k == "type" {
continue
}
if !arkSearchFields[k] {
drop = true
continue
}
if k == "user_location" {
loc, err := rawObject(v)
if err != nil {
drop = true
continue
}
for lk := range loc {
if !arkLocationFields[lk] {
delete(loc, lk)
drop = true
}
}
if v, err = marshalPlain(loc); err != nil {
continue
}
}
out[k] = v
}
if !drop {
continue
}
b, err := marshalPlain(out)
if err != nil {
continue
}
tools[i], changed = b, true
}
if !changed {
return body
}
if q["tools"], err = marshalPlain(tools); err != nil {
return body
}
b, err := marshalPlain(q)
if err != nil {
return body
}
return b
}
+169
View File
@@ -0,0 +1,169 @@
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)
}
}