diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 649925747..3c2227656 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -1002,9 +1002,29 @@ own, as before. A plan's own search service (Kimi Code's, WorkBuddy's: plan's provider id and name, badged "Web search". Not covered: the Routing page, which lists only requests through `serve`. +A search a provider's model runs with its provider's own tool is a row +the same way when its reply shows it (cybercaius on Discord: DeepSeek +searched and Usage showed nothing). `searchTally` in +[`search_native.go`](../../internal/gateway/search_native.go) counts +Anthropic's `server_tool_use` blocks named `web_search` (DeepSeek's +Anthropic API answers them too) and `usage.server_tool_use.web_search_requests`, +and the Responses API's `web_search_call` items: what a stream named as +it went (a block's start, an item done, by id), what a whole reply or the +stream's end listed, and what the usage said are counted apart, and the +most of them is the count. The usage sniffer of a relayed reply and both +translated readers feed it (`Usage.searches`), and after the request's own +row `logNativeSearches` writes one row a search, at most 20: `Source` +`search`, `Kind` `web_search`, the request's agent, provider id, host and +model, status 200, no query and no time of its own. An event is parsed for +it only when it holds `server_tool_use` or `web_search_call`. A provider +whose reply doesn't show its searches (a Chat API's model that searches +inside, with nothing in the reply but text) has none to show, and +DeepSeek's Chat API has no search tool at all. + Covered by `TestSearchAPIAsksAreLogged`, `TestSearchAPIFailureKeepsNoURL`, `TestOwnSearchIsLogged`, `TestWorkBuddyPluginSearches`, -`TestSearchAPIRowsListedNotCounted` and `usage-ledger-search.test.cjs`. +`TestSearchAPIRowsListedNotCounted`, `TestOwnProviderSearchesAreLogged`, +`TestSearchRowsListTheirPurpose` and `usage-ledger-search.test.cjs`. ## Web search as an MCP server diff --git a/internal/gateway/continuation.go b/internal/gateway/continuation.go index 90d78160c..830b432a7 100644 --- a/internal/gateway/continuation.go +++ b/internal/gateway/continuation.go @@ -552,6 +552,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov } ended := false // the upstream said its reply ended var tail chatTail + var found searchTally // the searches it ran by itself // the client is kept alive while the upstream says // nothing at all, its first event yet to come too: the // upstream's 200 is in, and a holdWriter holds what is @@ -567,8 +568,9 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov defer wmu.Unlock() heard() tail.see([]byte(data)) + found.see(actual, []byte(data)) st := upstreamStop([]byte(data)) - u.add(Usage{Upstream: upstreamOf([]byte(data)), Stop: st, Tier: upstreamTier([]byte(data))}) + u.add(Usage{Upstream: upstreamOf([]byte(data)), Stop: st, Tier: upstreamTier([]byte(data)), searches: found.count()}) ended = ended || replyEnds(actual, data, st) if err := dec(data, attemptSee); err != nil { return err diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 82161fa36..2b43e6e3d 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -4130,6 +4130,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro failedWith(&rec, call.Status, call.Error, call.Usage.ErrType) withBodies(&rec, &call) appendUsage(r, rec) + if call.Status < 400 { + // what its model searched with its provider's own tool + logNativeSearches(r.Context(), call.Usage.searches, start, call.Agent, call.Provider, where, model) + } } } @@ -6943,10 +6947,12 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr var col collector ended := false // the upstream said its reply ended var tail chatTail + var found searchTally // the searches it ran by itself see, held := written(zenSee(zen, col.add)) err = readSSE(rd, func(_, data string) error { tail.see([]byte(data)) - u.add(Usage{Upstream: upstreamOf([]byte(data)), Tier: upstreamTier([]byte(data))}) + found.see(actual, []byte(data)) + u.add(Usage{Upstream: upstreamOf([]byte(data)), Tier: upstreamTier([]byte(data)), searches: found.count()}) ended = ended || replyEnds(actual, data, upstreamStop([]byte(data))) return dec(data, see) }) diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index fbf948c75..9dbb90653 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -419,6 +419,10 @@ type Usage struct { // cacheUnknown: the reply said its vendor counts no cache tokens // (a plugin's magpie_cache_unknown), so a CacheRead of 0 is not a miss cacheUnknown bool + // searches: the web searches the reply says its model ran with its + // provider's own tool (searchTally), for the request log's Web search + // rows; told nowhere else + searches int Reasoning int `json:"reasoning"` // Served: the model the vendor's reply says answered, when it named @@ -498,6 +502,7 @@ func (u *Usage) add(v Usage) { } u.cacheCreationReported = u.cacheCreationReported || v.cacheCreationReported u.cacheUnknown = u.cacheUnknown || v.cacheUnknown + u.searches = max(u.searches, v.searches) if v.Reasoning > 0 { u.Reasoning = v.Reasoning } diff --git a/internal/gateway/search_native.go b/internal/gateway/search_native.go new file mode 100644 index 000000000..79bcc17f0 --- /dev/null +++ b/internal/gateway/search_native.go @@ -0,0 +1,112 @@ +package gateway + +import ( + "bytes" + "cmp" + "context" + "net/http" + "time" + + "github.com/tidwall/gjson" + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/budget" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// searchTally counts the web searches a provider's reply says it ran by +// itself: Anthropic's server_tool_use blocks named web_search (DeepSeek's +// Anthropic API answers with them too, #669) and its usage's +// server_tool_use.web_search_requests, and the Responses API's +// web_search_call items. A model searching with its own provider's tool +// was in no row of the request log (cybercaius on Discord: DeepSeek +// searched and Usage showed nothing of it). A stream names each search +// once as it goes (a block's start, an item done) and may list them all +// again at its end, so what it streamed, what it listed whole and what +// its usage said are counted apart, and the most of them is the count. +type searchTally struct { + ids map[string]bool + anon int // streamed blocks or items with no id + listed int // in a whole reply's content or output + said int // what the reply's usage counted itself +} + +// see reads one event of a reply, or a whole reply, of proto. Only one +// that names a search is parsed: every event of every relayed reply goes +// by here. +func (t *searchTally) see(proto provider.Protocol, b []byte) { + switch proto { + case provider.Anthropic: + if !bytes.Contains(b, []byte("server_tool_use")) { + return + } + v := gjson.ParseBytes(b) + if c := v.Get("content_block"); isSearchBlock(c) { + t.streamed(c.Get("id").String()) + } + t.listed = max(t.listed, countOf(v.Get("content"), isSearchBlock)) + for _, u := range []gjson.Result{v.Get("usage"), v.Get("message.usage")} { + t.said = max(t.said, int(u.Get("server_tool_use.web_search_requests").Int())) + } + case provider.Responses: + if !bytes.Contains(b, []byte("web_search_call")) { + return + } + v := gjson.ParseBytes(b) + if it := v.Get("item"); v.Get("type").String() == "response.output_item.done" && isSearchItem(it) { + t.streamed(it.Get("id").String()) + } + t.listed = max(t.listed, countOf(v.Get("output"), isSearchItem), countOf(v.Get("response.output"), isSearchItem)) + } +} + +func isSearchBlock(c gjson.Result) bool { + return c.Get("type").String() == "server_tool_use" && c.Get("name").String() == "web_search" +} + +func isSearchItem(it gjson.Result) bool { return it.Get("type").String() == "web_search_call" } + +func countOf(list gjson.Result, is func(gjson.Result) bool) int { + n := 0 + for _, x := range list.Array() { + if is(x) { + n++ + } + } + return n +} + +func (t *searchTally) streamed(id string) { + if id == "" { + t.anon++ + return + } + if t.ids == nil { + t.ids = map[string]bool{} + } + t.ids[id] = true +} + +// count is how many searches the reply ran. +func (t *searchTally) count() int { + return max(len(t.ids)+t.anon, t.listed, t.said) +} + +// maxNativeSearchRows bounds the rows one reply writes: a reply that says +// it searched a thousand times is not a thousand rows. +const maxNativeSearchRows = 20 + +// logNativeSearches writes a row of the request log for each web search +// the provider's model ran with its own provider's tool, beside the +// request's own row: the Web search purpose, under the provider, its +// model, and how it ended (the reply came, so 200). The query is never +// kept, as no search row keeps one, and the row is counted nowhere: its +// tokens are the request's. +func logNativeSearches(ctx context.Context, n int, at time.Time, agent, providerID, host, model string) { + who := access.Caller(ctx) + for range min(n, maxNativeSearchRows) { + budget.Append(usage.Record{Time: at, Agent: cmp.Or(agent, "magpie"), Kind: "web_search", Source: usage.SourceSearch, + Provider: providerID, Host: host, Requested: model, Model: model, Status: http.StatusOK, + CallerKeyID: who.KeyID, CallerKeyName: who.KeyName}) + } +} diff --git a/internal/gateway/search_native_test.go b/internal/gateway/search_native_test.go new file mode 100644 index 000000000..82f184575 --- /dev/null +++ b/internal/gateway/search_native_test.go @@ -0,0 +1,141 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// what the Anthropic API streams of a search its model ran by itself, as +// Anthropic documents it and DeepSeek's Anthropic API answers (#669) +var deepSeekNativeStream = sse( + `event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"m","type":"message","role":"assistant","model":"deepseek-flash","content":[],"usage":{"input_tokens":4672,"output_tokens":1}}}`, + `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"server_tool_use","id":"call_00_x","name":"web_search","input":{}}}`, + `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"query\":\"kangaroo orbit 7781\"}"}}`, + `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`, + `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":1,"content_block":{"type":"web_search_tool_result","tool_use_id":"call_00_x","content":[{"type":"web_search_result","title":"t","url":"https://example.com/","encrypted_content":"SEALED"}]}}`, + `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":1}`, + `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":2,"content_block":{"type":"text","text":""}}`, + `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":2,"delta":{"type":"text_delta","text":"Found it."}}`, + `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":2}`, + `event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":825,"server_tool_use":{"web_search_requests":1}}}`, + `event: message_stop`+"\n"+`data: {"type":"message_stop"}`) + +// two searches on a Responses API: each item comes added and done, and +// the end lists them again +var responsesNativeStream = sse( + `data: {"type":"response.created","response":{"id":"r1","model":"deepseek-flash"}}`, + `data: {"type":"response.output_item.added","output_index":0,"item":{"id":"ws_1","type":"web_search_call","status":"in_progress"}}`, + `data: {"type":"response.output_item.done","output_index":0,"item":{"id":"ws_1","type":"web_search_call","status":"completed","action":{"type":"search","query":"kangaroo orbit 7781"}}}`, + `data: {"type":"response.output_item.added","output_index":1,"item":{"id":"ws_2","type":"web_search_call","status":"in_progress"}}`, + `data: {"type":"response.output_item.done","output_index":1,"item":{"id":"ws_2","type":"web_search_call","status":"completed","action":{"type":"search","query":"kangaroo orbit 7782"}}}`, + `data: {"type":"response.output_text.delta","delta":"Found it."}`, + `data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"id":"ws_1","type":"web_search_call","status":"completed"},{"id":"ws_2","type":"web_search_call","status":"completed"},{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Found it."}]}],"usage":{"input_tokens":4000,"output_tokens":20}}}`) + +const responsesNative = `{"id":"r1","object":"response","status":"completed","model":"deepseek-flash","output":[ + {"id":"ws_1","type":"web_search_call","status":"completed","action":{"type":"search","query":"kangaroo orbit 7781"}}, + {"id":"ws_2","type":"web_search_call","status":"completed","action":{"type":"search","query":"kangaroo orbit 7782"}}, + {"type":"message","role":"assistant","content":[{"type":"output_text","text":"Found it."}]}], + "usage":{"input_tokens":4000,"output_tokens":20}}` + +// cybercaius on Discord: with magpie's search off, DeepSeek searched by +// itself and Usage showed nothing of it. A search a provider's model runs +// with its provider's own tool, which its reply shows (Anthropic's +// server_tool_use, the Responses API's web_search_call), is a Web search +// row of the request log under that provider and model, streamed or +// whole, once per search however often the reply names it. The query is +// in no such row, and a reply that searched nothing writes none. +func TestOwnProviderSearchesAreLogged(t *testing.T) { + fresh(t) + searchless := false + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/models") { + io.WriteString(w, `{"data":[{"id":"deepseek-flash"}]}`) + return + } + var q struct { + Stream bool `json:"stream"` + } + b, _ := io.ReadAll(r.Body) + json.Unmarshal(b, &q) + switch { + case searchless && strings.HasSuffix(r.URL.Path, "/messages"): + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"m","type":"message","role":"assistant","model":"deepseek-flash","content":[{"type":"text","text":"server_tool_use is a block type."}],"stop_reason":"end_turn","usage":{"input_tokens":10,"output_tokens":5}}`) + case r.URL.Path == "/anthropic/v1/messages" && q.Stream: + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, deepSeekNativeStream) + case r.URL.Path == "/anthropic/v1/messages": + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, deepSeekNative) + case r.URL.Path == "/v1/responses" && q.Stream: + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, responsesNativeStream) + case r.URL.Path == "/v1/responses": + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, responsesNative) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + searchesOn(t, provider.Anthropic, srv.URL) + searchesOn(t, provider.Responses, srv.URL) + save(t, provider.Provider{ID: "ds", Name: "DeepSeek", Key: "k", Anthropic: srv.URL + "/anthropic", Responses: srv.URL + "/v1", Models: []string{"deepseek-flash"}}) + + h := New().Handler() + send := func(path, body string) { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%s: %d %s", path, rec.Code, rec.Body.String()) + } + } + rowsNow := func() []usage.Record { + t.Helper() + rows, _ := searchRows(t) + return rows + } + const msgs = `"messages":[{"role":"user","content":"search kangaroo orbit 7781"}],"tools":[{"type":"web_search_20250305","name":"web_search"}]` + const input = `"input":"search kangaroo orbit 7781","tools":[{"type":"web_search"}]` + for _, c := range []struct { + name, path, body string + searches int + }{ + {"anthropic whole", "/v1/messages", `{"model":"ds/deepseek-flash","max_tokens":100,` + msgs + `}`, 1}, + {"anthropic stream", "/v1/messages", `{"model":"ds/deepseek-flash","max_tokens":100,"stream":true,` + msgs + `}`, 1}, + {"responses stream", "/v1/responses", `{"model":"ds/deepseek-flash","stream":true,` + input + `}`, 2}, + {"responses whole", "/v1/responses", `{"model":"ds/deepseek-flash",` + input + `}`, 2}, + } { + before := len(rowsNow()) + send(c.path, c.body) + rows := rowsNow() + if got := len(rows) - before; got != c.searches { + t.Fatalf("%s: %d search rows, want %d: %+v", c.name, got, c.searches, rows[before:]) + } + for _, r := range rows[before:] { + if r.Kind != "web_search" || r.Source != usage.SourceSearch || r.Provider != "ds" || r.Model != "deepseek-flash" || + r.Host != provider.HostOf(srv.URL) || r.Status != 200 || r.Failed() { + t.Fatalf("%s: row %+v", c.name, r) + } + if b, _ := json.Marshal(r); strings.Contains(string(b), "kangaroo") { + t.Fatalf("%s: the query is in the row: %s", c.name, b) + } + } + } + searchless = true + before := len(rowsNow()) + send("/v1/messages", `{"model":"ds/deepseek-flash","max_tokens":100,`+msgs+`}`) + if rows := rowsNow(); len(rows) != before { + t.Fatalf("a reply that searched nothing wrote %+v", rows[before:]) + } +} diff --git a/internal/gateway/sniff.go b/internal/gateway/sniff.go index aada6ca1a..278c9b0b6 100644 --- a/internal/gateway/sniff.go +++ b/internal/gateway/sniff.go @@ -28,6 +28,8 @@ type usageSniffer struct { failed string // tail: what a Chat stream's chunks say of its end (chatTail) tail chatTail + // found: the searches the reply ran by itself (searchTally) + found searchTally } func newSniffer(proto provider.Protocol, contentType string) *usageSniffer { @@ -126,6 +128,7 @@ func (s *usageSniffer) parse(b []byte) { s.u.ErrType = provider.ErrorType(body) } } + s.found.see(s.proto, b) if up := upstreamOf(b); up != "" { s.u.Upstream = up } @@ -291,5 +294,6 @@ func (s *usageSniffer) usage() Usage { } u := s.u u.Served = s.served + u.searches = s.found.count() return u } diff --git a/internal/usage/search_calls_test.go b/internal/usage/search_calls_test.go index e2014555f..022a0ad1c 100644 --- a/internal/usage/search_calls_test.go +++ b/internal/usage/search_calls_test.go @@ -74,3 +74,23 @@ func TestSearchAPIRowsListedNotCounted(t *testing.T) { t.Fatalf("hosts %v", hosts) } } + +// cybercaius on Discord: the Requests page's purposes were All, Connection +// check and Unmarked while the log held searches. A search row, a search +// API's or one a provider's model ran with its own tool, gives the purpose +// list Web search, and that purpose picks it. +func TestSearchRowsListTheirPurpose(t *testing.T) { + reportedHome(t) + now := time.Now().Add(-time.Hour) + Append(Record{Time: now, Agent: "claude", Provider: "deepseek", Host: "api.deepseek.com", Model: "deepseek-flash", Requested: "deepseek-flash", Status: 200, Millis: 3000}) + Append(Record{Time: now, Agent: "claude", Provider: "deepseek", Host: "api.deepseek.com", Model: "deepseek-flash", Requested: "deepseek-flash", + Status: 200, Kind: "web_search", Source: SourceSearch}) + page := QueryPage(All, Filter{}, 0, 50) + if !slices.Contains(page.Purposes, PurposeOf("web_search")) { + t.Fatalf("purposes %v", page.Purposes) + } + p := QueryPage(All, Filter{Purpose: PurposeOf("web_search")}, 0, 50) + if p.Total != 1 || p.Rows[0].Source != SourceSearch || p.Sum.Calls != 0 { + t.Fatalf("purpose filter: total %d rows %+v sum %+v", p.Total, p.Rows, p.Sum) + } +}