Files
magpie/internal/gateway/search_kimi.go
T
yetone dc2f0da820 gateway, gui: Image recognition and Web search pick how hard their model thinks (MOMO on Discord)
MOMO asked on Discord, "外置模型能不能提供思考深度选项": the model that
describes images (Image recognition, analyze_image) and the searcher's
model (e.g. Antigravity's Gemini 3 Flash) had no reasoning level of
their own to pick.

Settings › Models now has a chip beside each of those two pickers. It
opens the app's menu (openProtoMenu, no native select) and offers
Default plus only the levels that model has (Efforts, weakest first;
none shown when the model's levels aren't known, or the row is Off).
The pick is saved as settings.visionEffort / searcherEffort, one of
catalog.EffortRank or empty, and is checked on save. prefsKeep carries
both, so saving another setting keeps them.

Default keeps what magpie did before. Image recognition is still asked
at the least level the model has (classifyEffort), and the searcher
still gets no level. A picked level is fitted to the model's levels at
call time (fitEffort), and only these two calls carry it
(side_effort.go):
- askVisionWith sends reasoning_effort. The image cache key includes
  the level, so changing the level reads the image again.
- searchBody puts thinking (disabled for none, else enabled with
  budgetOf's budget) and output_config.effort (except for pre-adaptive
  Claude) on the searcher's Anthropic body. The gateway's translation
  turns that into each vendor's own form: adaptive or between_tools
  for new Claude, reasoning.effort for Responses, and thinkingLevel
  for Gemini 3 on Code Assist / Antigravity.
- A picked level raises max_tokens by its budget (replyRoom), so the
  thinking doesn't eat the reply.
- ownSearch and Kimi's search service are sent no level. A fallback
  searcher is sent the level fitted to its own model.

docs/subsystems/gateway-routing.md: new "How hard a side model thinks".

Tests:
- TestVisionEffortPicked and TestVisionEffortOnAnthropic check the
  vision body.
- TestSearcherEffortPicked checks the searcher body on new Claude, old
  Claude and Responses.
- TestSearcherEffortOnGemini checks the searcher body through
  buildCodeAssist for antigravity.
- TestSideEffortChecked covers settings validation.
- side-effort.test.cjs covers the chips: levels shown, a pick saved,
  Default clears it, toggle and Escape, no scroll, fit in the row and
  the menu inside the window. It runs in Chromium and WebKit at 1100
  and 420, in en/zh/zh-TW/ja/de.

Run:
- go test -tags nogui ./internal/gateway/ (full, -timeout 30m) on
  origin/main 3a9d73c5c + this change: everything passes except
  TestRateLimitIsWaitedOut "an hour away" (1.9s against its 1s bound,
  load ~190). That test passes on freshly fetched origin/main 41972b25f
  alone (-count=10) and in 8 parallel -cpu 1 copies. Filed as #1971.
- go test -tags nogui ./internal/settings/ ./internal/gui/: ok.
- Broken by hand, each goes red:
  - searchBody dropping the effort fails TestSearcherEffortPicked and
    TestSearcherEffortOnGemini;
  - askVisionWith back to classifyEffort fails TestVisionEffortPicked
    and TestVisionEffortOnAnthropic;
  - the settings check removed fails TestSideEffortChecked;
  - prefsKeep without the two fields fails side-effort.test.cjs.
- GUI:
  - side-effort.test.cjs: 10/10.
  - searcher-pick, images-*, vision-mcp, settings-search/sections/
    general, routing-vision-why and i18n-keys: 123/123.
  - 67 more Settings files: 778 pass. text-size "zh, dark ... 150%"
    failed in WebKit under parallel load; it passes 11/11 alone and is
    #1866.
- gofmt -l is clean. go vet passes for darwin, plus GOOS=linux and
  GOOS=windows with -tags nogui, on gateway, settings and gui. go build
  passes.
- Not tried against a real Antigravity or other real account: the
  request shapes are checked against fakes and the gateway's own
  translators.
2026-10-13 16:40:24 +08:00

166 lines
5.9 KiB
Go

package gateway
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// A Kimi Code plan searches the web with its own key, as kimi-cli's
// SearchWeb tool does (kimi_cli/tools/web/search.py, 1.52.0): a POST to the
// plan's /coding/v1/search of
//
// {"text_query":"…","limit":5,"enable_page_crawling":false,"timeout_seconds":30}
//
// with the key as a Bearer, answered with
//
// {"search_results":[{"site_name","title","url","snippet","content","date","icon","mime"}]}
//
// No model is asked. A model served by a Kimi Code plan has its searches
// done there first, so a Kimi user's searches stay on Kimi, as a provider
// that searches by itself does; failing, the searcher magpie picks or
// Settings names comes next. For other providers' models a plan searches
// only when Settings names it: picking it by itself would spend the plan's
// allowance on them, and change the searcher users have now.
// kimiSearchAgent is the User-Agent kimi-cli sends (constant.py,
// get_user_agent: KimiCLI/<version>).
const kimiSearchAgent = "KimiCLI/1.52.0"
// searchOnKey holds the provider serving the conversation a search is
// made for.
type searchOnKey struct{}
// searchCallKey holds the id of the model's call a search answers, which
// kimi-cli sends as X-Msh-Tool-Call-Id.
type searchCallKey struct{}
// canSearchFor is whether a model of p that can't search is given magpie's
// search: one of p's own (a Kimi Code plan, a Google sign-in), or
// canSearch.
func canSearchFor(p provider.Provider) bool {
return searchesOwn(p) || canSearch()
}
// searchesOwn is whether p searches for its own models: by its Kimi Code
// plan's or WorkBuddy plan's search service (#1798), or a Google sign-in's
// own Gemini. Never with provider search Off in Settings (#1483), which
// leaves the search APIs alone.
func searchesOwn(p provider.Provider) bool {
if settings.Load().Searcher == "off" {
return false
}
return provider.KimiCodeSearch(p) != "" || wbSearches(p) || googleAccount(p) && searcherModel(p) != ""
}
// searchingOn is ctx for the searches made for a model of p.
func searchingOn(ctx context.Context, p provider.Provider) context.Context {
return context.WithValue(ctx, searchOnKey{}, p)
}
// ownSearcher is the provider serving the conversation when it searches
// for itself: by a search service of its own plan (Kimi Code), or, a
// Google sign-in, by its own Gemini's googleSearch — which a request with
// function tools can't have (codeAssistSearches), so the search goes out
// on its own, and not to another subscription's allowance (#757).
func ownSearcher(ctx context.Context) (provider.Provider, bool) {
p, ok := ctx.Value(searchOnKey{}).(provider.Provider)
return p, ok && searchesOwn(p)
}
// ownSearch searches with the conversation's own provider (ownSearcher).
func (s *Server) ownSearch(ctx context.Context, p provider.Provider, query string) (string, []Hit, error) {
if provider.KimiCodeSearch(p) != "" {
return s.kimiSearch(ctx, p, query)
}
if wbSearches(p) {
return s.wbSearch(ctx, p, query)
}
ctx, cancel := context.WithTimeout(context.WithValue(ctx, searchingKey{}, true), searchTimeout)
defer cancel()
return s.searchWith(ctx, p, searcherModel(p), query, "")
}
// searchBy searches with one searcher: a Kimi Code plan by its search
// service, any other by its model.
func (s *Server) searchBy(ctx context.Context, p provider.Provider, model, query, effort string) (string, []Hit, error) {
if provider.KimiCodeSearch(p) != "" {
return s.kimiSearch(ctx, p, query)
}
return s.searchWith(ctx, p, model, query, effort)
}
// kimiSearch asks a Kimi Code plan's search service.
func (s *Server) kimiSearch(ctx context.Context, p provider.Provider, query string) (string, []Hit, error) {
// the service gives itself 30 s, as kimi-cli asks
// through the plan's own proxy, if it has one (#237, #1522)
ctx, cancel := context.WithTimeout(s.metered(p.Via(ctx), p, ""), searchTimeout/2)
defer cancel()
body, _ := json.Marshal(map[string]any{"text_query": query, "limit": searchHits, "enable_page_crawling": false, "timeout_seconds": 30})
r, err := http.NewRequestWithContext(ctx, http.MethodPost, provider.KimiCodeSearch(p), bytes.NewReader(body))
if err != nil {
return "", nil, err
}
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Accept", "application/json")
r.Header.Set("User-Agent", kimiSearchAgent)
r.Header.Set("Authorization", "Bearer "+p.Key)
if id, _ := ctx.Value(searchCallKey{}).(string); id != "" {
r.Header.Set("X-Msh-Tool-Call-Id", id)
}
res, err := s.client.Do(r)
if err != nil {
if ctx.Err() != nil {
return "", nil, fmt.Errorf("%s: no answer in time", p.Name)
}
return "", nil, fmt.Errorf("%s: %w", p.Name, err)
}
defer res.Body.Close()
b, _ := io.ReadAll(io.LimitReader(res.Body, 4<<20))
if res.StatusCode >= 300 {
return "", nil, errors.New(p.Name + ": " + provider.APIError(b, res.Status))
}
var out struct {
Results *[]struct {
Title string `json:"title"`
URL string `json:"url"`
Snippet string `json:"snippet"`
Content string `json:"content"`
Date string `json:"date"`
} `json:"search_results"`
}
if err := json.Unmarshal(b, &out); err != nil || out.Results == nil {
return "", nil, fmt.Errorf("%s: unexpected reply: %s", p.Name, provider.APIError(b, res.Status))
}
var pages []foundPage
for _, x := range *out.Results {
if x.URL == "" {
continue
}
title := searchPlain(x.Title)
if title == "" {
title = x.URL
}
text := x.Content
if text == "" {
text = x.Snippet
}
pages = append(pages, foundPage{Title: title, URL: x.URL, Text: clipText(searchPlain(text), pageText), Age: x.Date})
if len(pages) == searchHits {
break
}
}
if len(pages) == 0 {
return "", nil, fmt.Errorf("%s %w", p.Name, errFoundNothing)
}
said, hits := pagesSaid(pages)
return said, hits, nil
}