From bdd2da919ca629301f52a5209c6cf2294e26cc33 Mon Sep 17 00:00:00 2001 From: ji ruo <79234113+RuoJi6@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:24:43 +0800 Subject: [PATCH] =?UTF-8?q?feat(llm):=20=E6=94=AF=E6=8C=81=E5=8E=9F?= =?UTF-8?q?=E7=94=9F=20Google=20Gemini=20API=20=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 agent/gemini.go 原生 Gemini generateContent / streamGenerateContent?alt=sse llm.Provider,支持流式/非流式、工具调用与 JSON Schema 清洗、thoughtSignature 回传、thinkingConfig(Gemini 2.5 thinkingBudget / Gemini 3+ thinkingLevel)、建连/空响应重试及限流/抓包透传。 - agent.ConfigFrom / FromEnv / Provider() 支持 gemini 格式与 BaseURL 归一化(自动补全 /v1beta 并容忍粘贴完整端点 URL),环境变量支持 GEMINI_API_KEY / GOOGLE_API_KEY。 - db/schema.sql 放开 llm_profiles.format CHECK 约束加入 gemini 并幂等迁移旧库。 - server/server_mgmt.go 模型列表接口支持 Gemini /models(剥离 models/ 前缀并过滤支持 generateContent 的模型)。 - web LLM 配置页与类型/国际化新增 Google Gemini 协议选项及占位提示。 - 补充 agent/gemini_test.go、server/gemini_models_test.go 与限流重试测试。 Fixes #170 --- .env.example | 3 +- agent/gemini.go | 1190 ++++++++++++++++++++++++ agent/gemini_test.go | 405 ++++++++ agent/provider.go | 34 +- agent/request_limiter_test.go | 4 +- db/config.go | 4 +- db/schema.sql | 10 +- server/gemini_models_test.go | 113 +++ server/server.go | 2 +- server/server_mgmt.go | 48 +- web/src/app/(main)/system/llm/page.tsx | 21 +- web/src/i18n/messages.ts | 4 + web/src/lib/types.ts | 2 +- 13 files changed, 1810 insertions(+), 30 deletions(-) create mode 100644 agent/gemini.go create mode 100644 agent/gemini_test.go create mode 100644 server/gemini_models_test.go diff --git a/.env.example b/.env.example index 9e885e3..e973105 100644 --- a/.env.example +++ b/.env.example @@ -6,9 +6,10 @@ POSTGRES_USER=artex POSTGRES_PASSWORD=change-me-please POSTGRES_DB=artex -# LLM(二选一或都填;也可留空到 UI 里配) +# LLM(任选其一或都填;也可留空到 UI 里配) ANTHROPIC_API_KEY= OPENAI_API_KEY= +GEMINI_API_KEY= ARTEX_LLM_PROVIDER= ARTEX_LLM_MODEL= ARTEX_LLM_BASE_URL= diff --git a/agent/gemini.go b/agent/gemini.go new file mode 100644 index 0000000..a8abad0 --- /dev/null +++ b/agent/gemini.go @@ -0,0 +1,1190 @@ +package agent + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "iter" + "net/http" + "net/url" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/Autumn-27/norma/llm" +) + +// FormatGemini selects the native Google Gemini generateContent REST API +// (POST /{version}/models/{model}:streamGenerateContent?alt=sse and +// POST /{version}/models/{model}:generateContent). +const FormatGemini llm.Format = "gemini" + +const ( + defaultGeminiBaseURL = "https://generativelanguage.googleapis.com/v1beta" + defaultGeminiModel = "gemini-2.5-pro" + syntheticGeminiCallPrefix = "gemini_call_" + + geminiDefaultConnectRetries = 3 + geminiDefaultEmptyRetries = 2 + geminiSigCacheMax = 2048 +) + +// NormalizeGeminiBaseURL strips a pasted Gemini endpoint suffix +// (/models/{model}:generateContent, /models/{model}:streamGenerateContent?alt=sse, +// or /models) back to the API base URL. Empty stays empty so callers can decide +// whether to apply defaultGeminiBaseURL. +func NormalizeGeminiBaseURL(raw string) string { + s := strings.TrimSpace(raw) + if s == "" { + return "" + } + if idx := strings.Index(s, "/models/"); idx >= 0 { + s = s[:idx] + } else { + // Strip query string when user pasted ".../models?pageSize=..." or ".../models?key=...". + noQuery := s + if q := strings.IndexByte(noQuery, '?'); q >= 0 { + noQuery = noQuery[:q] + } + trimmed := strings.TrimRight(noQuery, "/") + if strings.HasSuffix(trimmed, "/models") { + s = strings.TrimSuffix(trimmed, "/models") + } + } + return strings.TrimRight(s, "/") +} + +// GeminiBaseWithVersion normalizes raw, applies the official Google AI Studio +// default when empty, and appends "/v1beta" when the URL has no explicit API +// version segment (/v1, /v1beta, /v1alpha, /v1beta1). +func GeminiBaseWithVersion(raw string) string { + base := NormalizeGeminiBaseURL(raw) + if base == "" { + return defaultGeminiBaseURL + } + if hasGeminiAPIVersion(base) { + return base + } + return base + "/v1beta" +} + +func hasGeminiAPIVersion(base string) bool { + u, err := url.Parse(base) + if err != nil { + return false + } + p := strings.TrimRight(u.Path, "/") + if p == "" { + return false + } + seg := p + if i := strings.LastIndexByte(p, '/'); i >= 0 { + seg = p[i+1:] + } + switch strings.ToLower(seg) { + case "v1", "v1beta", "v1alpha", "v1beta1": + return true + } + return false +} + +func isGeminiV1(base string) bool { + u, err := url.Parse(base) + if err != nil { + return false + } + p := strings.TrimRight(u.Path, "/") + seg := p + if i := strings.LastIndexByte(p, '/'); i >= 0 { + seg = p[i+1:] + } + return strings.EqualFold(seg, "v1") +} + +// geminiProvider implements llm.Provider against the native Google Gemini +// generateContent REST API, translating between norma's Anthropic-shaped +// content-block model and Gemini's contents/parts/functionDeclarations format. +type geminiProvider struct { + cfg Config + client *http.Client + baseURL string + model string + v1 bool + + callSeq atomic.Uint64 + + sigMu sync.Mutex + sigCache map[string]string + sigOrder []string +} + +func newGeminiProvider(cfg Config, client *http.Client) (*geminiProvider, error) { + baseURL := GeminiBaseWithVersion(cfg.BaseURL) + model := strings.TrimPrefix(strings.TrimSpace(cfg.Model), "models/") + if model == "" { + model = defaultGeminiModel + } + return &geminiProvider{ + cfg: cfg, + client: client, + baseURL: baseURL, + model: model, + v1: isGeminiV1(baseURL), + sigCache: make(map[string]string), + }, nil +} + +func (p *geminiProvider) endpointURL(stream bool) string { + u := p.baseURL + "/models/" + url.PathEscape(p.model) + if stream { + return u + ":streamGenerateContent?alt=sse" + } + return u + ":generateContent" +} + +func (p *geminiProvider) nextCallID() string { + return fmt.Sprintf("%s%d", syntheticGeminiCallPrefix, p.callSeq.Add(1)) +} + +func (p *geminiProvider) rememberSignature(callID, sig string) { + if callID == "" || sig == "" { + return + } + p.sigMu.Lock() + defer p.sigMu.Unlock() + if _, exists := p.sigCache[callID]; !exists { + if len(p.sigOrder) >= geminiSigCacheMax { + evict := p.sigOrder[0] + p.sigOrder = p.sigOrder[1:] + delete(p.sigCache, evict) + } + p.sigOrder = append(p.sigOrder, callID) + } + p.sigCache[callID] = sig +} + +func (p *geminiProvider) lookupSignature(callID string) string { + if callID == "" { + return "" + } + p.sigMu.Lock() + defer p.sigMu.Unlock() + return p.sigCache[callID] +} + +// ---- wire request types ---- + +type geminiReq struct { + SystemInstruction *geminiContent `json:"systemInstruction,omitempty"` + Contents []geminiContent `json:"contents"` + Tools []geminiTool `json:"tools,omitempty"` + GenerationConfig *geminiGenConfig `json:"generationConfig,omitempty"` +} + +type geminiContent struct { + Role string `json:"role,omitempty"` + Parts []geminiPart `json:"parts"` +} + +type geminiPart struct { + Text string `json:"text,omitempty"` + Thought bool `json:"thought,omitempty"` + ThoughtSignature string `json:"thoughtSignature,omitempty"` + FunctionCall *geminiFunctionCall `json:"functionCall,omitempty"` + FunctionResponse *geminiFunctionResponse `json:"functionResponse,omitempty"` +} + +type geminiFunctionCall struct { + ID string `json:"id,omitempty"` + Name string `json:"name"` + Args map[string]any `json:"args,omitempty"` +} + +type geminiFunctionResponse struct { + ID string `json:"id,omitempty"` + Name string `json:"name"` + Response map[string]any `json:"response"` +} + +type geminiTool struct { + FunctionDeclarations []geminiFuncDecl `json:"functionDeclarations"` +} + +type geminiFuncDecl struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` + Parameters map[string]any `json:"parameters,omitempty"` +} + +type geminiGenConfig struct { + MaxOutputTokens int `json:"maxOutputTokens,omitempty"` + Temperature *float64 `json:"temperature,omitempty"` + StopSequences []string `json:"stopSequences,omitempty"` + ThinkingConfig *geminiThinkingConfig `json:"thinkingConfig,omitempty"` +} + +type geminiThinkingConfig struct { + IncludeThoughts *bool `json:"includeThoughts,omitempty"` + ThinkingBudget *int `json:"thinkingBudget,omitempty"` + ThinkingLevel string `json:"thinkingLevel,omitempty"` +} + +func (p *geminiProvider) buildBody(req llm.CompletionRequest) ([]byte, error) { + body := geminiReq{ + Contents: p.toGeminiContents(req.Messages), + } + if sys := joinGeminiSystem(req.System); sys != "" { + body.SystemInstruction = &geminiContent{ + Parts: []geminiPart{{Text: sys}}, + } + } + if len(req.Tools) > 0 { + decls := make([]geminiFuncDecl, 0, len(req.Tools)) + for _, t := range req.Tools { + decls = append(decls, geminiFuncDecl{ + Name: t.Name, + Description: t.Description, + Parameters: sanitizeGeminiTopSchema(t.InputSchema), + }) + } + body.Tools = []geminiTool{{FunctionDeclarations: decls}} + } + + var gc geminiGenConfig + hasGC := false + if req.MaxTokens > 0 { + gc.MaxOutputTokens = req.MaxTokens + hasGC = true + } + if req.Temperature != nil { + gc.Temperature = req.Temperature + hasGC = true + } + if len(req.Stop) > 0 { + gc.StopSequences = req.Stop + hasGC = true + } + if tc := p.buildThinkingConfig(req.Thinking); tc != nil { + gc.ThinkingConfig = tc + hasGC = true + } + if hasGC { + body.GenerationConfig = &gc + } + return json.Marshal(body) +} + +func (p *geminiProvider) buildThinkingConfig(reqThinking string) *geminiThinkingConfig { + // Per-request "disabled" (compaction summary / intercept judge) suppresses + // thinking config so Gemini 2.0 (no thinkingConfig) and Gemini 2.5/3 Pro + // (rejects thinkingBudget=0) both succeed cleanly. + if reqThinking == "disabled" { + return nil + } + thinkingType := p.cfg.ThinkingType + if reqThinking != "" { + thinkingType = reqThinking + } + if thinkingType == "disabled" { + zero := 0 + return &geminiThinkingConfig{ThinkingBudget: &zero} + } + effort := strings.ToLower(strings.TrimSpace(p.cfg.ReasoningEffort)) + if thinkingType == "" && effort == "" { + return nil + } + tc := &geminiThinkingConfig{} + if thinkingType == "enabled" { + t := true + tc.IncludeThoughts = &t + } + if effort != "" { + if isGemini25Model(p.model) { + if budget, ok := gemini25EffortBudget(effort); ok { + tc.ThinkingBudget = &budget + } + } else { + if level := gemini3EffortLevel(effort); level != "" { + tc.ThinkingLevel = level + } + } + } + if tc.IncludeThoughts == nil && tc.ThinkingBudget == nil && tc.ThinkingLevel == "" { + return nil + } + return tc +} + +func isGemini25Model(model string) bool { + return strings.Contains(strings.ToLower(model), "gemini-2.5") +} + +func gemini25EffortBudget(effort string) (int, bool) { + switch effort { + case "low": + return 1024, true + case "medium": + return 8192, true + case "high": + return 16384, true + case "xhigh", "max": + return 24576, true + default: + return 0, false + } +} + +func gemini3EffortLevel(effort string) string { + switch effort { + case "low": + return "low" + case "medium": + return "medium" + case "high", "xhigh", "max": + return "high" + default: + return "" + } +} + +func joinGeminiSystem(segs []string) string { + parts := make([]string, 0, len(segs)) + for _, s := range segs { + if s = strings.TrimSpace(s); s != "" { + parts = append(parts, s) + } + } + return strings.Join(parts, "\n\n") +} + +func (p *geminiProvider) wireCallID(id string) string { + if id == "" || p.v1 || strings.HasPrefix(id, syntheticGeminiCallPrefix) { + return "" + } + return id +} + +func (p *geminiProvider) toGeminiContents(rawMsgs []llm.Message) []geminiContent { + msgs := llm.MessagesForAPI(rawMsgs) + + // Map tool_use ID -> tool Name so every functionResponse carries the exact + // matching function name required by Gemini. + toolNames := make(map[string]string) + for _, m := range msgs { + for _, b := range m.Content { + if b.Type == llm.BlockToolUse && b.ID != "" && b.Name != "" { + toolNames[b.ID] = b.Name + } + } + } + + out := make([]geminiContent, 0, len(msgs)) + for _, m := range msgs { + var role string + var parts []geminiPart + + switch m.Role { + case llm.RoleAssistant: + role = "model" + var turnSig string + for _, b := range m.Content { + if b.Type == llm.BlockThinking && b.Signature != "" { + turnSig = b.Signature + } + } + firstCall := true + hasCall := false + for _, b := range m.Content { + switch b.Type { + case llm.BlockText: + if b.Text != "" { + parts = append(parts, geminiPart{Text: b.Text}) + } + case llm.BlockToolUse: + sig := p.lookupSignature(b.ID) + if sig == "" && firstCall && turnSig != "" { + sig = turnSig + } + firstCall = false + hasCall = true + parts = append(parts, geminiPart{ + ThoughtSignature: sig, + FunctionCall: &geminiFunctionCall{ + ID: p.wireCallID(b.ID), + Name: b.Name, + Args: decodeGeminiArgs(b.Input), + }, + }) + } + } + if !hasCall && turnSig != "" && len(parts) > 0 { + parts[len(parts)-1].ThoughtSignature = turnSig + } + case llm.RoleUser: + role = "user" + var fnResps []geminiPart + var textParts []geminiPart + for _, b := range m.Content { + switch b.Type { + case llm.BlockToolResult: + name := toolNames[b.ToolUseID] + if name == "" { + continue + } + txt := flattenGeminiText(b.Content) + payload := map[string]any{"output": txt} + if b.IsError { + payload = map[string]any{"error": txt} + } + fnResps = append(fnResps, geminiPart{ + FunctionResponse: &geminiFunctionResponse{ + ID: p.wireCallID(b.ToolUseID), + Name: name, + Response: payload, + }, + }) + case llm.BlockText: + if b.Text != "" { + textParts = append(textParts, geminiPart{Text: b.Text}) + } + } + } + parts = append(fnResps, textParts...) + default: + continue + } + + if len(parts) == 0 { + continue + } + if n := len(out); n > 0 && out[n-1].Role == role { + out[n-1].Parts = append(out[n-1].Parts, parts...) + continue + } + out = append(out, geminiContent{Role: role, Parts: parts}) + } + return out +} + +func flattenGeminiText(blocks []llm.ContentBlock) string { + var sb strings.Builder + for _, b := range blocks { + if b.Type == llm.BlockText { + sb.WriteString(b.Text) + } + } + return sb.String() +} + +func decodeGeminiArgs(raw json.RawMessage) map[string]any { + if len(bytes.TrimSpace(raw)) == 0 { + return map[string]any{} + } + var m map[string]any + if err := json.Unmarshal(raw, &m); err != nil || m == nil { + return map[string]any{} + } + return m +} + +func marshalGeminiArgs(args map[string]any) string { + if len(args) == 0 { + return "{}" + } + b, err := json.Marshal(args) + if err != nil || len(b) == 0 { + return "{}" + } + return string(b) +} + +// ---- JSON Schema -> Gemini Schema sanitization ---- + +// sanitizeGeminiTopSchema prepares a tool's InputSchema for Gemini's +// FunctionDeclaration.parameters (OpenAPI 3.0 Schema subset). Tools with no +// parameters return nil so the parameters field is omitted (Gemini rejects +// OBJECT schemas with an empty properties map). +func sanitizeGeminiTopSchema(schema map[string]any) map[string]any { + if len(schema) == 0 { + return nil + } + clean := sanitizeGeminiSchema(schema) + if len(clean) == 0 { + return nil + } + if typ, _ := clean["type"].(string); strings.EqualFold(typ, "object") { + props, _ := clean["properties"].(map[string]any) + if len(props) == 0 { + return nil + } + } + return clean +} + +func sanitizeGeminiSchema(schema map[string]any) map[string]any { + if len(schema) == 0 { + return nil + } + // Collapse Pydantic/Zod-style nullable anyOf/oneOf: [{"type":"X"}, {"type":"null"}]. + for _, unionKey := range []string{"anyOf", "oneOf"} { + if rawList, ok := schema[unionKey].([]any); ok && len(rawList) > 0 { + var nonNull []map[string]any + hasNull := false + for _, item := range rawList { + sub, ok := item.(map[string]any) + if !ok { + continue + } + if t, _ := sub["type"].(string); strings.EqualFold(t, "null") { + hasNull = true + continue + } + nonNull = append(nonNull, sub) + } + if hasNull && len(nonNull) == 1 { + merged := make(map[string]any, len(nonNull[0])+2) + for k, v := range nonNull[0] { + merged[k] = v + } + if desc, ok := schema["description"]; ok && merged["description"] == nil { + merged["description"] = desc + } + merged["nullable"] = true + return sanitizeGeminiSchema(merged) + } + } + } + + out := make(map[string]any, len(schema)) + var schemaType string + + switch t := schema["type"].(type) { + case string: + schemaType = strings.ToLower(strings.TrimSpace(t)) + if schemaType != "" && schemaType != "null" { + out["type"] = schemaType + } + case []any: + for _, elem := range t { + s, ok := elem.(string) + if !ok { + continue + } + s = strings.ToLower(strings.TrimSpace(s)) + if s == "null" { + out["nullable"] = true + } else if schemaType == "" && s != "" { + schemaType = s + out["type"] = s + } + } + case []string: + for _, s := range t { + s = strings.ToLower(strings.TrimSpace(s)) + if s == "null" { + out["nullable"] = true + } else if schemaType == "" && s != "" { + schemaType = s + out["type"] = s + } + } + } + + if desc, ok := schema["description"].(string); ok && desc != "" { + out["description"] = desc + } + if nullable, ok := schema["nullable"].(bool); ok && nullable { + out["nullable"] = true + } + + if constVal, ok := schema["const"]; ok { + if s, ok := constVal.(string); ok { + out["enum"] = []string{s} + if schemaType == "" { + schemaType = "string" + out["type"] = "string" + } + } + } else if rawEnum, ok := schema["enum"]; ok { + if enumStrs := toStringSlice(rawEnum); len(enumStrs) > 0 { + out["enum"] = enumStrs + if schemaType == "" { + schemaType = "string" + out["type"] = "string" + } + } + } + + if format, ok := schema["format"].(string); ok && isGeminiAllowedFormat(schemaType, format) { + out["format"] = format + } + + if rawProps, ok := schema["properties"].(map[string]any); ok && len(rawProps) > 0 { + props := make(map[string]any, len(rawProps)) + for k, v := range rawProps { + if sub, ok := v.(map[string]any); ok { + if cleanSub := sanitizeGeminiSchema(sub); len(cleanSub) > 0 { + props[k] = cleanSub + } + } + } + if len(props) > 0 { + out["properties"] = props + if schemaType == "" { + schemaType = "object" + out["type"] = "object" + } + } + } + + if rawReq, ok := schema["required"]; ok { + if props, ok := out["properties"].(map[string]any); ok && len(props) > 0 { + reqList := toStringSlice(rawReq) + kept := make([]string, 0, len(reqList)) + for _, name := range reqList { + if _, exists := props[name]; exists { + kept = append(kept, name) + } + } + if len(kept) > 0 { + out["required"] = kept + } + } + } + + if rawItems, ok := schema["items"].(map[string]any); ok { + if cleanItems := sanitizeGeminiSchema(rawItems); len(cleanItems) > 0 { + out["items"] = cleanItems + if schemaType == "" { + schemaType = "array" + out["type"] = "array" + } + } + } + if schemaType == "array" && out["items"] == nil { + out["items"] = map[string]any{"type": "string"} + } + + // Preserve numeric/length bounds supported by Gemini Schema. + for _, k := range []string{"minimum", "maximum", "minItems", "maxItems", "minLength", "maxLength", "minProperties", "maxProperties"} { + if v, ok := schema[k]; ok { + out[k] = v + } + } + + // Handle non-nullable anyOf / oneOf. + for _, unionKey := range []string{"anyOf", "oneOf"} { + if rawList, ok := schema[unionKey].([]any); ok && len(rawList) > 0 && out["type"] == nil { + cleaned := make([]any, 0, len(rawList)) + for _, item := range rawList { + if sub, ok := item.(map[string]any); ok { + if cs := sanitizeGeminiSchema(sub); len(cs) > 0 { + cleaned = append(cleaned, cs) + } + } + } + if len(cleaned) > 0 { + out["anyOf"] = cleaned + } + break + } + } + + if len(out) == 0 { + return map[string]any{"type": "string"} + } + return out +} + +func isGeminiAllowedFormat(schemaType, format string) bool { + switch schemaType { + case "string": + return format == "enum" || format == "date-time" + case "number": + return format == "float" || format == "double" + case "integer": + return format == "int32" || format == "int64" + } + return false +} + +func toStringSlice(v any) []string { + switch list := v.(type) { + case []string: + return list + case []any: + out := make([]string, 0, len(list)) + for _, elem := range list { + if s, ok := elem.(string); ok { + out = append(out, s) + } + } + return out + } + return nil +} + +// ---- wire response types ---- + +type geminiResp struct { + Candidates []struct { + Content struct { + Role string `json:"role"` + Parts []geminiPart `json:"parts"` + } `json:"content"` + FinishReason string `json:"finishReason"` + } `json:"candidates"` + PromptFeedback *struct { + BlockReason string `json:"blockReason"` + } `json:"promptFeedback"` + UsageMetadata *geminiUsage `json:"usageMetadata"` + Error *struct { + Code int `json:"code"` + Message string `json:"message"` + Status string `json:"status"` + } `json:"error"` +} + +type geminiUsage struct { + PromptTokenCount int `json:"promptTokenCount"` + CandidatesTokenCount int `json:"candidatesTokenCount"` + ThoughtsTokenCount int `json:"thoughtsTokenCount"` + CachedContentTokenCount int `json:"cachedContentTokenCount"` +} + +func (u geminiUsage) norm() llm.Usage { + return llm.Usage{ + InputTokens: u.PromptTokenCount, + OutputTokens: u.CandidatesTokenCount + u.ThoughtsTokenCount, + CacheReadTokens: u.CachedContentTokenCount, + } +} + +func mapGeminiFinish(reason string, hasToolCall bool) string { + switch reason { + case "MAX_TOKENS": + return "max_tokens" + case "STOP", "": + if hasToolCall { + return "tool_use" + } + return "end_turn" + default: + if hasToolCall { + return "tool_use" + } + return "end_turn" + } +} + +func isGeminiEmptyRetryable(stopReason string) bool { + return stopReason == "end_turn" || stopReason == "" +} + +// ---- HTTP + retry ---- + +func (p *geminiProvider) doRequest(ctx context.Context, endpoint string, body []byte, accept string) (*http.Response, error) { + retries := geminiConnectRetries(p.cfg.Retry.ConnectAttempts) + for attempt := 0; ; attempt++ { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body)) + if err != nil { + return nil, err + } + req.Header.Set("content-type", "application/json") + req.Header.Set("x-goog-api-key", p.cfg.APIKey) + req.Header.Set("accept", accept) + + resp, err := p.client.Do(req) + if err == nil && resp.StatusCode == http.StatusOK { + return resp, nil + } + + retryable := false + switch { + case err != nil: + retryable = ctx.Err() == nil + case isGeminiRetryableStatus(resp.StatusCode): + retryable = true + } + if attempt >= retries || !retryable { + if err != nil { + return nil, err + } + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + return nil, fmt.Errorf("gemini: status %d: %s", resp.StatusCode, strings.TrimSpace(string(data))) + } + if resp != nil { + resp.Body.Close() + } + if !geminiBackoffSleep(ctx, geminiRetryDelay(attempt, p.cfg.Retry.ConnectInterval)) { + return nil, ctx.Err() + } + } +} + +func geminiConnectRetries(n int) int { + if n == 0 { + return geminiDefaultConnectRetries + } + if n < 0 { + return 0 + } + return n +} + +func geminiEmptyRetries(n int) int { + if n == 0 { + return geminiDefaultEmptyRetries + } + if n < 0 { + return 0 + } + return n +} + +func isGeminiRetryableStatus(code int) bool { + switch code { + case http.StatusRequestTimeout, // 408 + http.StatusTooManyRequests, // 429 + http.StatusInternalServerError, // 500 + http.StatusBadGateway, // 502 + http.StatusServiceUnavailable, // 503 + http.StatusGatewayTimeout: // 504 + return true + } + return false +} + +func geminiRetryDelay(attempt int, fixed time.Duration) time.Duration { + if fixed > 0 { + return fixed + } + d := 500 * time.Millisecond * (1 << attempt) + if d > 8*time.Second { + d = 8 * time.Second + } + return d +} + +func geminiBackoffSleep(ctx context.Context, d time.Duration) bool { + if d <= 0 { + return ctx.Err() == nil + } + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return false + case <-t.C: + return true + } +} + +// ---- streaming ---- + +func (p *geminiProvider) Stream(ctx context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { + return func(yield func(llm.StreamEvent, error) bool) { + body, err := p.buildBody(req) + if err != nil { + yield(llm.StreamEvent{}, err) + return + } + endpoint := p.endpointURL(true) + maxEmpty := geminiEmptyRetries(p.cfg.Retry.EmptyAttempts) + + for attempt := 0; ; attempt++ { + resp, err := p.doRequest(ctx, endpoint, body, "text/event-stream") + if err != nil { + yield(llm.StreamEvent{}, err) + return + } + + scan := newGeminiSSEScanner(resp.Body) + var usage llm.Usage + var rawFinish, blockReason string + hasToolCall := false + emitted := false + consumerStopped := false + var streamErr error + + for { + data, serr := scan.next() + if serr == io.EOF { + break + } + if serr != nil { + streamErr = serr + break + } + data = strings.TrimSpace(data) + if data == "" || data == "[DONE]" { + continue + } + var chunk geminiResp + if err := json.Unmarshal([]byte(data), &chunk); err != nil { + continue // tolerate keepalives + } + if chunk.Error != nil && (chunk.Error.Message != "" || chunk.Error.Code != 0) { + streamErr = fmt.Errorf("gemini: %s", chunk.Error.Message) + break + } + if chunk.UsageMetadata != nil { + usage = chunk.UsageMetadata.norm() + } + if len(chunk.Candidates) == 0 { + if chunk.PromptFeedback != nil && chunk.PromptFeedback.BlockReason != "" { + blockReason = chunk.PromptFeedback.BlockReason + } + continue + } + cand := chunk.Candidates[0] + if cand.FinishReason != "" { + rawFinish = cand.FinishReason + } + for _, part := range cand.Content.Parts { + switch { + case part.Thought: + if part.Text != "" { + emitted = true + if !yield(llm.StreamEvent{Type: llm.SEThinkingDelta, Text: part.Text}, nil) { + consumerStopped = true + break + } + } + if part.ThoughtSignature != "" { + if !yield(llm.StreamEvent{Type: llm.SEThinkingSignature, Text: part.ThoughtSignature}, nil) { + consumerStopped = true + break + } + } + case part.FunctionCall != nil: + callID := part.FunctionCall.ID + if callID == "" { + callID = p.nextCallID() + } + if part.ThoughtSignature != "" { + p.rememberSignature(callID, part.ThoughtSignature) + if !yield(llm.StreamEvent{Type: llm.SEThinkingSignature, Text: part.ThoughtSignature}, nil) { + consumerStopped = true + break + } + } + emitted = true + hasToolCall = true + if !yield(llm.StreamEvent{ + Type: llm.SEToolUseStart, + ToolID: callID, + ToolName: part.FunctionCall.Name, + }, nil) { + consumerStopped = true + break + } + if !yield(llm.StreamEvent{ + Type: llm.SEToolInputJSON, + Text: marshalGeminiArgs(part.FunctionCall.Args), + }, nil) { + consumerStopped = true + break + } + default: + if part.ThoughtSignature != "" { + if !yield(llm.StreamEvent{Type: llm.SEThinkingSignature, Text: part.ThoughtSignature}, nil) { + consumerStopped = true + break + } + } + if part.Text != "" { + emitted = true + if !yield(llm.StreamEvent{Type: llm.SETextDelta, Text: part.Text}, nil) { + consumerStopped = true + break + } + } + } + if consumerStopped { + break + } + } + if consumerStopped { + break + } + } + resp.Body.Close() + + if consumerStopped { + return + } + if streamErr != nil { + yield(llm.StreamEvent{}, streamErr) + return + } + if !emitted && blockReason != "" { + yield(llm.StreamEvent{}, fmt.Errorf("gemini: prompt blocked (%s)", blockReason)) + return + } + if !emitted && rawFinish == "MALFORMED_FUNCTION_CALL" { + yield(llm.StreamEvent{}, fmt.Errorf("gemini: malformed function call")) + return + } + stopReason := mapGeminiFinish(rawFinish, hasToolCall) + if !emitted && isGeminiEmptyRetryable(stopReason) && attempt < maxEmpty { + if !geminiBackoffSleep(ctx, geminiRetryDelay(attempt, p.cfg.Retry.EmptyInterval)) { + yield(llm.StreamEvent{}, ctx.Err()) + return + } + continue + } + if !yield(llm.StreamEvent{Type: llm.SEMessageDelta, StopReason: stopReason, Usage: usage}, nil) { + return + } + yield(llm.StreamEvent{Type: llm.SEMessageStop}, nil) + return + } + } +} + +// ---- non-streaming ---- + +func (p *geminiProvider) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + body, err := p.buildBody(req) + if err != nil { + return llm.Message{}, "", llm.Usage{}, err + } + endpoint := p.endpointURL(false) + maxEmpty := geminiEmptyRetries(p.cfg.Retry.EmptyAttempts) + + for attempt := 0; ; attempt++ { + resp, err := p.doRequest(ctx, endpoint, body, "application/json") + if err != nil { + return llm.Message{}, "", llm.Usage{}, err + } + raw, rerr := io.ReadAll(resp.Body) + resp.Body.Close() + if rerr != nil { + return llm.Message{}, "", llm.Usage{}, rerr + } + msg, stop, usage, perr := p.parseResponse(raw) + if perr != nil { + return llm.Message{}, "", llm.Usage{}, perr + } + if len(msg.Content) == 0 && isGeminiEmptyRetryable(stop) && attempt < maxEmpty { + if !geminiBackoffSleep(ctx, geminiRetryDelay(attempt, p.cfg.Retry.EmptyInterval)) { + return llm.Message{}, "", llm.Usage{}, ctx.Err() + } + continue + } + return msg, stop, usage, nil + } +} + +func (p *geminiProvider) parseResponse(raw []byte) (llm.Message, string, llm.Usage, error) { + var r geminiResp + if err := json.Unmarshal(raw, &r); err != nil { + return llm.Message{}, "", llm.Usage{}, fmt.Errorf("gemini: decode response: %w (body: %s)", err, clipBody(string(raw))) + } + if r.Error != nil && (r.Error.Message != "" || r.Error.Code != 0) { + return llm.Message{}, "", llm.Usage{}, fmt.Errorf("gemini: %s", r.Error.Message) + } + var usage llm.Usage + if r.UsageMetadata != nil { + usage = r.UsageMetadata.norm() + } + if len(r.Candidates) == 0 { + if r.PromptFeedback != nil && r.PromptFeedback.BlockReason != "" { + return llm.Message{}, "", usage, fmt.Errorf("gemini: prompt blocked (%s)", r.PromptFeedback.BlockReason) + } + return llm.Message{Role: llm.RoleAssistant}, "end_turn", usage, nil + } + + cand := r.Candidates[0] + var blocks []llm.ContentBlock + hasToolCall := false + lastThinkingIdx := -1 + + for _, part := range cand.Content.Parts { + switch { + case part.Thought: + if part.Text != "" { + blocks = append(blocks, llm.ContentBlock{ + Type: llm.BlockThinking, + Thinking: part.Text, + Signature: part.ThoughtSignature, + }) + lastThinkingIdx = len(blocks) - 1 + } else if part.ThoughtSignature != "" && lastThinkingIdx >= 0 { + blocks[lastThinkingIdx].Signature = part.ThoughtSignature + } + case part.FunctionCall != nil: + callID := part.FunctionCall.ID + if callID == "" { + callID = p.nextCallID() + } + if part.ThoughtSignature != "" { + p.rememberSignature(callID, part.ThoughtSignature) + if lastThinkingIdx >= 0 && blocks[lastThinkingIdx].Signature == "" { + blocks[lastThinkingIdx].Signature = part.ThoughtSignature + } + } + blocks = append(blocks, llm.ContentBlock{ + Type: llm.BlockToolUse, + ID: callID, + Name: part.FunctionCall.Name, + Input: json.RawMessage(marshalGeminiArgs(part.FunctionCall.Args)), + }) + hasToolCall = true + default: + if part.ThoughtSignature != "" && lastThinkingIdx >= 0 && blocks[lastThinkingIdx].Signature == "" { + blocks[lastThinkingIdx].Signature = part.ThoughtSignature + } + if part.Text != "" { + blocks = append(blocks, llm.TextBlock(part.Text)) + } + } + } + + if len(blocks) == 0 && cand.FinishReason == "MALFORMED_FUNCTION_CALL" { + return llm.Message{}, "", usage, fmt.Errorf("gemini: malformed function call") + } + stop := mapGeminiFinish(cand.FinishReason, hasToolCall) + return llm.Message{Role: llm.RoleAssistant, Content: blocks}, stop, usage, nil +} + +// ---- SSE scanner ---- + +type geminiSSEScanner struct { + r *bufio.Reader +} + +func newGeminiSSEScanner(body io.Reader) *geminiSSEScanner { + return &geminiSSEScanner{r: bufio.NewReaderSize(body, 64*1024)} +} + +func (s *geminiSSEScanner) next() (string, error) { + var buf bytes.Buffer + for { + line, err := s.r.ReadString('\n') + if err != nil { + if err == io.EOF && buf.Len() > 0 { + return strings.TrimRight(buf.String(), "\n"), nil + } + return "", err + } + line = strings.TrimRight(line, "\r\n") + if line == "" { + if buf.Len() > 0 { + return strings.TrimRight(buf.String(), "\n"), nil + } + continue + } + if strings.HasPrefix(line, "data:") { + d := strings.TrimPrefix(line[len("data:"):], " ") + buf.WriteString(d) + buf.WriteByte('\n') + } + } +} diff --git a/agent/gemini_test.go b/agent/gemini_test.go new file mode 100644 index 0000000..d926bb7 --- /dev/null +++ b/agent/gemini_test.go @@ -0,0 +1,405 @@ +package agent + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Autumn-27/artex/llmrec" + "github.com/Autumn-27/norma/llm" +) + +func TestConfigFromGeminiAndBaseURLNormalization(t *testing.T) { + cases := []struct { + in string + norm string + ver string + }{ + {"", "", "https://generativelanguage.googleapis.com/v1beta"}, + {"https://generativelanguage.googleapis.com", "https://generativelanguage.googleapis.com", "https://generativelanguage.googleapis.com/v1beta"}, + {"https://generativelanguage.googleapis.com/v1beta/", "https://generativelanguage.googleapis.com/v1beta", "https://generativelanguage.googleapis.com/v1beta"}, + {"https://generativelanguage.googleapis.com/v1", "https://generativelanguage.googleapis.com/v1", "https://generativelanguage.googleapis.com/v1"}, + {"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent", "https://generativelanguage.googleapis.com/v1beta", "https://generativelanguage.googleapis.com/v1beta"}, + {"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse", "https://generativelanguage.googleapis.com/v1beta", "https://generativelanguage.googleapis.com/v1beta"}, + {"https://proxy.example/gemini/models?pageSize=50", "https://proxy.example/gemini", "https://proxy.example/gemini/v1beta"}, + {"https://proxy.example/v1alpha", "https://proxy.example/v1alpha", "https://proxy.example/v1alpha"}, + } + for _, tc := range cases { + if got := NormalizeGeminiBaseURL(tc.in); got != tc.norm { + t.Errorf("NormalizeGeminiBaseURL(%q) = %q, want %q", tc.in, got, tc.norm) + } + if got := GeminiBaseWithVersion(tc.in); got != tc.ver { + t.Errorf("GeminiBaseWithVersion(%q) = %q, want %q", tc.in, got, tc.ver) + } + } + + c := ConfigFrom("gemini", "", "https://gw.example/v1beta/models/gemini-2.5-pro:generateContent", "AIza-test", "") + if c.Format != FormatGemini { + t.Fatalf("format=%v, want FormatGemini", c.Format) + } + if c.Model != defaultGeminiModel { + t.Fatalf("model=%q, want %q", c.Model, defaultGeminiModel) + } + if c.BaseURL != "https://gw.example/v1beta" { + t.Fatalf("base_url=%q", c.BaseURL) + } + if c.Provider() != "gemini" { + t.Fatalf("Provider()=%q", c.Provider()) + } + if !c.Stream { + t.Fatal("Stream should default true") + } + if _, err := c.NewProvider(); err != nil { + t.Fatalf("NewProvider: %v", err) + } +} + +func TestFromEnvGemini(t *testing.T) { + t.Setenv("ARTEX_LLM_PROVIDER", "") + t.Setenv("ANTHROPIC_API_KEY", "") + t.Setenv("OPENAI_API_KEY", "") + t.Setenv("GEMINI_API_KEY", "AIza-env-key") + t.Setenv("GOOGLE_API_KEY", "") + t.Setenv("ARTEX_LLM_MODEL", "") + t.Setenv("ARTEX_LLM_BASE_URL", "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent") + + c, ok := FromEnv() + if !ok { + t.Fatal("FromEnv returned ok=false") + } + if c.Format != FormatGemini || c.Provider() != "gemini" || c.APIKey != "AIza-env-key" { + t.Fatalf("unexpected config: %+v", c) + } + if c.BaseURL != "https://generativelanguage.googleapis.com/v1beta" { + t.Fatalf("BaseURL=%q", c.BaseURL) + } +} + +func TestGeminiStreamThinkingToolCallsAndReplay(t *testing.T) { + var requests []string + var paths []string + turn := 0 + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("x-goog-api-key") != "AIza-secret" { + t.Errorf("missing x-goog-api-key header: %q", r.Header.Get("x-goog-api-key")) + } + b, _ := io.ReadAll(r.Body) + requests = append(requests, string(b)) + paths = append(paths, r.URL.RequestURI()) + turn++ + + w.Header().Set("content-type", "text/event-stream") + if turn == 1 { + // Turn 1: thought delta + functionCall carrying thoughtSignature (no wire id) + sse := strings.Join([]string{ + `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"checking host","thought":true}]}}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":0,"thoughtsTokenCount":12,"cachedContentTokenCount":40}}`, + ``, + `data: {"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"name":"bash","args":{"command":"id"}},"thoughtSignature":"sig-turn-1"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":8,"thoughtsTokenCount":12,"cachedContentTokenCount":40}}`, + ``, + }, "\n") + _, _ = io.WriteString(w, sse) + return + } + // Turn 2: final text reply + sse := strings.Join([]string{ + `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"uid=0(root)"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":150,"candidatesTokenCount":5,"thoughtsTokenCount":0}}`, + ``, + }, "\n") + _, _ = io.WriteString(w, sse) + })) + defer srv.Close() + + cfg := ConfigFrom("gemini", "models/gemini-2.5-pro", srv.URL, "AIza-secret", "") + cfg.ThinkingType = "enabled" + cfg.ReasoningEffort = "medium" + prov, err := cfg.NewProvider() + if err != nil { + t.Fatalf("NewProvider: %v", err) + } + + req1 := llm.CompletionRequest{ + System: []string{"sys part 1", "sys part 2"}, + Messages: []llm.Message{llm.UserText("who am i?")}, + Tools: []llm.ToolSchema{{ + Name: "bash", + Description: "run shell", + InputSchema: map[string]any{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "additionalProperties": false, + "properties": map[string]any{ + "command": map[string]any{"type": "string", "description": "cmd", "format": "uri"}, + }, + "required": []string{"command", "nonexistent"}, + }, + }, { + Name: "noop", + Description: "no params", + InputSchema: map[string]any{"type": "object", "properties": map[string]any{}}, + }}, + MaxTokens: 2048, + } + + ctx, capt := llmrec.NewCapture(context.Background()) + acc := llm.NewAccumulator() + for ev, err := range prov.Stream(ctx, req1) { + if err != nil { + t.Fatalf("turn 1 stream: %v", err) + } + acc.Add(ev) + } + if paths[0] != "/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse" { + t.Fatalf("turn 1 path=%q", paths[0]) + } + if capt.RawRequest() != requests[0] { + t.Fatalf("llmrec capture mismatch:\ngot: %s\nwant: %s", capt.RawRequest(), requests[0]) + } + if acc.StopReason != "tool_use" { + t.Fatalf("turn 1 stop=%q, want tool_use", acc.StopReason) + } + if acc.Usage.InputTokens != 100 || acc.Usage.OutputTokens != 20 || acc.Usage.CacheReadTokens != 40 { + t.Fatalf("turn 1 usage=%+v, want in=100 out=20 cache=40", acc.Usage) + } + + msg1 := acc.Message() + uses := msg1.ToolUses() + if len(uses) != 1 || uses[0].Name != "bash" || string(uses[0].Input) != `{"command":"id"}` { + t.Fatalf("unexpected tool uses: %+v", uses) + } + if !strings.HasPrefix(uses[0].ID, syntheticGeminiCallPrefix) { + t.Fatalf("expected synthetic id, got %q", uses[0].ID) + } + + // Verify turn 1 wire body: systemInstruction, sanitized tools, thinkingBudget for 2.5 + var wire1 map[string]any + if err := json.Unmarshal([]byte(requests[0]), &wire1); err != nil { + t.Fatal(err) + } + gc := wire1["generationConfig"].(map[string]any) + if gc["maxOutputTokens"].(float64) != 2048 { + t.Fatalf("maxOutputTokens=%v", gc["maxOutputTokens"]) + } + tc := gc["thinkingConfig"].(map[string]any) + if tc["includeThoughts"] != true || tc["thinkingBudget"].(float64) != 8192 { + t.Fatalf("thinkingConfig=%v", tc) + } + tools := wire1["tools"].([]any)[0].(map[string]any)["functionDeclarations"].([]any) + bashDecl := tools[0].(map[string]any) + bashParams := bashDecl["parameters"].(map[string]any) + if _, bad := bashParams["additionalProperties"]; bad { + t.Fatal("additionalProperties was not stripped") + } + if _, bad := bashParams["$schema"]; bad { + t.Fatal("$schema was not stripped") + } + cmdProp := bashParams["properties"].(map[string]any)["command"].(map[string]any) + if _, bad := cmdProp["format"]; bad { + t.Fatal("unsupported string format 'uri' was not stripped") + } + if reqFields := bashParams["required"].([]any); len(reqFields) != 1 || reqFields[0] != "command" { + t.Fatalf("required=%v, want [command]", reqFields) + } + noopDecl := tools[1].(map[string]any) + if _, hasParams := noopDecl["parameters"]; hasParams { + t.Fatalf("zero-arg tool should omit parameters, got %v", noopDecl["parameters"]) + } + + // Turn 2: rebuild a fresh provider (simulating restart / transcript resume) and + // verify thoughtSignature is still replayed via BlockThinking.Signature and + // functionResponse carries the matched tool name "bash". + prov2, err := cfg.NewProvider() + if err != nil { + t.Fatalf("NewProvider 2: %v", err) + } + req2 := llm.CompletionRequest{ + System: req1.System, + Messages: []llm.Message{ + llm.UserText("who am i?"), + msg1, + {Role: llm.RoleUser, Content: []llm.ContentBlock{ + llm.ToolResultText(uses[0].ID, "uid=0(root)", false), + }}, + }, + } + acc2 := llm.NewAccumulator() + for ev, err := range prov2.Stream(context.Background(), req2) { + if err != nil { + t.Fatalf("turn 2 stream: %v", err) + } + acc2.Add(ev) + } + if acc2.StopReason != "end_turn" || acc2.Message().Text() != "uid=0(root)" { + t.Fatalf("turn 2 stop=%q text=%q", acc2.StopReason, acc2.Message().Text()) + } + + var wire2 geminiReq + if err := json.Unmarshal([]byte(requests[1]), &wire2); err != nil { + t.Fatal(err) + } + if len(wire2.Contents) != 3 { + t.Fatalf("contents len=%d, want 3", len(wire2.Contents)) + } + modelPart := wire2.Contents[1].Parts[0] + if modelPart.FunctionCall == nil || modelPart.FunctionCall.Name != "bash" || modelPart.ThoughtSignature != "sig-turn-1" { + t.Fatalf("model turn functionCall mismatch: %+v", modelPart) + } + if modelPart.FunctionCall.ID != "" { + t.Fatalf("synthetic ID should not be sent on wire, got %q", modelPart.FunctionCall.ID) + } + userRespPart := wire2.Contents[2].Parts[0] + if userRespPart.FunctionResponse == nil || userRespPart.FunctionResponse.Name != "bash" || userRespPart.FunctionResponse.Response["output"] != "uid=0(root)" { + t.Fatalf("functionResponse mismatch: %+v", userRespPart) + } +} + +func TestGeminiCompleteAndThoughtSignatureCacheWithoutThoughtText(t *testing.T) { + var seen []geminiReq + turn := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body geminiReq + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Errorf("decode request: %v", err) + } + seen = append(seen, body) + turn++ + w.Header().Set("content-type", "application/json") + if turn == 1 { + // Gemini 3 style: functionCall carries wire id + thoughtSignature, NO thought text part. + _, _ = io.WriteString(w, `{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"id":"fc_99","name":"lookup","args":{"k":"v"}},"thoughtSignature":"enc-sig-99"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":50,"candidatesTokenCount":10}}`) + return + } + _, _ = io.WriteString(w, `{"candidates":[{"content":{"role":"model","parts":[{"text":"done"}]},"finishReason":"MAX_TOKENS"}],"usageMetadata":{"promptTokenCount":80,"candidatesTokenCount":15}}`) + })) + defer srv.Close() + + cfg := ConfigFrom("gemini", "gemini-3-pro", srv.URL, "AIza-test", "") + cfg.ReasoningEffort = "high" + prov, err := cfg.NewProvider() + if err != nil { + t.Fatal(err) + } + + msg1, stop1, usage1, err := prov.Complete(context.Background(), llm.CompletionRequest{ + Messages: []llm.Message{llm.UserText("run")}, + }) + if err != nil { + t.Fatalf("Complete 1: %v", err) + } + if stop1 != "tool_use" || usage1.InputTokens != 50 || usage1.OutputTokens != 10 { + t.Fatalf("stop=%q usage=%+v", stop1, usage1) + } + if seen[0].GenerationConfig == nil || seen[0].GenerationConfig.ThinkingConfig == nil || seen[0].GenerationConfig.ThinkingConfig.ThinkingLevel != "high" { + t.Fatalf("expected thinkingLevel=high for gemini-3, got %+v", seen[0].GenerationConfig) + } + + msg2, stop2, _, err := prov.Complete(context.Background(), llm.CompletionRequest{ + Messages: []llm.Message{ + llm.UserText("run"), + msg1, + {Role: llm.RoleUser, Content: []llm.ContentBlock{llm.ToolResultText("fc_99", "err text", true)}}, + }, + Thinking: "disabled", // compaction / judge override must suppress thinkingConfig + }) + if err != nil { + t.Fatalf("Complete 2: %v", err) + } + if stop2 != "max_tokens" || msg2.Text() != "done" { + t.Fatalf("stop=%q text=%q", stop2, msg2.Text()) + } + if seen[1].GenerationConfig != nil && seen[1].GenerationConfig.ThinkingConfig != nil { + t.Fatalf("Thinking=disabled override must suppress thinkingConfig, got %+v", seen[1].GenerationConfig.ThinkingConfig) + } + fcPart := seen[1].Contents[1].Parts[0] + if fcPart.ThoughtSignature != "enc-sig-99" || fcPart.FunctionCall.ID != "fc_99" { + t.Fatalf("expected cached thoughtSignature and wire ID replayed, got %+v", fcPart) + } + frPart := seen[1].Contents[2].Parts[0] + if frPart.FunctionResponse.ID != "fc_99" || frPart.FunctionResponse.Response["error"] != "err text" { + t.Fatalf("expected error functionResponse with matching ID, got %+v", frPart) + } +} + +func TestGeminiTestConnectionAndQuota429(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v1beta/models/gemini-2.5-flash:generateContent" { + w.Header().Set("content-type", "application/json") + _, _ = io.WriteString(w, `{"candidates":[{"content":{"role":"model","parts":[{"text":"OK"}]},"finishReason":"STOP"}]}`) + return + } + w.WriteHeader(http.StatusTooManyRequests) + _, _ = io.WriteString(w, `{"error":{"code":429,"message":"You exceeded your current quota, please check your plan and billing details.","status":"RESOURCE_EXHAUSTED"}}`) + })) + defer srv.Close() + + // Non-streaming TestConnection + cfg := ConfigFrom("gemini", "gemini-2.5-flash", srv.URL, "AIza-test", "") + cfg.Stream = false + lat, reply, err := TestConnection(context.Background(), cfg) + if err != nil { + t.Fatalf("TestConnection: %v", err) + } + if lat < 0 || strings.TrimSpace(reply) != "OK" { + t.Fatalf("lat=%v reply=%q", lat, reply) + } + + // Quota-exhausted 429 must be normalized to 402 and fail immediately without retries + quotaCfg := ConfigFrom("gemini", "gemini-2.5-pro", srv.URL, "AIza-test", "") + quotaCfg.Retry.ConnectInterval = time.Millisecond + prov, err := quotaCfg.NewProvider() + if err != nil { + t.Fatal(err) + } + _, _, _, err = prov.Complete(context.Background(), llm.CompletionRequest{Messages: []llm.Message{llm.UserText("hi")}}) + if err == nil || !strings.Contains(err.Error(), "status 402") { + t.Fatalf("expected 402 normalized quota error, got %v", err) + } +} + +func TestSanitizeGeminiSchemaEdgeCases(t *testing.T) { + raw := map[string]any{ + "type": "object", + "properties": map[string]any{ + "nullable_arr": map[string]any{ + "type": []any{"string", "null"}, + }, + "nullable_anyof": map[string]any{ + "description": "opt int", + "anyOf": []any{ + map[string]any{"type": "integer", "format": "int64"}, + map[string]any{"type": "null"}, + }, + }, + "bare_array": map[string]any{ + "type": "array", + }, + "const_field": map[string]any{ + "const": "fixed", + }, + }, + } + got := sanitizeGeminiTopSchema(raw) + props := got["properties"].(map[string]any) + + na := props["nullable_arr"].(map[string]any) + if na["type"] != "string" || na["nullable"] != true { + t.Fatalf("nullable_arr=%v", na) + } + ao := props["nullable_anyof"].(map[string]any) + if ao["type"] != "integer" || ao["format"] != "int64" || ao["nullable"] != true || ao["description"] != "opt int" { + t.Fatalf("nullable_anyof=%v", ao) + } + ba := props["bare_array"].(map[string]any) + if items, ok := ba["items"].(map[string]any); !ok || items["type"] != "string" { + t.Fatalf("bare_array=%v", ba) + } + cf := props["const_field"].(map[string]any) + if cf["type"] != "string" || len(cf["enum"].([]string)) != 1 || cf["enum"].([]string)[0] != "fixed" { + t.Fatalf("const_field=%v", cf) + } +} diff --git a/agent/provider.go b/agent/provider.go index 3525c74..a1d633a 100644 --- a/agent/provider.go +++ b/agent/provider.go @@ -3,8 +3,8 @@ // §4.3 (planner) and §4.4 (work agent). // // Provider configuration is read from the environment so the system runs with -// any Anthropic- or OpenAI-format endpoint. If no key is configured, FromEnv -// returns ok=false and the exploration engine stays idle (an LLM is required). +// any Anthropic-, OpenAI-, or Gemini-format endpoint. If no key is configured, +// FromEnv returns ok=false and the exploration engine stays idle (an LLM is required). package agent import ( @@ -140,15 +140,19 @@ func compactionConfig(windowTokens int) *compaction.Config { // FromEnv resolves the LLM provider config: // -// ARTEX_LLM_PROVIDER = anthropic|openai (default: inferred from keys) +// ARTEX_LLM_PROVIDER = anthropic|openai|openai-responses|gemini (default: inferred from keys) // ARTEX_LLM_MODEL = model id (default: per provider) // ARTEX_LLM_BASE_URL = endpoint (optional) // ARTEX_LLM_PROXY = proxy URL (optional; http/https/socks5) -// ANTHROPIC_API_KEY / OPENAI_API_KEY = credentials +// ANTHROPIC_API_KEY / OPENAI_API_KEY / GEMINI_API_KEY = credentials func FromEnv() (Config, bool) { prov := os.Getenv("ARTEX_LLM_PROVIDER") anthKey := os.Getenv("ANTHROPIC_API_KEY") oaiKey := os.Getenv("OPENAI_API_KEY") + geminiKey := os.Getenv("GEMINI_API_KEY") + if geminiKey == "" { + geminiKey = os.Getenv("GOOGLE_API_KEY") + } if prov == "" { switch { @@ -156,6 +160,8 @@ func FromEnv() (Config, bool) { prov = "anthropic" case oaiKey != "": prov = "openai" + case geminiKey != "": + prov = "gemini" default: return Config{}, false } @@ -181,6 +187,13 @@ func FromEnv() (Config, bool) { if c.Model == "" { c.Model = "gpt-5" } + case "gemini": + c.Format = FormatGemini + c.BaseURL = NormalizeGeminiBaseURL(c.BaseURL) + c.APIKey = geminiKey + if c.Model == "" { + c.Model = defaultGeminiModel + } default: c.Format = llm.FormatAnthropic c.APIKey = anthKey @@ -226,6 +239,12 @@ func ConfigFrom(provider, model, baseURL, apiKey, proxy string) Config { if c.Model == "" { c.Model = "gpt-5" } + case "gemini": + c.Format = FormatGemini + c.BaseURL = NormalizeGeminiBaseURL(c.BaseURL) + if c.Model == "" { + c.Model = defaultGeminiModel + } default: c.Format = llm.FormatAnthropic // provider appends "/v1/messages". @@ -247,7 +266,7 @@ func isFalsy(s string) bool { return false } -// Provider returns the short provider name ("anthropic"/"openai"). +// Provider returns the short provider name ("anthropic"/"openai"/"openai-responses"/"gemini"/"jev"). func (c Config) Provider() string { if c.Jev { return "jev" @@ -257,6 +276,8 @@ func (c Config) Provider() string { return "openai" case llm.FormatOpenAIResponses: return "openai-responses" + case FormatGemini: + return "gemini" } return "anthropic" } @@ -288,6 +309,9 @@ func (c Config) newProvider(client *http.Client, limiter *RequestLimiter) (llm.P return nil, err } client.Transport = rateLimitedTransport{base: client.Transport, limiter: limiter} + if c.Format == FormatGemini { + return newGeminiProvider(c, client) + } lc := llm.Config{ Format: c.Format, BaseURL: c.BaseURL, diff --git a/agent/request_limiter_test.go b/agent/request_limiter_test.go index 480686a..f3be202 100644 --- a/agent/request_limiter_test.go +++ b/agent/request_limiter_test.go @@ -178,7 +178,7 @@ func TestRequestLimiterDisabledAndCancelled(t *testing.T) { // Exercise the actual Norma retry loops for all formats and both completion // modes. In-memory HTTP responses let synctest advance a full minute instantly. func TestProviderRateLimitCountsHTTPRetries(t *testing.T) { - for _, format := range []string{"openai", "anthropic", "openai-responses"} { + for _, format := range []string{"openai", "anthropic", "openai-responses", "gemini"} { for _, streaming := range []bool{false, true} { mode := "complete" if streaming { @@ -392,7 +392,7 @@ func TestRateLimitedTransportCancellationDoesNotSend(t *testing.T) { } func TestProviderRateLimitPublicFactory(t *testing.T) { - for _, format := range []string{"openai", "anthropic", "openai-responses"} { + for _, format := range []string{"openai", "anthropic", "openai-responses", "gemini"} { for _, streaming := range []bool{false, true} { mode := "complete" if streaming { diff --git a/db/config.go b/db/config.go index 86ab479..87c951e 100644 --- a/db/config.go +++ b/db/config.go @@ -52,8 +52,8 @@ type LLMProfile struct { // MaxTokensField picks the request key carrying MaxTokens, for format // "openai" only: "" = max_tokens (default); "max_completion_tokens" = the // newer key, which OpenAI's reasoning models require and whose budget covers - // reasoning tokens plus visible output. Ignored by anthropic and - // openai-responses, which name the field themselves. + // reasoning tokens plus visible output. Ignored by anthropic, + // openai-responses, and gemini, which name the field themselves. MaxTokensField string `json:"max_tokens_field"` // SessionHeaderKey, when non-empty, names a custom HTTP header sent on every // request built from this profile; its value is the current run's session id diff --git a/db/schema.sql b/db/schema.sql index 9831819..fe0d4ec 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -362,7 +362,7 @@ CREATE TABLE IF NOT EXISTS settings ( CREATE TABLE IF NOT EXISTS llm_profiles ( id BIGSERIAL PRIMARY KEY, name TEXT NOT NULL UNIQUE, - format TEXT NOT NULL CHECK (format IN ('openai','anthropic','openai-responses','jev')), + format TEXT NOT NULL CHECK (format IN ('openai','anthropic','openai-responses','gemini','jev')), base_url TEXT, proxy TEXT, model TEXT NOT NULL, @@ -390,7 +390,7 @@ CREATE TABLE IF NOT EXISTS llm_profiles ( -- '' = max_tokens(默认,兼容绝大多数网关) -- 'max_completion_tokens' = 新字段;OpenAI 推理模型(o 系列/GPT-5)只认它, -- 发 max_tokens 会被 unsupported_parameter 拒绝。 - -- anthropic(max_tokens 必填)与 openai-responses(max_output_tokens)自带字段名,不受此值影响。 + -- anthropic(max_tokens 必填)、openai-responses(max_output_tokens)与 gemini(maxOutputTokens)自带字段名,不受此值影响。 max_tokens_field TEXT NOT NULL DEFAULT '', -- 自定义会话头:非空时每次请求带一个该名字的 HTTP 头,头值=当前运行的 session id -- (chat 会话/worker 意图)。用于某些按 session-id 头做提示缓存/粘性路由的网关。''=不发送。 @@ -415,11 +415,11 @@ ALTER TABLE llm_profiles ADD COLUMN IF NOT EXISTS priority INTEGER NOT NULL ALTER TABLE llm_profiles ADD COLUMN IF NOT EXISTS pool_exclude BOOLEAN NOT NULL DEFAULT false; -- 流式开关;补旧库。默认 true = 保持既有的流式行为,旧配置无感升级。 ALTER TABLE llm_profiles ADD COLUMN IF NOT EXISTS streaming BOOLEAN NOT NULL DEFAULT true; --- 放开 format 约束以容纳 openai-responses(OpenAI Responses API)和 Jev System One;补旧库。 --- 每次启动执行,幂等:先删旧 CHECK 再建含三值的新 CHECK。 +-- 放开 format 约束以容纳 openai-responses(OpenAI Responses API)、gemini(Google Gemini)和 Jev System One;补旧库。 +-- 每次启动执行,幂等:先删旧 CHECK 再建新 CHECK。 ALTER TABLE llm_profiles DROP CONSTRAINT IF EXISTS llm_profiles_format_check; ALTER TABLE llm_profiles ADD CONSTRAINT llm_profiles_format_check - CHECK (format IN ('openai','anthropic','openai-responses','jev')); + CHECK (format IN ('openai','anthropic','openai-responses','gemini','jev')); -- 输出上限及其字段名;补旧库。默认 0 / '' = 不发送上限、沿用 max_tokens 字段名, -- 旧配置行为完全不变。 diff --git a/server/gemini_models_test.go b/server/gemini_models_test.go new file mode 100644 index 0000000..62f65ea --- /dev/null +++ b/server/gemini_models_test.go @@ -0,0 +1,113 @@ +package server + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestGeminiModelListAndConnectionEndpoints(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("x-goog-api-key") != "AIza-test-key" { + t.Errorf("missing x-goog-api-key header: %q", r.Header.Get("x-goog-api-key")) + } + switch r.URL.Path { + case "/v1beta/models": + if r.Method != http.MethodGet { + t.Errorf("models must use GET, got %s", r.Method) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"models":[ + {"name":"models/gemini-2.5-pro","supportedGenerationMethods":["generateContent","countTokens"]}, + {"name":"models/text-embedding-004","supportedGenerationMethods":["embedContent"]}, + {"name":"models/gemini-2.5-flash","supportedGenerationMethods":["generateContent"]} + ]}`)) + case "/v1beta/models/gemini-2.5-pro:streamGenerateContent": + if r.URL.Query().Get("alt") != "sse" { + t.Errorf("missing alt=sse query, got %q", r.URL.RawQuery) + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"text\":\"OK\"}]},\"finishReason\":\"STOP\"}]}\n\n") + case "/v1/models/gemini-2.5-pro:generateContent": + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"candidates":[{"content":{"role":"model","parts":[{"text":"OK"}]},"finishReason":"STOP"}]}`) + default: + t.Errorf("unexpected URL %s", r.URL.RequestURI()) + http.NotFound(w, r) + } + })) + defer upstream.Close() + + s := &Server{} + + t.Run("models", func(t *testing.T) { + // Bare URL without /v1beta should auto-append /v1beta and filter to generateContent models. + payload, _ := json.Marshal(map[string]any{ + "provider": "gemini", + "base_url": upstream.URL, + "api_key": "AIza-test-key", + }) + w := httptest.NewRecorder() + s.pgListModels(w, httptest.NewRequest(http.MethodPost, "/api/llm/models", strings.NewReader(string(payload)))) + var got struct { + OK bool `json:"ok"` + Models []string `json:"models"` + Error string `json:"error"` + } + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil || w.Code != 200 || !got.OK { + t.Fatalf("response=%d %s err=%v", w.Code, w.Body, err) + } + if strings.Join(got.Models, ",") != "gemini-2.5-pro,gemini-2.5-flash" { + t.Fatalf("models=%v, want [gemini-2.5-pro gemini-2.5-flash]", got.Models) + } + }) + + t.Run("connection_streaming", func(t *testing.T) { + payload, _ := json.Marshal(map[string]any{ + "provider": "gemini", + "model": "gemini-2.5-pro", + "base_url": upstream.URL + "/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse", + "api_key": "AIza-test-key", + }) + w := httptest.NewRecorder() + s.testLLM(w, httptest.NewRequest(http.MethodPost, "/api/llm/test", strings.NewReader(string(payload)))) + var got struct { + OK bool `json:"ok"` + Reply string `json:"reply"` + Error string `json:"error"` + } + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil || w.Code != 200 || !got.OK { + t.Fatalf("response=%d %s err=%v", w.Code, w.Body, err) + } + if strings.TrimSpace(got.Reply) != "OK" { + t.Fatalf("reply=%q", got.Reply) + } + }) + + t.Run("connection_non_streaming_v1", func(t *testing.T) { + streaming := false + payload, _ := json.Marshal(map[string]any{ + "provider": "gemini", + "model": "gemini-2.5-pro", + "base_url": upstream.URL + "/v1", + "api_key": "AIza-test-key", + "streaming": streaming, + }) + w := httptest.NewRecorder() + s.testLLM(w, httptest.NewRequest(http.MethodPost, "/api/llm/test", strings.NewReader(string(payload)))) + var got struct { + OK bool `json:"ok"` + Reply string `json:"reply"` + Error string `json:"error"` + } + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil || w.Code != 200 || !got.OK { + t.Fatalf("response=%d %s err=%v", w.Code, w.Body, err) + } + if strings.TrimSpace(got.Reply) != "OK" { + t.Fatalf("reply=%q", got.Reply) + } + }) +} diff --git a/server/server.go b/server/server.go index 7da95ad..6defced 100644 --- a/server/server.go +++ b/server/server.go @@ -423,7 +423,7 @@ func (s *Server) saveLLMConfig(cfg agent.Config) error { return db.ErrJevProfileJudgeOnly } // cfg.Provider() returns one of the chat format strings - // (anthropic / openai / openai-responses), matching the DB CHECK constraint; + // (anthropic / openai / openai-responses / gemini), matching the DB CHECK constraint; // Jev is intentionally handled by the dedicated intercept path. format := cfg.Provider() var id int64 diff --git a/server/server_mgmt.go b/server/server_mgmt.go index 9ede0f6..1c7c88e 100644 --- a/server/server_mgmt.go +++ b/server/server_mgmt.go @@ -1830,7 +1830,7 @@ func (s *Server) pgSaveProfile(w http.ResponseWriter, r *http.Request) { p.APIKey = body.APIKey p.Streaming = body.Streaming == nil || *body.Streaming // 输出上限:负数无意义,归零(= 不发送该字段)。字段名开关只有 Chat Completions - // 用得上——anthropic 与 openai-responses 各自定死了字段名,存下来只会误导后续读者, + // 用得上——anthropic、openai-responses 与 gemini 各自定死了字段名,存下来只会误导后续读者, // 故非 openai 格式一律清空。未知取值同样清空,避免把 DB CHECK 的报错甩给用户。 if p.MaxTokens < 0 { p.MaxTokens = 0 @@ -2005,12 +2005,13 @@ func (s *Server) pgLLMPoolReset(w http.ResponseWriter, r *http.Request) { } // pgListModels fetches available models from the provider's API endpoint. -// Supports OpenAI-format (GET /models) and Anthropic-format (GET /v1/models); for -// Anthropic-compatible third parties (e.g. DeepSeek) whose model list lives only on -// the OpenAI path, it falls back to the OpenAI endpoint at the stripped root. +// Supports OpenAI-format (GET /models), Anthropic-format (GET /v1/models), and +// Gemini-format (GET /{version}/models); for Anthropic-compatible third parties +// (e.g. DeepSeek) whose model list lives only on the OpenAI path, it falls back +// to the OpenAI endpoint at the stripped root. func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) { var req struct { - Provider string `json:"provider"` // "openai" | "anthropic" + Provider string `json:"provider"` // "openai" | "anthropic" | "openai-responses" | "gemini" | "jev" BaseURL string `json:"base_url"` APIKey string `json:"api_key"` Proxy string `json:"proxy"` @@ -2075,6 +2076,11 @@ func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) { h.Set("anthropic-version", "2023-06-01") return h } + geminiHdr := func() http.Header { + h := http.Header{} + h.Set("x-goog-api-key", apiKey) + return h + } var candidates []candidate switch provider { @@ -2086,6 +2092,9 @@ func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) { } b := strings.TrimRight(strings.TrimSuffix(strings.TrimSuffix(baseURL, "/chat/completions"), "/responses"), "/") candidates = append(candidates, candidate{b + "/models", bearerHdr()}) + case "gemini": + b := agent.GeminiBaseWithVersion(baseURL) + candidates = append(candidates, candidate{b + "/models?pageSize=1000", geminiHdr()}) default: // anthropic if baseURL == "" { baseURL = "https://api.anthropic.com" @@ -2131,22 +2140,38 @@ func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) { lastErr = fmt.Sprintf("API 返回 %d: %s", resp.StatusCode, string(body[:min(len(body), 512)])) continue } - // Both OpenAI and Anthropic return {"data": [{"id": "..."},...]}. + // OpenAI and Anthropic return {"data": [{"id": "..."},...]}; + // Gemini returns {"models": [{"name": "models/...", "supportedGenerationMethods": [...]}, ...]}. var parsed struct { Data []struct { ID string `json:"id"` } `json:"data"` + Models []struct { + Name string `json:"name"` + SupportedGenerationMethods []string `json:"supportedGenerationMethods"` + } `json:"models"` } if err := json.Unmarshal(body, &parsed); err != nil { lastErr = "解析响应失败: " + err.Error() continue } - models := make([]string, 0, len(parsed.Data)) + models := make([]string, 0, len(parsed.Data)+len(parsed.Models)) for _, m := range parsed.Data { if m.ID != "" { models = append(models, m.ID) } } + if len(models) == 0 && len(parsed.Models) > 0 { + for _, m := range parsed.Models { + if len(m.SupportedGenerationMethods) > 0 && !containsString(m.SupportedGenerationMethods, "generateContent") { + continue + } + id := strings.TrimPrefix(strings.TrimSpace(m.Name), "models/") + if id != "" { + models = append(models, id) + } + } + } if len(models) > 0 { writeJSON(w, 200, map[string]any{"ok": true, "models": models}) return @@ -2163,6 +2188,15 @@ func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, map[string]any{"ok": false, "error": lastErr}) } +func containsString(list []string, target string) bool { + for _, s := range list { + if s == target { + return true + } + } + return false +} + // --- prompt template helpers (Go text/template + catalog 白名单) --- // globalPromptVars are runtime variables available to EVERY agent (built-in and diff --git a/web/src/app/(main)/system/llm/page.tsx b/web/src/app/(main)/system/llm/page.tsx index c312ce9..4f41e36 100644 --- a/web/src/app/(main)/system/llm/page.tsx +++ b/web/src/app/(main)/system/llm/page.tsx @@ -49,11 +49,12 @@ const MAX_TOKENS_FIELDS = (ui: UITranslate): { value: string; label: string }[] { value: NONE, label: ui("screen.af7202f4ddd9ce") }, { value: "max_completion_tokens", label: "max_completion_tokens" }, ]; -// 另外两种格式各自定死了字段名,选项对它们无意义,说明文案里直接讲清楚。 +// 另外几种格式各自定死了字段名,选项对它们无意义,说明文案里直接讲清楚。 const MAX_TOKENS_FIELD_HINTS = (ui: UITranslate): Record => ({ openai: ui("screen.8565b2d7398535"), anthropic: ui("screen.55138cdb37fe16"), "openai-responses": ui("screen.82b05dbd905574"), + gemini: ui("llm.maxTokensFieldHint.gemini"), }); const EFFORT_LEVELS = (ui: UITranslate): { value: string; label: string }[] => [ { value: NONE, label: ui("screen.d703a9bcd8b626") }, @@ -325,7 +326,9 @@ function ProfileSheet({ const isNew = !profile; const [name, setName] = React.useState(""); - const [format, setFormat] = React.useState<"anthropic" | "openai" | "openai-responses" | "jev">("anthropic"); + const [format, setFormat] = React.useState<"anthropic" | "openai" | "openai-responses" | "gemini" | "jev">( + "anthropic", + ); const [model, setModel] = React.useState(""); const [baseUrl, setBaseUrl] = React.useState(""); const [proxy, setProxy] = React.useState(""); @@ -355,7 +358,10 @@ function ProfileSheet({ if (!open) return; setName(profile?.name ?? ""); setFormat( - profile?.format === "openai" || profile?.format === "openai-responses" || profile?.format === "jev" + profile?.format === "openai" || + profile?.format === "openai-responses" || + profile?.format === "gemini" || + profile?.format === "jev" ? profile.format : "anthropic", ); @@ -509,7 +515,7 @@ function ProfileSheet({ @@ -533,7 +540,7 @@ function ProfileSheet({ setModel(e.target.value)} /> @@ -585,7 +592,9 @@ function ProfileSheet({ setBaseUrl(e.target.value)} /> diff --git a/web/src/i18n/messages.ts b/web/src/i18n/messages.ts index 58df462..d9666b8 100644 --- a/web/src/i18n/messages.ts +++ b/web/src/i18n/messages.ts @@ -214,6 +214,10 @@ export const messages = { ], "ui.ascending": ["正序", "ascending"], "ui.descending": ["倒序", "descending"], + "llm.maxTokensFieldHint.gemini": [ + "仅 openai 格式可选。Gemini 的字段名固定为 maxOutputTokens。", + "Only configurable for the openai format. Gemini uses maxOutputTokens.", + ], } satisfies Record; const statuses: Record = { diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts index 4309eed..6e5f068 100644 --- a/web/src/lib/types.ts +++ b/web/src/lib/types.ts @@ -1154,7 +1154,7 @@ export interface NotificationDelivery { export interface LLMProfile { id: string; name: string; - format: "openai" | "anthropic" | "openai-responses" | "jev"; + format: "openai" | "anthropic" | "openai-responses" | "gemini" | "jev"; base_url?: string; proxy?: string; model: string;