mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-11-24 09:41:51 +08:00
Merge pull request #182 from RuoJi6/RuoJi6/gemini
feat(llm): 支持原生 Google Gemini API 格式 (#170)
This commit is contained in:
13 files changed
+1810
-30
No files matched your search
+2
-1
@@ -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=
|
||||
|
||||
+1190
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
}
|
||||
}
|
||||
+29
-5
@@ -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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+2
-2
@@ -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
|
||||
|
||||
+5
-5
@@ -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 字段名,
|
||||
-- 旧配置行为完全不变。
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
+1
-1
@@ -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
|
||||
|
||||
+41
-7
@@ -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
|
||||
|
||||
@@ -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<string, string> => ({
|
||||
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({
|
||||
<Select
|
||||
value={format}
|
||||
onValueChange={(v) => {
|
||||
const next = v as "anthropic" | "openai" | "openai-responses" | "jev";
|
||||
const next = v as "anthropic" | "openai" | "openai-responses" | "gemini" | "jev";
|
||||
setFormat(next);
|
||||
if (next === "jev" && !model.trim()) setModel("jev-latest");
|
||||
}}
|
||||
@@ -521,6 +527,7 @@ function ProfileSheet({
|
||||
<SelectItem value="anthropic">Anthropic</SelectItem>
|
||||
<SelectItem value="openai">OpenAI (Chat Completions)</SelectItem>
|
||||
<SelectItem value="openai-responses">OpenAI (Responses API)</SelectItem>
|
||||
<SelectItem value="gemini">Google Gemini</SelectItem>
|
||||
<SelectItem value="jev">{ui("screen.1959e996efa50a")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
@@ -533,7 +540,7 @@ function ProfileSheet({
|
||||
<Input
|
||||
id="p-model"
|
||||
className="font-mono"
|
||||
placeholder="claude-opus-4-8"
|
||||
placeholder={format === "gemini" ? "gemini-2.5-pro" : "claude-opus-4-8"}
|
||||
value={model}
|
||||
onChange={(e) => setModel(e.target.value)}
|
||||
/>
|
||||
@@ -585,7 +592,9 @@ function ProfileSheet({
|
||||
<Input
|
||||
id="p-base-url"
|
||||
className="font-mono"
|
||||
placeholder="https://api.openai.com/v1"
|
||||
placeholder={
|
||||
format === "gemini" ? "https://generativelanguage.googleapis.com/v1beta" : "https://api.openai.com/v1"
|
||||
}
|
||||
value={baseUrl}
|
||||
onChange={(e) => setBaseUrl(e.target.value)}
|
||||
/>
|
||||
|
||||
@@ -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.",
|
||||
],
|
||||
"findingsCleanup.button": ["一键清理", "One-click cleanup"],
|
||||
"findingsCleanup.title": ["一键清理历史漏洞", "Clean up historical findings"],
|
||||
"findingsCleanup.description": [
|
||||
|
||||
@@ -1156,7 +1156,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;
|
||||
|
||||
Reference in new issue
Block a user