diff --git a/README.md b/README.md index b0602653..f9e7d4a5 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ ## 当前功能 - **CLI 与 Gateway**:本地交互、单次提问,或通过消息渠道持续运行。 -- **模型接入**:支持多种模型提供商、OpenAI 兼容接口、多模型配置与切换。 +- **模型接入**:仅保留 OpenAI(Responses / Chat Completions)和 Anthropic Messages,支持兼容端点、多模型配置与切换。 - **会话管理**:保存对话上下文,支持摘要压缩,以及通过 `/new` 清空上下文后重新提问。 - **工具与扩展**:文件操作、命令执行、网页搜索与抓取、MCP、Skills 和定时任务。 - **语音能力**:保留语音识别与合成,实际可用能力取决于模型、服务及渠道配置。 @@ -150,7 +150,7 @@ picoclaw update --url https://github.com/loveuer/picoclaw/releases/tag/v1.0.0 -- } ``` -`model_name` 是本地别名,`agents.defaults.model_name` 用它选择默认模型;`provider` 指定提供商,`model` 是远端模型 ID。使用兼容接口时,可在该模型条目中添加 `api_base`。 +`model_name` 是本地别名,`agents.defaults.model_name` 用它选择默认模型;`provider` 指定提供商,`model` 是远端模型 ID。使用兼容接口时,仍选择 `provider: "openai"` 或 `"anthropic"`,并显式填写 `api_base` 和远端 `model`。其他厂商专用名称、原生 Gemini / Azure / Bedrock、Copilot、Antigravity 和 CLI 代理已移除;原有配置需要按协议调整。 已有 `.security.yml` 中的值可能覆盖主配置中的同名设置。修改密钥时请同时检查该文件。完整字段示例见 [config/config.example.json](config/config.example.json),提供商说明见[模型配置文档](docs/guides/providers.zh.md)。 diff --git a/cmd/picoclaw/internal/auth/command.go b/cmd/picoclaw/internal/auth/command.go index 9de083d8..73a80f2b 100644 --- a/cmd/picoclaw/internal/auth/command.go +++ b/cmd/picoclaw/internal/auth/command.go @@ -15,7 +15,6 @@ func NewAuthCommand() *cobra.Command { newLoginCommand(), newLogoutCommand(), newStatusCommand(), - newModelsCommand(), newWeixinCommand(), newWeComCommand(), ) diff --git a/cmd/picoclaw/internal/auth/command_test.go b/cmd/picoclaw/internal/auth/command_test.go index 3c7f2d3d..f762ba51 100644 --- a/cmd/picoclaw/internal/auth/command_test.go +++ b/cmd/picoclaw/internal/auth/command_test.go @@ -31,7 +31,6 @@ func TestNewAuthCommand(t *testing.T) { "login", "logout", "status", - "models", "weixin", "wecom", } diff --git a/cmd/picoclaw/internal/auth/helpers.go b/cmd/picoclaw/internal/auth/helpers.go index 10bb3a11..0709cd9a 100644 --- a/cmd/picoclaw/internal/auth/helpers.go +++ b/cmd/picoclaw/internal/auth/helpers.go @@ -2,13 +2,9 @@ package auth import ( "bufio" - "encoding/json" "fmt" - "io" - "net/http" "os" "strings" - "time" "github.com/sipeed/picoclaw/cmd/picoclaw/internal" "github.com/sipeed/picoclaw/pkg/auth" @@ -17,7 +13,7 @@ import ( ) const ( - supportedProvidersMsg = "supported providers: openai, anthropic, google-antigravity, antigravity" + supportedProvidersMsg = "supported providers: openai, anthropic" defaultAnthropicModel = "claude-sonnet-4.6" ) @@ -27,8 +23,6 @@ func authLoginCmd(provider string, useDeviceCode bool, useOauth bool, noBrowser return authLoginOpenAI(useDeviceCode, noBrowser) case "anthropic": return authLoginAnthropic(useOauth) - case "google-antigravity", "antigravity": - return authLoginGoogleAntigravity(noBrowser) default: return fmt.Errorf("unsupported provider: %s (%s)", provider, supportedProvidersMsg) } @@ -92,75 +86,6 @@ func authLoginOpenAI(useDeviceCode bool, noBrowser bool) error { return nil } -func authLoginGoogleAntigravity(noBrowser bool) error { - cfg := auth.GoogleAntigravityOAuthConfig() - - cred, err := auth.LoginBrowserWithOptions(cfg, auth.LoginBrowserOptions{NoBrowser: noBrowser}) - if err != nil { - return fmt.Errorf("login failed: %w", err) - } - - cred.Provider = "google-antigravity" - - // Fetch user email from Google userinfo - email, err := fetchGoogleUserEmail(cred.AccessToken) - if err != nil { - fmt.Printf("Warning: could not fetch email: %v\n", err) - } else { - cred.Email = email - fmt.Printf("Email: %s\n", email) - } - - // Fetch Cloud Code Assist project ID - projectID, err := providers.FetchAntigravityProjectID(cred.AccessToken) - if err != nil { - fmt.Printf("Warning: could not fetch project ID: %v\n", err) - fmt.Println("You may need Google Cloud Code Assist enabled on your account.") - } else { - cred.ProjectID = projectID - fmt.Printf("Project: %s\n", projectID) - } - - if err = auth.SetCredential("google-antigravity", cred); err != nil { - return fmt.Errorf("failed to save credentials: %w", err) - } - - appCfg, err := internal.LoadConfig() - if err == nil { - // Update or add antigravity in ModelList - foundAntigravity := false - for i := range appCfg.ModelList { - if isAntigravityModel(appCfg.ModelList[i]) { - appCfg.ModelList[i].AuthMethod = "oauth" - foundAntigravity = true - break - } - } - - // If no antigravity in ModelList, add it - if !foundAntigravity { - appCfg.ModelList = append(appCfg.ModelList, &config.ModelConfig{ - ModelName: "gemini-flash", - Model: "antigravity/gemini-3-flash", - AuthMethod: "oauth", - }) - } - - // Update default model - appCfg.Agents.Defaults.ModelName = "gemini-flash" - - if err := config.SaveConfig(internal.GetConfigPath(), appCfg); err != nil { - fmt.Printf("Warning: could not update config: %v\n", err) - } - } - - fmt.Println("\n✓ Google Antigravity login successful!") - fmt.Println("Default model set to: gemini-flash") - fmt.Println("Try it: picoclaw agent -m \"Hello world\"") - - return nil -} - func authLoginAnthropic(useOauth bool) error { if useOauth { return authLoginAnthropicSetupToken() @@ -234,37 +159,6 @@ func authLoginAnthropicSetupToken() error { return nil } -func fetchGoogleUserEmail(accessToken string) (string, error) { - req, err := http.NewRequest("GET", "https://www.googleapis.com/oauth2/v2/userinfo", nil) - if err != nil { - return "", err - } - req.Header.Set("Authorization", "Bearer "+accessToken) - - client := &http.Client{Timeout: 10 * time.Second} - resp, err := client.Do(req) - if err != nil { - return "", err - } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return "", fmt.Errorf("reading userinfo response: %w", err) - } - if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf("userinfo request failed: %s", string(body)) - } - - var userInfo struct { - Email string `json:"email"` - } - if err := json.Unmarshal(body, &userInfo); err != nil { - return "", err - } - return userInfo.Email, nil -} - func authLoginPasteToken(provider string) error { cred, err := auth.LoginPasteToken(provider, os.Stdin) if err != nil { @@ -349,10 +243,6 @@ func authLogoutCmd(provider string) error { if isAnthropicModel(appCfg.ModelList[i]) { appCfg.ModelList[i].AuthMethod = "" } - case "google-antigravity", "antigravity": - if isAntigravityModel(appCfg.ModelList[i]) { - appCfg.ModelList[i].AuthMethod = "" - } } } config.SaveConfig(internal.GetConfigPath(), appCfg) @@ -433,64 +323,6 @@ func authStatusCmd() error { return nil } -func authModelsCmd() error { - cred, err := auth.GetCredential("google-antigravity") - if err != nil || cred == nil { - return fmt.Errorf( - "not logged in to Google Antigravity.\nrun: picoclaw auth login --provider google-antigravity", - ) - } - - // Refresh token if needed - if cred.NeedsRefresh() && cred.RefreshToken != "" { - oauthCfg := auth.GoogleAntigravityOAuthConfig() - refreshed, refreshErr := auth.RefreshAccessToken(cred, oauthCfg) - if refreshErr == nil { - cred = refreshed - _ = auth.SetCredential("google-antigravity", cred) - } - } - - projectID := cred.ProjectID - if projectID == "" { - return fmt.Errorf("no project id stored. Try logging in again") - } - - fmt.Printf("Fetching models for project: %s\n\n", projectID) - - models, err := providers.FetchAntigravityModels(cred.AccessToken, projectID) - if err != nil { - return fmt.Errorf("error fetching models: %w", err) - } - - if len(models) == 0 { - return fmt.Errorf("no models available") - } - - fmt.Println("Available Antigravity Models:") - fmt.Println("-----------------------------") - for _, m := range models { - status := "✓" - if m.IsExhausted { - status = "✗ (quota exhausted)" - } - name := m.ID - if m.DisplayName != "" { - name = fmt.Sprintf("%s (%s)", m.ID, m.DisplayName) - } - fmt.Printf(" %s %s\n", status, name) - } - - return nil -} - -// isAntigravityModel checks if a model config belongs to an Antigravity provider. -func isAntigravityModel(modelCfg *config.ModelConfig) bool { - protocol, _ := providers.ExtractProtocol(modelCfg) - return protocol == "antigravity" || protocol == "google-antigravity" -} - -// isOpenAIModel checks if a model config belongs to the OpenAI provider. func isOpenAIModel(modelCfg *config.ModelConfig) bool { protocol, _ := providers.ExtractProtocol(modelCfg) return protocol == "openai" diff --git a/cmd/picoclaw/internal/auth/login.go b/cmd/picoclaw/internal/auth/login.go index b9b44db3..ade5682d 100644 --- a/cmd/picoclaw/internal/auth/login.go +++ b/cmd/picoclaw/internal/auth/login.go @@ -20,7 +20,7 @@ func newLoginCommand() *cobra.Command { } cmd.Flags().StringVarP( - &provider, "provider", "p", "", "Provider to login with (openai, anthropic, google-antigravity, antigravity)", + &provider, "provider", "p", "", "Provider to login with (openai, anthropic)", ) cmd.Flags().BoolVar(&useDeviceCode, "device-code", false, "Use device code flow (for headless environments)") cmd.Flags().BoolVar(&noBrowser, "no-browser", false, "Do not auto-open a browser during OAuth login") diff --git a/cmd/picoclaw/internal/auth/models.go b/cmd/picoclaw/internal/auth/models.go deleted file mode 100644 index cabe6822..00000000 --- a/cmd/picoclaw/internal/auth/models.go +++ /dev/null @@ -1,15 +0,0 @@ -package auth - -import "github.com/spf13/cobra" - -func newModelsCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "models", - Short: "Show available models", - RunE: func(_ *cobra.Command, _ []string) error { - return authModelsCmd() - }, - } - - return cmd -} diff --git a/cmd/picoclaw/internal/auth/models_test.go b/cmd/picoclaw/internal/auth/models_test.go deleted file mode 100644 index 26ca6778..00000000 --- a/cmd/picoclaw/internal/auth/models_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package auth - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestNewModelsCommand(t *testing.T) { - cmd := newModelsCommand() - - require.NotNil(t, cmd) - - assert.Equal(t, "models", cmd.Use) - assert.Equal(t, "Show available models", cmd.Short) - - assert.False(t, cmd.HasFlags()) -} diff --git a/cmd/picoclaw/internal/auth/status_test.go b/cmd/picoclaw/internal/auth/status_test.go index 2f9a7072..1867079e 100644 --- a/cmd/picoclaw/internal/auth/status_test.go +++ b/cmd/picoclaw/internal/auth/status_test.go @@ -2,18 +2,14 @@ package auth import ( "bytes" - "encoding/json" "io" "os" "path/filepath" - "strings" "testing" - "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - pkgauth "github.com/sipeed/picoclaw/pkg/auth" "github.com/sipeed/picoclaw/pkg/config" ) @@ -57,47 +53,3 @@ func TestNewStatusSubcommand(t *testing.T) { assert.False(t, cmd.HasFlags()) } - -func TestAuthStatusCmdShowsCanonicalGoogleAntigravityAfterLegacyRefresh(t *testing.T) { - tmpDir := setAuthStatusTestHome(t) - - legacyExpiry := time.Date(2026, 4, 16, 10, 0, 0, 0, time.UTC) - legacyStore := map[string]any{ - "credentials": map[string]any{ - "antigravity": map[string]any{ - "access_token": "legacy-token", - "expires_at": legacyExpiry.Format(time.RFC3339), - "provider": "antigravity", - "auth_method": "oauth", - "project_id": "legacy-project", - }, - }, - } - data, err := json.Marshal(legacyStore) - require.NoError(t, err) - - authPath := filepath.Join(tmpDir, ".picoclaw", "auth.json") - require.NoError(t, os.MkdirAll(filepath.Dir(authPath), 0o755)) - require.NoError(t, os.WriteFile(authPath, data, 0o600)) - - refreshedExpiry := time.Date(2026, 4, 16, 12, 30, 0, 0, time.UTC) - err = pkgauth.SetCredential("google-antigravity", &pkgauth.AuthCredential{ - AccessToken: "fresh-token", - ExpiresAt: refreshedExpiry, - Provider: "google-antigravity", - AuthMethod: "oauth", - ProjectID: "fresh-project", - }) - require.NoError(t, err) - - output := captureAuthStdout(t, func() { - require.NoError(t, authStatusCmd()) - }) - - assert.Contains(t, output, "\nAuthenticated Providers:") - assert.Contains(t, output, "\n google-antigravity:\n") - assert.NotContains(t, output, "\n antigravity:\n") - assert.Contains(t, output, " Project: fresh-project") - assert.Contains(t, output, " Expires: 2026-04-16 12:30") - assert.Equal(t, 1, strings.Count(output, ":\n Method: oauth")) -} diff --git a/config/config.example.json b/config/config.example.json index 7ac0f981..fe1fef1a 100644 --- a/config/config.example.json +++ b/config/config.example.json @@ -33,77 +33,21 @@ "model_list": [ { "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_keys": ["sk-your-openai-key"], - "api_base": "https://api.openai.com/v1" + "provider": "openai", + "model": "gpt-5.4", + "api_base": "https://api.openai.com/v1", + "api_keys": [ + "YOUR_OPENAI_API_KEY" + ] }, { "model_name": "claude-sonnet-4.6", - "model": "anthropic/claude-sonnet-4.6", - "api_keys": ["sk-ant-your-key"], + "provider": "anthropic", + "model": "claude-sonnet-4-6", "api_base": "https://api.anthropic.com/v1", - "thinking_level": "high" - }, - { - "_comment": "Anthropic Messages API - use native format for direct Anthropic API access", - "model_name": "claude-opus-4-6", - "model": "anthropic-messages/claude-opus-4-6", - "api_keys": ["sk-ant-your-key"], - "api_base": "https://api.anthropic.com" - }, - { - "model_name": "gemini", - "_comment": "Optional: set \"tool_schema_transform\": \"simple\" for providers that reject complex tool JSON Schema.", - "model": "antigravity/gemini-2.0-flash", - "auth_method": "oauth" - }, - { - "model_name": "deepseek", - "model": "deepseek/deepseek-chat", - "api_keys": ["sk-your-deepseek-key"] - }, - { - "model_name": "venice-uncensored", - "model": "venice/venice-uncensored", - "api_keys": ["your-venice-api-key"] - }, - { - "model_name": "nearai-glm", - "model": "nearai/zai-org/GLM-5.1-FP8", - "api_keys": ["your-nearai-api-key"] - }, - { - "model_name": "lmstudio-local", - "model": "lmstudio/openai/gpt-oss-20b" - }, - { - "model_name": "longcat", - "model": "longcat/LongCat-Flash-Thinking", - "api_keys": ["your-longcat-api-key"] - }, - { - "model_name": "modelscope-qwen", - "model": "modelscope/Qwen/Qwen3-235B-A22B-Instruct-2507", - "api_keys": ["your-modelscope-access-token"], - "api_base": "https://api-inference.modelscope.cn/v1" - }, - { - "model_name": "azure-gpt5", - "model": "azure/my-gpt5-deployment", - "api_keys": ["your-azure-api-key"], - "api_base": "https://your-resource.openai.azure.com" - }, - { - "model_name": "loadbalanced-gpt-5.4", - "model": "openai/gpt-5.4", - "api_keys": ["sk-key1"], - "api_base": "https://api1.example.com/v1" - }, - { - "model_name": "loadbalanced-gpt-5.4", - "model": "openai/gpt-5.4", - "api_keys": ["sk-key2"], - "api_base": "https://api2.example.com/v1" + "api_keys": [ + "YOUR_ANTHROPIC_API_KEY" + ] } ], "channel_list": { diff --git a/docs/design/provider-refactoring-tests.md b/docs/design/provider-refactoring-tests.md index 060be9ba..5868aac9 100644 --- a/docs/design/provider-refactoring-tests.md +++ b/docs/design/provider-refactoring-tests.md @@ -1,5 +1,7 @@ # Provider Architecture Refactoring - Test Suite Summary +> Historical design notes. This fork now supports only OpenAI and Anthropic; see the [current provider guide](../guides/providers.md). References below to other providers describe the earlier implementation. + This document summarizes the complete test suite designed for the Provider architecture refactoring. ## Test File Structure diff --git a/docs/design/provider-refactoring.md b/docs/design/provider-refactoring.md index e754a639..314e83b0 100644 --- a/docs/design/provider-refactoring.md +++ b/docs/design/provider-refactoring.md @@ -1,5 +1,7 @@ # Provider Architecture Refactoring Design +> Historical design notes. This fork now supports only OpenAI and Anthropic; see the [current provider guide](../guides/providers.md). References below to other providers describe the earlier implementation. + > Issue: #283 > Discussion: #122 > Branch: feat/refactor-provider-by-protocol diff --git a/docs/guides/configuration.md b/docs/guides/configuration.md index 42439134..714e6ab0 100644 --- a/docs/guides/configuration.md +++ b/docs/guides/configuration.md @@ -604,533 +604,9 @@ The subagent has access to tools (message, web_search, etc.) and can communicate * `PICOCLAW_HEARTBEAT_ENABLED=false` to disable * `PICOCLAW_HEARTBEAT_INTERVAL=60` to change interval -### Providers +### Model providers -> [!NOTE] -> Groq provides free voice transcription via Whisper. If configured, audio messages from any channel will be automatically transcribed at the agent level. - -| Provider | Purpose | Get API Key | -| ------------ | --------------------------------------- | ------------------------------------------------------------ | -| `gemini` | LLM (Gemini direct) | [aistudio.google.com](https://aistudio.google.com) | -| `zhipu` | LLM (Zhipu direct) | [bigmodel.cn](https://bigmodel.cn) | -| `volcengine` | LLM (Volcengine direct) | [volcengine.com](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| `openrouter` | LLM (recommended, access to all models) | [openrouter.ai](https://openrouter.ai) | -| `anthropic` | LLM (Claude direct) | [console.anthropic.com](https://console.anthropic.com) | -| `openai` | LLM (GPT direct) | [platform.openai.com](https://platform.openai.com) | -| `deepseek` | LLM (DeepSeek direct) | [platform.deepseek.com](https://platform.deepseek.com) | -| `qwen` | LLM (Qwen direct) | [dashscope.console.aliyun.com](https://dashscope.console.aliyun.com) | -| `groq` | LLM + **Voice transcription** (Whisper) | [console.groq.com](https://console.groq.com) | -| `cerebras` | LLM (Cerebras direct) | [cerebras.ai](https://cerebras.ai) | -| `vivgrid` | LLM (Vivgrid direct) | [vivgrid.com](https://vivgrid.com) | - -### Model Configuration (model_list) - -> **What's New?** PicoClaw now prefers explicit `provider` + native `model` configuration (for example `"provider": "zhipu", "model": "glm-4.7"`). The legacy single-field `provider/model` form remains supported for compatibility when `provider` is omitted. - -This design also enables **multi-agent support** with flexible provider selection: - -- **Different agents, different providers**: Each agent can use its own LLM provider -- **Model fallbacks**: Configure primary and fallback models for resilience -- **Load balancing**: Distribute requests across multiple endpoints or keys -- **Centralized configuration**: Manage all providers in one place -- **Model enable/disable**: Use the `enabled` field to temporarily disable a model without removing its configuration - -#### 🔒 Security Configuration (Recommended) - -PicoClaw supports separating sensitive data (API keys, tokens, secrets) from your main configuration by storing them in a `.security.yml` file. - -**Key Benefits:** -- **Security**: Sensitive data is never in your main config file -- **Easy sharing**: Share config.json without exposing API keys -- **Version control**: Add `.security.yml` to `.gitignore` -- **Flexible deployment**: Different environments can use different security files - -**Quick Setup:** - -1. Create `~/.picoclaw/.security.yml` with your API keys: -```yaml -model_list: - gpt-5.4: - api_keys: - - "sk-proj-your-actual-openai-key" - claude-sonnet-4.6: - api_keys: - - "sk-ant-your-actual-anthropic-key" -channels: - telegram: - token: "your-telegram-bot-token" -web: - brave: - api_keys: - - "BSAyour-brave-api-key" - glm_search: - api_key: "your-glm-search-api-key" -``` - -2. Set proper permissions: -```bash -chmod 600 ~/.picoclaw/.security.yml -``` - -3. Remove sensitive fields from `config.json` (recommended): -```json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4" - // api_key loaded from .security.yml - } - ], - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - // token loaded from .security.yml - } - } -} -``` - -**How it works:** -- Values from `.security.yml` are automatically mapped to config fields -- No special syntax needed — just omit sensitive fields from config.json -- If a field exists in both files, `.security.yml` value takes precedence -- You can mix direct values in config.json with security values - -For complete documentation, see [`../security/security_configuration.md`](../security/security_configuration.md). - -#### All Supported Vendors - -| Vendor | `provider` Value | Default API Base | Protocol | API Key | -| ----------------------- | ----------------- | --------------------------------------------------- | --------- | ---------------------------------------------------------------- | -| **OpenAI** | `openai` | `https://api.openai.com/v1` | OpenAI | [Get Key](https://platform.openai.com) | -| **Anthropic** | `anthropic` | `https://api.anthropic.com/v1` | Anthropic | [Get Key](https://console.anthropic.com) | -| **智谱 AI (GLM)** | `zhipu` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [Get Key](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) | -| **DeepSeek** | `deepseek` | `https://api.deepseek.com/v1` | OpenAI | [Get Key](https://platform.deepseek.com) | -| **Google Gemini** | `gemini` | `https://generativelanguage.googleapis.com/v1beta` | Gemini | [Get Key](https://aistudio.google.com/api-keys) | -| **Groq** | `groq` | `https://api.groq.com/openai/v1` | OpenAI | [Get Key](https://console.groq.com) | -| **Moonshot** | `moonshot` | `https://api.moonshot.cn/v1` | OpenAI | [Get Key](https://platform.moonshot.cn) | -| **通义千问 (Qwen)** | `qwen` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [Get Key](https://dashscope.console.aliyun.com) | -| **NVIDIA** | `nvidia` | `https://integrate.api.nvidia.com/v1` | OpenAI | [Get Key](https://build.nvidia.com) | -| **Ollama** | `ollama` | `http://localhost:11434/v1` | OpenAI | Local (no key needed) | -| **LM Studio** | `lmstudio` | `http://localhost:1234/v1` | OpenAI | Optional (local default: no key) | -| **OpenRouter** | `openrouter` | `https://openrouter.ai/api/v1` | OpenAI | [Get Key](https://openrouter.ai/keys) | -| **LiteLLM Proxy** | `litellm` | `http://localhost:4000/v1` | OpenAI | Your LiteLLM proxy key | -| **VLLM** | `vllm` | `http://localhost:8000/v1` | OpenAI | Local | -| **Cerebras** | `cerebras` | `https://api.cerebras.ai/v1` | OpenAI | [Get Key](https://cerebras.ai) | -| **VolcEngine (Doubao)** | `volcengine` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [Get Key](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| **神算云** | `shengsuanyun` | `https://router.shengsuanyun.com/api/v1` | OpenAI | — | -| **BytePlus** | `byteplus` | `https://ark.ap-southeast.bytepluses.com/api/v3` | OpenAI | [Get Key](https://www.byteplus.com) | -| **Vivgrid** | `vivgrid` | `https://api.vivgrid.com/v1` | OpenAI | [Get Key](https://vivgrid.com) | -| **LongCat** | `longcat` | `https://api.longcat.chat/openai` | OpenAI | [Get Key](https://longcat.chat/platform) | -| **ModelScope (魔搭)** | `modelscope` | `https://api-inference.modelscope.cn/v1` | OpenAI | [Get Token](https://modelscope.cn/my/tokens) | -| **Antigravity** | `antigravity` | Google Cloud | Custom | OAuth only | -| **GitHub Copilot** | `github-copilot` | `localhost:4321` | gRPC | — | - -#### Basic Configuration - -```json -{ - "model_list": [ - { - "model_name": "ark-code-latest", - "provider": "volcengine", - "model": "ark-code-latest", - "api_keys": ["sk-your-api-key"] - }, - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_keys": ["sk-your-openai-key"] - }, - { - "model_name": "claude-sonnet-4.6", - "provider": "anthropic", - "model": "claude-sonnet-4.6", - "api_keys": ["sk-ant-your-key"] - }, - { - "model_name": "glm-4.7", - "provider": "zhipu", - "model": "glm-4.7", - "api_keys": ["your-zhipu-key"] - } - ], - "agents": { - "defaults": { - "model": "gpt-5.4" - } - } -} -``` - -> **Security Note**: You can remove `api_keys` fields from your config and store them in `.security.yml` instead. See [Security Configuration](#-security-configuration-recommended) above for details. -> -> **Note**: The `enabled` field can be set to `false` to disable a model entry without removing it. When omitted, it defaults to `true` during migration for models that have API keys. - -Resolution rules: - -- Prefer explicit `"provider": "openai", "model": "gpt-5.4"`. -- If `provider` is set, PicoClaw sends `model` unchanged. -- If `provider` is omitted, PicoClaw treats the first `/` segment in `model` as the provider and everything after that first `/` as the runtime model ID. -- This means `"model": "openrouter/openai/gpt-5.4"` still works as a compatibility form and sends `openai/gpt-5.4` to OpenRouter. - -#### Streaming Configuration - -Provider streaming uses a double opt-in and is disabled by default. The agent only tries streaming when the current channel has `settings.streaming.enabled: true`, the active model entry has `streaming.enabled: true`, and both the provider and channel support streaming. If any condition is missing, PicoClaw uses the normal non-streaming request path. - -Leave `streaming` unset when you do not want streaming. An omitted `streaming` block means disabled; you do not need to write `"streaming": {"enabled": false}`. - -Opt-in example: - -```json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_keys": ["sk-your-openai-key"], - "streaming": { - "enabled": true - } - } - ], - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "settings": { - "token": "YOUR_TELEGRAM_TOKEN", - "streaming": { - "enabled": true - } - } - } - } -} -``` - -| Field | Type | Default | Description | -| ----- | ---- | ------- | ----------- | -| `channel_list..settings.streaming.enabled` | bool | `false` | Allows this channel to display provider streaming output | -| `channel_list..settings.streaming.throttle_seconds` | int | Telegram: `3` | Minimum interval for intermediate updates; final content is always flushed | -| `channel_list..settings.streaming.min_growth_chars` | int | Telegram: `200` | Minimum character growth before sending an intermediate update; final content is always flushed | -| `model_list[].streaming.enabled` | bool | `false` | Allows this model entry to try provider streaming requests | - -Legacy Telegram environment variables remain compatible: `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`, `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS`, and `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. - -Failure behavior is intentionally conservative: if streaming fails before any visible chunk is sent, PicoClaw retries once through the normal `Chat()` path. If a chunk has already been shown to the user, PicoClaw does not send a second non-streaming answer, because that would duplicate visible output. - -For model-specific TTS request fields such as custom speech `voice` names or -`response_format: "mp3"`, use `model_list[].extra_body`. - -#### Vendor-Specific Examples - -> **Tip**: You can omit `api_key` fields and store them in `.security.yml` for better security. See [Security Configuration](#-security-configuration-recommended). - -
-OpenAI - -```json -{ - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4" - // api_key: set in .security.yml -} -``` - -
- -
-OpenRouter TTS (MAI Voice 2) - -```json -{ - "model_name": "mai-voice-2", - "provider": "openrouter", - "model": "microsoft/mai-voice-2", - "api_base": "https://openrouter.ai/api/v1", - "extra_body": { - "voice": "en-US-Harper:MAI-Voice-2", - "response_format": "mp3" - } - // api_key: set in .security.yml -} -``` - -Pair this with: - -```json -{ - "voice": { - "tts_model_name": "mai-voice-2" - } -} -``` - -
- -
-VolcEngine (Doubao) - -```json -{ - "model_name": "ark-code-latest", - "provider": "volcengine", - "model": "ark-code-latest" - // api_key: set in .security.yml -} -``` - -
- -
-智谱 AI (GLM) - -```json -{ - "model_name": "glm-4.7", - "provider": "zhipu", - "model": "glm-4.7" - // api_key: set in .security.yml -} -``` - -
- -
-DeepSeek - -```json -{ - "model_name": "deepseek-chat", - "provider": "deepseek", - "model": "deepseek-chat" - // api_key: set in .security.yml -} -``` - -
- -
-Anthropic - -```json -{ - "model_name": "claude-sonnet-4.6", - "provider": "anthropic", - "model": "claude-sonnet-4.6" - // api_key: set in .security.yml -} -``` - -> Run `picoclaw auth login --provider anthropic` to paste your API token. - -For direct Anthropic API access or custom endpoints that only support Anthropic's native message format: - -```json -{ - "model_name": "claude-opus-4-6", - "provider": "anthropic-messages", - "model": "claude-opus-4-6", - "api_keys": ["sk-ant-your-key"], - "api_base": "https://api.anthropic.com" -} -``` - -> Use `anthropic-messages` when the endpoint requires Anthropic's native `/v1/messages` format instead of OpenAI-compatible `/v1/chat/completions`. - -
- -
-Ollama (local) - -```json -{ - "model_name": "llama3", - "provider": "ollama", - "model": "llama3" -} -``` - -
- -
-LM Studio (local) - -```json -{ - "model_name": "lmstudio-local", - "provider": "lmstudio", - "model": "openai/gpt-oss-20b" -} -``` - -`api_base` defaults to `http://localhost:1234/v1`. API key is optional unless your LM Studio server enables authentication.
-With explicit `provider`, PicoClaw sends `openai/gpt-oss-20b` unchanged to LM Studio. The legacy compatibility form `"model": "lmstudio/openai/gpt-oss-20b"` still resolves to the same upstream model ID when `provider` is omitted. - -
- -
-Custom Proxy / LiteLLM - -```json -{ - "model_name": "my-custom-model", - "provider": "openai", - "model": "custom-model", - "api_base": "https://my-proxy.com/v1" - // api_key: set in .security.yml -} -``` - -With explicit `provider`, PicoClaw sends `model` unchanged. That means `"provider": "litellm", "model": "lite-gpt4"` sends `lite-gpt4`, while `"provider": "litellm", "model": "openai/gpt-4o"` sends `openai/gpt-4o`. The legacy compatibility forms `litellm/lite-gpt4` and `litellm/openai/gpt-4o` still resolve the same way when `provider` is omitted. - -
- -#### Load Balancing - -Configure multiple endpoints for the same model name — PicoClaw will automatically round-robin between them: - -**Option 1: Multiple API Keys in .security.yml (Recommended)** - -```yaml -# .security.yml -model_list: - gpt-5.4: - api_keys: - - "sk-proj-key-1" - - "sk-proj-key-2" -``` - -```json -// config.json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_base": "https://api.openai.com/v1" - // api_keys loaded from .security.yml - } - ] -} -``` - -**Option 2: Multiple Model Entries** - -```json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_base": "https://api1.example.com/v1", - "api_keys": ["sk-key1"] - }, - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_base": "https://api2.example.com/v1", - "api_keys": ["sk-key2"] - } - ] -} -``` - -#### Migration from Legacy `providers` Config - -The old `providers` configuration is **deprecated** and has been removed in V2. Existing V0/V1 configs are auto-migrated. See [docs/migration/model-list-migration.md](../migration/model-list-migration.md) for the full guide. - -### Provider Architecture - -PicoClaw routes providers by protocol family: - -- **OpenAI-compatible**: OpenRouter, Groq, Zhipu, vLLM-style endpoints, and most others. -- **Gemini native**: Google Gemini via the native `models/*:generateContent` and `models/*:streamGenerateContent` endpoints. -- **Anthropic**: Claude-native API behavior. -- **Codex/OAuth**: OpenAI OAuth/token authentication route. - -This keeps the runtime lightweight while making new OpenAI-compatible backends mostly a config operation (`api_base` + `api_keys`). - -
-Zhipu (legacy providers format) - -```json -{ - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model": "glm-4.7", - "max_tokens": 8192, - "temperature": 0.7, - "max_tool_iterations": 20, - "max_parallel_turns": 1 - } - }, - "providers": { - "zhipu": { - "api_key": "Your API Key", - "api_base": "https://open.bigmodel.cn/api/paas/v4" - } - } -} -``` - -> **Note**: The `providers` format is deprecated. Use the new `model_list` format with `.security.yml` for better security. -> -> **`max_parallel_turns`**: Controls concurrent processing of messages from different sessions. `1` (default) = sequential; `>1` = parallel. Messages from the same session are always serialized. See [Steering docs](../architecture/steering.md) for details. - -
- -
-Full config example - -```json -{ - "agents": { - "defaults": { - "model_name": "claude-opus-4-5" - } - }, - "session": { - "dm_scope": "per-channel-peer", - "backlog_limit": 20 - }, - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - // token: set in .security.yml - "allow_from": ["123456789"] - } - }, - "tools": { - "web": { - "duckduckgo": { - "enabled": true, - "max_results": 5 - } - } - }, - "heartbeat": { - "enabled": true, - "interval": 30 - } -} -``` - -> **Note**: Sensitive fields (`api_key`, `token`, etc.) can be omitted and stored in `.security.yml` for better security. - -
+This fork supports OpenAI (Responses / Chat Completions) and Anthropic Messages. See the [provider guide](providers.md) for model configuration, streaming, authentication, compatible endpoints, multiple keys and fallback. The upstream named-provider catalog and CLI proxies have been removed. ### Scheduled Tasks / Reminders diff --git a/docs/guides/configuration.zh.md b/docs/guides/configuration.zh.md index 81566b28..31141e65 100644 --- a/docs/guides/configuration.zh.md +++ b/docs/guides/configuration.zh.md @@ -467,401 +467,9 @@ Agent 读取 HEARTBEAT.md 子 Agent 拥有工具访问权限(message、web_search 等),可以独立与用户通信,无需经过主 Agent。 -### Providers(模型提供商) +### 模型提供商 -> [!NOTE] -> Groq 通过 Whisper 提供免费语音转录。配置后,任意渠道的语音消息都会在 Agent 层自动转录为文字。 - -| 提供商 | 用途 | 获取 API Key | -| ------------ | --------------------------------------- | ------------------------------------------------------------ | -| `gemini` | LLM(Gemini 直连) | [aistudio.google.com](https://aistudio.google.com) | -| `zhipu` | LLM(智谱直连) | [bigmodel.cn](https://bigmodel.cn) | -| `volcengine` | LLM(火山引擎直连) | [volcengine.com](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| `openrouter` | LLM(推荐,可访问所有模型) | [openrouter.ai](https://openrouter.ai) | -| `anthropic` | LLM(Claude 直连) | [console.anthropic.com](https://console.anthropic.com) | -| `openai` | LLM(GPT 直连) | [platform.openai.com](https://platform.openai.com) | -| `deepseek` | LLM(DeepSeek 直连) | [platform.deepseek.com](https://platform.deepseek.com) | -| `qwen` | LLM(通义千问直连) | [dashscope.console.aliyun.com](https://dashscope.console.aliyun.com) | -| `groq` | LLM + **语音转录**(Whisper) | [console.groq.com](https://console.groq.com) | -| `cerebras` | LLM(Cerebras 直连) | [cerebras.ai](https://cerebras.ai) | -| `vivgrid` | LLM(Vivgrid 直连) | [vivgrid.com](https://vivgrid.com) | - -### 模型配置 (model_list) - -> **新特性:** PicoClaw 现在优先推荐显式 `provider` + 原生 `model` 的配置方式,例如 `"provider": "zhipu", "model": "glm-4.7"`。如果未设置 `provider`,旧的单字段 `provider/model` 写法仍然兼容。 - -这一设计同时支持**多 Agent**场景,灵活选择提供商: - -- **不同 Agent 使用不同提供商**:每个 Agent 可以使用独立的 LLM 提供商 -- **模型降级**:配置主模型和备用模型,提升可用性 -- **负载均衡**:将请求分发到多个端点 -- **集中管理**:在一处管理所有提供商配置 - -#### 所有支持的厂商 - -| 厂商 | `provider` 值 | 默认 API Base | 协议 | API Key | -| ----------------------- | ----------------- | --------------------------------------------------- | --------- | ---------------------------------------------------------------- | -| **OpenAI** | `openai` | `https://api.openai.com/v1` | OpenAI | [获取](https://platform.openai.com) | -| **Anthropic** | `anthropic` | `https://api.anthropic.com/v1` | Anthropic | [获取](https://console.anthropic.com) | -| **智谱 AI (GLM)** | `zhipu` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [获取](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) | -| **DeepSeek** | `deepseek` | `https://api.deepseek.com/v1` | OpenAI | [获取](https://platform.deepseek.com) | -| **Google Gemini** | `gemini` | `https://generativelanguage.googleapis.com/v1beta` | Gemini | [获取](https://aistudio.google.com/api-keys) | -| **Groq** | `groq` | `https://api.groq.com/openai/v1` | OpenAI | [获取](https://console.groq.com) | -| **Moonshot** | `moonshot` | `https://api.moonshot.cn/v1` | OpenAI | [获取](https://platform.moonshot.cn) | -| **通义千问 (Qwen)** | `qwen` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [获取](https://dashscope.console.aliyun.com) | -| **NVIDIA** | `nvidia` | `https://integrate.api.nvidia.com/v1` | OpenAI | [获取](https://build.nvidia.com) | -| **Ollama** | `ollama` | `http://localhost:11434/v1` | OpenAI | 本地(无需 Key) | -| **LM Studio** | `lmstudio` | `http://localhost:1234/v1` | OpenAI | 可选(本地默认无需密钥) | -| **OpenRouter** | `openrouter` | `https://openrouter.ai/api/v1` | OpenAI | [获取](https://openrouter.ai/keys) | -| **LiteLLM Proxy** | `litellm` | `http://localhost:4000/v1` | OpenAI | 你的 LiteLLM 代理 Key | -| **VLLM** | `vllm` | `http://localhost:8000/v1` | OpenAI | 本地 | -| **Cerebras** | `cerebras` | `https://api.cerebras.ai/v1` | OpenAI | [获取](https://cerebras.ai) | -| **火山引擎 (豆包)** | `volcengine` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [获取](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| **神算云** | `shengsuanyun` | `https://router.shengsuanyun.com/api/v1` | OpenAI | — | -| **BytePlus** | `byteplus` | `https://ark.ap-southeast.bytepluses.com/api/v3` | OpenAI | [获取](https://www.byteplus.com) | -| **Vivgrid** | `vivgrid` | `https://api.vivgrid.com/v1` | OpenAI | [获取](https://vivgrid.com) | -| **LongCat** | `longcat` | `https://api.longcat.chat/openai` | OpenAI | [获取](https://longcat.chat/platform) | -| **ModelScope (魔搭)** | `modelscope` | `https://api-inference.modelscope.cn/v1` | OpenAI | [获取](https://modelscope.cn/my/tokens) | -| **Antigravity** | `antigravity` | Google Cloud | Custom | 仅 OAuth | -| **GitHub Copilot** | `github-copilot` | `localhost:4321` | gRPC | — | - -#### 基础配置 - -```json -{ - "model_list": [ - { - "model_name": "ark-code-latest", - "provider": "volcengine", - "model": "ark-code-latest", - "api_keys": ["sk-your-api-key"] - }, - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_keys": ["sk-your-openai-key"] - }, - { - "model_name": "claude-sonnet-4.6", - "provider": "anthropic", - "model": "claude-sonnet-4.6", - "api_keys": ["sk-ant-your-key"] - }, - { - "model_name": "glm-4.7", - "provider": "zhipu", - "model": "glm-4.7", - "api_keys": ["your-zhipu-key"] - } - ], - "agents": { - "defaults": { - "model": "gpt-5.4" - } - } -} -``` - -解析规则: - -- 推荐显式写成 `"provider": "openai", "model": "gpt-5.4"`。 -- 如果设置了 `provider`,PicoClaw 会将 `model` 原样发送。 -- 如果未设置 `provider`,PicoClaw 会把 `model` 第一个 `/` 之前的字段当作 provider,并把第一个 `/` 之后的全部内容当作最终模型 ID。 -- 这意味着 `"model": "openrouter/openai/gpt-5.4"` 这样的兼容写法仍然可用,并会把 `openai/gpt-5.4` 发送给 OpenRouter。 - -#### 流式输出配置 - -Provider 流式输出采用双开关,默认关闭。只有当前 channel 的 `settings.streaming.enabled` 和当前模型条目的 `streaming.enabled` 都为 `true`,并且 provider 与 channel 都支持流式能力时,Agent 才会尝试流式请求;任一条件不满足时仍使用普通非流式请求。 - -不需要流式时请省略 `streaming` 配置块。省略表示关闭,不需要写 `"streaming": {"enabled": false}`。 - -开启示例: - -```json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_keys": ["sk-your-openai-key"], - "streaming": { - "enabled": true - } - } - ], - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "settings": { - "token": "YOUR_TELEGRAM_TOKEN", - "streaming": { - "enabled": true - } - } - } - } -} -``` - -| 字段 | 类型 | 默认值 | 说明 | -|------|------|--------|------| -| `channel_list..settings.streaming.enabled` | bool | `false` | 是否允许该 channel 尝试展示 provider 流式输出 | -| `channel_list..settings.streaming.throttle_seconds` | int | Telegram: `3` | 中间更新的最小时间间隔,最终内容不受此限制 | -| `channel_list..settings.streaming.min_growth_chars` | int | Telegram: `200` | 中间更新相比上次发送至少增长的字符数,最终内容不受此限制 | -| `model_list[].streaming.enabled` | bool | `false` | 是否允许该模型条目尝试 provider 流式请求 | - -Telegram 旧环境变量仍兼容:`PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`、`PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS`、`PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. - -失败处理保持保守:如果还没有任何可见 chunk 就失败,PicoClaw 会回退到普通 `Chat()` 路径重试一次;如果已经有 chunk 展示给用户,则不会再发送一条非流式最终答案,避免界面重复输出。 - -#### 各厂商配置示例 - -
-OpenAI - -```json -{ - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_keys": ["sk-..."] -} -``` - -
- -
-火山引擎(豆包) - -```json -{ - "model_name": "ark-code-latest", - "provider": "volcengine", - "model": "ark-code-latest", - "api_keys": ["sk-..."] -} -``` - -
- -
-智谱 AI (GLM) - -```json -{ - "model_name": "glm-4.7", - "provider": "zhipu", - "model": "glm-4.7", - "api_keys": ["your-key"] -} -``` - -
- -
-DeepSeek - -```json -{ - "model_name": "deepseek-chat", - "provider": "deepseek", - "model": "deepseek-chat", - "api_keys": ["sk-..."] -} -``` - -
- -
-Anthropic - -```json -{ - "model_name": "claude-sonnet-4.6", - "provider": "anthropic", - "model": "claude-sonnet-4.6", - "api_keys": ["sk-ant-your-key"] -} -``` - -> 运行 `picoclaw auth login --provider anthropic` 粘贴 API Token。 - -如需直连 Anthropic 原生接口(不兼容 OpenAI 格式的端点): - -```json -{ - "model_name": "claude-opus-4-6", - "provider": "anthropic-messages", - "model": "claude-opus-4-6", - "api_keys": ["sk-ant-your-key"], - "api_base": "https://api.anthropic.com" -} -``` - -> 当端点不支持 OpenAI 兼容格式(`/v1/chat/completions`),需要 Anthropic 原生 `/v1/messages` 时使用 `anthropic-messages`。 - -
- -
-Ollama(本地) - -```json -{ - "model_name": "llama3", - "provider": "ollama", - "model": "llama3" -} -``` - -
- -
-LM Studio(本地) - -```json -{ - "model_name": "lmstudio-local", - "provider": "lmstudio", - "model": "openai/gpt-oss-20b" -} -``` - -`api_base` 默认是 `http://localhost:1234/v1`。除非你在 LM Studio 侧启用了认证,否则不需要配置 API Key。 -显式设置 `provider` 后,PicoClaw 会把 `openai/gpt-oss-20b` 原样发送给 LM Studio。旧的兼容写法 `"model": "lmstudio/openai/gpt-oss-20b"` 在未设置 `provider` 时也会解析成相同的上游模型 ID。 - -
- -
-自定义代理 / LiteLLM - -```json -{ - "model_name": "my-custom-model", - "provider": "openai", - "model": "custom-model", - "api_base": "https://my-proxy.com/v1", - "api_keys": ["sk-..."] -} -``` - -显式设置 `provider` 后,PicoClaw 会将 `model` 原样发送。因此 `"provider": "litellm", "model": "lite-gpt4"` 会发送 `lite-gpt4`,而 `"provider": "litellm", "model": "openai/gpt-4o"` 会发送 `openai/gpt-4o`。旧的兼容写法 `litellm/lite-gpt4` 和 `litellm/openai/gpt-4o` 在未设置 `provider` 时也会得到相同结果。 - -
- -#### 负载均衡 - -为同一模型名称配置多个端点,PicoClaw 会自动轮询: - -```json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_base": "https://api1.example.com/v1", - "api_keys": ["sk-key1"] - }, - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_base": "https://api2.example.com/v1", - "api_keys": ["sk-key2"] - } - ] -} -``` - -#### 从旧版 `providers` 配置迁移 - -旧版 `providers` 配置**已废弃**,V2 中已移除。现有 V0/V1 配置会自动迁移。完整迁移指南见 [docs/migration/model-list-migration.md](../migration/model-list-migration.md)。 - -### Provider 架构 - -PicoClaw 按协议族路由提供商: - -- **OpenAI 兼容**:OpenRouter、Groq、智谱、vLLM 风格端点及大多数其他提供商。 -- **Gemini 原生**:Google Gemini 通过原生 `models/*:generateContent` 和 `models/*:streamGenerateContent` 端点接入。 -- **Anthropic**:Claude 原生 API 行为。 -- **Codex/OAuth**:OpenAI OAuth/Token 认证路由。 - -这使运行时保持轻量,同时让接入新的 OpenAI 兼容后端基本只需配置 `api_base` + `api_keys`。 - -
-智谱(旧版 providers 格式) - -```json -{ - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model": "glm-4.7", - "max_tokens": 8192, - "temperature": 0.7, - "max_tool_iterations": 20 - } - }, - "providers": { - "zhipu": { - "api_key": "Your API Key", - "api_base": "https://open.bigmodel.cn/api/paas/v4" - } - } -} -``` - -
- -
-完整配置示例 - -```json -{ - "agents": { - "defaults": { - "model_name": "claude-opus-4-5" - } - }, - "session": { - "dm_scope": "per-channel-peer", - "backlog_limit": 20 - }, - "providers": { - "openrouter": { - "api_key": "sk-or-v1-xxx" - }, - "groq": { - "api_key": "gsk_xxx" - } - }, - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "token": "123456:ABC...", - "allow_from": ["123456789"] - } - }, - "tools": { - "web": { - "duckduckgo": { - "enabled": true, - "max_results": 5 - } - } - }, - "heartbeat": { - "enabled": true, - "interval": 30 - } -} -``` - -
+当前 fork 仅保留 OpenAI(Responses / Chat Completions)和 Anthropic Messages。模型配置、流式输出、登录、兼容端点、多 Key 和 fallback 说明统一见[模型接入文档](providers.zh.md)。原版的厂商专用 provider 和 CLI 代理已移除。 ### 事件日志 diff --git a/docs/guides/providers.fr.md b/docs/guides/providers.fr.md index cb4a18d9..eec7d629 100644 --- a/docs/guides/providers.fr.md +++ b/docs/guides/providers.fr.md @@ -1,448 +1,5 @@ -# 🔌 Fournisseurs et Configuration des Modèles +# Model providers -> Retour au [README](../project/README.fr.md) +This fork now supports only OpenAI (Responses and Chat Completions) and Anthropic (Messages). The previous upstream provider catalog no longer applies. -### Fournisseurs - -> [!NOTE] -> Groq fournit la transcription vocale gratuite via Whisper. Si configuré, les messages audio de n'importe quel canal seront automatiquement transcrits au niveau de l'agent. - -| Provider | Purpose | Get API Key | -| ------------ | --------------------------------------- | ------------------------------------------------------------ | -| `gemini` | LLM (Gemini direct) | [aistudio.google.com](https://aistudio.google.com) | -| `zhipu` | LLM (Zhipu direct) | [bigmodel.cn](https://bigmodel.cn) | -| `volcengine` | LLM (Volcengine direct) | [volcengine.com](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| `openrouter` | LLM (recommended, access to all models) | [openrouter.ai](https://openrouter.ai) | -| `anthropic` | LLM (Claude direct) | [console.anthropic.com](https://console.anthropic.com) | -| `openai` | LLM (GPT direct) | [platform.openai.com](https://platform.openai.com) | -| `deepseek` | LLM (DeepSeek direct) | [platform.deepseek.com](https://platform.deepseek.com) | -| `qwen` | LLM (Qwen direct) | [dashscope.console.aliyun.com](https://dashscope.console.aliyun.com) | -| `groq` | LLM + **Voice transcription** (Whisper) | [console.groq.com](https://console.groq.com) | -| `cerebras` | LLM (Cerebras direct) | [cerebras.ai](https://cerebras.ai) | -| `vivgrid` | LLM (Vivgrid direct) | [vivgrid.com](https://vivgrid.com) | -| `moonshot` | LLM (Kimi/Moonshot direct) | [platform.moonshot.cn](https://platform.moonshot.cn) | -| `minimax` | LLM (Minimax direct) | [platform.minimaxi.com](https://platform.minimaxi.com) | -| `avian` | LLM (Avian direct) | [avian.io](https://avian.io) | -| `mistral` | LLM (Mistral direct) | [console.mistral.ai](https://console.mistral.ai) | -| `longcat` | LLM (Longcat direct) | [longcat.ai](https://longcat.ai) | -| `modelscope` | LLM (ModelScope direct) | [modelscope.cn](https://modelscope.cn) | - -### Configuration des Modèles (model_list) - -> **Nouveauté** PicoClaw utilise désormais une approche de configuration **centrée sur le modèle**. Spécifiez simplement le format `vendor/model` (par ex. `zhipu/glm-4.7`) pour ajouter de nouveaux fournisseurs — **aucune modification de code requise !** - -Cette conception permet également le **support multi-agents** avec une sélection flexible de fournisseurs : - -- **Différents agents, différents fournisseurs** : Chaque agent peut utiliser son propre fournisseur LLM -- **Modèles de repli** : Configurez des modèles principaux et de repli pour la résilience -- **Répartition de charge** : Distribuez les requêtes entre plusieurs endpoints -- **Configuration centralisée** : Gérez tous les fournisseurs en un seul endroit - -#### 📋 Tous les Vendors Supportés - -| Vendor | `model` Prefix | Default API Base | Protocol | API Key | -| ------------------- | ----------------- |-----------------------------------------------------| --------- | ---------------------------------------------------------------- | -| **OpenAI** | `openai/` | `https://api.openai.com/v1` | OpenAI | [Get Key](https://platform.openai.com) | -| **Anthropic** | `anthropic/` | `https://api.anthropic.com/v1` | Anthropic | [Get Key](https://console.anthropic.com) | -| **智谱 AI (GLM)** | `zhipu/` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [Get Key](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) | -| **DeepSeek** | `deepseek/` | `https://api.deepseek.com/v1` | OpenAI | [Get Key](https://platform.deepseek.com) | -| **Google Gemini** | `gemini/` | `https://generativelanguage.googleapis.com/v1beta` | Gemini | [Get Key](https://aistudio.google.com/api-keys) | -| **Groq** | `groq/` | `https://api.groq.com/openai/v1` | OpenAI | [Get Key](https://console.groq.com) | -| **Moonshot** | `moonshot/` | `https://api.moonshot.cn/v1` | OpenAI | [Get Key](https://platform.moonshot.cn) | -| **通义千问 (Qwen)** | `qwen/` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [Get Key](https://dashscope.console.aliyun.com) | -| **NVIDIA** | `nvidia/` | `https://integrate.api.nvidia.com/v1` | OpenAI | [Get Key](https://build.nvidia.com) | -| **Ollama** | `ollama/` | `http://localhost:11434/v1` | OpenAI | Local (no key needed) | -| **OpenRouter** | `openrouter/` | `https://openrouter.ai/api/v1` | OpenAI | [Get Key](https://openrouter.ai/keys) | -| **LiteLLM Proxy** | `litellm/` | `http://localhost:4000/v1` | OpenAI | Your LiteLLM proxy key | -| **VLLM** | `vllm/` | `http://localhost:8000/v1` | OpenAI | Local | -| **Cerebras** | `cerebras/` | `https://api.cerebras.ai/v1` | OpenAI | [Get Key](https://cerebras.ai) | -| **VolcEngine (Doubao)** | `volcengine/` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [Get Key](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| **神算云** | `shengsuanyun/` | `https://router.shengsuanyun.com/api/v1` | OpenAI | - | -| **BytePlus** | `byteplus/` | `https://ark.ap-southeast.bytepluses.com/api/v3` | OpenAI | [Get Key](https://www.byteplus.com) | -| **Vivgrid** | `vivgrid/` | `https://api.vivgrid.com/v1` | OpenAI | [Get Key](https://vivgrid.com) | -| **LongCat** | `longcat/` | `https://api.longcat.chat/openai` | OpenAI | [Get Key](https://longcat.chat/platform) | -| **ModelScope (魔搭)**| `modelscope/` | `https://api-inference.modelscope.cn/v1` | OpenAI | [Get Token](https://modelscope.cn/my/tokens) | -| **Antigravity** | `antigravity/` | Google Cloud | Custom | OAuth only | -| **GitHub Copilot** | `github-copilot/` | `localhost:4321` | gRPC | - | - -#### Configuration de Base - -```json -{ - "model_list": [ - { - "model_name": "ark-code-latest", - "model": "volcengine/ark-code-latest", - "api_keys": ["sk-your-api-key"] - }, - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_keys": ["sk-your-openai-key"] - }, - { - "model_name": "claude-sonnet-4.6", - "model": "anthropic/claude-sonnet-4.6", - "api_keys": ["sk-ant-your-key"] - }, - { - "model_name": "glm-4.7", - "model": "zhipu/glm-4.7", - "api_keys": ["your-zhipu-key"] - } - ], - "agents": { - "defaults": { - "model_name": "gpt-5.4" - } - } -} -``` - -#### Champs d'entrée `model_list` - -| Champ | Type | Requis | Description | -|-------|------|--------|-------------| -| `model_name` | string | Oui | Nom unique pour référencer ce modèle dans la config agent | -| `model` | string | Oui | Identifiant fournisseur/modèle (ex : `openai/gpt-5.4`, `azure/gpt-5.4`, `anthropic/claude-sonnet-4.6`) | -| `api_keys` | string[] | Oui* | Clé(s) API pour l'authentification. Plusieurs clés permettent la rotation par requête. Non requis pour les fournisseurs locaux (Ollama, LM Studio, VLLM) | -| `api_base` | string | Non | Remplace l'URL de base API par défaut | -| `proxy` | string | Non | URL du proxy HTTP pour cette entrée de modèle | -| `user_agent` | string | Non | En-tête `User-Agent` personnalisé pour les requêtes API (supporté par les providers compatibles OpenAI, Gemini, Anthropic et Azure) | -| `request_timeout` | int | Non | Délai d'expiration de la requête en secondes (la valeur par défaut varie selon le provider) | -| `max_tokens_field` | string | Non | Remplace le nom du champ max tokens dans le corps de la requête (ex : `max_completion_tokens` pour les modèles o1) | -| `thinking_level` | string | Non | Niveau de pensée étendue : `off`, `low`, `medium`, `high`, `xhigh` ou `adaptive` | -| `extra_body` | object | Non | Champs supplémentaires à injecter dans chaque corps de requête | -| `streaming.enabled` | bool | Non | Opt-in pour le streaming provider sur cette entrée de modèle. Par défaut `false`, et le channel actif doit aussi avoir `settings.streaming.enabled` à `true` | -| `rpm` | int | Non | Limite de requêtes par minute | -| `fallbacks` | string[] | Non | Noms des modèles de secours pour le basculement automatique | -| `enabled` | bool | Non | Activer ou désactiver cette entrée de modèle (par défaut : `true`) | - -Lorsque le streaming est désactivé, omettez le bloc `streaming`. Écrire `"streaming": {"enabled": false}` est optionnel et n'est pas nécessaire. - -#### Exemples par Vendor - -**OpenAI** - -```json -{ - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_keys": ["sk-..."] -} -``` - -**VolcEngine (Doubao)** - -```json -{ - "model_name": "ark-code-latest", - "model": "volcengine/ark-code-latest", - "api_keys": ["sk-..."] -} -``` - -**智谱 AI (GLM)** - -```json -{ - "model_name": "glm-4.7", - "model": "zhipu/glm-4.7", - "api_keys": ["your-key"] -} -``` - -**DeepSeek** - -```json -{ - "model_name": "deepseek-chat", - "model": "deepseek/deepseek-chat", - "api_keys": ["sk-..."] -} -``` - -**Anthropic (avec clé API)** - -```json -{ - "model_name": "claude-sonnet-4.6", - "model": "anthropic/claude-sonnet-4.6", - "api_keys": ["sk-ant-your-key"] -} -``` - -> Exécutez `picoclaw auth login --provider anthropic` pour coller votre token API. - -**API Anthropic Messages (format natif)** - -Pour l'accès direct à l'API Anthropic ou les endpoints personnalisés qui ne prennent en charge que le format de message natif d'Anthropic : - -```json -{ - "model_name": "claude-opus-4-6", - "model": "anthropic-messages/claude-opus-4-6", - "api_keys": ["sk-ant-your-key"], - "api_base": "https://api.anthropic.com" -} -``` - -> Utilisez le protocole `anthropic-messages` lorsque : -> - Vous utilisez des proxys tiers qui ne prennent en charge que l'endpoint natif `/v1/messages` d'Anthropic (pas le format compatible OpenAI `/v1/chat/completions`) -> - Vous vous connectez à des services comme MiniMax, Synthetic qui nécessitent le format de message natif d'Anthropic -> - Le protocole `anthropic` existant renvoie des erreurs 404 (indiquant que l'endpoint ne prend pas en charge le format compatible OpenAI) -> -> **Note :** Le protocole `anthropic` utilise le format compatible OpenAI (`/v1/chat/completions`), tandis que `anthropic-messages` utilise le format natif d'Anthropic (`/v1/messages`). Choisissez en fonction du format pris en charge par votre endpoint. - -**Ollama (local)** - -```json -{ - "model_name": "llama3", - "model": "ollama/llama3" -} -``` - -**Proxy/API Personnalisé** - -```json -{ - "model_name": "my-custom-model", - "model": "openai/custom-model", - "api_base": "https://my-proxy.com/v1", - "api_keys": ["sk-..."], - "user_agent": "MyApp/1.0", - "request_timeout": 300 -} -``` - -**LiteLLM Proxy** - -```json -{ - "model_name": "lite-gpt4", - "model": "litellm/lite-gpt4", - "api_base": "http://localhost:4000/v1", - "api_keys": ["sk-..."] -} -``` - -PicoClaw ne supprime que le préfixe externe `litellm/` avant d'envoyer la requête, donc les alias de proxy comme `litellm/lite-gpt4` envoient `lite-gpt4`, tandis que `litellm/openai/gpt-4o` envoie `openai/gpt-4o`. - -#### Répartition de Charge - -Configurez plusieurs endpoints pour le même nom de modèle — PicoClaw effectuera automatiquement un round-robin entre eux : - -```json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_base": "https://api1.example.com/v1", - "api_keys": ["sk-key1"] - }, - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_base": "https://api2.example.com/v1", - "api_keys": ["sk-key2"] - } - ] -} -``` - -#### Migration depuis l'Ancienne Configuration `providers` - -L'ancienne configuration `providers` est **dépréciée** et a été supprimée dans V2. Les configs V0/V1 existantes sont auto-migrées. - -**Ancienne configuration (dépréciée) :** - -```json -{ - "providers": { - "zhipu": { - "api_key": "your-key", - "api_base": "https://open.bigmodel.cn/api/paas/v4" - } - }, - "agents": { - "defaults": { - "provider": "zhipu", - "model": "glm-4.7" - } - } -} -``` - -**Nouvelle configuration (recommandée) :** - -```json -{ - "version": 3, - "model_list": [ - { - "model_name": "glm-4.7", - "model": "zhipu/glm-4.7", - "api_keys": ["your-key"] - } - ], - "agents": { - "defaults": { - "model_name": "glm-4.7" - } - } -} -``` - -Pour un guide de migration détaillé, voir [migration/model-list-migration.md](../migration/model-list-migration.md). - -### Architecture des Fournisseurs - -PicoClaw route les fournisseurs par famille de protocoles : - -- Protocole compatible OpenAI : OpenRouter, passerelles compatibles OpenAI, Groq, Zhipu et endpoints de type vLLM. -- Protocole Gemini natif : Google Gemini via les endpoints natifs `models/*:generateContent` et `models/*:streamGenerateContent`. -- Protocole Anthropic : Comportement natif de l'API Claude. -- Chemin Codex/OAuth : Route d'authentification OAuth/token OpenAI. - -Cela maintient le runtime léger tout en faisant des nouveaux backends compatibles OpenAI principalement une opération de configuration (`api_base` + `api_keys`). - -
-Zhipu - -**1. Obtenir la clé API et l'URL de base** - -* Obtenir la [clé API](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) - -**2. Configurer** - -```json -{ - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model_name": "glm-4.7", - "max_tokens": 8192, - "temperature": 0.7, - "max_tool_iterations": 20 - } - }, - "providers": { - "zhipu": { - "api_key": "Your API Key", - "api_base": "https://open.bigmodel.cn/api/paas/v4" - } - } -} -``` - -**3. Lancer** - -```bash -picoclaw agent -m "Hello" -``` - -
- -
-Exemple de configuration complète - -```json -{ - "agents": { - "defaults": { - "model_name": "anthropic/claude-opus-4-5" - } - }, - "session": { - "dm_scope": "per-channel-peer" - }, - "providers": { - "openrouter": { - "api_key": "sk-or-v1-xxx" - }, - "groq": { - "api_key": "gsk_xxx" - } - }, - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "token": "123456:ABC...", - "allow_from": ["123456789"] - }, - "feishu": { - "enabled": false, - "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "xxx", - "encrypt_key": "", - "verification_token": "", - "allow_from": [] - }, - "qq": { - "enabled": false, - "type": "qq", - "app_id": "", - "app_secret": "", - "allow_from": [] - } - }, - "tools": { - "web": { - "brave": { - "enabled": false, - "api_key": "BSA...", - "max_results": 5 - }, - "duckduckgo": { - "enabled": true, - "max_results": 5 - }, - "perplexity": { - "enabled": false, - "api_key": "", - "max_results": 5 - }, - "searxng": { - "enabled": false, - "base_url": "http://localhost:8888", - "max_results": 5 - } - }, - "cron": { - "exec_timeout_minutes": 5 - } - }, - "heartbeat": { - "enabled": true, - "interval": 30 - } -} -``` - -
- ---- - -## 📝 Comparaison des Clés API - -| Service | Pricing | Use Case | -| ---------------- | ------------------------ | ------------------------------------- | -| **OpenRouter** | Free: 200K tokens/month | Multiple models (Claude, GPT-4, etc.) | -| **Volcengine CodingPlan** | ¥9.9/first month | Best for Chinese users, multiple SOTA models (Doubao, DeepSeek, etc.) | -| **Zhipu** | Free: 200K tokens/month | Suitable for Chinese users | -| **Brave Search** | $5/1000 queries | Web search functionality | -| **SearXNG** | Free (self-hosted) | Privacy-focused metasearch (70+ engines) | -| **Groq** | Free tier available | Fast inference (Llama, Mixtral) | -| **Cerebras** | Free tier available | Fast inference (Llama, Qwen, etc.) | -| **LongCat** | Free: up to 5M tokens/day | Fast inference | -| **ModelScope** | Free: 2000 requests/day | Inference (Qwen, GLM, DeepSeek, etc.) | - ---- - -
- PicoClaw Meme -
+See the maintained [provider guide](providers.md) or [中文说明](providers.zh.md) for configuration, compatible endpoints, and login options. diff --git a/docs/guides/providers.ja.md b/docs/guides/providers.ja.md index 48d586af..eec7d629 100644 --- a/docs/guides/providers.ja.md +++ b/docs/guides/providers.ja.md @@ -1,460 +1,5 @@ -# 🔌 プロバイダーとモデル設定 +# Model providers -> [README](../project/README.ja.md) に戻る +This fork now supports only OpenAI (Responses and Chat Completions) and Anthropic (Messages). The previous upstream provider catalog no longer applies. -### プロバイダー - -> [!NOTE] -> Groq は Whisper による無料の音声文字起こしを提供しています。Groq を設定すると、任意のチャネルからの音声メッセージが Agent レベルで自動的にテキストに変換されます。 - -| プロバイダー | 用途 | API Key の取得 | -| -------------------- | ---------------------------- | -------------------------------------------------------------------- | -| `gemini` | LLM (Gemini 直接接続) | [aistudio.google.com](https://aistudio.google.com) | -| `zhipu` | LLM (Zhipu 直接接続) | [bigmodel.cn](https://bigmodel.cn) | -| `volcengine` | LLM (Volcengine 直接接続) | [volcengine.com](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| `openrouter` | LLM (推奨、全モデルアクセス可) | [openrouter.ai](https://openrouter.ai) | -| `anthropic` | LLM (Claude 直接接続) | [console.anthropic.com](https://console.anthropic.com) | -| `openai` | LLM (GPT 直接接続) | [platform.openai.com](https://platform.openai.com) | -| `deepseek` | LLM (DeepSeek 直接接続) | [platform.deepseek.com](https://platform.deepseek.com) | -| `qwen` | LLM (Qwen 直接接続) | [dashscope.console.aliyun.com](https://dashscope.console.aliyun.com) | -| `groq` | LLM + **音声文字起こし** (Whisper) | [console.groq.com](https://console.groq.com) | -| `cerebras` | LLM (Cerebras 直接接続) | [cerebras.ai](https://cerebras.ai) | -| `vivgrid` | LLM (Vivgrid 直接接続) | [vivgrid.com](https://vivgrid.com) | -| `moonshot` | LLM (Kimi/Moonshot 直接接続) | [platform.moonshot.cn](https://platform.moonshot.cn) | -| `minimax` | LLM (Minimax 直接接続) | [platform.minimaxi.com](https://platform.minimaxi.com) | -| `avian` | LLM (Avian 直接接続) | [avian.io](https://avian.io) | -| `mistral` | LLM (Mistral 直接接続) | [console.mistral.ai](https://console.mistral.ai) | -| `longcat` | LLM (Longcat 直接接続) | [longcat.ai](https://longcat.ai) | -| `modelscope` | LLM (ModelScope 直接接続) | [modelscope.cn](https://modelscope.cn) | - - -### モデル設定 (model_list) - -> **新機能!** PicoClaw は**モデル中心**の設定方式を採用しました。`ベンダー/モデル` 形式(例: `zhipu/glm-4.7`)を指定するだけで新しい provider を追加できます——**コード変更は一切不要です!** - -この設計は**マルチ Agent シナリオ**もサポートし、柔軟な Provider 選択を提供します: - -- **Agent ごとに異なる Provider**: 各 Agent が独自の LLM provider を使用可能 -- **モデルフォールバック**: プライマリモデルとフォールバックモデルを設定し、信頼性を向上 -- **ロードバランシング**: 複数の API エンドポイント間でリクエストを分散 -- **一元管理**: すべての provider を一箇所で管理 - -#### 📋 サポートされている全ベンダー - -| ベンダー | `model` プレフィックス | デフォルト API Base | プロトコル | API Key の取得 | -| ------------------- | --------------------- | --------------------------------------------------- | ---------- | ----------------------------------------------------------------- | -| **OpenAI** | `openai/` | `https://api.openai.com/v1` | OpenAI | [キーを取得](https://platform.openai.com) | -| **Anthropic** | `anthropic/` | `https://api.anthropic.com/v1` | Anthropic | [キーを取得](https://console.anthropic.com) | -| **智谱 AI (GLM)** | `zhipu/` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [キーを取得](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) | -| **DeepSeek** | `deepseek/` | `https://api.deepseek.com/v1` | OpenAI | [キーを取得](https://platform.deepseek.com) | -| **Google Gemini** | `gemini/` | `https://generativelanguage.googleapis.com/v1beta` | Gemini | [キーを取得](https://aistudio.google.com/api-keys) | -| **Groq** | `groq/` | `https://api.groq.com/openai/v1` | OpenAI | [キーを取得](https://console.groq.com) | -| **Moonshot** | `moonshot/` | `https://api.moonshot.cn/v1` | OpenAI | [キーを取得](https://platform.moonshot.cn) | -| **通義千問 (Qwen)** | `qwen/` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [キーを取得](https://dashscope.console.aliyun.com) | -| **NVIDIA** | `nvidia/` | `https://integrate.api.nvidia.com/v1` | OpenAI | [キーを取得](https://build.nvidia.com) | -| **Ollama** | `ollama/` | `http://localhost:11434/v1` | OpenAI | ローカル(キー不要) | -| **OpenRouter** | `openrouter/` | `https://openrouter.ai/api/v1` | OpenAI | [キーを取得](https://openrouter.ai/keys) | -| **LiteLLM Proxy** | `litellm/` | `http://localhost:4000/v1` | OpenAI | LiteLLM プロキシキー | -| **VLLM** | `vllm/` | `http://localhost:8000/v1` | OpenAI | ローカル | -| **Cerebras** | `cerebras/` | `https://api.cerebras.ai/v1` | OpenAI | [キーを取得](https://cerebras.ai) | -| **VolcEngine (Doubao)** | `volcengine/` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [キーを取得](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| **神算云** | `shengsuanyun/` | `https://router.shengsuanyun.com/api/v1` | OpenAI | - | -| **BytePlus** | `byteplus/` | `https://ark.ap-southeast.bytepluses.com/api/v3` | OpenAI | [キーを取得](https://www.byteplus.com) | -| **Vivgrid** | `vivgrid/` | `https://api.vivgrid.com/v1` | OpenAI | [キーを取得](https://vivgrid.com) | -| **LongCat** | `longcat/` | `https://api.longcat.chat/openai` | OpenAI | [キーを取得](https://longcat.chat/platform) | -| **ModelScope (魔搭)**| `modelscope/` | `https://api-inference.modelscope.cn/v1` | OpenAI | [トークンを取得](https://modelscope.cn/my/tokens) | -| **Antigravity** | `antigravity/` | Google Cloud | カスタム | OAuth のみ | -| **GitHub Copilot** | `github-copilot/` | `localhost:4321` | gRPC | - | - -#### 基本設定 - -```json -{ - "model_list": [ - { - "model_name": "ark-code-latest", - "model": "volcengine/ark-code-latest", - "api_keys": ["sk-your-api-key"] - }, - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_keys": ["sk-your-openai-key"] - }, - { - "model_name": "claude-sonnet-4.6", - "model": "anthropic/claude-sonnet-4.6", - "api_keys": ["sk-ant-your-key"] - }, - { - "model_name": "glm-4.7", - "model": "zhipu/glm-4.7", - "api_keys": ["your-zhipu-key"] - } - ], - "agents": { - "defaults": { - "model_name": "gpt-5.4" - } - } -} -``` - -#### `model_list` エントリフィールド - -| フィールド | 型 | 必須 | 説明 | -|-----------|------|------|------| -| `model_name` | string | はい | agent 設定でこのモデルを参照するための一意の名前 | -| `model` | string | はい | ベンダー/モデル識別子(例:`openai/gpt-5.4`、`azure/gpt-5.4`、`anthropic/claude-sonnet-4.6`) | -| `api_keys` | string[] | はい* | 認証キー。複数キーでリクエストごとのローテーションが可能。ローカル provider(Ollama、LM Studio、VLLM)には不要 | -| `api_base` | string | いいえ | デフォルトの API エンドポイント URL を上書き | -| `proxy` | string | いいえ | このモデルエントリの HTTP プロキシ URL | -| `user_agent` | string | いいえ | カスタム `User-Agent` リクエストヘッダー(OpenAI 互換、Gemini、Anthropic、Azure provider で対応) | -| `request_timeout` | int | いいえ | リクエストタイムアウト(秒)。デフォルト値は provider により異なる | -| `max_tokens_field` | string | いいえ | リクエストボディの max tokens フィールド名を上書き(例:o1 モデルでは `max_completion_tokens`) | -| `thinking_level` | string | いいえ | 拡張思考レベル:`off`、`low`、`medium`、`high`、`xhigh`、`adaptive` | -| `extra_body` | object | いいえ | 各リクエストボディに注入する追加フィールド | -| `streaming.enabled` | bool | いいえ | このモデルエントリで provider ストリーミングを試行するための opt-in。デフォルトは `false` で、アクティブな channel の `settings.streaming.enabled` も `true` である必要があります | -| `rpm` | int | いいえ | 1 分あたりのリクエストレート制限 | -| `fallbacks` | string[] | いいえ | 自動フェイルオーバーのフォールバックモデル名 | -| `enabled` | bool | いいえ | このモデルエントリを有効にするかどうか(デフォルト:`true`) | - -ストリーミングを無効にする場合は `streaming` ブロックを省略してください。`"streaming": {"enabled": false}` を書くことは任意であり、必須ではありません。 - -#### ベンダー別設定例 - -**OpenAI** - -```json -{ - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_keys": ["sk-..."] -} -``` - -**VolcEngine (Doubao)** - -```json -{ - "model_name": "ark-code-latest", - "model": "volcengine/ark-code-latest", - "api_keys": ["sk-..."] -} -``` - -**智谱 AI (GLM)** - -```json -{ - "model_name": "glm-4.7", - "model": "zhipu/glm-4.7", - "api_keys": ["your-key"] -} -``` - -**LiteLLM Proxy** - -```json -{ - "model_name": "lite-gpt4", - "model": "litellm/lite-gpt4", - "api_base": "http://localhost:4000/v1", - "api_keys": ["sk-..."] -} -``` - -**DeepSeek** - -```json -{ - "model_name": "deepseek-chat", - "model": "deepseek/deepseek-chat", - "api_keys": ["sk-..."] -} -``` - -**Anthropic (API キー使用)** - -```json -{ - "model_name": "claude-sonnet-4.6", - "model": "anthropic/claude-sonnet-4.6", - "api_keys": ["sk-ant-your-key"] -} -``` - -> `picoclaw auth login --provider anthropic` を実行して API トークンを設定してください。 - -**Anthropic Messages API(ネイティブ形式)** - -Anthropic API への直接アクセスや、Anthropic のネイティブメッセージ形式のみをサポートするカスタムエンドポイント向け: - -```json -{ - "model_name": "claude-opus-4-6", - "model": "anthropic-messages/claude-opus-4-6", - "api_keys": ["sk-ant-your-key"], - "api_base": "https://api.anthropic.com" -} -``` - -> `anthropic-messages` プロトコルを使用するケース: -> - Anthropic のネイティブ `/v1/messages` エンドポイントのみをサポートするサードパーティプロキシを使用する場合(OpenAI 互換の `/v1/chat/completions` 非対応) -> - MiniMax、Synthetic など Anthropic のネイティブメッセージ形式を必要とするサービスに接続する場合 -> - 既存の `anthropic` プロトコルが 404 エラーを返す場合(エンドポイントが OpenAI 互換形式をサポートしていないことを示す) -> -> **注意:** `anthropic` プロトコルは OpenAI 互換形式(`/v1/chat/completions`)を使用し、`anthropic-messages` は Anthropic のネイティブ形式(`/v1/messages`)を使用します。エンドポイントがサポートする形式に応じて選択してください。 - -**Ollama (ローカル)** - -```json -{ - "model_name": "llama3", - "model": "ollama/llama3" -} -``` - -**カスタムプロキシ/API** - -```json -{ - "model_name": "my-custom-model", - "model": "openai/custom-model", - "api_base": "https://my-proxy.com/v1", - "api_keys": ["sk-..."], - "user_agent": "MyApp/1.0", - "request_timeout": 300 -} -``` - -**LiteLLM Proxy** - -```json -{ - "model_name": "lite-gpt4", - "model": "litellm/lite-gpt4", - "api_base": "http://localhost:4000/v1", - "api_keys": ["sk-..."] -} -``` - -PicoClaw はリクエスト送信前に外側の `litellm/` プレフィックスのみを除去するため、`litellm/lite-gpt4` は `lite-gpt4` を送信し、`litellm/openai/gpt-4o` は `openai/gpt-4o` を送信します。 - -#### ロードバランシング - -同じモデル名に複数のエンドポイントを設定すると、PicoClaw が自動的にラウンドロビンで分散します: - -```json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_base": "https://api1.example.com/v1", - "api_keys": ["sk-key1"] - }, - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_base": "https://api2.example.com/v1", - "api_keys": ["sk-key2"] - } - ] -} -``` - -#### レガシー `providers` 設定からの移行 - -旧 `providers` 設定形式は**非推奨**となり、V2 で削除されました。既存の V0/V1 設定は自動的に移行されます。 - -**旧設定(非推奨):** - -```json -{ - "providers": { - "zhipu": { - "api_key": "your-key", - "api_base": "https://open.bigmodel.cn/api/paas/v4" - } - }, - "agents": { - "defaults": { - "provider": "zhipu", - "model": "glm-4.7" - } - } -} -``` - -**新設定(推奨):** - -```json -{ - "version": 3, - "model_list": [ - { - "model_name": "glm-4.7", - "model": "zhipu/glm-4.7", - "api_keys": ["your-key"] - } - ], - "agents": { - "defaults": { - "model_name": "glm-4.7" - } - } -} -``` - -詳細な移行ガイドは [docs/migration/model-list-migration.md](../migration/model-list-migration.md) を参照してください。 - -### Provider アーキテクチャ - -PicoClaw はプロトコルファミリーごとに Provider をルーティングします: - -- OpenAI 互換プロトコル:OpenRouter、OpenAI 互換ゲートウェイ、Groq、Zhipu、vLLM スタイルのエンドポイント。 -- Gemini ネイティブプロトコル:Google Gemini のネイティブ `models/*:generateContent` / `models/*:streamGenerateContent` エンドポイント。 -- Anthropic プロトコル:Claude ネイティブ API 動作。 -- Codex/OAuth パス:OpenAI OAuth/Token 認証ルート。 - -これによりランタイムを軽量に保ちつつ、新しい OpenAI 互換バックエンドの追加をほぼ設定操作(`api_base` + `api_keys`)のみで実現しています。 - -
-Zhipu 設定例 - -**1. API key と base URL を取得** - -- [API key](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) を取得 - -**2. 設定** - -```json -{ - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model_name": "glm-4.7", - "max_tokens": 8192, - "temperature": 0.7, - "max_tool_iterations": 20 - } - }, - "providers": { - "zhipu": { - "api_key": "Your API Key", - "api_base": "https://open.bigmodel.cn/api/paas/v4" - } - } -} -``` - -**3. 実行** - -```bash -picoclaw agent -m "こんにちは" -``` - -
- -
-完全な設定例 - -```json -{ - "agents": { - "defaults": { - "model_name": "anthropic/claude-opus-4-5" - } - }, - "session": { - "dm_scope": "per-channel-peer" - }, - "providers": { - "openrouter": { - "api_key": "sk-or-v1-xxx" - }, - "groq": { - "api_key": "gsk_xxx" - } - }, - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "token": "123456:ABC...", - "allow_from": ["123456789"] - }, - "feishu": { - "enabled": false, - "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "xxx", - "encrypt_key": "", - "verification_token": "", - "allow_from": [] - }, - "qq": { - "enabled": false, - "type": "qq", - "app_id": "", - "app_secret": "", - "allow_from": [] - } - }, - "tools": { - "web": { - "brave": { - "enabled": false, - "api_key": "BSA...", - "max_results": 5 - }, - "duckduckgo": { - "enabled": true, - "max_results": 5 - }, - "perplexity": { - "enabled": false, - "api_key": "", - "max_results": 5 - }, - "searxng": { - "enabled": false, - "base_url": "http://localhost:8888", - "max_results": 5 - } - }, - "cron": { - "exec_timeout_minutes": 5 - } - }, - "heartbeat": { - "enabled": true, - "interval": 30 - } -} -``` - -
- ---- - -## 📝 API Key 比較表 - -| サービス | Pricing | ユースケース | -| ---------------- | ------------------------ | ------------------------------------- | -| **OpenRouter** | Free: 200K tokens/month | マルチモデル (Claude, GPT-4 など) | -| **Volcengine CodingPlan** | ¥9.9/first month | 中国ユーザー向け、複数の SOTA モデル (Doubao, DeepSeek など) | -| **Zhipu** | Free: 200K tokens/month | 中国ユーザー向け | -| **Brave Search** | $5/1000 queries | Web 検索機能 | -| **SearXNG** | Free (self-hosted) | プライバシー重視のメタ検索 (70+ engines) | -| **Groq** | Free tier available | 高速推論 (Llama, Mixtral) | -| **Cerebras** | Free tier available | 高速推論 (Llama, Qwen など) | -| **LongCat** | Free: up to 5M tokens/day | 高速推論 | -| **ModelScope** | Free: 2000 requests/day | 推論 (Qwen, GLM, DeepSeek など) | - ---- - -
- PicoClaw Meme -
+See the maintained [provider guide](providers.md) or [中文说明](providers.zh.md) for configuration, compatible endpoints, and login options. diff --git a/docs/guides/providers.md b/docs/guides/providers.md index b699b41c..5da87a9d 100644 --- a/docs/guides/providers.md +++ b/docs/guides/providers.md @@ -1,686 +1,47 @@ -# 🔌 Providers & Model Configuration +# Model providers -> Back to [README](../README.md) - -### Providers - -> [!NOTE] -> Voice transcription can use a configured multimodal model via `voice.model_name`. Groq Whisper remains available as a fallback when no voice model is configured. - -| Provider | Purpose | Get API Key | -| ------------ | --------------------------------------- | ------------------------------------------------------------ | -| `gemini` | LLM (Gemini direct) | [aistudio.google.com](https://aistudio.google.com) | -| `zhipu` | LLM (Zhipu direct) | [bigmodel.cn](https://bigmodel.cn) | -| `zai-coding` | LLM (Z.AI Coding Plan) | [z.ai](https://z.ai/manage-apikey/apikey-list) | -| `volcengine` | LLM(Volcengine direct) | [volcengine.com](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| `openrouter` | LLM (recommended, access to all models) | [openrouter.ai](https://openrouter.ai) | -| `anthropic` | LLM (Claude direct) | [console.anthropic.com](https://console.anthropic.com) | -| `openai` | LLM (GPT direct) | [platform.openai.com](https://platform.openai.com) | -| `venice` | LLM (Venice AI direct) | [venice.ai](https://venice.ai) | -| `nearai` | LLM (NEAR AI Cloud TEE inference) | [near.ai](https://near.ai) | -| `deepseek` | LLM (DeepSeek direct) | [platform.deepseek.com](https://platform.deepseek.com) | -| `qwen` | LLM (Qwen direct) | [dashscope.console.aliyun.com](https://dashscope.console.aliyun.com) | -| `groq` | LLM + **Voice transcription** (Whisper) | [console.groq.com](https://console.groq.com) | -| `cerebras` | LLM (Cerebras direct) | [cerebras.ai](https://cerebras.ai) | -| `vivgrid` | LLM (Vivgrid direct) | [vivgrid.com](https://vivgrid.com) | -| `nvidia` | LLM (NVIDIA NIM) | [build.nvidia.com](https://build.nvidia.com) | -| `moonshot` | LLM (Kimi/Moonshot direct) | [platform.moonshot.cn](https://platform.moonshot.cn) | -| `minimax` | LLM (Minimax direct) | [platform.minimaxi.com](https://platform.minimaxi.com) | -| `avian` | LLM (Avian direct) | [avian.io](https://avian.io) | -| `mistral` | LLM (Mistral direct) | [console.mistral.ai](https://console.mistral.ai) | -| `longcat` | LLM (Longcat direct) | [longcat.ai](https://longcat.ai) | -| `modelscope` | LLM (ModelScope direct) | [modelscope.cn](https://modelscope.cn) | -| `mimo` | LLM (Xiaomi MiMo direct) | [platform.xiaomimimo.com](https://platform.xiaomimimo.com) | - -### Model Configuration (model_list) - -> **What's New?** PicoClaw now prefers explicit `provider` + native `model` configuration (for example `"provider": "zhipu", "model": "glm-4.7"`). The legacy single-field `provider/model` form remains supported for compatibility when `provider` is omitted. - -For agent dispatch and light-model routing examples, see the [Routing Guide](routing-guide.md). - -This design also enables **multi-agent support** with flexible provider selection: - -- **Different agents, different providers**: Each agent can use its own LLM provider -- **Model fallbacks**: Configure primary and fallback models for resilience -- **Load balancing**: Distribute requests across multiple endpoints -- **Centralized configuration**: Manage all providers in one place - -#### 📋 All Supported Vendors - -| Vendor | `provider` Value | Default API Base | Protocol | API Key | -| ------------------- | ----------------- |-----------------------------------------------------| --------- | ---------------------------------------------------------------- | -| **OpenAI** | `openai` | `https://api.openai.com/v1` | OpenAI | [Get Key](https://platform.openai.com) | -| **Venice AI** | `venice` | `https://api.venice.ai/api/v1` | OpenAI | [Get Key](https://venice.ai) | -| **NEAR AI Cloud** | `nearai` | `https://cloud-api.near.ai/v1` | OpenAI | [Get Key](https://near.ai) | -| **Anthropic** | `anthropic` | `https://api.anthropic.com/v1` | Anthropic | [Get Key](https://console.anthropic.com) | -| **智谱 AI (GLM)** | `zhipu` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [Get Key](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) | -| **Z.AI Coding Plan** | `openai` | `https://api.z.ai/api/coding/paas/v4` | OpenAI | [Get Key](https://z.ai/manage-apikey/apikey-list) | -| **DeepSeek** | `deepseek` | `https://api.deepseek.com/v1` | OpenAI | [Get Key](https://platform.deepseek.com) | -| **Google Gemini** | `gemini` | `https://generativelanguage.googleapis.com/v1beta` | Gemini | [Get Key](https://aistudio.google.com/api-keys) | -| **Groq** | `groq` | `https://api.groq.com/openai/v1` | OpenAI | [Get Key](https://console.groq.com) | -| **Moonshot** | `moonshot` | `https://api.moonshot.cn/v1` | OpenAI | [Get Key](https://platform.moonshot.cn) | -| **通义千问 (Qwen)** | `qwen` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [Get Key](https://dashscope.console.aliyun.com) | -| **NVIDIA** | `nvidia` | `https://integrate.api.nvidia.com/v1` | OpenAI | [Get Key](https://build.nvidia.com) | -| **Ollama** | `ollama` | `http://localhost:11434/v1` | OpenAI | Local (no key needed) | -| **LM Studio** | `lmstudio` | `http://localhost:1234/v1` | OpenAI | Optional (local default: no key) | -| **OpenRouter** | `openrouter` | `https://openrouter.ai/api/v1` | OpenAI | [Get Key](https://openrouter.ai/keys) | -| **LiteLLM Proxy** | `litellm` | `http://localhost:4000/v1` | OpenAI | Your LiteLLM proxy key | -| **VLLM** | `vllm` | `http://localhost:8000/v1` | OpenAI | Local | -| **Cerebras** | `cerebras` | `https://api.cerebras.ai/v1` | OpenAI | [Get Key](https://cerebras.ai) | -| **VolcEngine (Doubao)** | `volcengine` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [Get Key](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| **神算云** | `shengsuanyun` | `https://router.shengsuanyun.com/api/v1` | OpenAI | - | -| **BytePlus** | `byteplus` | `https://ark.ap-southeast.bytepluses.com/api/v3` | OpenAI | [Get Key](https://www.byteplus.com) | -| **Vivgrid** | `vivgrid` | `https://api.vivgrid.com/v1` | OpenAI | [Get Key](https://vivgrid.com) | -| **LongCat** | `longcat` | `https://api.longcat.chat/openai` | OpenAI | [Get Key](https://longcat.chat/platform) | -| **ModelScope (魔搭)**| `modelscope` | `https://api-inference.modelscope.cn/v1` | OpenAI | [Get Token](https://modelscope.cn/my/tokens) | -| **Xiaomi MiMo** | `mimo` | `https://api.xiaomimimo.com/v1` | OpenAI | [Get Key](https://platform.xiaomimimo.com) | -| **Azure OpenAI** | `azure` | `https://{resource}.openai.azure.com` | Azure | [Get Key](https://portal.azure.com) | -| **Antigravity** | `antigravity` | Google Cloud | Custom | OAuth only | -| **GitHub Copilot** | `github-copilot` | `localhost:4321` | gRPC | - | - -#### Basic Configuration +This fork supports two model protocols: **OpenAI** and **Anthropic**. OpenAI supports Responses, Chat Completions, and streaming. Anthropic uses its native Messages API with tool calls and thinking controls. ```json { + "version": 3, + "agents": {"defaults": {"model_name": "main"}}, "model_list": [ { - "model_name": "ark-code-latest", - "provider": "volcengine", - "model": "ark-code-latest", - "api_keys": ["sk-your-api-key"] - }, - { - "model_name": "gpt-5.4", + "model_name": "main", "provider": "openai", "model": "gpt-5.4", - "api_keys": ["sk-your-openai-key"] + "api_base": "https://api.openai.com/v1", + "api_keys": ["YOUR_OPENAI_API_KEY"] }, { - "model_name": "claude-sonnet-4.6", + "model_name": "claude", "provider": "anthropic", - "model": "claude-sonnet-4.6", - "api_keys": ["sk-ant-your-key"] - }, - { - "model_name": "glm-4.7", - "provider": "zhipu", - "model": "glm-4.7", - "api_keys": ["your-zhipu-key"] - } - ], - "agents": { - "defaults": { - "model_name": "gpt-5.4" - } - } -} -``` - -#### `model_list` Entry Fields - -| Field | Type | Required | Description | -|-------|------|----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `model_name` | string | Yes | Unique name used to reference this model in agent config | -| `provider` | string | No | Preferred provider identifier. When present, PicoClaw sends `model` unchanged to that provider | -| `model` | string | Yes | Native model ID when `provider` is set. If `provider` is omitted, the legacy `provider/model` form is still supported | -| `api_keys` | string[] | Yes* | API key(s) for authentication. Multiple keys enable per-request rotation. Not required for local providers (Ollama, LM Studio, VLLM) | -| `api_base` | string | No | Override the default API endpoint URL | -| `proxy` | string | No | HTTP proxy URL for this model entry | -| `user_agent` | string | No | Custom `User-Agent` header sent with API requests (supported by OpenAI-compatible, Gemini, Anthropic, and Azure providers) | -| `request_timeout` | int | No | Request timeout in seconds (default varies by provider) | -| `max_tokens_field` | string | No | Override the max tokens field name in request body (e.g., `max_completion_tokens` for o1 models) | -| `thinking_level` | string | No | Extended thinking level: `off`, `low`, `medium`, `high`, `xhigh`, or `adaptive` | -| `tool_schema_transform` | string | No | Optional compatibility transform for tool parameter schemas. Default: disabled. Supported values: `simple`. | -| `extra_body` | object | No | Additional fields to inject into every request body | -| `custom_headers` | object | No | Additional HTTP headers to inject into every request (e.g., `{"X-Source":"coding-plan"}`). If a key matches a built-in header, the custom value overrides the built-in one (e.g., `Authorization`, `User-Agent`, `Content-Type`, `Accept`). | -| `streaming.enabled` | bool | No | Opt-in for provider streaming on this model entry. Defaults to `false` and also requires the active channel's `settings.streaming.enabled` to be `true`. | -| `rpm` | int | No | Per-minute request rate limit | -| `fallbacks` | string[] | No | Fallback model names for automatic failover | -| `enabled` | bool | No | Whether this model entry is active (default: `true`) | - -When streaming is disabled, omit the `streaming` block. Writing `"streaming": {"enabled": false}` is optional and not needed in generated or hand-written config. - -`extra_body` is especially useful for model-specific TTS fields on OpenAI-compatible -speech routes, for example custom `voice` names or `response_format: "mp3"`. - -#### Tool Schema Compatibility - -By default, PicoClaw now forwards tool JSON Schemas unchanged. - -Some providers reject advanced JSON Schema features such as `$ref`, `$defs`, `anyOf`, `oneOf`, `allOf`, `pattern`, or numeric/string constraints inside tool declarations. For those models, you can opt into a compatibility transform per model entry with `tool_schema_transform`. - -Use `simple` when the upstream provider expects the conservative style function schema subset: - -```json -{ - "model_name": "gemini-2.5-flash-safe-tools", - "provider": "gemini", - "model": "gemini-2.5-flash", - "api_keys": ["your-gemini-key"], - "tool_schema_transform": "simple" -} -``` - -Notes: - -- Default behavior is disabled. If you omit `tool_schema_transform`, PicoClaw sends the original tool schema. -- The setting is per model entry, so you can enable it only for the providers that need it. - -#### Provider / Model Resolution - -PicoClaw resolves `provider` and the runtime model ID using these rules: - -- If `provider` is set, `model` is used as-is. -- If `provider` is omitted, PicoClaw treats the first `/` segment in `model` as the provider and everything after that first `/` as the runtime model ID. - -Examples: - -| Config | Resolved Provider | Model Sent Upstream | -| --- | --- | --- | -| `"provider": "openai", "model": "gpt-5.4"` | `openai` | `gpt-5.4` | -| `"model": "openai/gpt-5.4"` | `openai` | `gpt-5.4` | -| `"provider": "openrouter", "model": "openai/gpt-5.4"` | `openrouter` | `openai/gpt-5.4` | -| `"model": "openrouter/openai/gpt-5.4"` | `openrouter` | `openai/gpt-5.4` | - -#### Voice Transcription - -You can configure a dedicated model for audio transcription with `voice.model_name`. This lets you reuse existing multimodal providers that support audio input instead of relying only on Groq. - -If `voice.model_name` is not configured, PicoClaw will continue to fall back to Groq transcription when a Groq API key is available. - -```json -{ - "model_list": [ - { - "model_name": "voice-gemini", - "provider": "gemini", - "model": "gemini-2.5-flash", - "api_keys": ["your-gemini-key"] - } - ], - "voice": { - "model_name": "voice-gemini", - "echo_transcription": false - }, - "providers": { - "groq": { - "api_key": "gsk_xxx" - } - } -} -``` - -#### Voice Synthesis - -You can configure a dedicated text-to-speech model with `voice.tts_model_name`. -When the provider needs model-specific TTS request fields, put them in -`model_list[].extra_body`. - -Example with OpenRouter `microsoft/mai-voice-2`: - -```json -{ - "model_list": [ - { - "model_name": "mai-voice-2", - "provider": "openrouter", - "model": "microsoft/mai-voice-2", - "api_base": "https://openrouter.ai/api/v1", - "extra_body": { - "voice": "en-US-Harper:MAI-Voice-2", - "response_format": "mp3" - }, - "api_keys": ["sk-or-your-openrouter-key"] - } - ], - "voice": { - "tts_model_name": "mai-voice-2" - } -} -``` - -Notes that matter: - -- PicoClaw still uses the OpenAI-compatible `/audio/speech` route for this setup. -- The default TTS request uses `voice: alloy` and `response_format: opus`. -- Override those defaults with `extra_body` when your selected TTS model requires different values. - -#### Vendor-Specific Examples - -**OpenAI** - -```json -{ - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_keys": ["sk-..."], - "thinking_level": "high" -} -``` - -For OpenAI Responses models that support reasoning, `thinking_level` maps to `reasoning.effort`: `off` becomes `none`, `low`, `medium`, `high`, and `xhigh` pass through, and `adaptive` uses the model default. Supported levels vary by model. PicoClaw omits its default `temperature` when reasoning is enabled. - -**NEAR AI Cloud** - -```json -{ - "model_name": "nearai-glm", - "provider": "nearai", - "model": "zai-org/GLM-5.1-FP8", - "api_keys": ["your-nearai-api-key"] -} -``` - -**VolcEngine (Doubao)** - -```json -{ - "model_name": "ark-code-latest", - "provider": "volcengine", - "model": "ark-code-latest", - "api_keys": ["sk-..."] -} -``` - -**智谱 AI (GLM)** - -```json -{ - "model_name": "glm-4.7", - "provider": "zhipu", - "model": "glm-4.7", - "api_keys": ["your-key"] -} -``` - -**Z.AI Coding Plan (GLM)** -> Z.AI and 智谱 AI are two brands of the same provider. For the Z.AI Coding Plan use the `openai` model key and the api base as follows, rather than the zhipu config -```json -{ - "model_name": "glm-4.7", - "provider": "openai", - "model": "glm-4.7", - "api_keys": ["your-z.ai-key"], - "api_base": "https://api.z.ai/api/coding/paas/v4" -} -``` - -**DeepSeek** - -```json -{ - "model_name": "deepseek-chat", - "provider": "deepseek", - "model": "deepseek-chat", - "api_keys": ["sk-..."] -} -``` - -**Anthropic (with API key)** - -```json -{ - "model_name": "claude-sonnet-4.6", - "provider": "anthropic", - "model": "claude-sonnet-4.6", - "api_keys": ["sk-ant-your-key"] -} -``` - -> Run `picoclaw auth login --provider anthropic` to paste your API token. - -**Anthropic Messages API (native format)** - -For direct Anthropic API access or custom endpoints that only support Anthropic's native message format: - -```json -{ - "model_name": "claude-opus-4-6", - "provider": "anthropic-messages", - "model": "claude-opus-4-6", - "api_keys": ["sk-ant-your-key"], - "api_base": "https://api.anthropic.com" -} -``` - -> Use `anthropic-messages` protocol when: -> - Using third-party proxies that only support Anthropic's native `/v1/messages` endpoint (not OpenAI-compatible `/v1/chat/completions`) -> - Connecting to services like MiniMax, Synthetic that require Anthropic's native message format -> - The existing `anthropic` protocol returns 404 errors (indicating the endpoint doesn't support OpenAI-compatible format) -> -> **Note:** The `anthropic` protocol uses OpenAI-compatible format (`/v1/chat/completions`), while `anthropic-messages` uses Anthropic's native format (`/v1/messages`). Choose based on your endpoint's supported format. - -**Ollama (local)** - -```json -{ - "model_name": "llama3", - "provider": "ollama", - "model": "llama3" -} -``` - -**LM Studio (local)** - -```json -{ - "model_name": "lmstudio-local", - "provider": "lmstudio", - "model": "openai/gpt-oss-20b" -} -``` - -`api_base` defaults to `http://localhost:1234/v1`. API key is optional unless your LM Studio server enables authentication.
-With explicit `provider`, PicoClaw sends `openai/gpt-oss-20b` unchanged to the LM Studio server. The legacy compatibility form `"model": "lmstudio/openai/gpt-oss-20b"` still resolves to the same upstream model ID when `provider` is omitted. - -**Custom Proxy/API** - -```json -{ - "model_name": "my-custom-model", - "provider": "openai", - "model": "custom-model", - "api_base": "https://my-proxy.com/v1", - "api_keys": ["sk-..."], - "user_agent": "MyApp/1.0", - "request_timeout": 300 -} -``` - -**LiteLLM Proxy** - -```json -{ - "model_name": "lite-gpt4", - "provider": "litellm", - "model": "lite-gpt4", - "api_base": "http://localhost:4000/v1", - "api_keys": ["sk-..."] -} -``` - -With explicit `provider`, PicoClaw sends `model` unchanged. That means `"provider": "litellm", "model": "lite-gpt4"` sends `lite-gpt4`, while `"provider": "litellm", "model": "openai/gpt-4o"` sends `openai/gpt-4o`. The legacy compatibility forms `litellm/lite-gpt4` and `litellm/openai/gpt-4o` still resolve the same way when `provider` is omitted. - -**Z.AI Coding Plan** - -If the standard Zhipu endpoint (`https://open.bigmodel.cn/api/paas/v4`) returns 429 (code 1113: insufficient balance), try using the Z.AI Coding Plan endpoint instead: - -```json -{ - "model_name": "glm-4.7", - "provider": "openai", - "model": "glm-4.7", - "api_keys": ["your-zhipu-api-key"], - "api_base": "https://api.z.ai/api/coding/paas/v4" -} -``` - -**Note:** The Z.AI Coding Plan endpoint and standard Zhipu endpoint use the same API key format but have separate billing. If you encounter 429 errors with the standard Zhipu endpoint, the Z.AI Coding Plan endpoint may have available balance. - -#### Load Balancing - -Configure multiple endpoints for the same model name—PicoClaw will automatically round-robin between them: - -```json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_base": "https://api1.example.com/v1", - "api_keys": ["sk-key1"] - }, - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_base": "https://api2.example.com/v1", - "api_keys": ["sk-key2"] + "model": "claude-sonnet-4-6", + "api_base": "https://api.anthropic.com/v1", + "api_keys": ["YOUR_ANTHROPIC_API_KEY"] } ] } ``` -#### Automatic Model Failover (Cascade) +With an explicit `provider`, use the remote model ID, including any vendor namespace. Without it, `openai/` and `anthropic/` prefixes remain supported; bare IDs default to OpenAI. `gpt`, `claude`, and the legacy `anthropic-messages` spelling remain aliases. -PicoClaw already supports automatic failover when you configure `primary` + `fallbacks` in the agent model settings. -The runtime fallback chain retries the next candidate for retriable failures such as HTTP `429`, quota/rate-limit errors, and timeout errors. -It also applies cooldown tracking per candidate to avoid immediately retrying a recently failed target. +OpenAI's official endpoint uses Responses first. Custom endpoints use Responses for GPT models except `gpt-oss`, with fallback to Chat Completions when Responses is unsupported. Other compatible models use Chat Completions. Authentication and rate-limit failures do not trigger arbitrary endpoint fallback. -```json -{ - "model_list": [ - { - "model_name": "qwen-main", - "provider": "openai", - "model": "qwen3.5:cloud", - "api_base": "https://api.example.com/v1", - "api_keys": ["sk-main"] - }, - { - "model_name": "deepseek-backup", - "provider": "deepseek", - "model": "deepseek-chat", - "api_keys": ["sk-backup-1"] - }, - { - "model_name": "gemini-backup", - "provider": "gemini", - "model": "gemini-2.5-flash", - "api_keys": ["sk-backup-2"] - } - ], - "agents": { - "defaults": { - "model_name": "qwen-main", - "model_fallbacks": ["deepseek-backup", "gemini-backup"] - } - } -} -``` +For third-party compatible services, choose `openai` or `anthropic` and specify `api_base` and the remote `model`. Named vendor presets, native Gemini, Azure, Bedrock, Antigravity, Copilot, and CLI proxies have been removed. Existing named-provider configurations require an explicit supported protocol and endpoint; incompatible APIs cannot be migrated by renaming the provider alone. -If you use key-level failover for the same model, PicoClaw can chain through additional key-backed candidates before moving to cross-model backups. +HTTP proxy, request timeout, custom headers, extra body fields, user agent, thinking, schema transforms, multiple models/keys, rate limits, and fallback remain available. Both protocols support the `streaming` configuration. Anthropic login tokens also retain their internal streaming request handling. Speech-only ASR/TTS services keep separate selection logic and are not chat providers. -#### Migration from Legacy `providers` Config - -The old `providers` configuration is **deprecated** and has been removed in V2. Existing V0/V1 configs are auto-migrated. - -**Old Config (deprecated):** - -```json -{ - "providers": { - "zhipu": { - "api_key": "your-key", - "api_base": "https://open.bigmodel.cn/api/paas/v4" - } - }, - "agents": { - "defaults": { - "provider": "zhipu", - "model": "glm-4.7" - } - } -} -``` - -**New Config (recommended):** - -```json -{ - "version": 3, - "model_list": [ - { - "model_name": "glm-4.7", - "provider": "zhipu", - "model": "glm-4.7", - "api_keys": ["your-key"] - } - ], - "agents": { - "defaults": { - "model_name": "glm-4.7" - } - } -} -``` - -For detailed migration guide, see [migration/model-list-migration.md](../migration/model-list-migration.md). - -### Provider Architecture - -PicoClaw routes providers by protocol family: - -- OpenAI-compatible protocol: OpenRouter, OpenAI-compatible gateways, Groq, Zhipu, and vLLM-style endpoints. -- Gemini native protocol: Google Gemini via the native `models/*:generateContent` and `models/*:streamGenerateContent` endpoints. -- Anthropic protocol: Claude-native API behavior. -- Codex/OAuth path: OpenAI OAuth/token authentication route. - -This keeps the runtime lightweight while making new OpenAI-compatible backends mostly a config operation (`api_base` + `api_keys`). - -
-Zhipu - -**1. Get API key and base URL** - -* Get [API key](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) - -**2. Configure** - -```json -{ - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model_name": "glm-4.7", - "max_tokens": 8192, - "temperature": 0.7, - "max_tool_iterations": 20 - } - }, - "providers": { - "zhipu": { - "api_key": "Your API Key", - "api_base": "https://open.bigmodel.cn/api/paas/v4" - } - } -} -``` - -**3. Run** +OpenAI OAuth and Anthropic setup-token login remain available: ```bash -picoclaw agent -m "Hello" +picoclaw auth login --provider openai +picoclaw auth login --provider openai --device-code +picoclaw auth login --provider anthropic --setup-token +picoclaw auth status ``` -
+Use `auth_method: "oauth"` or `"token"` to select stored login credentials. API keys are the usual choice for custom endpoints. Weixin and WeCom channel login remain available. Antigravity login and its `auth models` command have been removed. -
-Full config example - -```json -{ - "agents": { - "defaults": { - "model_name": "claude-opus-4-5" - } - }, - "session": { - "dm_scope": "per-channel-peer" - }, - "providers": { - "openrouter": { - "api_key": "sk-or-v1-xxx" - }, - "groq": { - "api_key": "gsk_xxx" - } - }, - "voice": { - "model_name": "voice-gemini", - "echo_transcription": false - }, - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "token": "123456:ABC...", - "allow_from": ["123456789"] - }, - "feishu": { - "enabled": false, - "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "xxx", - "encrypt_key": "", - "verification_token": "", - "allow_from": [] - }, - "qq": { - "enabled": false, - "type": "qq", - "app_id": "", - "app_secret": "", - "allow_from": [] - } - }, - "tools": { - "web": { - "brave": { - "enabled": false, - "api_key": "BSA...", - "max_results": 5 - }, - "duckduckgo": { - "enabled": true, - "max_results": 5 - }, - "perplexity": { - "enabled": false, - "api_key": "", - "max_results": 5 - }, - "searxng": { - "enabled": false, - "base_url": "http://localhost:8888", - "max_results": 5 - } - }, - "cron": { - "exec_timeout_minutes": 5, - "allow_command": true, - "command_allowed_remotes": [] - } - }, - "heartbeat": { - "enabled": true, - "interval": 30 - } -} -``` - -
- ---- - -## 📝 API Key Comparison - -| Service | Pricing | Use Case | -| ---------------- | ------------------------ | ------------------------------------- | -| **OpenRouter** | Free: 200K tokens/month | Multiple models (Claude, GPT-4, etc.) | -| **Volcengine CodingPlan** | ¥9.9/first month | Best for Chinese users, multiple SOTA models (Doubao, DeepSeek, etc.) | -| **Zhipu** | Free: 200K tokens/month | Suitable for Chinese users | -| **Brave Search** | $5/1000 queries | Web search functionality | -| **SearXNG** | Free (self-hosted) | Privacy-focused metasearch (70+ engines) | -| **Groq** | Free tier available | Fast inference (Llama, Mixtral) | -| **Cerebras** | Free tier available | Fast inference (Llama, Qwen, etc.) | -| **LongCat** | Free: up to 5M tokens/day | Fast inference | -| **ModelScope** | Free: 2000 requests/day | Inference (Qwen, GLM, DeepSeek, etc.) | - ---- - -
- PicoClaw Meme -
+See the [configuration example](../../config/config.example.json), [Chinese guide](providers.zh.md), and [README](../../README.md). Settings from `.security.yml` may override corresponding values in the main configuration. diff --git a/docs/guides/providers.pt-br.md b/docs/guides/providers.pt-br.md index 4789df14..eec7d629 100644 --- a/docs/guides/providers.pt-br.md +++ b/docs/guides/providers.pt-br.md @@ -1,448 +1,5 @@ -# 🔌 Provedores e Configuração de Modelos +# Model providers -> Voltar ao [README](../project/README.pt-br.md) +This fork now supports only OpenAI (Responses and Chat Completions) and Anthropic (Messages). The previous upstream provider catalog no longer applies. -### Provedores - -> [!NOTE] -> O Groq fornece transcrição de voz gratuita via Whisper. Se configurado, mensagens de áudio de qualquer canal serão automaticamente transcritas no nível do agente. - -| Provider | Purpose | Get API Key | -| ------------ | --------------------------------------- | ------------------------------------------------------------ | -| `gemini` | LLM (Gemini direct) | [aistudio.google.com](https://aistudio.google.com) | -| `zhipu` | LLM (Zhipu direct) | [bigmodel.cn](https://bigmodel.cn) | -| `volcengine` | LLM(Volcengine direct) | [volcengine.com](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| `openrouter` | LLM (recommended, access to all models) | [openrouter.ai](https://openrouter.ai) | -| `anthropic` | LLM (Claude direct) | [console.anthropic.com](https://console.anthropic.com) | -| `openai` | LLM (GPT direct) | [platform.openai.com](https://platform.openai.com) | -| `deepseek` | LLM (DeepSeek direct) | [platform.deepseek.com](https://platform.deepseek.com) | -| `qwen` | LLM (Qwen direct) | [dashscope.console.aliyun.com](https://dashscope.console.aliyun.com) | -| `groq` | LLM + **Voice transcription** (Whisper) | [console.groq.com](https://console.groq.com) | -| `cerebras` | LLM (Cerebras direct) | [cerebras.ai](https://cerebras.ai) | -| `vivgrid` | LLM (Vivgrid direct) | [vivgrid.com](https://vivgrid.com) | -| `moonshot` | LLM (Kimi/Moonshot direct) | [platform.moonshot.cn](https://platform.moonshot.cn) | -| `minimax` | LLM (Minimax direct) | [platform.minimaxi.com](https://platform.minimaxi.com) | -| `avian` | LLM (Avian direct) | [avian.io](https://avian.io) | -| `mistral` | LLM (Mistral direct) | [console.mistral.ai](https://console.mistral.ai) | -| `longcat` | LLM (Longcat direct) | [longcat.ai](https://longcat.ai) | -| `modelscope` | LLM (ModelScope direct) | [modelscope.cn](https://modelscope.cn) | - -### Configuração de Modelos (model_list) - -> **Novidade?** O PicoClaw agora usa uma abordagem de configuração **centrada no modelo**. Basta especificar o formato `vendor/model` (ex.: `zhipu/glm-4.7`) para adicionar novos provedores — **sem necessidade de alteração de código!** - -Este design também permite **suporte multi-agente** com seleção flexível de provedores: - -- **Agentes diferentes, provedores diferentes**: Cada agente pode usar seu próprio provedor LLM -- **Fallback de modelos**: Configure modelos primários e de fallback para resiliência -- **Balanceamento de carga**: Distribua requisições entre múltiplos endpoints -- **Configuração centralizada**: Gerencie todos os provedores em um só lugar - -#### 📋 Todos os Vendors Suportados - -| Vendor | `model` Prefix | Default API Base | Protocol | API Key | -| ------------------- | ----------------- |-----------------------------------------------------| --------- | ---------------------------------------------------------------- | -| **OpenAI** | `openai/` | `https://api.openai.com/v1` | OpenAI | [Get Key](https://platform.openai.com) | -| **Anthropic** | `anthropic/` | `https://api.anthropic.com/v1` | Anthropic | [Get Key](https://console.anthropic.com) | -| **智谱 AI (GLM)** | `zhipu/` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [Get Key](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) | -| **DeepSeek** | `deepseek/` | `https://api.deepseek.com/v1` | OpenAI | [Get Key](https://platform.deepseek.com) | -| **Google Gemini** | `gemini/` | `https://generativelanguage.googleapis.com/v1beta` | Gemini | [Get Key](https://aistudio.google.com/api-keys) | -| **Groq** | `groq/` | `https://api.groq.com/openai/v1` | OpenAI | [Get Key](https://console.groq.com) | -| **Moonshot** | `moonshot/` | `https://api.moonshot.cn/v1` | OpenAI | [Get Key](https://platform.moonshot.cn) | -| **通义千问 (Qwen)** | `qwen/` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [Get Key](https://dashscope.console.aliyun.com) | -| **NVIDIA** | `nvidia/` | `https://integrate.api.nvidia.com/v1` | OpenAI | [Get Key](https://build.nvidia.com) | -| **Ollama** | `ollama/` | `http://localhost:11434/v1` | OpenAI | Local (no key needed) | -| **OpenRouter** | `openrouter/` | `https://openrouter.ai/api/v1` | OpenAI | [Get Key](https://openrouter.ai/keys) | -| **LiteLLM Proxy** | `litellm/` | `http://localhost:4000/v1` | OpenAI | Your LiteLLM proxy key | -| **VLLM** | `vllm/` | `http://localhost:8000/v1` | OpenAI | Local | -| **Cerebras** | `cerebras/` | `https://api.cerebras.ai/v1` | OpenAI | [Get Key](https://cerebras.ai) | -| **VolcEngine (Doubao)** | `volcengine/` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [Get Key](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| **神算云** | `shengsuanyun/` | `https://router.shengsuanyun.com/api/v1` | OpenAI | - | -| **BytePlus** | `byteplus/` | `https://ark.ap-southeast.bytepluses.com/api/v3` | OpenAI | [Get Key](https://www.byteplus.com) | -| **Vivgrid** | `vivgrid/` | `https://api.vivgrid.com/v1` | OpenAI | [Get Key](https://vivgrid.com) | -| **LongCat** | `longcat/` | `https://api.longcat.chat/openai` | OpenAI | [Get Key](https://longcat.chat/platform) | -| **ModelScope (魔搭)**| `modelscope/` | `https://api-inference.modelscope.cn/v1` | OpenAI | [Get Token](https://modelscope.cn/my/tokens) | -| **Antigravity** | `antigravity/` | Google Cloud | Custom | OAuth only | -| **GitHub Copilot** | `github-copilot/` | `localhost:4321` | gRPC | - | - -#### Configuração Básica - -```json -{ - "model_list": [ - { - "model_name": "ark-code-latest", - "model": "volcengine/ark-code-latest", - "api_keys": ["sk-your-api-key"] - }, - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_keys": ["sk-your-openai-key"] - }, - { - "model_name": "claude-sonnet-4.6", - "model": "anthropic/claude-sonnet-4.6", - "api_keys": ["sk-ant-your-key"] - }, - { - "model_name": "glm-4.7", - "model": "zhipu/glm-4.7", - "api_keys": ["your-zhipu-key"] - } - ], - "agents": { - "defaults": { - "model_name": "gpt-5.4" - } - } -} -``` - -#### Campos de entrada `model_list` - -| Campo | Tipo | Obrigatório | Descrição | -|-------|------|-------------|-----------| -| `model_name` | string | Sim | Nome único para referenciar este modelo na config do agent | -| `model` | string | Sim | Identificador fornecedor/modelo (ex: `openai/gpt-5.4`, `azure/gpt-5.4`, `anthropic/claude-sonnet-4.6`) | -| `api_keys` | string[] | Sim* | Chave(s) API para autenticação. Múltiplas chaves permitem rotação por requisição. Não necessário para providers locais (Ollama, LM Studio, VLLM) | -| `api_base` | string | Não | Substitui a URL base da API padrão | -| `proxy` | string | Não | URL do proxy HTTP para esta entrada de modelo | -| `user_agent` | string | Não | Cabeçalho `User-Agent` personalizado enviado com requisições API (suportado por providers OpenAI-compatible, Gemini, Anthropic e Azure) | -| `request_timeout` | int | Não | Timeout de requisição em segundos (o padrão varia por provider) | -| `max_tokens_field` | string | Não | Substitui o nome do campo max tokens no corpo da requisição (ex: `max_completion_tokens` para modelos o1) | -| `thinking_level` | string | Não | Nível de pensamento estendido: `off`, `low`, `medium`, `high`, `xhigh` ou `adaptive` | -| `extra_body` | object | Não | Campos adicionais para injetar em cada corpo de requisição | -| `streaming.enabled` | bool | Não | Opt-in para provider streaming nesta entrada de modelo. O padrão é `false` e o canal ativo também precisa de `settings.streaming.enabled` como `true` | -| `rpm` | int | Não | Limite de requisições por minuto | -| `fallbacks` | string[] | Não | Nomes dos modelos de fallback para failover automático | -| `enabled` | bool | Não | Ativar ou desativar esta entrada de modelo (padrão: `true`) | - -Quando streaming estiver desativado, omita o bloco `streaming`. Escrever `"streaming": {"enabled": false}` é opcional e não é necessário. - -#### Exemplos por Vendor - -**OpenAI** - -```json -{ - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_keys": ["sk-..."] -} -``` - -**VolcEngine (Doubao)** - -```json -{ - "model_name": "ark-code-latest", - "model": "volcengine/ark-code-latest", - "api_keys": ["sk-..."] -} -``` - -**智谱 AI (GLM)** - -```json -{ - "model_name": "glm-4.7", - "model": "zhipu/glm-4.7", - "api_keys": ["your-key"] -} -``` - -**DeepSeek** - -```json -{ - "model_name": "deepseek-chat", - "model": "deepseek/deepseek-chat", - "api_keys": ["sk-..."] -} -``` - -**Anthropic (com chave de API)** - -```json -{ - "model_name": "claude-sonnet-4.6", - "model": "anthropic/claude-sonnet-4.6", - "api_keys": ["sk-ant-your-key"] -} -``` - -> Execute `picoclaw auth login --provider anthropic` para colar seu token de API. - -**Anthropic Messages API (formato nativo)** - -Para acesso direto à API Anthropic ou endpoints personalizados que suportam apenas o formato de mensagem nativo da Anthropic: - -```json -{ - "model_name": "claude-opus-4-6", - "model": "anthropic-messages/claude-opus-4-6", - "api_keys": ["sk-ant-your-key"], - "api_base": "https://api.anthropic.com" -} -``` - -> Use o protocolo `anthropic-messages` quando: -> - Usar proxies de terceiros que suportam apenas o endpoint nativo `/v1/messages` da Anthropic (não o compatível com OpenAI `/v1/chat/completions`) -> - Conectar a serviços como MiniMax, Synthetic que requerem o formato de mensagem nativo da Anthropic -> - O protocolo `anthropic` existente retorna erros 404 (indicando que o endpoint não suporta formato compatível com OpenAI) -> -> **Nota:** O protocolo `anthropic` usa formato compatível com OpenAI (`/v1/chat/completions`), enquanto `anthropic-messages` usa o formato nativo da Anthropic (`/v1/messages`). Escolha com base no formato suportado pelo seu endpoint. - -**Ollama (local)** - -```json -{ - "model_name": "llama3", - "model": "ollama/llama3" -} -``` - -**Proxy/API Personalizado** - -```json -{ - "model_name": "my-custom-model", - "model": "openai/custom-model", - "api_base": "https://my-proxy.com/v1", - "api_keys": ["sk-..."], - "user_agent": "MyApp/1.0", - "request_timeout": 300 -} -``` - -**LiteLLM Proxy** - -```json -{ - "model_name": "lite-gpt4", - "model": "litellm/lite-gpt4", - "api_base": "http://localhost:4000/v1", - "api_keys": ["sk-..."] -} -``` - -O PicoClaw remove apenas o prefixo externo `litellm/` antes de enviar a requisição, então aliases de proxy como `litellm/lite-gpt4` enviam `lite-gpt4`, enquanto `litellm/openai/gpt-4o` envia `openai/gpt-4o`. - -#### Balanceamento de Carga - -Configure múltiplos endpoints para o mesmo nome de modelo — o PicoClaw fará automaticamente round-robin entre eles: - -```json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_base": "https://api1.example.com/v1", - "api_keys": ["sk-key1"] - }, - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_base": "https://api2.example.com/v1", - "api_keys": ["sk-key2"] - } - ] -} -``` - -#### Migração da Configuração Legacy `providers` - -A configuração antiga `providers` está **descontinuada** e foi removida no V2. Configs V0/V1 existentes são auto-migradas. - -**Configuração Antiga (descontinuada):** - -```json -{ - "providers": { - "zhipu": { - "api_key": "your-key", - "api_base": "https://open.bigmodel.cn/api/paas/v4" - } - }, - "agents": { - "defaults": { - "provider": "zhipu", - "model": "glm-4.7" - } - } -} -``` - -**Configuração Nova (recomendada):** - -```json -{ - "version": 3, - "model_list": [ - { - "model_name": "glm-4.7", - "model": "zhipu/glm-4.7", - "api_keys": ["your-key"] - } - ], - "agents": { - "defaults": { - "model_name": "glm-4.7" - } - } -} -``` - -Para guia de migração detalhado, veja [migration/model-list-migration.md](../migration/model-list-migration.md). - -### Arquitetura de Provedores - -O PicoClaw roteia provedores por família de protocolo: - -- Protocolo compatível com OpenAI: OpenRouter, gateways compatíveis com OpenAI, Groq, Zhipu e endpoints estilo vLLM. -- Protocolo Gemini nativo: Google Gemini via endpoints nativos `models/*:generateContent` e `models/*:streamGenerateContent`. -- Protocolo Anthropic: Comportamento nativo da API Claude. -- Caminho Codex/OAuth: Rota de autenticação OAuth/token da OpenAI. - -Isso mantém o runtime leve enquanto torna novos backends compatíveis com OpenAI basicamente uma operação de configuração (`api_base` + `api_keys`). - -
-Zhipu - -**1. Obter chave de API e URL base** - -* Obtenha a [chave de API](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) - -**2. Configurar** - -```json -{ - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model_name": "glm-4.7", - "max_tokens": 8192, - "temperature": 0.7, - "max_tool_iterations": 20 - } - }, - "providers": { - "zhipu": { - "api_key": "Your API Key", - "api_base": "https://open.bigmodel.cn/api/paas/v4" - } - } -} -``` - -**3. Executar** - -```bash -picoclaw agent -m "Hello" -``` - -
- -
-Exemplo de configuração completa - -```json -{ - "agents": { - "defaults": { - "model_name": "anthropic/claude-opus-4-5" - } - }, - "session": { - "dm_scope": "per-channel-peer" - }, - "providers": { - "openrouter": { - "api_key": "sk-or-v1-xxx" - }, - "groq": { - "api_key": "gsk_xxx" - } - }, - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "token": "123456:ABC...", - "allow_from": ["123456789"] - }, - "feishu": { - "enabled": false, - "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "xxx", - "encrypt_key": "", - "verification_token": "", - "allow_from": [] - }, - "qq": { - "enabled": false, - "type": "qq", - "app_id": "", - "app_secret": "", - "allow_from": [] - } - }, - "tools": { - "web": { - "brave": { - "enabled": false, - "api_key": "BSA...", - "max_results": 5 - }, - "duckduckgo": { - "enabled": true, - "max_results": 5 - }, - "perplexity": { - "enabled": false, - "api_key": "", - "max_results": 5 - }, - "searxng": { - "enabled": false, - "base_url": "http://localhost:8888", - "max_results": 5 - } - }, - "cron": { - "exec_timeout_minutes": 5 - } - }, - "heartbeat": { - "enabled": true, - "interval": 30 - } -} -``` - -
- ---- - -## 📝 Comparação de Chaves de API - -| Service | Pricing | Use Case | -| ---------------- | ------------------------ | ------------------------------------- | -| **OpenRouter** | Free: 200K tokens/month | Multiple models (Claude, GPT-4, etc.) | -| **Volcengine CodingPlan** | ¥9.9/first month | Best for Chinese users, multiple SOTA models (Doubao, DeepSeek, etc.) | -| **Zhipu** | Free: 200K tokens/month | Suitable for Chinese users | -| **Brave Search** | $5/1000 queries | Web search functionality | -| **SearXNG** | Free (self-hosted) | Privacy-focused metasearch (70+ engines) | -| **Groq** | Free tier available | Fast inference (Llama, Mixtral) | -| **Cerebras** | Free tier available | Fast inference (Llama, Qwen, etc.) | -| **LongCat** | Free: up to 5M tokens/day | Fast inference | -| **ModelScope** | Free: 2000 requests/day | Inference (Qwen, GLM, DeepSeek, etc.) | - ---- - -
- PicoClaw Meme -
+See the maintained [provider guide](providers.md) or [中文说明](providers.zh.md) for configuration, compatible endpoints, and login options. diff --git a/docs/guides/providers.vi.md b/docs/guides/providers.vi.md index 8e3a3b43..eec7d629 100644 --- a/docs/guides/providers.vi.md +++ b/docs/guides/providers.vi.md @@ -1,448 +1,5 @@ -# 🔌 Nhà Cung Cấp và Cấu Hình Mô Hình +# Model providers -> Quay lại [README](../project/README.vi.md) +This fork now supports only OpenAI (Responses and Chat Completions) and Anthropic (Messages). The previous upstream provider catalog no longer applies. -### Nhà Cung Cấp - -> [!NOTE] -> Groq cung cấp chuyển đổi giọng nói miễn phí qua Whisper. Nếu được cấu hình, tin nhắn âm thanh từ bất kỳ kênh nào sẽ được tự động chuyển đổi ở cấp agent. - -| Provider | Purpose | Get API Key | -| ------------ | --------------------------------------- | ------------------------------------------------------------ | -| `gemini` | LLM (Gemini direct) | [aistudio.google.com](https://aistudio.google.com) | -| `zhipu` | LLM (Zhipu direct) | [bigmodel.cn](https://bigmodel.cn) | -| `volcengine` | LLM(Volcengine direct) | [volcengine.com](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| `openrouter` | LLM (recommended, access to all models) | [openrouter.ai](https://openrouter.ai) | -| `anthropic` | LLM (Claude direct) | [console.anthropic.com](https://console.anthropic.com) | -| `openai` | LLM (GPT direct) | [platform.openai.com](https://platform.openai.com) | -| `deepseek` | LLM (DeepSeek direct) | [platform.deepseek.com](https://platform.deepseek.com) | -| `qwen` | LLM (Qwen direct) | [dashscope.console.aliyun.com](https://dashscope.console.aliyun.com) | -| `groq` | LLM + **Voice transcription** (Whisper) | [console.groq.com](https://console.groq.com) | -| `cerebras` | LLM (Cerebras direct) | [cerebras.ai](https://cerebras.ai) | -| `vivgrid` | LLM (Vivgrid direct) | [vivgrid.com](https://vivgrid.com) | -| `moonshot` | LLM (Kimi/Moonshot direct) | [platform.moonshot.cn](https://platform.moonshot.cn) | -| `minimax` | LLM (Minimax direct) | [platform.minimaxi.com](https://platform.minimaxi.com) | -| `avian` | LLM (Avian direct) | [avian.io](https://avian.io) | -| `mistral` | LLM (Mistral direct) | [console.mistral.ai](https://console.mistral.ai) | -| `longcat` | LLM (Longcat direct) | [longcat.ai](https://longcat.ai) | -| `modelscope` | LLM (ModelScope direct) | [modelscope.cn](https://modelscope.cn) | - -### Cấu Hình Mô Hình (model_list) - -> **Có gì mới?** PicoClaw hiện sử dụng cách tiếp cận cấu hình **tập trung vào mô hình**. Chỉ cần chỉ định định dạng `vendor/model` (ví dụ: `zhipu/glm-4.7`) để thêm provider mới — **không cần thay đổi code!** - -Thiết kế này cũng cho phép **hỗ trợ đa agent** với lựa chọn provider linh hoạt: - -- **Agent khác nhau, provider khác nhau**: Mỗi agent có thể sử dụng provider LLM riêng -- **Fallback mô hình**: Cấu hình mô hình chính và dự phòng cho khả năng phục hồi -- **Cân bằng tải**: Phân phối yêu cầu qua nhiều endpoint -- **Cấu hình tập trung**: Quản lý tất cả provider tại một nơi - -#### 📋 Tất Cả Vendor Được Hỗ Trợ - -| Vendor | `model` Prefix | Default API Base | Protocol | API Key | -| ------------------- | ----------------- |-----------------------------------------------------| --------- | ---------------------------------------------------------------- | -| **OpenAI** | `openai/` | `https://api.openai.com/v1` | OpenAI | [Get Key](https://platform.openai.com) | -| **Anthropic** | `anthropic/` | `https://api.anthropic.com/v1` | Anthropic | [Get Key](https://console.anthropic.com) | -| **智谱 AI (GLM)** | `zhipu/` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [Get Key](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) | -| **DeepSeek** | `deepseek/` | `https://api.deepseek.com/v1` | OpenAI | [Get Key](https://platform.deepseek.com) | -| **Google Gemini** | `gemini/` | `https://generativelanguage.googleapis.com/v1beta` | Gemini | [Get Key](https://aistudio.google.com/api-keys) | -| **Groq** | `groq/` | `https://api.groq.com/openai/v1` | OpenAI | [Get Key](https://console.groq.com) | -| **Moonshot** | `moonshot/` | `https://api.moonshot.cn/v1` | OpenAI | [Get Key](https://platform.moonshot.cn) | -| **通义千问 (Qwen)** | `qwen/` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [Get Key](https://dashscope.console.aliyun.com) | -| **NVIDIA** | `nvidia/` | `https://integrate.api.nvidia.com/v1` | OpenAI | [Get Key](https://build.nvidia.com) | -| **Ollama** | `ollama/` | `http://localhost:11434/v1` | OpenAI | Local (no key needed) | -| **OpenRouter** | `openrouter/` | `https://openrouter.ai/api/v1` | OpenAI | [Get Key](https://openrouter.ai/keys) | -| **LiteLLM Proxy** | `litellm/` | `http://localhost:4000/v1` | OpenAI | Your LiteLLM proxy key | -| **VLLM** | `vllm/` | `http://localhost:8000/v1` | OpenAI | Local | -| **Cerebras** | `cerebras/` | `https://api.cerebras.ai/v1` | OpenAI | [Get Key](https://cerebras.ai) | -| **VolcEngine (Doubao)** | `volcengine/` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [Get Key](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| **神算云** | `shengsuanyun/` | `https://router.shengsuanyun.com/api/v1` | OpenAI | - | -| **BytePlus** | `byteplus/` | `https://ark.ap-southeast.bytepluses.com/api/v3` | OpenAI | [Get Key](https://www.byteplus.com) | -| **Vivgrid** | `vivgrid/` | `https://api.vivgrid.com/v1` | OpenAI | [Get Key](https://vivgrid.com) | -| **LongCat** | `longcat/` | `https://api.longcat.chat/openai` | OpenAI | [Get Key](https://longcat.chat/platform) | -| **ModelScope (魔搭)**| `modelscope/` | `https://api-inference.modelscope.cn/v1` | OpenAI | [Get Token](https://modelscope.cn/my/tokens) | -| **Antigravity** | `antigravity/` | Google Cloud | Custom | OAuth only | -| **GitHub Copilot** | `github-copilot/` | `localhost:4321` | gRPC | - | - -#### Cấu Hình Cơ Bản - -```json -{ - "model_list": [ - { - "model_name": "ark-code-latest", - "model": "volcengine/ark-code-latest", - "api_keys": ["sk-your-api-key"] - }, - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_keys": ["sk-your-openai-key"] - }, - { - "model_name": "claude-sonnet-4.6", - "model": "anthropic/claude-sonnet-4.6", - "api_keys": ["sk-ant-your-key"] - }, - { - "model_name": "glm-4.7", - "model": "zhipu/glm-4.7", - "api_keys": ["your-zhipu-key"] - } - ], - "agents": { - "defaults": { - "model_name": "gpt-5.4" - } - } -} -``` - -#### Các trường entry `model_list` - -| Trường | Kiểu | Bắt buộc | Mô tả | -|--------|------|----------|------| -| `model_name` | string | Có | Tên duy nhất để tham chiếu model này trong cấu hình agent | -| `model` | string | Có | Định danh nhà cung cấp/model (ví dụ: `openai/gpt-5.4`, `azure/gpt-5.4`, `anthropic/claude-sonnet-4.6`) | -| `api_keys` | string[] | Có* | Khóa API xác thực. Nhiều khóa cho phép xoay vòng theo yêu cầu. Không cần thiết cho provider nội bộ (Ollama, LM Studio, VLLM) | -| `api_base` | string | Không | Ghi đè URL endpoint API mặc định | -| `proxy` | string | Không | URL proxy HTTP cho entry model này | -| `user_agent` | string | Không | Header `User-Agent` tùy chỉnh gửi với yêu cầu API (được hỗ trợ bởi provider OpenAI-compatible, Gemini, Anthropic và Azure) | -| `request_timeout` | int | Không | Timeout yêu cầu tính bằng giây (mặc định khác nhau tùy provider) | -| `max_tokens_field` | string | Không | Ghi đè tên trường max tokens trong request body (ví dụ: `max_completion_tokens` cho model o1) | -| `thinking_level` | string | Không | Mức độ tư duy mở rộng: `off`, `low`, `medium`, `high`, `xhigh` hoặc `adaptive` | -| `extra_body` | object | Không | Các trường bổ sung để chèn vào mỗi request body | -| `streaming.enabled` | bool | Không | Opt-in cho provider streaming trên entry model này. Mặc định là `false` và channel đang hoạt động cũng cần `settings.streaming.enabled` là `true` | -| `rpm` | int | Không | Giới hạn tốc độ yêu cầu mỗi phút | -| `fallbacks` | string[] | Không | Tên model dự phòng cho failover tự động | -| `enabled` | bool | Không | Kích hoạt hay vô hiệu hóa entry model này (mặc định: `true`) | - -Khi không dùng streaming, hãy bỏ qua block `streaming`. Viết `"streaming": {"enabled": false}` là tùy chọn và không cần thiết. - -#### Ví Dụ Theo Vendor - -**OpenAI** - -```json -{ - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_keys": ["sk-..."] -} -``` - -**VolcEngine (Doubao)** - -```json -{ - "model_name": "ark-code-latest", - "model": "volcengine/ark-code-latest", - "api_keys": ["sk-..."] -} -``` - -**智谱 AI (GLM)** - -```json -{ - "model_name": "glm-4.7", - "model": "zhipu/glm-4.7", - "api_keys": ["your-key"] -} -``` - -**DeepSeek** - -```json -{ - "model_name": "deepseek-chat", - "model": "deepseek/deepseek-chat", - "api_keys": ["sk-..."] -} -``` - -**Anthropic (với API key)** - -```json -{ - "model_name": "claude-sonnet-4.6", - "model": "anthropic/claude-sonnet-4.6", - "api_keys": ["sk-ant-your-key"] -} -``` - -> Chạy `picoclaw auth login --provider anthropic` để dán API token. - -**Anthropic Messages API (định dạng native)** - -Để truy cập trực tiếp API Anthropic hoặc endpoint tùy chỉnh chỉ hỗ trợ định dạng message native của Anthropic: - -```json -{ - "model_name": "claude-opus-4-6", - "model": "anthropic-messages/claude-opus-4-6", - "api_keys": ["sk-ant-your-key"], - "api_base": "https://api.anthropic.com" -} -``` - -> Sử dụng giao thức `anthropic-messages` khi: -> - Sử dụng proxy bên thứ ba chỉ hỗ trợ endpoint native `/v1/messages` của Anthropic (không tương thích OpenAI `/v1/chat/completions`) -> - Kết nối đến dịch vụ như MiniMax, Synthetic yêu cầu định dạng message native của Anthropic -> - Giao thức `anthropic` hiện tại trả về lỗi 404 (cho thấy endpoint không hỗ trợ định dạng tương thích OpenAI) -> -> **Lưu ý:** Giao thức `anthropic` sử dụng định dạng tương thích OpenAI (`/v1/chat/completions`), trong khi `anthropic-messages` sử dụng định dạng native của Anthropic (`/v1/messages`). Chọn dựa trên định dạng endpoint hỗ trợ. - -**Ollama (local)** - -```json -{ - "model_name": "llama3", - "model": "ollama/llama3" -} -``` - -**Proxy/API Tùy Chỉnh** - -```json -{ - "model_name": "my-custom-model", - "model": "openai/custom-model", - "api_base": "https://my-proxy.com/v1", - "api_keys": ["sk-..."], - "user_agent": "MyApp/1.0", - "request_timeout": 300 -} -``` - -**LiteLLM Proxy** - -```json -{ - "model_name": "lite-gpt4", - "model": "litellm/lite-gpt4", - "api_base": "http://localhost:4000/v1", - "api_keys": ["sk-..."] -} -``` - -PicoClaw chỉ loại bỏ tiền tố ngoài `litellm/` trước khi gửi yêu cầu, nên alias proxy như `litellm/lite-gpt4` gửi `lite-gpt4`, trong khi `litellm/openai/gpt-4o` gửi `openai/gpt-4o`. - -#### Cân Bằng Tải - -Cấu hình nhiều endpoint cho cùng tên mô hình — PicoClaw sẽ tự động round-robin giữa chúng: - -```json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_base": "https://api1.example.com/v1", - "api_keys": ["sk-key1"] - }, - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_base": "https://api2.example.com/v1", - "api_keys": ["sk-key2"] - } - ] -} -``` - -#### Di Chuyển Từ Cấu Hình Legacy `providers` - -Cấu hình `providers` cũ đã **bị deprecated** và đã được loại bỏ trong V2. Các cấu hình V0/V1 hiện có sẽ được tự động migrate. - -**Cấu hình cũ (ngừng hỗ trợ):** - -```json -{ - "providers": { - "zhipu": { - "api_key": "your-key", - "api_base": "https://open.bigmodel.cn/api/paas/v4" - } - }, - "agents": { - "defaults": { - "provider": "zhipu", - "model": "glm-4.7" - } - } -} -``` - -**Cấu hình mới (khuyến nghị):** - -```json -{ - "version": 3, - "model_list": [ - { - "model_name": "glm-4.7", - "model": "zhipu/glm-4.7", - "api_keys": ["your-key"] - } - ], - "agents": { - "defaults": { - "model_name": "glm-4.7" - } - } -} -``` - -Để xem hướng dẫn di chuyển chi tiết, xem [migration/model-list-migration.md](../migration/model-list-migration.md). - -### Kiến Trúc Provider - -PicoClaw định tuyến provider theo họ giao thức: - -- Giao thức tương thích OpenAI: OpenRouter, gateway tương thích OpenAI, Groq, Zhipu, và endpoint kiểu vLLM. -- Giao thức Gemini native: Google Gemini qua các endpoint native `models/*:generateContent` và `models/*:streamGenerateContent`. -- Giao thức Anthropic: Hành vi API native của Claude. -- Đường dẫn Codex/OAuth: Tuyến xác thực OAuth/token của OpenAI. - -Điều này giữ runtime nhẹ trong khi làm cho backend tương thích OpenAI mới chủ yếu là thao tác cấu hình (`api_base` + `api_keys`). - -
-Zhipu - -**1. Lấy API key và URL base** - -* Lấy [API key](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) - -**2. Cấu hình** - -```json -{ - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model_name": "glm-4.7", - "max_tokens": 8192, - "temperature": 0.7, - "max_tool_iterations": 20 - } - }, - "providers": { - "zhipu": { - "api_key": "Your API Key", - "api_base": "https://open.bigmodel.cn/api/paas/v4" - } - } -} -``` - -**3. Chạy** - -```bash -picoclaw agent -m "Hello" -``` - -
- -
-Ví dụ cấu hình đầy đủ - -```json -{ - "agents": { - "defaults": { - "model_name": "anthropic/claude-opus-4-5" - } - }, - "session": { - "dm_scope": "per-channel-peer" - }, - "providers": { - "openrouter": { - "api_key": "sk-or-v1-xxx" - }, - "groq": { - "api_key": "gsk_xxx" - } - }, - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "token": "123456:ABC...", - "allow_from": ["123456789"] - }, - "feishu": { - "enabled": false, - "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "xxx", - "encrypt_key": "", - "verification_token": "", - "allow_from": [] - }, - "qq": { - "enabled": false, - "type": "qq", - "app_id": "", - "app_secret": "", - "allow_from": [] - } - }, - "tools": { - "web": { - "brave": { - "enabled": false, - "api_key": "BSA...", - "max_results": 5 - }, - "duckduckgo": { - "enabled": true, - "max_results": 5 - }, - "perplexity": { - "enabled": false, - "api_key": "", - "max_results": 5 - }, - "searxng": { - "enabled": false, - "base_url": "http://localhost:8888", - "max_results": 5 - } - }, - "cron": { - "exec_timeout_minutes": 5 - } - }, - "heartbeat": { - "enabled": true, - "interval": 30 - } -} -``` - -
- ---- - -## 📝 So Sánh API Key - -| Service | Pricing | Use Case | -| ---------------- | ------------------------ | ------------------------------------- | -| **OpenRouter** | Free: 200K tokens/month | Multiple models (Claude, GPT-4, etc.) | -| **Volcengine CodingPlan** | ¥9.9/first month | Best for Chinese users, multiple SOTA models (Doubao, DeepSeek, etc.) | -| **Zhipu** | Free: 200K tokens/month | Suitable for Chinese users | -| **Brave Search** | $5/1000 queries | Web search functionality | -| **SearXNG** | Free (self-hosted) | Privacy-focused metasearch (70+ engines) | -| **Groq** | Free tier available | Fast inference (Llama, Mixtral) | -| **Cerebras** | Free tier available | Fast inference (Llama, Qwen, etc.) | -| **LongCat** | Free: up to 5M tokens/day | Fast inference | -| **ModelScope** | Free: 2000 requests/day | Inference (Qwen, GLM, DeepSeek, etc.) | - ---- - -
- PicoClaw Meme -
+See the maintained [provider guide](providers.md) or [中文说明](providers.zh.md) for configuration, compatible endpoints, and login options. diff --git a/docs/guides/providers.zh.md b/docs/guides/providers.zh.md index bf746856..dbb2cbb7 100644 --- a/docs/guides/providers.zh.md +++ b/docs/guides/providers.zh.md @@ -1,572 +1,59 @@ -# 🔌 提供商与模型配置 +# 模型接入 -> 返回 [README](../project/README.zh.md) +本 fork 仅保留 OpenAI 和 Anthropic 两种模型协议。OpenAI 支持 Responses API、Chat Completions 和流式输出;Anthropic 使用原生 Messages API,支持工具调用和思考参数。 -### 提供商 (Providers) - -> [!NOTE] -> 语音转录现在可以通过 `voice.model_name` 指定的多模态模型完成;如果未配置语音模型,Groq Whisper 仍可作为回退方案。 - -| 提供商 | 用途 | 获取 API Key | -| -------------------- | ---------------------------- | -------------------------------------------------------------------- | -| `gemini` | LLM (Gemini 直连) | [aistudio.google.com](https://aistudio.google.com) | -| `zhipu` | LLM (智谱直连) | [bigmodel.cn](https://bigmodel.cn) | -| `volcengine` | LLM (火山引擎直连) | [volcengine.com](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| `openrouter` | LLM (推荐,可访问所有模型) | [openrouter.ai](https://openrouter.ai) | -| `anthropic` | LLM (Claude 直连) | [console.anthropic.com](https://console.anthropic.com) | -| `openai` | LLM (GPT 直连) | [platform.openai.com](https://platform.openai.com) | -| `venice` | LLM (Venice AI 直连) | [venice.ai](https://venice.ai) | -| `deepseek` | LLM (DeepSeek 直连) | [platform.deepseek.com](https://platform.deepseek.com) | -| `qwen` | LLM (通义千问) | [dashscope.console.aliyun.com](https://dashscope.console.aliyun.com) | -| `groq` | LLM + **语音转录** (Whisper) | [console.groq.com](https://console.groq.com) | -| `cerebras` | LLM (Cerebras 直连) | [cerebras.ai](https://cerebras.ai) | -| `vivgrid` | LLM (Vivgrid 直连) | [vivgrid.com](https://vivgrid.com) | -| `moonshot` | LLM (Kimi/Moonshot 直连) | [platform.moonshot.cn](https://platform.moonshot.cn) | -| `minimax` | LLM (Minimax 直连) | [platform.minimaxi.com](https://platform.minimaxi.com) | -| `avian` | LLM (Avian 直连) | [avian.io](https://avian.io) | -| `mistral` | LLM (Mistral 直连) | [console.mistral.ai](https://console.mistral.ai) | -| `longcat` | LLM (Longcat 直连) | [longcat.ai](https://longcat.ai) | -| `modelscope` | LLM (ModelScope 直连) | [modelscope.cn](https://modelscope.cn) | -| `mimo` | LLM (小米 MiMo 直连) | [platform.xiaomimimo.com](https://platform.xiaomimimo.com) | - - -### 模型配置 (model_list) - -> **新功能!** PicoClaw 现在优先推荐显式 `provider` + 原生 `model` 的配置方式,例如 `"provider": "zhipu", "model": "glm-4.7"`。如果未设置 `provider`,旧的单字段 `provider/model` 写法仍然兼容。 - -如果你想看 agent 分发和轻量模型路由的完整示例,请看 [路由使用指南](routing-guide.zh.md)。 - -该设计同时支持**多 Agent 场景**,提供灵活的 Provider 选择: - -- **不同 Agent 使用不同 Provider**:每个 Agent 可以使用自己的 LLM provider -- **模型回退(Fallback)**:配置主模型和备用模型,提高可靠性 -- **负载均衡**:在多个 API 端点之间分配请求 -- **集中化配置**:在一个地方管理所有 provider - -#### 📋 所有支持的厂商 - -| 厂商 | `provider` 值 | 默认 API Base | 协议 | 获取 API Key | -| ------------------- | ----------------- | --------------------------------------------------- | --------- | ----------------------------------------------------------------- | -| **OpenAI** | `openai` | `https://api.openai.com/v1` | OpenAI | [获取密钥](https://platform.openai.com) | -| **Venice AI** | `venice` | `https://api.venice.ai/api/v1` | OpenAI | [获取密钥](https://venice.ai) | -| **Anthropic** | `anthropic` | `https://api.anthropic.com/v1` | Anthropic | [获取密钥](https://console.anthropic.com) | -| **智谱 AI (GLM)** | `zhipu` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [获取密钥](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) | -| **DeepSeek** | `deepseek` | `https://api.deepseek.com/v1` | OpenAI | [获取密钥](https://platform.deepseek.com) | -| **Google Gemini** | `gemini` | `https://generativelanguage.googleapis.com/v1beta` | Gemini | [获取密钥](https://aistudio.google.com/api-keys) | -| **Groq** | `groq` | `https://api.groq.com/openai/v1` | OpenAI | [获取密钥](https://console.groq.com) | -| **Moonshot** | `moonshot` | `https://api.moonshot.cn/v1` | OpenAI | [获取密钥](https://platform.moonshot.cn) | -| **通义千问 (Qwen)** | `qwen` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [获取密钥](https://dashscope.console.aliyun.com) | -| **NVIDIA** | `nvidia` | `https://integrate.api.nvidia.com/v1` | OpenAI | [获取密钥](https://build.nvidia.com) | -| **Ollama** | `ollama` | `http://localhost:11434/v1` | OpenAI | 本地(无需密钥) | -| **LM Studio** | `lmstudio` | `http://localhost:1234/v1` | OpenAI | 可选(本地默认无需密钥) | -| **OpenRouter** | `openrouter` | `https://openrouter.ai/api/v1` | OpenAI | [获取密钥](https://openrouter.ai/keys) | -| **LiteLLM Proxy** | `litellm` | `http://localhost:4000/v1` | OpenAI | 你的 LiteLLM 代理密钥 | -| **VLLM** | `vllm` | `http://localhost:8000/v1` | OpenAI | 本地 | -| **Cerebras** | `cerebras` | `https://api.cerebras.ai/v1` | OpenAI | [获取密钥](https://cerebras.ai) | -| **火山引擎(Doubao)** | `volcengine` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [获取密钥](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| **神算云** | `shengsuanyun` | `https://router.shengsuanyun.com/api/v1` | OpenAI | - | -| **BytePlus** | `byteplus` | `https://ark.ap-southeast.bytepluses.com/api/v3` | OpenAI | [获取密钥](https://www.byteplus.com) | -| **Vivgrid** | `vivgrid` | `https://api.vivgrid.com/v1` | OpenAI | [获取密钥](https://vivgrid.com) | -| **LongCat** | `longcat` | `https://api.longcat.chat/openai` | OpenAI | [获取密钥](https://longcat.chat/platform) | -| **ModelScope (魔搭)**| `modelscope` | `https://api-inference.modelscope.cn/v1` | OpenAI | [获取 Token](https://modelscope.cn/my/tokens) | -| **小米 MiMo** | `mimo` | `https://api.xiaomimimo.com/v1` | OpenAI | [获取密钥](https://platform.xiaomimimo.com) | -| **Antigravity** | `antigravity` | Google Cloud | 自定义 | 仅 OAuth | -| **GitHub Copilot** | `github-copilot` | `localhost:4321` | gRPC | - | - -#### 基础配置示例 +## API Key 配置 ```json { + "version": 3, + "agents": {"defaults": {"model_name": "main"}}, "model_list": [ { - "model_name": "ark-code-latest", - "provider": "volcengine", - "model": "ark-code-latest", - "api_keys": ["sk-your-api-key"] - }, - { - "model_name": "gpt-5.4", + "model_name": "main", "provider": "openai", "model": "gpt-5.4", - "api_keys": ["sk-your-openai-key"] + "api_base": "https://api.openai.com/v1", + "api_keys": ["YOUR_OPENAI_API_KEY"] }, { - "model_name": "claude-sonnet-4.6", + "model_name": "claude", "provider": "anthropic", - "model": "claude-sonnet-4.6", - "api_keys": ["sk-ant-your-key"] - }, - { - "model_name": "glm-4.7", - "provider": "zhipu", - "model": "glm-4.7", - "api_keys": ["your-zhipu-key"] - } - ], - "agents": { - "defaults": { - "model_name": "gpt-5.4" - } - } -} -``` - -#### `model_list` 条目字段 - -| 字段 | 类型 | 必填 | 说明 | -|------|------|------|------| -| `model_name` | string | 是 | 在 agent 配置中引用此模型的唯一名称 | -| `provider` | string | 否 | 推荐的 provider 标识。设置后,PicoClaw 会将 `model` 原样发送给该 provider | -| `model` | string | 是 | 当设置 `provider` 时,这里填写 provider 原生模型 ID。若未设置 `provider`,仍兼容旧的 `provider/model` 写法 | -| `api_keys` | string[] | 是* | 认证密钥。多个密钥可按请求轮换。本地 provider(Ollama、LM Studio、VLLM)不需要 | -| `api_base` | string | 否 | 覆盖默认的 API 端点 URL | -| `proxy` | string | 否 | 此模型条目的 HTTP 代理 URL | -| `user_agent` | string | 否 | 自定义 `User-Agent` 请求头(支持 OpenAI 兼容、Gemini、Anthropic 和 Azure provider) | -| `request_timeout` | int | 否 | 请求超时时间(秒),默认值因 provider 而异 | -| `streaming.enabled` | bool | 否 | 是否允许此模型条目尝试 provider 流式请求,默认 `false`。它只表达模型/端点能力 opt-in,实际还需要当前 channel 的 `settings.streaming.enabled` 同时开启 | -| `max_tokens_field` | string | 否 | 覆盖请求体中 max tokens 的字段名(如 o1 模型使用 `max_completion_tokens`) | -| `thinking_level` | string | 否 | 扩展思考级别:`off`、`low`、`medium`、`high`、`xhigh` 或 `adaptive` | -| `extra_body` | object | 否 | 注入到每个请求体中的额外字段 | -| `custom_headers` | object | 否 | 注入到每个请求中的额外 HTTP 请求头(例如 `{"X-Source":"coding-plan"}`)。若键名与内置请求头同名,会覆盖内置值(如 `Authorization`、`User-Agent`、`Content-Type`、`Accept`)。 | -| `rpm` | int | 否 | 每分钟请求速率限制 | -| `fallbacks` | string[] | 否 | 自动故障转移的备用模型名称 | -| `enabled` | bool | 否 | 是否启用此模型条目(默认:`true`) | - -不需要流式时请省略 `streaming` 配置块。写 `"streaming": {"enabled": false}` 是可选的,手写或生成配置时都不需要。 - -#### `provider` / `model` 解析规则 - -PicoClaw 按下面的规则解析 `provider` 和最终发给上游的模型 ID: - -- 如果设置了 `provider`,则直接使用 `model`。 -- 如果未设置 `provider`,则把 `model` 中第一个 `/` 之前的字段当作 provider,第一个 `/` 之后的全部内容当作最终模型 ID。 - -示例: - -| 配置 | 解析后的 Provider | 实际发送的模型 ID | -| --- | --- | --- | -| `"provider": "openai", "model": "gpt-5.4"` | `openai` | `gpt-5.4` | -| `"model": "openai/gpt-5.4"` | `openai` | `gpt-5.4` | -| `"provider": "openrouter", "model": "openai/gpt-5.4"` | `openrouter` | `openai/gpt-5.4` | -| `"model": "openrouter/openai/gpt-5.4"` | `openrouter` | `openai/gpt-5.4` | - -#### 语音转录 - -你可以通过 `voice.model_name` 为语音转录指定一个专用模型。这样可以直接复用已经配置好的、支持音频输入的多模态 provider,而不必只依赖 Groq。 - -如果没有配置 `voice.model_name`,且存在 Groq API Key,PicoClaw 会继续回退到 Groq 转录。 - -```json -{ - "model_list": [ - { - "model_name": "voice-gemini", - "provider": "gemini", - "model": "gemini-2.5-flash", - "api_keys": ["your-gemini-key"] - } - ], - "voice": { - "model_name": "voice-gemini", - "echo_transcription": false - }, - "providers": { - "groq": { - "api_key": "gsk_xxx" - } - } -} -``` - -#### 各厂商配置示例 - -**OpenAI** - -```json -{ - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_keys": ["sk-..."], - "thinking_level": "high" -} -``` - -对于支持推理的 OpenAI Responses 模型,`thinking_level` 会映射为 `reasoning.effort`:`off` 对应 `none`,`low`、`medium`、`high`、`xhigh` 原样传递,`adaptive` 使用模型默认值。各模型支持的级别可能不同。启用思考时,PicoClaw 会省略默认的 `temperature` 参数。 - -**火山引擎(Doubao)** - -```json -{ - "model_name": "ark-code-latest", - "provider": "volcengine", - "model": "ark-code-latest", - "api_keys": ["sk-..."] -} -``` - -**智谱 AI (GLM)** - -```json -{ - "model_name": "glm-4.7", - "provider": "zhipu", - "model": "glm-4.7", - "api_keys": ["your-key"] -} -``` - -**DeepSeek** - -```json -{ - "model_name": "deepseek-chat", - "provider": "deepseek", - "model": "deepseek-chat", - "api_keys": ["sk-..."] -} -``` - -**Anthropic (使用 OAuth)** - -```json -{ - "model_name": "claude-sonnet-4.6", - "provider": "anthropic", - "model": "claude-sonnet-4.6", - "auth_method": "oauth" -} -``` - -> 运行 `picoclaw auth login --provider anthropic` 来设置 OAuth 凭证。 - -**Anthropic Messages API(原生格式)** - -用于直接访问 Anthropic API 或仅支持 Anthropic 原生消息格式的自定义端点: - -```json -{ - "model_name": "claude-opus-4-6", - "provider": "anthropic-messages", - "model": "claude-opus-4-6", - "api_keys": ["sk-ant-your-key"], - "api_base": "https://api.anthropic.com" -} -``` - -> 使用 `anthropic-messages` 协议的场景: -> - 使用仅支持 Anthropic 原生 `/v1/messages` 端点的第三方代理(不支持 OpenAI 兼容的 `/v1/chat/completions`) -> - 连接到 MiniMax、Synthetic 等需要 Anthropic 原生消息格式的服务 -> - 现有的 `anthropic` 协议返回 404 错误(说明端点不支持 OpenAI 兼容格式) -> -> **注意:** `anthropic` 协议使用 OpenAI 兼容格式(`/v1/chat/completions`),而 `anthropic-messages` 使用 Anthropic 原生格式(`/v1/messages`)。请根据端点支持的格式选择。 - -**Ollama (本地)** - -```json -{ - "model_name": "llama3", - "provider": "ollama", - "model": "llama3" -} -``` - -**LM Studio(本地)** - -```json -{ - "model_name": "lmstudio-local", - "provider": "lmstudio", - "model": "openai/gpt-oss-20b" -} -``` - -`api_base` 默认是 `http://localhost:1234/v1`。除非你在 LM Studio 侧启用了认证,否则不需要配置 API Key。 -显式设置 `provider` 后,PicoClaw 会把 `openai/gpt-oss-20b` 原样发送给 LM Studio。旧的兼容写法 `"model": "lmstudio/openai/gpt-oss-20b"` 在未设置 `provider` 时也会解析成相同的上游模型 ID。 - -**自定义代理/API** - -```json -{ - "model_name": "my-custom-model", - "provider": "openai", - "model": "custom-model", - "api_base": "https://my-proxy.com/v1", - "api_keys": ["sk-..."], - "user_agent": "MyApp/1.0", - "request_timeout": 300 -} -``` - -**LiteLLM Proxy** - -```json -{ - "model_name": "lite-gpt4", - "provider": "litellm", - "model": "lite-gpt4", - "api_base": "http://localhost:4000/v1", - "api_keys": ["sk-..."] -} -``` - -显式设置 `provider` 后,PicoClaw 会将 `model` 原样发送。因此 `"provider": "litellm", "model": "lite-gpt4"` 会发送 `lite-gpt4`,而 `"provider": "litellm", "model": "openai/gpt-4o"` 会发送 `openai/gpt-4o`。旧的兼容写法 `litellm/lite-gpt4` 和 `litellm/openai/gpt-4o` 在未设置 `provider` 时也会得到相同结果。 - -#### 负载均衡 - -为同一个模型名称配置多个端点——PicoClaw 会自动在它们之间轮询: - -```json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_base": "https://api1.example.com/v1", - "api_keys": ["sk-key1"] - }, - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_base": "https://api2.example.com/v1", - "api_keys": ["sk-key2"] + "model": "claude-sonnet-4-6", + "api_base": "https://api.anthropic.com/v1", + "api_keys": ["YOUR_ANTHROPIC_API_KEY"], + "thinking_level": "high" } ] } ``` -#### 自动模型失败切换(Cascade) +`model_name` 是本地别名,`model` 是远端模型 ID。显式填写 `provider` 时,`model` 会原样交给对应协议处理;推荐直接填写远端要求的 ID。未填写 `provider` 时,仍识别 `openai/`、`anthropic/` 前缀,普通模型名默认使用 OpenAI。 -当你在 Agent 的模型设置里配置 `primary` + `fallbacks` 时,PicoClaw 已经支持自动失败切换。 -运行时 fallback 链会在可重试错误时切到下一个候选(例如 HTTP `429`、配额/限流错误、超时错误)。 -同时会对每个候选应用 cooldown,避免对刚失败的目标立即重试。 +`gpt`、`claude` 分别是两种协议的别名,旧的 `anthropic-messages` 也归一化为 `anthropic`。 -```json -{ - "model_list": [ - { - "model_name": "qwen-main", - "provider": "openai", - "model": "qwen3.5:cloud", - "api_base": "https://api.example.com/v1", - "api_keys": ["sk-main"] - }, - { - "model_name": "deepseek-backup", - "provider": "deepseek", - "model": "deepseek-chat", - "api_keys": ["sk-backup-1"] - }, - { - "model_name": "gemini-backup", - "provider": "gemini", - "model": "gemini-2.5-flash", - "api_keys": ["sk-backup-2"] - } - ], - "agents": { - "defaults": { - "model_name": "qwen-main", - "model_fallbacks": ["deepseek-backup", "gemini-backup"] - } - } -} -``` +## Responses 与兼容端点 -如果你在同一模型上启用了 key 级失败切换,PicoClaw 会先在该模型的多 key 候选间切换,再继续切到跨模型备选。 +使用 OpenAI 官方端点时优先调用 `/responses`;自定义端点上,GPT 模型(不含 `gpt-oss`)也优先使用 Responses。端点明确不支持 Responses 时回退到 `/chat/completions`;其他兼容模型使用 Chat Completions。授权、限流等错误不会任意切换接口,具体回退条件由实现判定。 -#### 从旧的 `providers` 配置迁移 +第三方服务只要提供兼容 API,仍可使用:选择 `provider: "openai"` 或 `"anthropic"`,设置 `api_base` 和完整远端 `model`。例如模型 ID 可以包含 `vendor/model`,显式填写协议可避免它被当成协议前缀。 -旧的 `providers` 配置格式**已弃用**,V2 中已移除。现有 V0/V1 配置会自动迁移。 +兼容端点不再提供厂商默认 URL 或厂商专用 provider 名称。原来使用 `deepseek`、`openrouter`、`ollama` 等名称的配置,需要改为 `openai` 并显式填写端点;原生 Gemini、Azure、Bedrock、Antigravity、Copilot 和 CLI 代理已移除。不能将非兼容 API 仅靠改名称变成 OpenAI / Anthropic API。 -**旧配置(已弃用):** +保留 `proxy`、`request_timeout`(秒)、`custom_headers`、`extra_body`、`user_agent`、`thinking_level`、`tool_schema_transform`,以及多模型、多个 API Key、限速和 fallback。`extra_body` / `custom_headers` 可覆盖请求参数,请按实际服务配置。两种协议均支持 `streaming`;Anthropic 登录令牌也沿用其内部流式请求处理。语音专用 ASR/TTS 服务独立选择,不属于聊天模型提供商。 -```json -{ - "providers": { - "zhipu": { - "api_key": "your-key", - "api_base": "https://open.bigmodel.cn/api/paas/v4" - } - }, - "agents": { - "defaults": { - "provider": "zhipu", - "model": "glm-4.7" - } - } -} -``` - -**新配置(推荐):** - -```json -{ - "version": 3, - "model_list": [ - { - "model_name": "glm-4.7", - "provider": "zhipu", - "model": "glm-4.7", - "api_keys": ["your-key"] - } - ], - "agents": { - "defaults": { - "model_name": "glm-4.7" - } - } -} -``` - -详细的迁移指南请参考 [docs/migration/model-list-migration.md](../migration/model-list-migration.md)。 - -### Provider 架构 - -PicoClaw 按协议族路由 Provider: - -- OpenAI 兼容协议:OpenRouter、OpenAI 兼容网关、Groq、智谱、vLLM 风格端点。 -- Gemini 原生协议:Google Gemini 通过原生 `models/*:generateContent` 和 `models/*:streamGenerateContent` 端点接入。 -- Anthropic 协议:Claude 原生 API 行为。 -- Codex/OAuth 路径:OpenAI OAuth/Token 认证路由。 - -这使得运行时保持轻量,同时让新的 OpenAI 兼容后端基本只需配置操作(`api_base` + `api_keys`)。 - -
-智谱 (Zhipu) 配置示例 - -**1. 获取 API key 和 base URL** - -- 获取 [API key](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) - -**2. 配置** - -```json -{ - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model_name": "glm-4.7", - "max_tokens": 8192, - "temperature": 0.7, - "max_tool_iterations": 20 - } - }, - "providers": { - "zhipu": { - "api_key": "Your API Key", - "api_base": "https://open.bigmodel.cn/api/paas/v4" - } - } -} -``` - -**3. 运行** +## 登录与令牌 ```bash -picoclaw agent -m "你好" +picoclaw auth login --provider openai +picoclaw auth login --provider openai --device-code +picoclaw auth login --provider anthropic --setup-token +picoclaw auth status +picoclaw auth logout --provider openai ``` -
+OpenAI OAuth 和 Anthropic setup-token 登录仍保留,通过 `auth_method: "oauth"` 或 `"token"` 选择现有登录凭据。它们与 API Key 接入使用不同的认证路径,第三方兼容端点通常应使用 API Key。 -
-完整配置示例 +微信、企业微信的扫码登录不受模型提供商精简影响。原来的 Antigravity 登录和 `auth models` 命令已移除;模型查询可使用 `model add` 的兼容接口流程。 -```json -{ - "agents": { - "defaults": { - "model_name": "claude-opus-4-5" - } - }, - "session": { - "dm_scope": "per-channel-peer" - }, - "providers": { - "openrouter": { - "api_key": "sk-or-v1-xxx" - }, - "groq": { - "api_key": "gsk_xxx" - } - }, - "voice": { - "model_name": "voice-gemini", - "echo_transcription": false - }, - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "token": "123456:ABC...", - "allow_from": ["123456789"] - }, - "feishu": { - "enabled": false, - "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "xxx", - "encrypt_key": "", - "verification_token": "", - "allow_from": [] - }, - "qq": { - "enabled": false, - "type": "qq", - "app_id": "", - "app_secret": "", - "allow_from": [] - } - }, - "tools": { - "web": { - "brave": { - "enabled": false, - "api_key": "BSA...", - "max_results": 5 - }, - "duckduckgo": { - "enabled": true, - "max_results": 5 - }, - "perplexity": { - "enabled": false, - "api_key": "", - "max_results": 5 - }, - "searxng": { - "enabled": false, - "base_url": "http://localhost:8888", - "max_results": 5 - } - }, - "cron": { - "exec_timeout_minutes": 5 - } - }, - "heartbeat": { - "enabled": true, - "interval": 30 - } -} -``` - -
- ---- - -## 📝 API Key 对比 - -| 服务 | 价格 | 适用场景 | -| --- | --- | --- | -| **OpenRouter** | 免费: 200K tokens/月 | 多模型聚合 (Claude, GPT-4 等) | -| **火山引擎 CodingPlan** | ¥9.9/首月 | 最适合国内用户,多种 SOTA 模型(豆包、DeepSeek 等) | -| **智谱 (Zhipu)** | 免费: 200K tokens/月 | 适合中国用户 | -| **Brave Search** | $5/1000 次查询 | 网络搜索功能 | -| **SearXNG** | 免费(自建) | 隐私优先的元搜索引擎(70+ 搜索引擎) | -| **Groq** | 免费额度可用 | 极速推理 (Llama, Mixtral) | -| **Cerebras** | 免费额度可用 | 极速推理 (Llama, Qwen 等) | -| **LongCat** | 免费: 最多 5M tokens/天 | 极速推理 | -| **ModelScope (魔搭)** | 免费: 2000 次请求/天 | 推理 (Qwen, GLM, DeepSeek 等) | +密钥等敏感设置可能来自 `.security.yml`,修改配置时请同时检查。完整字段见 [配置示例](../../config/config.example.json),部署说明见 [README](../../README.md)。 diff --git a/go.mod b/go.mod index b28cc98b..4bbc7ecc 100644 --- a/go.mod +++ b/go.mod @@ -3,13 +3,8 @@ module github.com/sipeed/picoclaw go 1.25.13 require ( - github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 - github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0 github.com/adhocore/gronx v1.20.0 github.com/anthropics/anthropic-sdk-go v1.55.1 - github.com/aws/aws-sdk-go-v2 v1.42.0 - github.com/aws/aws-sdk-go-v2/config v1.32.25 - github.com/aws/aws-sdk-go-v2/service/bedrockruntime v1.53.3 github.com/caarlos0/env/v11 v11.4.1 github.com/charmbracelet/lipgloss v1.1.0 github.com/creack/pty v1.1.24 @@ -46,21 +41,6 @@ require ( require ( aead.dev/minisign v0.2.0 // indirect - github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect - github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2 // indirect - github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.12 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.19.24 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.29 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.29 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.29 // indirect - github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.30 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.12 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.29 // indirect - github.com/aws/aws-sdk-go-v2/service/signin v1.2.0 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.31.3 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.6 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.43.3 // indirect - github.com/aws/smithy-go v1.27.1 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/bahlo/generic-list-go v0.2.0 // indirect github.com/buger/jsonparser v1.1.2 // indirect @@ -70,12 +50,9 @@ require ( github.com/charmbracelet/x/term v0.2.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/dustin/go-humanize v1.0.1 // indirect - github.com/go-logr/logr v1.4.3 // indirect - github.com/go-logr/stdr v1.2.2 // indirect - github.com/golang-jwt/jwt/v5 v5.3.1 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/invopop/jsonschema v0.14.0 // indirect - github.com/kylelemons/godebug v1.1.0 // indirect + github.com/kr/pretty v0.3.1 // indirect github.com/lucasb-eyer/go-colorful v1.3.0 // indirect github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-isatty v0.0.20 // indirect @@ -83,17 +60,13 @@ require ( github.com/ncruces/go-strftime v1.0.0 // indirect github.com/pb33f/ordered-map/v2 v2.3.1 // indirect github.com/pion/randutil v0.1.0 // indirect - github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/rivo/uniseg v0.4.7 // indirect + github.com/rogpeppe/go-internal v1.13.1 // indirect github.com/segmentio/asm v1.1.3 // indirect github.com/segmentio/encoding v0.5.4 // indirect github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect - go.opentelemetry.io/auto/sdk v1.1.0 // indirect - go.opentelemetry.io/otel v1.35.0 // indirect - go.opentelemetry.io/otel/metric v1.35.0 // indirect - go.opentelemetry.io/otel/trace v1.35.0 // indirect go.yaml.in/yaml/v4 v4.0.0-rc.2 // indirect golang.org/x/text v0.39.0 // indirect modernc.org/libc v1.73.4 // indirect @@ -108,7 +81,6 @@ require ( github.com/bytedance/sonic v1.15.2 // indirect github.com/bytedance/sonic/loader v0.5.1 // indirect github.com/cloudwego/base64x v0.1.6 // indirect - github.com/github/copilot-sdk/go v0.2.0 github.com/go-resty/resty/v2 v2.17.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/google/jsonschema-go v0.4.3 diff --git a/go.sum b/go.sum index 1db5d969..d6d6dbc2 100644 --- a/go.sum +++ b/go.sum @@ -1,56 +1,12 @@ aead.dev/minisign v0.2.0 h1:kAWrq/hBRu4AARY6AlciO83xhNnW9UaC8YipS2uhLPk= aead.dev/minisign v0.2.0/go.mod h1:zdq6LdSd9TbuSxchxwhpA9zEb9YXcVGoE8JakuiGaIQ= cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= -github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0 h1:CU4+EJeJi3TKYWEcYuSdWsjzw0nVsK/H0MSQOiPcymU= -github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0/go.mod h1:q0+UTSRvShwUCrR/s5HtyInYphN7Wvxb7snFM3u+SLA= -github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0 h1:xFaZZ+IubdftrDHnGGwZ6QvQ3KHTtWl2MCK+GMt2vxs= -github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0/go.mod h1:mCBhUhlMjLLJKr5aqw2TNS/VqJOie8MzWq3DAMJeKso= -github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= -github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= -github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM= -github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE= -github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2 h1:RHK7bS+HQMslb1sZpAokUt+zTVmue0hKSs2C791hhzU= -github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk= github.com/adhocore/gronx v1.20.0 h1:PD13Mo0wekkZ7ZZR9yb1TqeqTfybs7/K3ez9DmjQwEs= github.com/adhocore/gronx v1.20.0/go.mod h1:7oUY1WAU8rEJWmAxXR2DN0JaO4gi9khSgKjiRypqteg= github.com/andybalholm/brotli v1.2.1 h1:R+f5xP285VArJDRgowrfb9DqL18yVK0gKAW/F+eTWro= github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= github.com/anthropics/anthropic-sdk-go v1.55.1 h1:GxukHUVou6AFIngxa/Aw1z79hmwg13Hmn++KE9werbM= github.com/anthropics/anthropic-sdk-go v1.55.1/go.mod h1:3EfIfmFqxH6rbiLcIP4tPFyXL/IHakx2wDG4OU+TIEI= -github.com/aws/aws-sdk-go-v2 v1.42.0 h1:XvXMJTkFQtpBKIWZnmr9ZEOc2InWM2yldjXEJ/bymhA= -github.com/aws/aws-sdk-go-v2 v1.42.0/go.mod h1:27+ACypSLljLAEKsCYOmrjKh83vuTRkuAe9Uv/3A4bg= -github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.12 h1:oRtsqWgxbpeXrOlxOoQStx2M9WNbIkPq4C4Xn1or6bc= -github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.12/go.mod h1:Zg0Oe9qT+9wcezlm1a64wGJp2qZdRElVxo/seJf7jYU= -github.com/aws/aws-sdk-go-v2/config v1.32.25 h1:ACCejvStYoilgwrfegSt5ZntCbPrk52qfwyNcnl3omM= -github.com/aws/aws-sdk-go-v2/config v1.32.25/go.mod h1:LJyU8sDRbXUxFn8xMJIGP+v9QYYwveNLI8a/giAOiAs= -github.com/aws/aws-sdk-go-v2/credentials v1.19.24 h1:2hQqYCV9yqyePQ9o6dCrZc/zO8U3TwPr9mIKlZnPu/I= -github.com/aws/aws-sdk-go-v2/credentials v1.19.24/go.mod h1:IDwpACtwqHLISdzfwUUNq4P9DsB/h5BLg4FwJPNfqFY= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.29 h1:r6qZHbT+wxgWO/e9vYNUEtg7lv5+UN3pRqKhLXvnArg= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.29/go.mod h1:QRnaRcTVGKPGRy8w78HMQtKUGRYcnMZAANATkeVA6Mo= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.29 h1:f3vKqSo13fhTYb+JEcXwXefZQE26I1FB5eTSniU67ko= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.29/go.mod h1:MzoLFUArKGpGD+ukmPiTPG1X5x4o6M2kq4v2dr1FiEc= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.29 h1:RdwIf/CuUsvJX3RgJagbOyotl/cxoLY4xviKuE7p2GY= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.29/go.mod h1:71wt8W2EgswdZy9Mf9KNnzxZ3TiZlv4caKghPktDOkA= -github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.30 h1:VTGy885W5DKBxWRUJbym9hytNaYzsyaPkCHGRRMAOhU= -github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.30/go.mod h1:AS0HycUvJRFvTt613AYDOgO2jzw+00cVSMny8XB3yMY= -github.com/aws/aws-sdk-go-v2/service/bedrockruntime v1.53.3 h1:HTzzFDJiFSNkZX1Al72+insR4dre/vUeT3YZ4b9h0MA= -github.com/aws/aws-sdk-go-v2/service/bedrockruntime v1.53.3/go.mod h1:dFhfMfXoFrnX6XK/gXDh+4azdybtKll2QnP239wm2O8= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.12 h1:ZD2+BSw9vFsNlKYIasSNt3uDbjqqXIBcM13UJv/Lx2k= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.12/go.mod h1:Ms4zlcVBbXbiP7EVLhl+lgjvA/a7YphqQ3Ih3174EmI= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.29 h1:DRebniUGZ2MqiiIVmQJ04vIXr918hubdHMnarSLEWyU= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.29/go.mod h1:LfRkPCD8YHDM2E5eTkos2UpwYeZnBcVarTa8L59bJHA= -github.com/aws/aws-sdk-go-v2/service/signin v1.2.0 h1:3nXpRcFwRCW8n7HgO2QGy0Dc20eQNfBuUemGQhpF8m8= -github.com/aws/aws-sdk-go-v2/service/signin v1.2.0/go.mod h1:LxYujSTLPRlp2vTtcUO/+1ilrew8ytt6SvQyOgejzFQ= -github.com/aws/aws-sdk-go-v2/service/sso v1.31.3 h1:ey1XLTYXb9PcLt4535632o5kCGXNXEhNb620Dqwuylo= -github.com/aws/aws-sdk-go-v2/service/sso v1.31.3/go.mod h1:Lk7PlmoTYryQmyBG0EXqj5BcUbj3whXdU2s3yGI3EAc= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.6 h1:yLr03zQE/5Eu5l3QU0Si+xMbLMbSDF2YXsigqXngs6g= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.6/go.mod h1:Q5N6icH+KJZDLh+ESNwzdv6cZ6vLFF/egy3IOxWhmz4= -github.com/aws/aws-sdk-go-v2/service/sts v1.43.3 h1:VrIhKRCSK1umelSgB9RghvA9RTUYeQffyAS5ApXehNI= -github.com/aws/aws-sdk-go-v2/service/sts v1.43.3/go.mod h1:r8wkDOuLaaMFqFiYAb8dGY2A3gJCOujMc6CFOVC4Zhc= -github.com/aws/smithy-go v1.27.1 h1:4T340VFndXtADGF52gYa1POyL7s9E4Z1OeZ1hCscIw8= -github.com/aws/smithy-go v1.27.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk= @@ -97,13 +53,6 @@ github.com/ergochat/readline v0.1.3 h1:/DytGTmwdUJcLAe3k3VJgowh5vNnsdifYT6uVaf4p github.com/ergochat/readline v0.1.3/go.mod h1:o3ux9QLHLm77bq7hDB21UTm6HlV2++IPDMfIfKDuOgY= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/github/copilot-sdk/go v0.2.0 h1:RnrIIirmtp4wGgqSQFJ2k9phbeveIxOtYZqDogoNEa0= -github.com/github/copilot-sdk/go v0.2.0/go.mod h1:uGWkjVYcp2DV9DgtqYihh5tEoJjNqxIFaUNnrwY4FxM= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= -github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= -github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= -github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-redis/redis/v8 v8.11.4/go.mod h1:2Z2wHZXdQpCDXEGzqMockDpNyYvi2l4Pxt6RJr792+w= github.com/go-resty/resty/v2 v2.6.0/go.mod h1:PwvJS6hvaPkjtjNg9ph+VrSD92bi5Zq73w/BIH7cC3Q= github.com/go-resty/resty/v2 v2.17.1 h1:x3aMpHK1YM9e4va/TMDRlusDDoZiQ+ViDu/WpA6xTM4= @@ -156,8 +105,6 @@ github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8i github.com/invopop/jsonschema v0.14.0/go.mod h1:ygm6C2EaVNMBDPpaPlnOA2pFAxBnxGjFlMZABxm9n2I= github.com/kagisearch/kagi-openapi-golang v0.0.0-20260526215348-96575e864d62 h1:nyUi7Wel3KlVSa5ArgX/snlizqfaxU48qtvXS/JK5GE= github.com/kagisearch/kagi-openapi-golang v0.0.0-20260526215348-96575e864d62/go.mod h1:vONkS+clG730HSKOw3nZVa22TjB21r6csKYzYt0a9zI= -github.com/keybase/go-keychain v0.0.1 h1:way+bWYa6lDppZoZcgMbYsvC7GxljxrskdNInRtuthU= -github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXwkPPMeUgOK1k= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao= @@ -173,8 +120,6 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= -github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/larksuite/oapi-sdk-go/v3 v3.9.4 h1:oMgcY7NBjJv1QXJqFAfcoN/TbScCkCuRZfbb1mCwZmI= github.com/larksuite/oapi-sdk-go/v3 v3.9.4/go.mod h1:ZEplY+kwuIrj/nqw5uSCINNATcH3KdxSN7y+UxYY5fI= github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag= @@ -217,8 +162,6 @@ github.com/pion/rtp v1.10.2 h1:l+f6tTDcAH6xwepaAoW791ddhuYsJlqRATOzirO04Mo= github.com/pion/rtp v1.10.2/go.mod h1:Au8fc6cEByy8RLTwKTQTEeQqDB/SJDxwL4mZuxYA5Pk= github.com/pion/webrtc/v3 v3.3.6 h1:7XAh4RPtlY1Vul6/GmZrv7z+NnxKA6If0KStXBI2ZLE= github.com/pion/webrtc/v3 v3.3.6/go.mod h1:zyN7th4mZpV27eXybfR/cnUf3J2DRy8zw/mdjD9JTNM= -github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= -github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -290,14 +233,6 @@ github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9dec github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= go.mau.fi/util v0.9.8 h1:+/jf8eM2dAT2wx9UidmaneH28r/CSCKCniCyby1qWz8= go.mau.fi/util v0.9.8/go.mod h1:up/5mbzH2M1pSBNXqRxODn8dg/hEKbLJu92W4/SNAX0= -go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= -go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= -go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ= -go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y= -go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M= -go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE= -go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs= -go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc= go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= @@ -366,7 +301,6 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/integration/README.md b/integration/README.md index 3f668d86..40206da3 100644 --- a/integration/README.md +++ b/integration/README.md @@ -24,7 +24,7 @@ That distinction matters: If a test should actively protect merges between PRs, it should be reachable from [`scripts/run-integration-tests.sh`](../scripts/run-integration-tests.sh), either by extending an existing suite or by adding a new one. -Some integration-tagged tests are intentionally opt-in and not part of the Docker suites. For example, real CLI smoke tests under `pkg/providers/cli/` depend on external binaries being installed locally. Those are useful for manual verification, but they do not gate PR merges. +Integration-tagged tests run through the Docker suites listed above. External CLI-provider smoke tests were removed with the CLI model providers. ## What CI Runs diff --git a/pkg/agent/agent_test.go b/pkg/agent/agent_test.go index cc9115e5..d21c0fc3 100644 --- a/pkg/agent/agent_test.go +++ b/pkg/agent/agent_test.go @@ -3508,7 +3508,7 @@ func TestProcessMessage_SwitchModelShowModelConsistency(t *testing.T) { }, { ModelName: "deepseek", - Model: "openrouter/deepseek/deepseek-v3.2", + Model: "openai/deepseek/deepseek-v3.2", APIBase: "https://openrouter.ai/api/v1", APIKeys: config.SimpleSecureStrings("test-key"), }, @@ -3536,7 +3536,7 @@ func TestProcessMessage_SwitchModelShowModelConsistency(t *testing.T) { ChatID: "chat1", Content: "/show model", }) - if !strings.Contains(showResp, "Current Model: deepseek (Provider: openrouter)") { + if !strings.Contains(showResp, "Current Model: deepseek (Provider: openai)") { t.Fatalf("unexpected /show model reply after switch: %q", showResp) } @@ -3638,13 +3638,13 @@ func TestProcessMessage_SwitchModelRoutesSubsequentRequestsToSelectedProvider(t }, { ModelName: "deepseek", - Model: "openrouter/deepseek/deepseek-v3.2", + Model: "openai/deepseek/deepseek-v3.2", APIBase: remoteServer.URL, APIKeys: config.SimpleSecureStrings("remote-key"), }, { ModelName: "deepseek", - Model: "openrouter/deepseek/deepseek-v3.2", + Model: "openai/deepseek/deepseek-v3.2", APIBase: remoteServer.URL, APIKeys: config.SimpleSecureStrings("remote-key-secondary"), }, @@ -3906,14 +3906,14 @@ func TestProcessMessage_FallbackUsesPerCandidateProvider(t *testing.T) { ModelList: []*config.ModelConfig{ { ModelName: "mistral-primary", - Model: "openrouter/mistralai/mistral-small-3.1", + Model: "openai/mistralai/mistral-small-3.1", APIBase: primaryServer.URL, APIKeys: config.SimpleSecureStrings("primary-key"), Workspace: workspace, }, { ModelName: "gemma-fallback", - Model: "openrouter/gemma-3-27b-it", + Model: "openai/gemma-3-27b-it", APIBase: fallbackServer.URL, APIKeys: config.SimpleSecureStrings("fallback-key"), Workspace: workspace, @@ -4012,7 +4012,7 @@ func TestProcessMessage_FallbackReceivesExplicitThinkingOff(t *testing.T) { ModelList: []*config.ModelConfig{ { ModelName: "primary-model", - Model: "openrouter/primary-model", + Model: "openai/primary-model", APIBase: primaryServer.URL, APIKeys: config.SimpleSecureStrings("primary-key"), Workspace: workspace, @@ -4106,7 +4106,7 @@ func TestProcessMessage_PrimaryThinkingOffDoesNotLeakToFallback(t *testing.T) { ModelList: []*config.ModelConfig{ { ModelName: "primary-model", - Model: "openrouter/primary-model", + Model: "openai/primary-model", APIBase: primaryServer.URL, APIKeys: config.SimpleSecureStrings("primary-key"), ThinkingLevel: "off", @@ -4200,7 +4200,7 @@ func TestProcessMessage_FallbackThinkingOffUsesCandidateIdentity(t *testing.T) { ModelList: []*config.ModelConfig{ { ModelName: "primary-model", - Model: "openrouter/primary-model", + Model: "openai/primary-model", APIBase: primaryServer.URL, APIKeys: config.SimpleSecureStrings("primary-key"), Workspace: workspace, @@ -4278,13 +4278,13 @@ func TestProcessMessage_FallbackUsesActiveProviderWhenCandidateNotRegistered(t * MaxTokens: 4096, MaxToolIterations: 3, // No model_list entry for this alias — absent from CandidateProviders. - ModelFallbacks: []string{"openrouter/fallback-model"}, + ModelFallbacks: []string{"openai/fallback-model"}, }, }, ModelList: []*config.ModelConfig{ { ModelName: "primary-model", - Model: "openrouter/primary-model", + Model: "openai/primary-model", APIBase: primaryServer.URL, APIKeys: config.SimpleSecureStrings("primary-key"), Workspace: workspace, diff --git a/pkg/agent/instance_test.go b/pkg/agent/instance_test.go index 8f65d588..ccf2666e 100644 --- a/pkg/agent/instance_test.go +++ b/pkg/agent/instance_test.go @@ -150,9 +150,9 @@ func TestNewAgentInstance_ResolveCandidatesFromModelListAlias(t *testing.T) { { name: "alias with provider prefix", aliasName: "step-3.5-flash", - modelName: "openrouter/stepfun/step-3.5-flash:free", + modelName: "openai/stepfun/step-3.5-flash:free", apiBase: "https://openrouter.ai/api/v1", - wantProvider: "openrouter", + wantProvider: "openai", wantModel: "stepfun/step-3.5-flash:free", }, { @@ -167,9 +167,9 @@ func TestNewAgentInstance_ResolveCandidatesFromModelListAlias(t *testing.T) { name: "explicit provider overrides model prefix", aliasName: "nvidia-gpt", modelName: "z-ai/glm-5.1", - provider: "nvidia", + provider: "openai", apiBase: "https://integrate.api.nvidia.com/v1", - wantProvider: "nvidia", + wantProvider: "openai", wantModel: "z-ai/glm-5.1", }, } @@ -229,12 +229,12 @@ func TestNewAgentInstance_PreservesDistinctLimiterIdentityForSharedResolvedModel ModelList: []*config.ModelConfig{ { ModelName: "glm-4.7", - Model: "zhipu/glm-4.7", + Model: "openai/glm-4.7", RPM: 1, }, { ModelName: "glm-4.7__key_1", - Model: "zhipu/glm-4.7", + Model: "openai/glm-4.7", RPM: 3, }, }, @@ -247,11 +247,11 @@ func TestNewAgentInstance_PreservesDistinctLimiterIdentityForSharedResolvedModel first := agent.Candidates[0] second := agent.Candidates[1] - if first.Provider != "zhipu" || first.Model != "glm-4.7" { - t.Fatalf("first candidate = %s/%s, want zhipu/glm-4.7", first.Provider, first.Model) + if first.Provider != "openai" || first.Model != "glm-4.7" { + t.Fatalf("first candidate = %s/%s, want openai/glm-4.7", first.Provider, first.Model) } - if second.Provider != "zhipu" || second.Model != "glm-4.7" { - t.Fatalf("second candidate = %s/%s, want zhipu/glm-4.7", second.Provider, second.Model) + if second.Provider != "openai" || second.Model != "glm-4.7" { + t.Fatalf("second candidate = %s/%s, want openai/glm-4.7", second.Provider, second.Model) } if first.IdentityKey != "model_name:glm-4.7" { t.Fatalf("first identity key = %q, want %q", first.IdentityKey, "model_name:glm-4.7") @@ -274,13 +274,13 @@ func TestNewAgentInstance_PreservesConfigIdentityForExplicitProviderModelRef(t * Agents: config.AgentsConfig{ Defaults: config.AgentDefaults{ Workspace: tmpDir, - ModelName: "nvidia/z-ai/glm-5.1", + ModelName: "openai/z-ai/glm-5.1", }, }, ModelList: []*config.ModelConfig{ { ModelName: "nvidia-glm", - Provider: "nvidia", + Provider: "openai", Model: "z-ai/glm-5.1", RPM: 7, }, @@ -293,8 +293,8 @@ func TestNewAgentInstance_PreservesConfigIdentityForExplicitProviderModelRef(t * } candidate := agent.Candidates[0] - if candidate.Provider != "nvidia" || candidate.Model != "z-ai/glm-5.1" { - t.Fatalf("candidate = %s/%s, want nvidia/z-ai/glm-5.1", candidate.Provider, candidate.Model) + if candidate.Provider != "openai" || candidate.Model != "z-ai/glm-5.1" { + t.Fatalf("candidate = %s/%s, want openai/z-ai/glm-5.1", candidate.Provider, candidate.Model) } if candidate.IdentityKey != "model_name:nvidia-glm" { t.Fatalf("identity key = %q, want %q", candidate.IdentityKey, "model_name:nvidia-glm") @@ -438,7 +438,7 @@ func TestPopulateCandidateProviders_ResolvesAlias(t *testing.T) { // TestPopulateCandidateProviders_ResolvesProtocolPrefix verifies that a // model_list entry using full "provider/model" notation (e.g. -// "gemini/gemma-3-27b-it") is matched correctly when referenced by model_name. +// "anthropic/gemma-3-27b-it") is matched correctly when referenced by model_name. func TestPopulateCandidateProviders_ResolvesProtocolPrefix(t *testing.T) { workspace := t.TempDir() out := map[string]providers.LLMProvider{} @@ -447,7 +447,7 @@ func TestPopulateCandidateProviders_ResolvesProtocolPrefix(t *testing.T) { ModelList: []*config.ModelConfig{ { ModelName: "gemma", - Model: "gemini/gemma-3-27b-it", + Model: "anthropic/gemma-3-27b-it", APIKeys: config.SimpleSecureStrings("gemini-test-key"), Workspace: workspace, }, @@ -455,7 +455,7 @@ func TestPopulateCandidateProviders_ResolvesProtocolPrefix(t *testing.T) { } populateCandidateProvidersFromNames(cfg, workspace, []string{"gemma"}, out) - key := providers.ModelKey("gemini", "gemma-3-27b-it") + key := providers.ModelKey("anthropic", "gemma-3-27b-it") if out[key] == nil { t.Fatalf("expected CandidateProviders[%q] to be populated for protocol-prefixed model", key) } @@ -464,11 +464,11 @@ func TestPopulateCandidateProviders_ResolvesProtocolPrefix(t *testing.T) { func TestLookupModelConfigByRef_BareUsesDefaultProvider(t *testing.T) { cfg := &config.Config{ Agents: config.AgentsConfig{ - Defaults: config.AgentDefaults{Provider: "openrouter"}, + Defaults: config.AgentDefaults{Provider: "openai"}, }, ModelList: []*config.ModelConfig{ - {ModelName: "openai-model", Provider: "openai", Model: "gpt-4o"}, - {ModelName: "openrouter-model", Provider: "openrouter", Model: "gpt-4o"}, + {ModelName: "anthropic-model", Provider: "anthropic", Model: "claude-sonnet-4-6"}, + {ModelName: "openrouter-model", Provider: "openai", Model: "gpt-4o"}, }, } @@ -484,7 +484,7 @@ func TestResolvePrimaryProviderForAgent_ResolvesRawUsingProviderTemplate(t *test cfg := &config.Config{ ModelList: []*config.ModelConfig{{ ModelName: "openrouter-template", - Model: "openrouter/auto", + Model: "openai/auto", APIBase: "https://openrouter.ai/api/v1", APIKeys: config.SimpleSecureStrings("sk-or-test"), }}, @@ -494,7 +494,7 @@ func TestResolvePrimaryProviderForAgent_ResolvesRawUsingProviderTemplate(t *test cfg, workspace, "raw-agent", - "openrouter/new-model", + "openai/new-model", fallback, ) if resolved == fallback { @@ -555,7 +555,7 @@ func TestProviderForFallbackCandidateRejectsMissingCrossProvider(t *testing.T) { agent, activeProvider, activeCandidates, - providers.FallbackCandidate{Provider: "openrouter", Model: "new-model"}, + providers.FallbackCandidate{Provider: "anthropic", Model: "claude-sonnet-4-6"}, ) if err == nil || provider != nil { t.Fatalf("provider = %T, error = %v, want missing cross-provider error", provider, err) @@ -758,20 +758,20 @@ func TestPopulateCandidateProvidersFromCandidatesUsesCandidateProvider(t *testin }, { ModelName: "backup", - Provider: "openrouter", + Provider: "openai", Model: "shared-model", APIKeys: config.SimpleSecureStrings("sk-openrouter"), }, }} candidate := providers.FallbackCandidate{ - Provider: "openrouter", + Provider: "openai", Model: "shared-model", DisplayName: "backup", IdentityKey: "model_name:backup", } populateCandidateProvidersFromCandidates(cfg, t.TempDir(), []providers.FallbackCandidate{candidate}, out) - if out[providers.ModelKey("openrouter", "shared-model")] == nil { + if out[providers.ModelKey("openai", "shared-model")] == nil { t.Fatal("candidate provider map did not use the already resolved OpenRouter candidate") } } @@ -782,7 +782,7 @@ func TestPopulateCandidateProviders_ResolvesRawUsingProviderTemplate(t *testing. cfg := &config.Config{ ModelList: []*config.ModelConfig{{ ModelName: "openrouter-template", - Model: "openrouter/auto", + Model: "openai/auto", APIBase: "https://openrouter.ai/api/v1", APIKeys: config.SimpleSecureStrings("sk-or-test"), Workspace: workspace, @@ -792,11 +792,11 @@ func TestPopulateCandidateProviders_ResolvesRawUsingProviderTemplate(t *testing. populateCandidateProvidersFromNames( cfg, workspace, - []string{"openrouter/deepseek/deepseek-v3.2"}, + []string{"openai/deepseek/deepseek-v3.2"}, out, ) - key := providers.ModelKey("openrouter", "deepseek/deepseek-v3.2") + key := providers.ModelKey("openai", "deepseek/deepseek-v3.2") if out[key] == nil { t.Fatalf("expected CandidateProviders[%q] to use the OpenRouter template", key) } @@ -835,7 +835,7 @@ func TestPopulateCandidateProviders_UnmatchedNameIsSkipped(t *testing.T) { out := map[string]providers.LLMProvider{} cfg := &config.Config{ ModelList: []*config.ModelConfig{ - {ModelName: "my-gemini", Model: "gemini/gemini-2.5-pro", APIKeys: config.SimpleSecureStrings("key")}, + {ModelName: "my-gemini", Model: "anthropic/gemini-2.5-pro", APIKeys: config.SimpleSecureStrings("key")}, }, } populateCandidateProvidersFromNames(cfg, t.TempDir(), []string{"nonexistent-model"}, out) @@ -863,20 +863,20 @@ func TestNewAgentInstance_CandidateProvidersPopulatedForCrossProviderFallbacks(t ModelList: []*config.ModelConfig{ { ModelName: "mistral-small-3.1", - Model: "openrouter/mistralai/mistral-small-3.1-24b-instruct:free", + Model: "openai/mistralai/mistral-small-3.1-24b-instruct:free", APIBase: "https://openrouter.ai/api/v1", APIKeys: config.SimpleSecureStrings("sk-or-test"), Workspace: workspace, }, { ModelName: "gemma-3-27b", - Model: "gemini/gemma-3-27b-it", + Model: "anthropic/gemma-3-27b-it", APIKeys: config.SimpleSecureStrings("AIzaSy-test"), Workspace: workspace, }, { ModelName: "gemini-images", - Model: "gemini/gemini-2.5-flash-lite", + Model: "anthropic/gemini-2.5-flash-lite", APIKeys: config.SimpleSecureStrings("AIzaSy-test"), Workspace: workspace, }, @@ -888,8 +888,8 @@ func TestNewAgentInstance_CandidateProvidersPopulatedForCrossProviderFallbacks(t // Only fallback models need entries — the primary uses the injected provider directly. wantKeys := []string{ - providers.ModelKey("gemini", "gemma-3-27b-it"), - providers.ModelKey("gemini", "gemini-2.5-flash-lite"), + providers.ModelKey("anthropic", "gemma-3-27b-it"), + providers.ModelKey("anthropic", "gemini-2.5-flash-lite"), } for _, key := range wantKeys { diff --git a/pkg/audio/asr/asr.go b/pkg/audio/asr/asr.go index 94ede23e..b0211243 100644 --- a/pkg/audio/asr/asr.go +++ b/pkg/audio/asr/asr.go @@ -4,8 +4,8 @@ import ( "context" "strings" + "github.com/sipeed/picoclaw/pkg/audio" "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/providers" ) const elevenLabsSupportedModelID = "scribe_v1" @@ -26,40 +26,13 @@ type TranscriptionResponse struct { } func supportsAudioTranscription(modelCfg *config.ModelConfig) bool { - protocol, _ := providers.ExtractProtocol(modelCfg) - - switch protocol { - case "openai", "azure", - "litellm", "openrouter", "groq", "zhipu", "gemini", "nvidia", - "ollama", "moonshot", "shengsuanyun", "deepseek", "cerebras", - "vivgrid", "volcengine", "vllm", "qwen-portal", "qwen-intl", "qwen-us", - "mistral", "avian", "minimax", "longcat", "modelscope", "novita", - "alibaba-coding", "zai": - // These protocols all go through the OpenAI-compatible or Azure provider path in - // providers.CreateProviderFromConfig, so they are the only ones that can supply - // the audio media payload shape expected by NewAudioModelTranscriber. - - // TODO: Further restrict this by modelID, since not every model under these - // protocols supports audio transcription. - return true - default: - return false - } + protocol, _, _ := audio.ResolveModel(modelCfg) + return protocol == "openai" } func supportsWhisperTranscription(modelCfg *config.ModelConfig) bool { - protocol, _ := providers.ExtractProtocol(modelCfg) - - switch protocol { - case "openai", "litellm", "openrouter", "groq", "zhipu", "gemini", "nvidia", - "ollama", "moonshot", "shengsuanyun", "deepseek", "cerebras", - "vivgrid", "volcengine", "vllm", "qwen-portal", "qwen-intl", "qwen-us", - "mistral", "avian", "minimax", "longcat", "modelscope", "novita", - "alibaba-coding", "zai", "mimo": - return true - default: - return false - } + protocol, _, _ := audio.ResolveModel(modelCfg) + return protocol == "openai" || protocol == "groq" || protocol == "mimo" } func whisperModelID(modelCfg *config.ModelConfig) string { @@ -71,7 +44,7 @@ func whisperModelID(modelCfg *config.ModelConfig) string { return "" } - _, modelID := providers.ExtractProtocol(modelCfg) + _, modelID, _ := audio.ResolveModel(modelCfg) if strings.Contains(strings.ToLower(modelID), "whisper") { return modelID } @@ -83,7 +56,7 @@ func isElevenLabsTranscriptionModel(modelCfg *config.ModelConfig) bool { return false } - protocol, _ := providers.ExtractProtocol(modelCfg) + protocol, _, _ := audio.ResolveModel(modelCfg) return protocol == "elevenlabs" } @@ -93,7 +66,7 @@ func transcriberFromModelConfig(modelCfg *config.ModelConfig) Transcriber { } if isElevenLabsTranscriptionModel(modelCfg) { - _, modelID := providers.ExtractProtocol(modelCfg) + _, modelID, _ := audio.ResolveModel(modelCfg) return NewElevenLabsTranscriber(modelCfg.APIKey(), modelCfg.APIBase, modelID) } if modelID := whisperModelID(modelCfg); modelID != "" { @@ -111,7 +84,7 @@ func fallbackTranscriberFromModelConfig(modelCfg *config.ModelConfig) Transcribe } if isElevenLabsTranscriptionModel(modelCfg) { - _, modelID := providers.ExtractProtocol(modelCfg) + _, modelID, _ := audio.ResolveModel(modelCfg) return NewElevenLabsTranscriber(modelCfg.APIKey(), modelCfg.APIBase, modelID) } if modelID := whisperModelID(modelCfg); modelID != "" { diff --git a/pkg/audio/asr/whisper_transcriber.go b/pkg/audio/asr/whisper_transcriber.go index fc1101e1..f80a561b 100644 --- a/pkg/audio/asr/whisper_transcriber.go +++ b/pkg/audio/asr/whisper_transcriber.go @@ -13,9 +13,9 @@ import ( "strings" "time" + "github.com/sipeed/picoclaw/pkg/audio" "github.com/sipeed/picoclaw/pkg/config" "github.com/sipeed/picoclaw/pkg/logger" - "github.com/sipeed/picoclaw/pkg/providers" "github.com/sipeed/picoclaw/pkg/utils" ) @@ -32,14 +32,14 @@ func NewWhisperTranscriber(modelCfg *config.ModelConfig) *WhisperTranscriber { return nil } - protocol, modelID := providers.ExtractProtocol(modelCfg) + protocol, modelID, apiBase := audio.ResolveModel(modelCfg) if modelID == "" { modelID = strings.TrimSpace(modelCfg.Model) } tr := newWhisperTranscriber( modelCfg.APIKey(), - providers.ResolveAPIBase(modelCfg), + apiBase, modelID, protocol, ) diff --git a/pkg/audio/models.go b/pkg/audio/models.go new file mode 100644 index 00000000..a2d23634 --- /dev/null +++ b/pkg/audio/models.go @@ -0,0 +1,38 @@ +package audio + +import ( + "strings" + + "github.com/sipeed/picoclaw/pkg/config" + "github.com/sipeed/picoclaw/pkg/providers" +) + +// ResolveModel keeps speech-only services independent of the chat provider catalog. +func ResolveModel(cfg *config.ModelConfig) (protocol, modelID, apiBase string) { + if cfg == nil { + return "", "", "" + } + defaults := map[string]string{ + "elevenlabs": "https://api.elevenlabs.io", + "groq": "https://api.groq.com/openai/v1", + "mimo": "https://api.xiaomimimo.com/v1", + } + protocol = strings.ToLower(strings.TrimSpace(cfg.Provider)) + modelID = strings.TrimSpace(cfg.Model) + if protocol == "" { + prefix, rest, found := strings.Cut(modelID, "/") + if _, ok := defaults[strings.ToLower(prefix)]; found && ok { + protocol, modelID = strings.ToLower(prefix), rest + } else { + protocol, modelID = providers.ExtractProtocol(cfg) + } + } + apiBase = strings.TrimRight(strings.TrimSpace(cfg.APIBase), "/") + if apiBase == "" { + apiBase = defaults[protocol] + if apiBase == "" { + apiBase = providers.DefaultAPIBaseForProtocol(protocol) + } + } + return protocol, modelID, apiBase +} diff --git a/pkg/audio/tts/tts.go b/pkg/audio/tts/tts.go index fc8a36ea..6f60e045 100644 --- a/pkg/audio/tts/tts.go +++ b/pkg/audio/tts/tts.go @@ -9,9 +9,9 @@ import ( "strings" "time" + "github.com/sipeed/picoclaw/pkg/audio" "github.com/sipeed/picoclaw/pkg/config" "github.com/sipeed/picoclaw/pkg/media" - "github.com/sipeed/picoclaw/pkg/providers" ) type TTSProvider interface { @@ -28,18 +28,18 @@ func providerFromModelConfig(mc *config.ModelConfig) TTSProvider { return nil } - protocol, modelID := providers.ExtractProtocol(mc) + protocol, modelID, apiBase := audio.ResolveModel(mc) if modelID == "" { modelID = strings.TrimSpace(mc.Model) } switch protocol { case "mimo": - return NewMimoTTSProvider(mc.APIKey(), providers.ResolveAPIBase(mc), modelID, mc.Proxy) + return NewMimoTTSProvider(mc.APIKey(), apiBase, modelID, mc.Proxy) default: return NewOpenAITTSProviderWithOptions( mc.APIKey(), - providers.ResolveAPIBase(mc), + apiBase, mc.Proxy, modelID, openAITTSOptionsFromModelConfig(mc), diff --git a/pkg/auth/oauth.go b/pkg/auth/oauth.go index c03c30d1..86d36aab 100644 --- a/pkg/auth/oauth.go +++ b/pkg/auth/oauth.go @@ -23,8 +23,8 @@ import ( type OAuthProviderConfig struct { Issuer string ClientID string - ClientSecret string // Required for Google OAuth (confidential client) - TokenURL string // Override token endpoint (Google uses a different URL than issuer) + ClientSecret string // Optional confidential-client secret + TokenURL string // Optional override for the token endpoint Scopes string Originator string Port int @@ -49,32 +49,6 @@ func OpenAIOAuthConfig() OAuthProviderConfig { } } -// GoogleAntigravityOAuthConfig returns the OAuth configuration for Google Cloud Code Assist (Antigravity). -// Client credentials are the same ones used by OpenCode/pi-ai for Cloud Code Assist access. -func GoogleAntigravityOAuthConfig() OAuthProviderConfig { - // These are the same client credentials used by the OpenCode antigravity plugin. - clientID := decodeBase64( - "MTA3MTAwNjA2MDU5MS10bWhzc2luMmgyMWxjcmUyMzV2dG9sb2poNGc0MDNlcC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbQ==", - ) - clientSecret := decodeBase64("R09DU1BYLUs1OEZXUjQ4NkxkTEoxbUxCOHNYQzR6NnFEQWY=") - return OAuthProviderConfig{ - Issuer: "https://accounts.google.com/o/oauth2/v2", - TokenURL: "https://oauth2.googleapis.com/token", - ClientID: clientID, - ClientSecret: clientSecret, - Scopes: "https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/cclog https://www.googleapis.com/auth/experimentsandconfigs", - Port: 51121, - } -} - -func decodeBase64(s string) string { - data, err := base64.StdEncoding.DecodeString(s) - if err != nil { - return s - } - return string(data) -} - // GenerateState generates a random state string for OAuth CSRF protection. func GenerateState() (string, error) { buf := make([]byte, 32) @@ -503,27 +477,15 @@ func buildAuthorizeURL(cfg OAuthProviderConfig, pkce PKCECodes, state, redirectU "state": {state}, } - isGoogle := strings.Contains(strings.ToLower(cfg.Issuer), "accounts.google.com") - if isGoogle { - // Google OAuth requires these for refresh token support - params.Set("access_type", "offline") - params.Set("prompt", "consent") - } else { - // OpenAI-specific parameters - params.Set("id_token_add_organizations", "true") - params.Set("codex_cli_simplified_flow", "true") - if strings.Contains(strings.ToLower(cfg.Issuer), "auth.openai.com") { - params.Set("originator", "picoclaw") - } - if cfg.Originator != "" { - params.Set("originator", cfg.Originator) - } + params.Set("id_token_add_organizations", "true") + params.Set("codex_cli_simplified_flow", "true") + if strings.Contains(strings.ToLower(cfg.Issuer), "auth.openai.com") { + params.Set("originator", "picoclaw") + } + if cfg.Originator != "" { + params.Set("originator", cfg.Originator) } - // Google uses /auth path, OpenAI uses /oauth/authorize - if isGoogle { - return cfg.Issuer + "/auth?" + params.Encode() - } return cfg.Issuer + "/oauth/authorize?" + params.Encode() } @@ -547,9 +509,6 @@ func ExchangeCodeForTokens(cfg OAuthProviderConfig, code, codeVerifier, redirect // Determine provider name from config provider := "openai" - if cfg.TokenURL != "" && strings.Contains(cfg.TokenURL, "googleapis.com") { - provider = "google-antigravity" - } resp, err := http.PostForm(tokenURL, data) if err != nil { diff --git a/pkg/auth/store.go b/pkg/auth/store.go index 0e6567a0..abaae569 100644 --- a/pkg/auth/store.go +++ b/pkg/auth/store.go @@ -26,11 +26,6 @@ type AuthStore struct { Credentials map[string]*AuthCredential `json:"credentials"` } -const ( - providerGoogleAntigravity = "google-antigravity" - providerAntigravityAlias = "antigravity" -) - func (c *AuthCredential) IsExpired() bool { if c.ExpiresAt.IsZero() { return false @@ -50,13 +45,7 @@ func authFilePath() string { } func canonicalProvider(provider string) string { - normalized := strings.ToLower(strings.TrimSpace(provider)) - switch normalized { - case providerAntigravityAlias: - return providerGoogleAntigravity - default: - return normalized - } + return strings.ToLower(strings.TrimSpace(provider)) } func cloneCredential(cred *AuthCredential) *AuthCredential { diff --git a/pkg/auth/store_test.go b/pkg/auth/store_test.go index 578ed4ea..82e9b274 100644 --- a/pkg/auth/store_test.go +++ b/pkg/auth/store_test.go @@ -1,7 +1,6 @@ package auth import ( - "encoding/json" "os" "path/filepath" "runtime" @@ -188,286 +187,14 @@ func TestLoadStoreEmpty(t *testing.T) { } } -func TestGetCredentialCanonicalizesLegacyAntigravityProvider(t *testing.T) { - tmpDir := setTestAuthHome(t) - - expiresAt := time.Date(2026, 4, 16, 10, 0, 0, 0, time.UTC) - store := map[string]any{ - "credentials": map[string]any{ - "antigravity": map[string]any{ - "access_token": "legacy-token", - "expires_at": expiresAt.Format(time.RFC3339), - "provider": "antigravity", - "auth_method": "oauth", - "project_id": "project-1", - }, - }, - } - data, err := json.Marshal(store) - if err != nil { - t.Fatalf("json.Marshal() error: %v", err) - } - path := filepath.Join(tmpDir, ".picoclaw", "auth.json") - err = os.MkdirAll(filepath.Dir(path), 0o755) - if err != nil { - t.Fatalf("MkdirAll() error: %v", err) - } - err = os.WriteFile(path, data, 0o600) - if err != nil { - t.Fatalf("WriteFile() error: %v", err) - } - - cred, err := GetCredential("google-antigravity") - if err != nil { - t.Fatalf("GetCredential() error: %v", err) - } - if cred == nil { - t.Fatal("GetCredential() returned nil") - } - if cred.Provider != "google-antigravity" { - t.Fatalf("Provider = %q, want %q", cred.Provider, "google-antigravity") - } - if !cred.ExpiresAt.Equal(expiresAt) { - t.Fatalf("ExpiresAt = %v, want %v", cred.ExpiresAt, expiresAt) - } -} - -func TestLoadStoreMergesAntigravityAliasesPreferringNewerExpiry(t *testing.T) { - tmpDir := setTestAuthHome(t) - - legacyExpiry := time.Date(2026, 4, 16, 10, 0, 0, 0, time.UTC) - refreshedExpiry := time.Date(2026, 4, 16, 12, 0, 0, 0, time.UTC) - store := map[string]any{ - "credentials": map[string]any{ - "antigravity": map[string]any{ - "access_token": "legacy-token", - "refresh_token": "legacy-refresh", - "expires_at": legacyExpiry.Format(time.RFC3339), - "provider": "antigravity", - "auth_method": "oauth", - "email": "legacy@example.com", - }, - "google-antigravity": map[string]any{ - "access_token": "fresh-token", - "expires_at": refreshedExpiry.Format(time.RFC3339), - "provider": "google-antigravity", - "auth_method": "oauth", - "project_id": "project-2", - }, - }, - } - data, err := json.Marshal(store) - if err != nil { - t.Fatalf("json.Marshal() error: %v", err) - } - path := filepath.Join(tmpDir, ".picoclaw", "auth.json") - err = os.MkdirAll(filepath.Dir(path), 0o755) - if err != nil { - t.Fatalf("MkdirAll() error: %v", err) - } - err = os.WriteFile(path, data, 0o600) - if err != nil { - t.Fatalf("WriteFile() error: %v", err) - } - - loaded, err := LoadStore() - if err != nil { - t.Fatalf("LoadStore() error: %v", err) - } - if len(loaded.Credentials) != 1 { - t.Fatalf("credential count = %d, want 1", len(loaded.Credentials)) - } - - cred := loaded.Credentials["google-antigravity"] - if cred == nil { - t.Fatal("google-antigravity credential missing") - } - if cred.AccessToken != "fresh-token" { - t.Fatalf("AccessToken = %q, want %q", cred.AccessToken, "fresh-token") - } - if cred.RefreshToken != "legacy-refresh" { - t.Fatalf("RefreshToken = %q, want %q", cred.RefreshToken, "legacy-refresh") - } - if cred.Email != "legacy@example.com" { - t.Fatalf("Email = %q, want %q", cred.Email, "legacy@example.com") - } - if cred.ProjectID != "project-2" { - t.Fatalf("ProjectID = %q, want %q", cred.ProjectID, "project-2") - } - if !cred.ExpiresAt.Equal(refreshedExpiry) { - t.Fatalf("ExpiresAt = %v, want %v", cred.ExpiresAt, refreshedExpiry) - } -} - -func TestLoadStorePrefersCanonicalKeyWhenExpiryMatchesAlias(t *testing.T) { - tmpDir := setTestAuthHome(t) - - expiresAt := time.Date(2026, 4, 16, 12, 0, 0, 0, time.UTC) - store := map[string]any{ - "credentials": map[string]any{ - "antigravity": map[string]any{ - "access_token": "legacy-token", - "refresh_token": "legacy-refresh", - "expires_at": expiresAt.Format(time.RFC3339), - "provider": "antigravity", - "auth_method": "oauth", - "email": "legacy@example.com", - }, - " Google-Antigravity ": map[string]any{ - "access_token": "fresh-token", - "expires_at": expiresAt.Format(time.RFC3339), - "provider": " Google-Antigravity ", - "auth_method": "oauth", - "project_id": "project-2", - }, - }, - } - data, err := json.Marshal(store) - if err != nil { - t.Fatalf("json.Marshal() error: %v", err) - } - path := filepath.Join(tmpDir, ".picoclaw", "auth.json") - err = os.MkdirAll(filepath.Dir(path), 0o755) - if err != nil { - t.Fatalf("MkdirAll() error: %v", err) - } - err = os.WriteFile(path, data, 0o600) - if err != nil { - t.Fatalf("WriteFile() error: %v", err) - } - - loaded, err := LoadStore() - if err != nil { - t.Fatalf("LoadStore() error: %v", err) - } - if len(loaded.Credentials) != 1 { - t.Fatalf("credential count = %d, want 1", len(loaded.Credentials)) - } - - cred := loaded.Credentials["google-antigravity"] - if cred == nil { - t.Fatal("google-antigravity credential missing") - } - if cred.AccessToken != "fresh-token" { - t.Fatalf("AccessToken = %q, want %q", cred.AccessToken, "fresh-token") - } - if cred.RefreshToken != "legacy-refresh" { - t.Fatalf("RefreshToken = %q, want %q", cred.RefreshToken, "legacy-refresh") - } - if cred.Email != "legacy@example.com" { - t.Fatalf("Email = %q, want %q", cred.Email, "legacy@example.com") - } - if cred.ProjectID != "project-2" { - t.Fatalf("ProjectID = %q, want %q", cred.ProjectID, "project-2") - } -} - -func TestSetCredentialReplacesLegacyAntigravityEntry(t *testing.T) { - tmpDir := setTestAuthHome(t) - - legacyStore := map[string]any{ - "credentials": map[string]any{ - "antigravity": map[string]any{ - "access_token": "legacy-token", - "expires_at": time.Date(2026, 4, 16, 10, 0, 0, 0, time.UTC).Format(time.RFC3339), - "provider": "antigravity", - "auth_method": "oauth", - }, - }, - } - data, err := json.Marshal(legacyStore) - if err != nil { - t.Fatalf("json.Marshal() error: %v", err) - } - path := filepath.Join(tmpDir, ".picoclaw", "auth.json") - err = os.MkdirAll(filepath.Dir(path), 0o755) - if err != nil { - t.Fatalf("MkdirAll() error: %v", err) - } - err = os.WriteFile(path, data, 0o600) - if err != nil { - t.Fatalf("WriteFile() error: %v", err) - } - - refreshedExpiry := time.Date(2026, 4, 16, 12, 30, 0, 0, time.UTC) - err = SetCredential("google-antigravity", &AuthCredential{ - AccessToken: "fresh-token", - ExpiresAt: refreshedExpiry, - Provider: "google-antigravity", - AuthMethod: "oauth", - }) - if err != nil { - t.Fatalf("SetCredential() error: %v", err) - } - - loaded, err := LoadStore() - if err != nil { - t.Fatalf("LoadStore() error: %v", err) - } - if len(loaded.Credentials) != 1 { - t.Fatalf("credential count = %d, want 1", len(loaded.Credentials)) - } - - cred := loaded.Credentials["google-antigravity"] - if cred == nil { - t.Fatal("google-antigravity credential missing") - } - if cred.AccessToken != "fresh-token" { - t.Fatalf("AccessToken = %q, want %q", cred.AccessToken, "fresh-token") - } - if !cred.ExpiresAt.Equal(refreshedExpiry) { - t.Fatalf("ExpiresAt = %v, want %v", cred.ExpiresAt, refreshedExpiry) - } -} - -func TestDeleteCredentialRemovesLegacyAntigravityAlias(t *testing.T) { - tmpDir := setTestAuthHome(t) - - legacyStore := map[string]any{ - "credentials": map[string]any{ - "antigravity": map[string]any{ - "access_token": "legacy-token", - "provider": "antigravity", - "auth_method": "oauth", - }, - }, - } - data, err := json.Marshal(legacyStore) - if err != nil { - t.Fatalf("json.Marshal() error: %v", err) - } - path := filepath.Join(tmpDir, ".picoclaw", "auth.json") - err = os.MkdirAll(filepath.Dir(path), 0o755) - if err != nil { - t.Fatalf("MkdirAll() error: %v", err) - } - err = os.WriteFile(path, data, 0o600) - if err != nil { - t.Fatalf("WriteFile() error: %v", err) - } - - err = DeleteCredential(" google-antigravity ") - if err != nil { - t.Fatalf("DeleteCredential() error: %v", err) - } - - loaded, err := LoadStore() - if err != nil { - t.Fatalf("LoadStore() error: %v", err) - } - if len(loaded.Credentials) != 0 { - t.Fatalf("credential count = %d, want 0", len(loaded.Credentials)) - } -} - func TestSetCredentialCanonicalizesTrimmedMixedCaseProvider(t *testing.T) { setTestAuthHome(t) expiresAt := time.Date(2026, 4, 16, 13, 0, 0, 0, time.UTC) - if err := SetCredential(" AnTiGrAvItY ", &AuthCredential{ + if err := SetCredential(" OpEnAi ", &AuthCredential{ AccessToken: "fresh-token", ExpiresAt: expiresAt, - Provider: " AnTiGrAvItY ", + Provider: " OpEnAi ", AuthMethod: "oauth", }); err != nil { t.Fatalf("SetCredential() error: %v", err) @@ -481,25 +208,25 @@ func TestSetCredentialCanonicalizesTrimmedMixedCaseProvider(t *testing.T) { t.Fatalf("credential count = %d, want 1", len(loaded.Credentials)) } - cred := loaded.Credentials["google-antigravity"] + cred := loaded.Credentials["openai"] if cred == nil { - t.Fatal("google-antigravity credential missing") + t.Fatal("openai credential missing") } - if cred.Provider != "google-antigravity" { - t.Fatalf("Provider = %q, want %q", cred.Provider, "google-antigravity") + if cred.Provider != "openai" { + t.Fatalf("Provider = %q, want %q", cred.Provider, "openai") } if !cred.ExpiresAt.Equal(expiresAt) { t.Fatalf("ExpiresAt = %v, want %v", cred.ExpiresAt, expiresAt) } - got, err := GetCredential(" GoOgLe-AnTiGrAvItY ") + got, err := GetCredential(" OpEnAi ") if err != nil { t.Fatalf("GetCredential() error: %v", err) } if got == nil { t.Fatal("GetCredential() returned nil") } - if got.Provider != "google-antigravity" { - t.Fatalf("GetCredential provider = %q, want %q", got.Provider, "google-antigravity") + if got.Provider != "openai" { + t.Fatalf("GetCredential provider = %q, want %q", got.Provider, "openai") } } diff --git a/pkg/config/config.go b/pkg/config/config.go index 4a21fc6e..7a321605 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -628,13 +628,8 @@ func (c ModelStreamingConfig) IsZero() bool { return !c.Enabled } -// ModelConfig represents a model-centric provider configuration. -// It allows adding new providers (especially OpenAI-compatible ones) via configuration only. -// The Model field may be either a plain model identifier or a provider-prefixed -// identifier such as "openai/gpt-5.4" or "nvidia/z-ai/glm-5.1". -// Supported providers include openai, anthropic, antigravity, claude-cli, -// codex-cli, github-copilot, and named OpenAI-compatible protocols such as -// groq, deepseek, modelscope, and novita. +// ModelConfig selects OpenAI or Anthropic, optionally using a compatible endpoint. +// Model may be a plain ID or a legacy protocol-prefixed ID such as openai/gpt-5.4. type ModelConfig struct { // Required fields ModelName string `json:"model_name"` // User-facing alias for the model @@ -646,10 +641,10 @@ type ModelConfig struct { Proxy string `json:"proxy,omitempty"` // HTTP proxy URL Fallbacks []string `json:"fallbacks,omitempty"` // Fallback model names for failover - // Special providers (CLI-based, OAuth, etc.) + // Authentication and legacy CLI settings (CLI fields are ignored). AuthMethod string `json:"auth_method,omitempty"` // Authentication method: oauth, token - ConnectMode string `json:"connect_mode,omitempty"` // Connection mode: stdio, grpc - Workspace string `json:"workspace,omitempty"` // Workspace path for CLI-based providers + ConnectMode string `json:"connect_mode,omitempty"` // Deprecated: retained only for loading old configs + Workspace string `json:"workspace,omitempty"` // Deprecated: retained only for loading old configs // Optional optimizations RPM int `json:"rpm,omitempty"` // Requests per minute limit diff --git a/pkg/config/config_old.go b/pkg/config/config_old.go index c1962042..44442f6f 100644 --- a/pkg/config/config_old.go +++ b/pkg/config/config_old.go @@ -29,6 +29,9 @@ func isProvidersMapEmpty(providers map[string]any) bool { } // v0ProvidersMapToModelList converts a V0 providers map to a model_list slice. +// Legacy mappings preserve existing settings, including removed providers; they +// do not register runtime providers. Users must select a supported protocol +// before using those old entries with this fork. func v0ProvidersMapToModelList(providers map[string]any, userProvider, userModel string) []any { // providerMigration defines migration rules for a provider type providerMigration struct { diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index 95ed61b0..911ff86d 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -2724,27 +2724,6 @@ func TestModelConfig_ToolSchemaTransformRoundTrip(t *testing.T) { } } -func TestDefaultConfig_MinimaxExtraBody(t *testing.T) { - cfg := DefaultConfig() - - var minimaxCfg *ModelConfig - for i := range cfg.ModelList { - if cfg.ModelList[i].Provider == "minimax" && cfg.ModelList[i].Model == "MiniMax-M2.5" { - minimaxCfg = cfg.ModelList[i] - break - } - } - if minimaxCfg == nil { - t.Fatal("Minimax model not found in ModelList") - } - if minimaxCfg.ExtraBody == nil { - t.Fatal("Minimax ExtraBody should not be nil") - } - if got, ok := minimaxCfg.ExtraBody["reasoning_split"]; !ok || got != true { - t.Fatalf("Minimax ExtraBody[reasoning_split] = %v, want true", got) - } -} - func TestFilterSensitiveData(t *testing.T) { // Test with nil security config cfg := &Config{} diff --git a/pkg/config/defaults.go b/pkg/config/defaults.go index aa19067b..178ddd97 100644 --- a/pkg/config/defaults.go +++ b/pkg/config/defaults.go @@ -64,246 +64,13 @@ func DefaultConfig() *Config { }, }, ModelList: []*ModelConfig{ - // ============================================ - // Add your API key to the model you want to use - // ============================================ - - // Zhipu AI (智谱) - https://open.bigmodel.cn/usercenter/apikeys - { - ModelName: "glm-4.7", - Provider: "zhipu", - Model: "glm-4.7", - APIBase: "https://open.bigmodel.cn/api/paas/v4", - }, - - // OpenAI - https://platform.openai.com/api-keys - { - ModelName: "gpt-5.4", - Provider: "openai", - Model: "gpt-5.4", - APIBase: "https://api.openai.com/v1", - }, - - // Anthropic Claude - https://console.anthropic.com/settings/keys + {ModelName: "gpt-5.4", Provider: "openai", Model: "gpt-5.4", APIBase: "https://api.openai.com/v1"}, { ModelName: "claude-sonnet-4.6", Provider: "anthropic", Model: "claude-sonnet-4-6", APIBase: "https://api.anthropic.com/v1", }, - - // DeepSeek - https://platform.deepseek.com/ - { - ModelName: "deepseek-chat", - Provider: "deepseek", - Model: "deepseek-chat", - APIBase: "https://api.deepseek.com/v1", - }, - - // Venice AI - https://venice.ai - { - ModelName: "venice-uncensored", - Provider: "venice", - Model: "venice-uncensored", - APIBase: "https://api.venice.ai/api/v1", - }, - - // NEAR AI Cloud TEE inference - https://near.ai - { - ModelName: "nearai-glm", - Provider: "nearai", - Model: "zai-org/GLM-5.1-FP8", - APIBase: "https://cloud-api.near.ai/v1", - }, - - // Google Gemini - https://ai.google.dev/ - { - ModelName: "gemini-2.0-flash", - Provider: "gemini", - Model: "gemini-2.0-flash-exp", - APIBase: "https://generativelanguage.googleapis.com/v1beta", - }, - - // Qwen (通义千问) - https://dashscope.console.aliyun.com/apiKey - { - ModelName: "qwen-plus", - Provider: "qwen", - Model: "qwen-plus", - APIBase: "https://dashscope.aliyuncs.com/compatible-mode/v1", - }, - - // Moonshot (月之暗面) - https://platform.moonshot.cn/console/api-keys - { - ModelName: "moonshot-v1-8k", - Provider: "moonshot", - Model: "moonshot-v1-8k", - APIBase: "https://api.moonshot.cn/v1", - }, - - // Groq - https://console.groq.com/keys - { - ModelName: "llama-3.3-70b", - Provider: "groq", - Model: "llama-3.3-70b-versatile", - APIBase: "https://api.groq.com/openai/v1", - }, - - // OpenRouter (100+ models) - https://openrouter.ai/keys - { - ModelName: "openrouter-auto", - Provider: "openrouter", - Model: "auto", - APIBase: "https://openrouter.ai/api/v1", - }, - { - ModelName: "openrouter-gpt-5.4", - Provider: "openrouter", - Model: "openai/gpt-5.4", - APIBase: "https://openrouter.ai/api/v1", - }, - - // NVIDIA - https://build.nvidia.com/ - { - ModelName: "nemotron-4-340b", - Provider: "nvidia", - Model: "nemotron-4-340b-instruct", - APIBase: "https://integrate.api.nvidia.com/v1", - }, - - // Cerebras - https://inference.cerebras.ai/ - { - ModelName: "cerebras-llama-3.3-70b", - Provider: "cerebras", - Model: "llama-3.3-70b", - APIBase: "https://api.cerebras.ai/v1", - }, - - // Vivgrid - https://vivgrid.com - { - ModelName: "vivgrid-auto", - Provider: "vivgrid", - Model: "auto", - APIBase: "https://api.vivgrid.com/v1", - }, - - // Volcengine (火山引擎) - https://console.volcengine.com/ark - { - ModelName: "ark-code-latest", - Provider: "volcengine", - Model: "ark-code-latest", - APIBase: "https://ark.cn-beijing.volces.com/api/v3", - }, - { - ModelName: "doubao-pro", - Provider: "volcengine", - Model: "doubao-pro-32k", - APIBase: "https://ark.cn-beijing.volces.com/api/v3", - }, - - // ShengsuanYun (神算云) - { - ModelName: "deepseek-v3", - Provider: "shengsuanyun", - Model: "deepseek-v3", - APIBase: "https://api.shengsuanyun.com/v1", - }, - - // Antigravity (Google Cloud Code Assist) - OAuth only - { - ModelName: "gemini-flash", - Provider: "antigravity", - Model: "gemini-3-flash", - AuthMethod: "oauth", - }, - - // GitHub Copilot - https://github.com/settings/tokens - { - ModelName: "copilot-gpt-5.4", - Provider: "github-copilot", - Model: "gpt-5.4", - APIBase: "http://localhost:4321", - AuthMethod: "oauth", - }, - - // Ollama (local) - https://ollama.com - { - ModelName: "llama3", - Provider: "ollama", - Model: "llama3", - APIBase: "http://localhost:11434/v1", - }, - - // Mistral AI - https://console.mistral.ai/api-keys - { - ModelName: "mistral-small", - Provider: "mistral", - Model: "mistral-small-latest", - APIBase: "https://api.mistral.ai/v1", - }, - - // Avian - https://avian.io - { - ModelName: "deepseek-v3.2", - Provider: "avian", - Model: "deepseek/deepseek-v3.2", - APIBase: "https://api.avian.io/v1", - }, - { - ModelName: "kimi-k2.5", - Provider: "avian", - Model: "moonshotai/kimi-k2.5", - APIBase: "https://api.avian.io/v1", - }, - - // Minimax - https://api.minimaxi.com/ - { - ModelName: "MiniMax-M2.5", - Provider: "minimax", - Model: "MiniMax-M2.5", - APIBase: "https://api.minimaxi.com/v1", - ExtraBody: map[string]any{"reasoning_split": true}, - }, - - // LongCat - https://longcat.chat/platform - { - ModelName: "LongCat-Flash-Thinking", - Provider: "longcat", - Model: "LongCat-Flash-Thinking", - APIBase: "https://api.longcat.chat/openai", - }, - - // ModelScope (魔搭社区) - https://modelscope.cn/my/tokens - { - ModelName: "modelscope-qwen", - Provider: "modelscope", - Model: "Qwen/Qwen3-235B-A22B-Instruct-2507", - APIBase: "https://api-inference.modelscope.cn/v1", - }, - - // VLLM (local) - http://localhost:8000 - { - ModelName: "local-model", - Provider: "vllm", - Model: "custom-model", - APIBase: "http://localhost:8000/v1", - }, - - // LM Studio (local) - http://localhost:1234 - { - ModelName: "lmstudio-local", - Provider: "lmstudio", - Model: "openai/gpt-oss-20b", - APIBase: "http://localhost:1234/v1", - }, - - // Azure OpenAI - https://portal.azure.com - // model_name is a user-friendly alias; the model field's path after "azure/" is your deployment name - { - ModelName: "azure-gpt5", - Provider: "azure", - Model: "my-gpt5-deployment", - APIBase: "https://your-resource.openai.azure.com", - }, }, Gateway: GatewayConfig{ Host: "localhost", diff --git a/pkg/isolation/README.md b/pkg/isolation/README.md index de16ce50..cd4be486 100644 --- a/pkg/isolation/README.md +++ b/pkg/isolation/README.md @@ -9,7 +9,6 @@ It does not sandbox the main `picoclaw` process itself. The current scope is the child-process startup path: - `exec` tool -- CLI providers such as `claude-cli` and `codex-cli` - process hooks - MCP `stdio` servers diff --git a/pkg/isolation/README.zh.md b/pkg/isolation/README.zh.md index 0529a84b..e7451af2 100644 --- a/pkg/isolation/README.zh.md +++ b/pkg/isolation/README.zh.md @@ -9,7 +9,6 @@ 当前生效范围是子进程启动链路: - `exec` 工具 -- `claude-cli`、`codex-cli` 等 CLI provider - 进程型 hooks - MCP `stdio` server diff --git a/pkg/providers/anthropic/provider.go b/pkg/providers/anthropic/provider.go index 7f0fe53c..aea04fda 100644 --- a/pkg/providers/anthropic/provider.go +++ b/pkg/providers/anthropic/provider.go @@ -6,6 +6,7 @@ import ( "fmt" "log" "strings" + "time" "github.com/anthropics/anthropic-sdk-go" "github.com/anthropics/anthropic-sdk-go/option" @@ -38,6 +39,40 @@ type Provider struct { // SupportsThinking implements providers.ThinkingCapable. func (p *Provider) SupportsThinking() bool { return true } +// NewAPIKeyProvider uses Anthropic's native Messages API with configured HTTP options. +func NewAPIKeyProvider( + apiKey, apiBase, proxy, userAgent string, + timeoutSeconds int, + extraBody map[string]any, + customHeaders map[string]string, +) *Provider { + baseURL := common.NormalizeBaseURL(apiBase, defaultBaseURL, false) + client := common.NewHTTPClient(proxy) + if timeoutSeconds > 0 { + client.Timeout = time.Duration(timeoutSeconds) * time.Second + } + opts := []option.RequestOption{ + option.WithAPIKey(apiKey), + option.WithAuthToken(""), + option.WithHeaderDel("Authorization"), + option.WithBaseURL(baseURL), + option.WithHTTPClient(client), + } + if userAgent != "" { + opts = append(opts, option.WithHeader("User-Agent", userAgent)) + } + for key, value := range extraBody { + opts = append(opts, option.WithJSONSet(key, value)) + } + for key, value := range customHeaders { + if strings.TrimSpace(key) != "" { + opts = append(opts, option.WithHeader(key, value)) + } + } + sdkClient := anthropic.NewClient(opts...) + return &Provider{client: &sdkClient, baseURL: baseURL} +} + func NewProvider(token string) *Provider { return NewProviderWithBaseURL(token, "") } @@ -77,6 +112,44 @@ func (p *Provider) Chat( tools []ToolDefinition, model string, options map[string]any, +) (*LLMResponse, error) { + return p.chat(ctx, messages, tools, model, options, false, nil) +} + +func (p *Provider) ChatStream( + ctx context.Context, + messages []Message, + tools []ToolDefinition, + model string, + options map[string]any, + onChunk func(string), +) (*LLMResponse, error) { + return p.ChatStreamEvents(ctx, messages, tools, model, options, func(chunk protocoltypes.StreamChunk) { + if onChunk != nil && chunk.Content != "" { + onChunk(chunk.Content) + } + }) +} + +func (p *Provider) ChatStreamEvents( + ctx context.Context, + messages []Message, + tools []ToolDefinition, + model string, + options map[string]any, + onChunk func(protocoltypes.StreamChunk), +) (*LLMResponse, error) { + return p.chat(ctx, messages, tools, model, options, true, onChunk) +} + +func (p *Provider) chat( + ctx context.Context, + messages []Message, + tools []ToolDefinition, + model string, + options map[string]any, + streaming bool, + onChunk func(protocoltypes.StreamChunk), ) (*LLMResponse, error) { var opts []option.RequestOption if p.tokenSource != nil { @@ -96,8 +169,8 @@ func (p *Provider) Chat( } // OAuth/setup-tokens require streaming; API keys use non-streaming. - if p.tokenSource != nil { - return p.chatStreaming(ctx, params, opts) + if p.tokenSource != nil || streaming { + return p.chatStreaming(ctx, params, opts, onChunk) } resp, err := p.client.Messages.New(ctx, params, opts...) @@ -112,16 +185,29 @@ func (p *Provider) chatStreaming( ctx context.Context, params anthropic.MessageNewParams, opts []option.RequestOption, + onChunk func(protocoltypes.StreamChunk), ) (*LLMResponse, error) { stream := p.client.Messages.NewStreaming(ctx, params, opts...) defer stream.Close() var msg anthropic.Message + var content, reasoning strings.Builder for stream.Next() { event := stream.Current() if err := msg.Accumulate(event); err != nil { return nil, fmt.Errorf("claude streaming accumulate: %w", err) } + if delta, ok := event.AsAny().(anthropic.ContentBlockDeltaEvent); ok && onChunk != nil { + switch value := delta.Delta.AsAny().(type) { + case anthropic.TextDelta: + content.WriteString(value.Text) + case anthropic.ThinkingDelta: + reasoning.WriteString(value.Thinking) + default: + continue + } + onChunk(protocoltypes.StreamChunk{Content: content.String(), ReasoningContent: reasoning.String()}) + } } if err := stream.Err(); err != nil { return nil, fmt.Errorf("claude API call: %w", err) diff --git a/pkg/providers/anthropic/provider_test.go b/pkg/providers/anthropic/provider_test.go index 0cb1a113..8b84860d 100644 --- a/pkg/providers/anthropic/provider_test.go +++ b/pkg/providers/anthropic/provider_test.go @@ -419,16 +419,21 @@ func TestProvider_ChatStreamingRoundTrip(t *testing.T) { return "refreshed-token", nil }, server.URL) - resp, err := p.Chat( + var chunks []string + resp, err := p.ChatStream( t.Context(), []Message{{Role: "user", Content: "Hello"}}, nil, "claude-sonnet-4.6", map[string]any{}, + func(content string) { chunks = append(chunks, content) }, ) if err != nil { t.Fatalf("Chat() error: %v", err) } + if !reflect.DeepEqual(chunks, []string{"Hello", "Hello world"}) { + t.Fatalf("streamed chunks = %v", chunks) + } if resp.Content != "Hello world" { t.Errorf("Content = %q, want %q", resp.Content, "Hello world") } diff --git a/pkg/providers/anthropic_messages/provider.go b/pkg/providers/anthropic_messages/provider.go deleted file mode 100644 index 3f168495..00000000 --- a/pkg/providers/anthropic_messages/provider.go +++ /dev/null @@ -1,402 +0,0 @@ -// PicoClaw - Ultra-lightweight personal AI agent -// License: MIT -// -// Copyright (c) 2026 PicoClaw contributors - -package anthropicmessages - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strings" - "time" - - "github.com/sipeed/picoclaw/pkg/providers/common" - "github.com/sipeed/picoclaw/pkg/providers/protocoltypes" -) - -type ( - ToolCall = protocoltypes.ToolCall - FunctionCall = protocoltypes.FunctionCall - LLMResponse = protocoltypes.LLMResponse - UsageInfo = protocoltypes.UsageInfo - Message = protocoltypes.Message - ToolDefinition = protocoltypes.ToolDefinition - ToolFunctionDefinition = protocoltypes.ToolFunctionDefinition -) - -const ( - defaultAPIVersion = "2023-06-01" - defaultBaseURL = "https://api.anthropic.com/v1" - defaultRequestTimeout = 120 * time.Second -) - -// Provider implements Anthropic Messages API via HTTP (without SDK). -// It supports custom endpoints that use Anthropic's native message format. -type Provider struct { - apiKey string - apiBase string - httpClient *http.Client - userAgent string -} - -// NewProvider creates a new Anthropic Messages API provider. -func NewProvider(apiKey, apiBase, userAgent string) *Provider { - return NewProviderWithTimeout(apiKey, apiBase, userAgent, 0) -} - -// NewProviderWithTimeout creates a provider with custom request timeout. -func NewProviderWithTimeout(apiKey, apiBase, userAgent string, timeoutSeconds int) *Provider { - baseURL := common.NormalizeBaseURL(apiBase, defaultBaseURL, true) - timeout := defaultRequestTimeout - if timeoutSeconds > 0 { - timeout = time.Duration(timeoutSeconds) * time.Second - } - - return &Provider{ - apiKey: apiKey, - apiBase: baseURL, - userAgent: userAgent, - httpClient: &http.Client{ - Timeout: timeout, - }, - } -} - -// Chat sends messages to the Anthropic Messages API and returns the response. -func (p *Provider) Chat( - ctx context.Context, - messages []Message, - tools []ToolDefinition, - model string, - options map[string]any, -) (*LLMResponse, error) { - if p.apiKey == "" { - return nil, fmt.Errorf("API key not configured") - } - - // Build request body - requestBody, err := buildRequestBody(messages, tools, model, options) - if err != nil { - return nil, fmt.Errorf("building request body: %w", err) - } - - // Serialize to JSON - jsonBody, err := json.Marshal(requestBody) - if err != nil { - return nil, fmt.Errorf("serializing request body: %w", err) - } - - // Build request URL - endpointURL, err := url.JoinPath(p.apiBase, "messages") - if err != nil { - return nil, fmt.Errorf("building endpoint URL: %w", err) - } - - // Create HTTP request - req, err := http.NewRequestWithContext(ctx, "POST", endpointURL, bytes.NewReader(jsonBody)) - if err != nil { - return nil, fmt.Errorf("creating HTTP request: %w", err) - } - - // Set headers - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-API-Key", p.apiKey) //nolint:canonicalheader // Anthropic API requires exact header name - req.Header.Set("Anthropic-Version", defaultAPIVersion) - if p.userAgent != "" { - req.Header.Set("User-Agent", p.userAgent) - } - - // Execute request - resp, err := p.httpClient.Do(req) - if err != nil { - return nil, fmt.Errorf("executing HTTP request: %w", err) - } - defer resp.Body.Close() - - // Read response body - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("reading response body: %w", err) - } - - // Check for HTTP errors with detailed messages - switch resp.StatusCode { - case http.StatusUnauthorized: - return nil, fmt.Errorf("authentication failed (401): check your API key") - case http.StatusTooManyRequests: - return nil, fmt.Errorf("rate limited (429): %s", string(body)) - case http.StatusBadRequest: - return nil, fmt.Errorf("bad request (400): %s", string(body)) - case http.StatusNotFound: - return nil, fmt.Errorf("endpoint not found (404): %s", string(body)) - case http.StatusInternalServerError: - return nil, fmt.Errorf("internal server error (500): %s", string(body)) - case http.StatusServiceUnavailable: - return nil, fmt.Errorf("service unavailable (503): %s", string(body)) - default: - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body)) - } - } - - // Parse response - return parseResponseBody(body) -} - -// GetDefaultModel returns the default model for this provider. -func (p *Provider) GetDefaultModel() string { - return "claude-sonnet-4.6" -} - -// buildRequestBody converts internal message format to Anthropic Messages API format. -func buildRequestBody( - messages []Message, - tools []ToolDefinition, - model string, - options map[string]any, -) (map[string]any, error) { - // max_tokens is required and guaranteed by agent loop - maxTokens, ok := common.AsInt(options["max_tokens"]) - if !ok { - return nil, fmt.Errorf("max_tokens is required in options") - } - - result := map[string]any{ - "model": model, - "max_tokens": int64(maxTokens), - "messages": []any{}, - } - - // Set temperature from options - if temp, ok := common.AsFloat(options["temperature"]); ok { - result["temperature"] = temp - } - - // Process messages - var systemPrompt string - var apiMessages []any - - for _, msg := range messages { - switch msg.Role { - case "system": - // Accumulate system messages - if systemPrompt != "" { - systemPrompt += "\n\n" + msg.Content - } else { - systemPrompt = msg.Content - } - - case "user": - if msg.ToolCallID != "" { - // Tool result message — merge into previous user message if it contains tool_results - toolResultBlock := map[string]any{ - "type": "tool_result", - "tool_use_id": msg.ToolCallID, - "content": msg.Content, - } - if len(apiMessages) > 0 { - if prev, ok := apiMessages[len(apiMessages)-1].(map[string]any); ok && prev["role"] == "user" { - if content, ok := prev["content"].([]map[string]any); ok { - prev["content"] = append(content, toolResultBlock) - continue - } - } - } - apiMessages = append(apiMessages, map[string]any{ - "role": "user", - "content": []map[string]any{toolResultBlock}, - }) - } else { - // Regular user message - apiMessages = append(apiMessages, map[string]any{ - "role": "user", - "content": msg.Content, - }) - } - - case "assistant": - content := []any{} - - // Add text content if present - if msg.Content != "" { - content = append(content, map[string]any{ - "type": "text", - "text": msg.Content, - }) - } - - // Add tool_use blocks - for _, tc := range msg.ToolCalls { - // Resolve tool name: prefer tc.Name, fallback to tc.Function.Name - // (tc.Name/tc.Arguments are json:"-" and may be empty when - // history is reloaded from the session store) - toolName := tc.Name - if toolName == "" && tc.Function != nil { - toolName = tc.Function.Name - } - if strings.TrimSpace(toolName) == "" { - continue - } - - // Resolve arguments: prefer tc.Arguments, fallback to parsing - // tc.Function.Arguments - input := tc.Arguments - if input == nil && tc.Function != nil && tc.Function.Arguments != "" { - if err := json.Unmarshal([]byte(tc.Function.Arguments), &input); err != nil { - input = map[string]any{} - } - } - // Handle nil Arguments (GLM-4 may return null input) - if input == nil { - input = map[string]any{} - } - - toolUse := map[string]any{ - "type": "tool_use", - "id": tc.ID, - "name": toolName, - "input": input, - } - content = append(content, toolUse) - } - - apiMessages = append(apiMessages, map[string]any{ - "role": "assistant", - "content": content, - }) - - case "tool": - // Tool result (alternative format) — merge into previous user message if it contains tool_results - toolResultBlock := map[string]any{ - "type": "tool_result", - "tool_use_id": msg.ToolCallID, - "content": msg.Content, - } - if len(apiMessages) > 0 { - if prev, ok := apiMessages[len(apiMessages)-1].(map[string]any); ok && prev["role"] == "user" { - if content, ok := prev["content"].([]map[string]any); ok { - prev["content"] = append(content, toolResultBlock) - continue - } - } - } - apiMessages = append(apiMessages, map[string]any{ - "role": "user", - "content": []map[string]any{toolResultBlock}, - }) - } - } - - result["messages"] = apiMessages - - // Set system prompt if present - if systemPrompt != "" { - result["system"] = systemPrompt - } - - // Add tools if present - if len(tools) > 0 { - result["tools"] = buildTools(tools) - } - - return result, nil -} - -// buildTools converts tool definitions to Anthropic format. -func buildTools(tools []ToolDefinition) []any { - result := make([]any, len(tools)) - for i, tool := range tools { - toolDef := map[string]any{ - "name": tool.Function.Name, - "description": tool.Function.Description, - "input_schema": tool.Function.Parameters, - } - result[i] = toolDef - } - return result -} - -// parseResponseBody parses Anthropic Messages API response. -func parseResponseBody(body []byte) (*LLMResponse, error) { - var resp anthropicMessageResponse - if err := json.Unmarshal(body, &resp); err != nil { - return nil, fmt.Errorf("parsing JSON response: %w", err) - } - - // Extract content and tool calls - var content strings.Builder - toolCalls := make([]ToolCall, 0) // Initialize as empty slice (not nil) for consistent JSON serialization - - for _, block := range resp.Content { - switch block.Type { - case "text": - content.WriteString(block.Text) - case "tool_use": - argsJSON, _ := json.Marshal(block.Input) - toolCalls = append(toolCalls, ToolCall{ - ID: block.ID, - Name: block.Name, - Arguments: block.Input, - Function: &FunctionCall{ - Name: block.Name, - Arguments: string(argsJSON), - }, - }) - } - } - - // Map stop_reason - finishReason := "stop" - switch resp.StopReason { - case "tool_use": - finishReason = "tool_calls" - case "max_tokens": - finishReason = "length" - case "end_turn": - finishReason = "stop" - case "stop_sequence": - finishReason = "stop" - } - - return &LLMResponse{ - Content: content.String(), - ToolCalls: toolCalls, - FinishReason: finishReason, - Usage: &UsageInfo{ - PromptTokens: int(resp.Usage.InputTokens), - CompletionTokens: int(resp.Usage.OutputTokens), - TotalTokens: int(resp.Usage.InputTokens + resp.Usage.OutputTokens), - }, - }, nil -} - -// Anthropic API response structures - -type anthropicMessageResponse struct { - ID string `json:"id"` - Type string `json:"type"` - Role string `json:"role"` - Content []contentBlock `json:"content"` - StopReason string `json:"stop_reason"` - Model string `json:"model"` - Usage usageInfo `json:"usage"` -} - -type contentBlock struct { - Type string `json:"type"` - Text string `json:"text,omitempty"` - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Input map[string]any `json:"input,omitempty"` -} - -type usageInfo struct { - InputTokens int64 `json:"input_tokens"` - OutputTokens int64 `json:"output_tokens"` -} diff --git a/pkg/providers/anthropic_messages/provider_test.go b/pkg/providers/anthropic_messages/provider_test.go deleted file mode 100644 index f62fe3d1..00000000 --- a/pkg/providers/anthropic_messages/provider_test.go +++ /dev/null @@ -1,839 +0,0 @@ -// PicoClaw - Ultra-lightweight personal AI agent -// License: MIT -// -// Copyright (c) 2026 PicoClaw contributors - -package anthropicmessages - -import ( - "context" - "encoding/json" - "reflect" - "strings" - "testing" -) - -func TestBuildRequestBody(t *testing.T) { - tests := []struct { - name string - messages []Message - tools []ToolDefinition - model string - options map[string]any - want map[string]any - wantErr bool - }{ - { - name: "basic user message", - messages: []Message{ - {Role: "user", Content: "Hello, world!"}, - }, - model: "test-model", - options: map[string]any{ - "max_tokens": 8192, - }, - want: map[string]any{ - "model": "test-model", - "max_tokens": int64(8192), - "messages": []any{ - map[string]any{ - "role": "user", - "content": "Hello, world!", - }, - }, - }, - }, - { - name: "user and assistant messages", - messages: []Message{ - {Role: "user", Content: "What is 2+2?"}, - {Role: "assistant", Content: "4"}, - }, - model: "test-model", - options: map[string]any{ - "max_tokens": 8192, - }, - want: map[string]any{ - "model": "test-model", - "max_tokens": int64(8192), - "messages": []any{ - map[string]any{ - "role": "user", - "content": "What is 2+2?", - }, - map[string]any{ - "role": "assistant", - "content": []any{ - map[string]any{ - "type": "text", - "text": "4", - }, - }, - }, - }, - }, - }, - { - name: "with system message", - messages: []Message{ - {Role: "system", Content: "You are a helpful assistant."}, - {Role: "user", Content: "Hello"}, - }, - model: "test-model", - options: map[string]any{ - "max_tokens": 8192, - }, - want: map[string]any{ - "model": "test-model", - "max_tokens": int64(8192), - "system": "You are a helpful assistant.", - "messages": []any{ - map[string]any{ - "role": "user", - "content": "Hello", - }, - }, - }, - }, - { - name: "with custom max_tokens and temperature", - messages: []Message{ - {Role: "user", Content: "Test"}, - }, - model: "test-model", - options: map[string]any{ - "max_tokens": 2048, - "temperature": 0.5, - }, - want: map[string]any{ - "model": "test-model", - "max_tokens": int64(2048), - "temperature": 0.5, - "messages": []any{ - map[string]any{ - "role": "user", - "content": "Test", - }, - }, - }, - }, - { - name: "missing max_tokens returns error", - messages: []Message{ - {Role: "user", Content: "Test"}, - }, - model: "test-model", - options: map[string]any{}, - want: nil, - wantErr: true, - }, - { - name: "with tools", - messages: []Message{ - {Role: "user", Content: "What's the weather?"}, - }, - tools: []ToolDefinition{ - { - Function: ToolFunctionDefinition{ - Name: "get_weather", - Description: "Get current weather", - Parameters: map[string]any{ - "type": "object", - "properties": map[string]any{ - "location": map[string]any{ - "type": "string", - "description": "City name", - }, - }, - }, - }, - }, - }, - model: "test-model", - options: map[string]any{ - "max_tokens": 8192, - }, - want: map[string]any{ - "model": "test-model", - "max_tokens": int64(8192), - "messages": []any{ - map[string]any{ - "role": "user", - "content": "What's the weather?", - }, - }, - "tools": []any{ - map[string]any{ - "name": "get_weather", - "description": "Get current weather", - "input_schema": map[string]any{ - "type": "object", - "properties": map[string]any{ - "location": map[string]any{ - "type": "string", - "description": "City name", - }, - }, - }, - }, - }, - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := buildRequestBody(tt.messages, tt.tools, tt.model, tt.options) - if (err != nil) != tt.wantErr { - t.Errorf("buildRequestBody() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(got, tt.want) { - gotJSON, _ := json.MarshalIndent(got, "", " ") - wantJSON, _ := json.MarshalIndent(tt.want, "", " ") - t.Errorf("buildRequestBody() mismatch:\ngot:\n%s\nwant:\n%s", gotJSON, wantJSON) - } - }) - } -} - -func TestParseResponseBody(t *testing.T) { - tests := []struct { - name string - body []byte - want *LLMResponse - wantErr bool - }{ - { - name: "basic text response", - body: []byte(`{ - "id": "msg-123", - "type": "message", - "role": "assistant", - "content": [ - {"type": "text", "text": "Hello, how can I help?"} - ], - "stop_reason": "end_turn", - "model": "test-model", - "usage": { - "input_tokens": 10, - "output_tokens": 5 - } - }`), - want: &LLMResponse{ - Content: "Hello, how can I help?", - ToolCalls: []ToolCall{}, - FinishReason: "stop", - Usage: &UsageInfo{ - PromptTokens: 10, - CompletionTokens: 5, - TotalTokens: 15, - }, - Reasoning: "", - ReasoningDetails: nil, - }, - wantErr: false, - }, - { - name: "response with tool use", - body: []byte(`{ - "id": "msg-456", - "type": "message", - "role": "assistant", - "content": [ - {"type": "text", "text": "I'll check the weather for you."}, - { - "type": "tool_use", - "id": "toolu-123", - "name": "get_weather", - "input": {"location": "Tokyo"} - } - ], - "stop_reason": "tool_use", - "model": "test-model", - "usage": { - "input_tokens": 20, - "output_tokens": 15 - } - }`), - want: &LLMResponse{ - Content: "I'll check the weather for you.", - ToolCalls: []ToolCall{ - { - ID: "toolu-123", - Name: "get_weather", - Arguments: map[string]any{ - "location": "Tokyo", - }, - Function: &FunctionCall{ - Name: "get_weather", - Arguments: `{"location":"Tokyo"}`, - }, - }, - }, - FinishReason: "tool_calls", - Usage: &UsageInfo{ - PromptTokens: 20, - CompletionTokens: 15, - TotalTokens: 35, - }, - Reasoning: "", - ReasoningDetails: nil, - }, - wantErr: false, - }, - { - name: "invalid JSON", - body: []byte(`invalid json`), - want: nil, - wantErr: true, - }, - { - name: "max_tokens stop reason", - body: []byte(`{ - "id": "msg-789", - "type": "message", - "role": "assistant", - "content": [ - {"type": "text", "text": "Partial response"} - ], - "stop_reason": "max_tokens", - "model": "test-model", - "usage": { - "input_tokens": 100, - "output_tokens": 4096 - } - }`), - want: &LLMResponse{ - Content: "Partial response", - ToolCalls: []ToolCall{}, - FinishReason: "length", - Usage: &UsageInfo{ - PromptTokens: 100, - CompletionTokens: 4096, - TotalTokens: 4196, - }, - Reasoning: "", - ReasoningDetails: nil, - }, - wantErr: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := parseResponseBody(tt.body) - if (err != nil) != tt.wantErr { - t.Errorf("parseResponseBody() error = %v, wantErr %v", err, tt.wantErr) - return - } - if err != nil { - return - } - - // Compare individual fields - if got.Content != tt.want.Content { - t.Errorf("Content = %q, want %q", got.Content, tt.want.Content) - } - if got.FinishReason != tt.want.FinishReason { - t.Errorf("FinishReason = %q, want %q", got.FinishReason, tt.want.FinishReason) - } - if got.Usage == nil && tt.want.Usage != nil { - t.Errorf("Usage = nil, want non-nil") - } else if got.Usage != nil && tt.want.Usage == nil { - t.Errorf("Usage = non-nil, want nil") - } else if got.Usage != nil && tt.want.Usage != nil { - if got.Usage.PromptTokens != tt.want.Usage.PromptTokens { - t.Errorf("Usage.PromptTokens = %d, want %d", got.Usage.PromptTokens, tt.want.Usage.PromptTokens) - } - if got.Usage.CompletionTokens != tt.want.Usage.CompletionTokens { - t.Errorf("Usage.CompletionTokens = %d, want %d", - got.Usage.CompletionTokens, tt.want.Usage.CompletionTokens) - } - if got.Usage.TotalTokens != tt.want.Usage.TotalTokens { - t.Errorf("Usage.TotalTokens = %d, want %d", got.Usage.TotalTokens, tt.want.Usage.TotalTokens) - } - } - if len(got.ToolCalls) != len(tt.want.ToolCalls) { - t.Errorf("ToolCalls length = %d, want %d", len(got.ToolCalls), len(tt.want.ToolCalls)) - } else { - for i := range got.ToolCalls { - if got.ToolCalls[i].ID != tt.want.ToolCalls[i].ID { - t.Errorf("ToolCalls[%d].ID = %q, want %q", - i, got.ToolCalls[i].ID, tt.want.ToolCalls[i].ID) - } - if got.ToolCalls[i].Name != tt.want.ToolCalls[i].Name { - t.Errorf("ToolCalls[%d].Name = %q, want %q", - i, got.ToolCalls[i].Name, tt.want.ToolCalls[i].Name) - } - } - } - }) - } -} - -func TestNewProvider(t *testing.T) { - provider := NewProvider("test-key", "https://api.example.com", "") - if provider == nil { - t.Fatal("NewProvider() returned nil") - } - if provider.apiKey != "test-key" { - t.Errorf("provider.apiKey = %q, want %q", provider.apiKey, "test-key") - } - if provider.apiBase != "https://api.example.com/v1" { - t.Errorf("provider.apiBase = %q, want %q", provider.apiBase, "https://api.example.com/v1") - } -} - -func TestGetDefaultModel(t *testing.T) { - provider := NewProvider("test-key", "", "") - got := provider.GetDefaultModel() - expected := "claude-sonnet-4.6" - if got != expected { - t.Errorf("GetDefaultModel() = %q, want %q", got, expected) - } -} - -// TestBuildRequestBodyEdgeCases tests edge cases for buildRequestBody. -func TestBuildRequestBodyEdgeCases(t *testing.T) { - tests := []struct { - name string - messages []Message - tools []ToolDefinition - model string - options map[string]any - wantErr bool - }{ - { - name: "empty message list", - messages: []Message{}, - model: "test-model", - options: map[string]any{ - "max_tokens": 8192, - }, - wantErr: false, - }, - { - name: "very long system message", - messages: []Message{ - {Role: "system", Content: strings.Repeat("This is a very long system prompt. ", 1000)}, - {Role: "user", Content: "Hello"}, - }, - model: "test-model", - options: map[string]any{ - "max_tokens": 8192, - }, - wantErr: false, - }, - { - name: "multiple consecutive system messages", - messages: []Message{ - {Role: "system", Content: "First system message"}, - {Role: "system", Content: "Second system message"}, - {Role: "system", Content: "Third system message"}, - {Role: "user", Content: "Hello"}, - }, - model: "test-model", - options: map[string]any{ - "max_tokens": 8192, - }, - wantErr: false, - }, - { - name: "tool result without tool call", - messages: []Message{ - {Role: "user", Content: "Use a tool"}, - {Role: "assistant", Content: "", ToolCalls: []ToolCall{ - {ID: "tool-1", Name: "test_tool", Arguments: map[string]any{"arg": "value"}}, - }}, - {Role: "user", ToolCallID: "tool-1", Content: "Tool result"}, - }, - model: "test-model", - options: map[string]any{ - "max_tokens": 8192, - }, - wantErr: false, - }, - { - name: "skip tool calls with empty names", - messages: []Message{ - {Role: "assistant", Content: "Calling tool", ToolCalls: []ToolCall{ - {ID: "tool-empty", Name: "", Arguments: map[string]any{"ignored": true}}, - {ID: "tool-valid", Name: "test_tool", Arguments: map[string]any{"arg": "value"}}, - }}, - }, - model: "test-model", - options: map[string]any{ - "max_tokens": 8192, - }, - wantErr: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := buildRequestBody(tt.messages, tt.tools, tt.model, tt.options) - if (err != nil) != tt.wantErr { - t.Errorf("buildRequestBody() error = %v, wantErr %v", err, tt.wantErr) - return - } - if err != nil { - return - } - - // Verify basic structure - if got == nil { - t.Error("buildRequestBody() returned nil") - return - } - if got["model"] != tt.model { - t.Errorf("model = %v, want %v", got["model"], tt.model) - } - - if tt.name == "skip tool calls with empty names" { - messages, ok := got["messages"].([]any) - if !ok || len(messages) != 1 { - t.Fatalf("messages = %#v, want single assistant message", got["messages"]) - } - - assistantMsg, ok := messages[0].(map[string]any) - if !ok { - t.Fatalf("assistant message = %#v, want map", messages[0]) - } - - content, ok := assistantMsg["content"].([]any) - if !ok { - t.Fatalf("assistant content = %#v, want []any", assistantMsg["content"]) - } - if len(content) != 2 { - t.Fatalf("assistant content length = %d, want 2", len(content)) - } - - toolUse, ok := content[1].(map[string]any) - if !ok { - t.Fatalf("tool_use block = %#v, want map", content[1]) - } - if gotName := toolUse["name"]; gotName != "test_tool" { - t.Fatalf("tool_use name = %v, want %q", gotName, "test_tool") - } - if gotID := toolUse["id"]; gotID != "tool-valid" { - t.Fatalf("tool_use id = %v, want %q", gotID, "tool-valid") - } - } - }) - } -} - -func TestBuildRequestBody_ConsecutiveToolResultsMerged(t *testing.T) { - // Consecutive tool results (role "tool") should be merged into a single "user" message - messages := []Message{ - {Role: "user", Content: "Use tools"}, - {Role: "assistant", Content: "", ToolCalls: []ToolCall{ - {ID: "t1", Name: "tool_a", Arguments: map[string]any{"x": 1}}, - {ID: "t2", Name: "tool_b", Arguments: map[string]any{"y": 2}}, - }}, - {Role: "tool", ToolCallID: "t1", Content: "result1"}, - {Role: "tool", ToolCallID: "t2", Content: "result2"}, - } - - got, err := buildRequestBody(messages, nil, "test-model", map[string]any{"max_tokens": 8192}) - if err != nil { - t.Fatalf("buildRequestBody() error: %v", err) - } - - apiMessages, ok := got["messages"].([]any) - if !ok { - t.Fatalf("messages is not []any") - } - - // Expect: user, assistant, user (merged tool results) - if len(apiMessages) != 3 { - for i, m := range apiMessages { - t.Logf("message[%d]: %+v", i, m) - } - t.Fatalf("expected 3 API messages, got %d", len(apiMessages)) - } - - // The third message should be a user message with 2 tool_result blocks - toolResultMsg, ok := apiMessages[2].(map[string]any) - if !ok { - t.Fatalf("tool result message is not map[string]any") - } - if toolResultMsg["role"] != "user" { - t.Errorf("expected role 'user', got %v", toolResultMsg["role"]) - } - content, ok := toolResultMsg["content"].([]map[string]any) - if !ok { - t.Fatalf("content is not []map[string]any: %T", toolResultMsg["content"]) - } - if len(content) != 2 { - t.Fatalf("expected 2 tool_result blocks, got %d", len(content)) - } - if content[0]["tool_use_id"] != "t1" { - t.Errorf("first tool_result tool_use_id = %v, want t1", content[0]["tool_use_id"]) - } - if content[1]["tool_use_id"] != "t2" { - t.Errorf("second tool_result tool_use_id = %v, want t2", content[1]["tool_use_id"]) - } -} - -func TestBuildRequestBody_UserToolResultsMerged(t *testing.T) { - // Consecutive tool results using role "user" with ToolCallID should also be merged - messages := []Message{ - {Role: "user", Content: "Use tools"}, - {Role: "assistant", Content: "", ToolCalls: []ToolCall{ - {ID: "t1", Name: "tool_a", Arguments: map[string]any{"x": 1}}, - {ID: "t2", Name: "tool_b", Arguments: map[string]any{"y": 2}}, - }}, - {Role: "user", ToolCallID: "t1", Content: "result1"}, - {Role: "user", ToolCallID: "t2", Content: "result2"}, - } - - got, err := buildRequestBody(messages, nil, "test-model", map[string]any{"max_tokens": 8192}) - if err != nil { - t.Fatalf("buildRequestBody() error: %v", err) - } - - apiMessages, ok := got["messages"].([]any) - if !ok { - t.Fatalf("messages is not []any") - } - - // Expect: user, assistant, user (merged tool results) - if len(apiMessages) != 3 { - t.Fatalf("expected 3 API messages, got %d", len(apiMessages)) - } - - toolResultMsg := apiMessages[2].(map[string]any) - content, ok := toolResultMsg["content"].([]map[string]any) - if !ok { - t.Fatalf("content is not []map[string]any: %T", toolResultMsg["content"]) - } - if len(content) != 2 { - t.Fatalf("expected 2 tool_result blocks, got %d", len(content)) - } -} - -// TestBuildRequestBody_ToolCallFunctionFallback verifies that tool calls whose -// runtime-only fields were lost in a JSON round-trip through the session store -// (ToolCall.Name/Arguments are json:"-"; only ToolCall.Function survives) fall -// back to Function.Name / Function.Arguments, so the tool_use block is still -// emitted and its tool_result pair stays intact. Without the fallback the -// tool_use is skipped and the orphaned tool_result 400s at the API -// ("unexpected tool_use_id found in tool_result blocks"). -func TestBuildRequestBody_ToolCallFunctionFallback(t *testing.T) { - tests := []struct { - name string - toolCall ToolCall - wantSkipped bool - wantToolName string - wantInput map[string]any - }{ - { - name: "deserialized history shape falls back to Function fields", - toolCall: ToolCall{ - ID: "toolu-fallback-1", - Name: "", - Arguments: nil, - Function: &FunctionCall{Name: "x", Arguments: `{"a":1}`}, - }, - wantToolName: "x", - wantInput: map[string]any{"a": float64(1)}, - }, - { - name: "runtime shape with Name set and Function nil still works", - toolCall: ToolCall{ - ID: "toolu-runtime-1", - Name: "y", - Arguments: map[string]any{"b": 2}, - }, - wantToolName: "y", - wantInput: map[string]any{"b": 2}, - }, - { - name: "both Name and Function.Name empty is skipped", - toolCall: ToolCall{ - ID: "toolu-empty-1", - Name: "", - Function: &FunctionCall{Name: "", Arguments: `{"c":3}`}, - }, - wantSkipped: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - messages := []Message{ - {Role: "user", Content: "run the tool"}, - {Role: "assistant", Content: "", ToolCalls: []ToolCall{tt.toolCall}}, - {Role: "tool", ToolCallID: tt.toolCall.ID, Content: "result"}, - } - - got, err := buildRequestBody(messages, nil, "test-model", map[string]any{"max_tokens": 8192}) - if err != nil { - t.Fatalf("buildRequestBody() error: %v", err) - } - - apiMessages := got["messages"].([]any) - if len(apiMessages) != 3 { - t.Fatalf("expected 3 API messages, got %d", len(apiMessages)) - } - - assistantMsg := apiMessages[1].(map[string]any) - content := assistantMsg["content"].([]any) - - if tt.wantSkipped { - if len(content) != 0 { - t.Fatalf("assistant content = %#v, want empty (tool call skipped)", content) - } - // Note: matching current behavior, the orphaned tool_result is - // still emitted in the following user message even though its - // tool_use block was skipped. - toolResultMsg := apiMessages[2].(map[string]any) - blocks := toolResultMsg["content"].([]map[string]any) - if len(blocks) != 1 || blocks[0]["tool_use_id"] != tt.toolCall.ID { - t.Fatalf("orphaned tool_result = %#v, want single block with tool_use_id %q", - blocks, tt.toolCall.ID) - } - return - } - - // (a) tool_use block emitted with resolved name, id, and parsed input. - if len(content) != 1 { - t.Fatalf("assistant content length = %d, want 1 tool_use block", len(content)) - } - toolUse := content[0].(map[string]any) - if toolUse["type"] != "tool_use" { - t.Fatalf("block type = %v, want tool_use", toolUse["type"]) - } - if toolUse["name"] != tt.wantToolName { - t.Errorf("tool_use name = %v, want %q", toolUse["name"], tt.wantToolName) - } - if toolUse["id"] != tt.toolCall.ID { - t.Errorf("tool_use id = %v, want %q", toolUse["id"], tt.toolCall.ID) - } - if !reflect.DeepEqual(toolUse["input"], tt.wantInput) { - t.Errorf("tool_use input = %#v, want %#v", toolUse["input"], tt.wantInput) - } - - // (b) the following user message's tool_result references the same - // id as the tool_use block — the pair is intact. - toolResultMsg := apiMessages[2].(map[string]any) - if toolResultMsg["role"] != "user" { - t.Fatalf("message after assistant role = %v, want user", toolResultMsg["role"]) - } - blocks := toolResultMsg["content"].([]map[string]any) - if len(blocks) != 1 { - t.Fatalf("tool_result blocks = %d, want 1", len(blocks)) - } - if blocks[0]["tool_use_id"] != toolUse["id"] { - t.Errorf("tool_result tool_use_id = %v, want %v (paired with tool_use)", - blocks[0]["tool_use_id"], toolUse["id"]) - } - }) - } -} - -// TestParseResponseBodyEdgeCases tests edge cases for parseResponseBody. -func TestParseResponseBodyEdgeCases(t *testing.T) { - tests := []struct { - name string - body []byte - wantErr bool - check func(*testing.T, *LLMResponse) - }{ - { - name: "empty content blocks", - body: []byte(`{ - "id": "msg-empty", - "type": "message", - "role": "assistant", - "content": [], - "stop_reason": "end_turn", - "model": "test-model", - "usage": {"input_tokens": 5, "output_tokens": 0} - }`), - wantErr: false, - check: func(t *testing.T, resp *LLMResponse) { - if resp.Content != "" { - t.Errorf("Content = %q, want empty string", resp.Content) - } - if len(resp.ToolCalls) != 0 { - t.Errorf("ToolCalls length = %d, want 0", len(resp.ToolCalls)) - } - }, - }, - { - name: "multiple tool use blocks", - body: []byte(`{ - "id": "msg-multi", - "type": "message", - "role": "assistant", - "content": [ - {"type": "tool_use", "id": "tool-1", "name": "func1", "input": {"arg": "val1"}}, - {"type": "tool_use", "id": "tool-2", "name": "func2", "input": {"arg": "val2"}} - ], - "stop_reason": "tool_use", - "model": "test-model", - "usage": {"input_tokens": 10, "output_tokens": 20} - }`), - wantErr: false, - check: func(t *testing.T, resp *LLMResponse) { - if len(resp.ToolCalls) != 2 { - t.Errorf("ToolCalls length = %d, want 2", len(resp.ToolCalls)) - } - }, - }, - { - name: "malformed JSON response", - body: []byte(`{invalid json`), - wantErr: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := parseResponseBody(tt.body) - if (err != nil) != tt.wantErr { - t.Errorf("parseResponseBody() error = %v, wantErr %v", err, tt.wantErr) - return - } - if tt.check != nil && err == nil { - tt.check(t, got) - } - }) - } -} - -// TestProviderChatErrors tests error handling in Chat. -// Note: apiBase check removed as it's dead code - normalizeBaseURL() always provides a default. -func TestProviderChatErrors(t *testing.T) { - tests := []struct { - name string - apiKey string - messages []Message - wantErrMsg string - }{ - { - name: "missing API key", - apiKey: "", - messages: []Message{{Role: "user", Content: "Test"}}, - wantErrMsg: "API key not configured", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Create provider using constructor to ensure proper initialization - provider := NewProvider(tt.apiKey, "https://api.example.com", "") - - _, err := provider.Chat(context.Background(), tt.messages, nil, "test-model", nil) - if err == nil { - t.Fatal("Chat() expected error, got nil") - } - if err.Error() != tt.wantErrMsg { - t.Errorf("Chat() error = %q, want %q", err.Error(), tt.wantErrMsg) - } - }) - } -} diff --git a/pkg/providers/azure/identity.go b/pkg/providers/azure/identity.go deleted file mode 100644 index 1283cb07..00000000 --- a/pkg/providers/azure/identity.go +++ /dev/null @@ -1,56 +0,0 @@ -//go:build azidentity - -// Entra ID (DefaultAzureCredential) auth adapter. -// Built only when -tags azidentity is supplied; otherwise identity_stub.go -// satisfies the same exported API with a friendly error. - -package azure - -import ( - "context" - "fmt" - "time" - - "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" - "github.com/Azure/azure-sdk-for-go/sdk/azidentity" -) - -// azureOpenAIScope is the OAuth scope for Azure OpenAI (Cognitive Services). -// Service-wide scope, so it covers all regions including sovereign clouds. -const azureOpenAIScope = "https://cognitiveservices.azure.com/.default" - -// NewProviderWithIdentity creates an Azure OpenAI provider authenticated via -// the DefaultAzureCredential chain (env vars, workload identity, managed -// identity, Azure CLI, ...). Construction itself only fails if the credential -// chain cannot be built; misconfigured environments surface their error on -// the first Chat call when GetToken is invoked. -func NewProviderWithIdentity(apiBase, proxy, userAgent string, opts ...Option) (*Provider, error) { - cred, err := azidentity.NewDefaultAzureCredential(nil) - if err != nil { - return nil, fmt.Errorf("creating azure default credential: %w", err) - } - - ts := func(ctx context.Context) (string, error) { - tok, err := cred.GetToken(ctx, policy.TokenRequestOptions{ - Scopes: []string{azureOpenAIScope}, - }) - if err != nil { - return "", fmt.Errorf("acquiring azure access token: %w", err) - } - return tok.Token, nil - } - - return NewProviderWithTokenSource(apiBase, proxy, userAgent, ts, opts...), nil -} - -// NewProviderWithIdentityAndTimeout mirrors NewProviderWithTimeout for the -// identity auth path. -func NewProviderWithIdentityAndTimeout( - apiBase, proxy, userAgent string, - requestTimeoutSeconds int, -) (*Provider, error) { - return NewProviderWithIdentity( - apiBase, proxy, userAgent, - WithRequestTimeout(time.Duration(requestTimeoutSeconds)*time.Second), - ) -} diff --git a/pkg/providers/azure/identity_stub.go b/pkg/providers/azure/identity_stub.go deleted file mode 100644 index c6d5a60d..00000000 --- a/pkg/providers/azure/identity_stub.go +++ /dev/null @@ -1,24 +0,0 @@ -//go:build !azidentity - -// Stub for the Entra ID auth path when built without the azidentity tag. -// Mirrors the exported surface of identity.go so callers compile cleanly -// in the default build. - -package azure - -import "fmt" - -const azidentityBuildHint = "azure identity auth not available: build with -tags azidentity to enable Entra ID auth, or set api_key" - -// NewProviderWithIdentity returns an error in the default build. -func NewProviderWithIdentity(apiBase, proxy, userAgent string, opts ...Option) (*Provider, error) { - return nil, fmt.Errorf("%s", azidentityBuildHint) -} - -// NewProviderWithIdentityAndTimeout returns an error in the default build. -func NewProviderWithIdentityAndTimeout( - apiBase, proxy, userAgent string, - requestTimeoutSeconds int, -) (*Provider, error) { - return nil, fmt.Errorf("%s", azidentityBuildHint) -} diff --git a/pkg/providers/azure/identity_test.go b/pkg/providers/azure/identity_test.go deleted file mode 100644 index e40fd1ce..00000000 --- a/pkg/providers/azure/identity_test.go +++ /dev/null @@ -1,39 +0,0 @@ -//go:build azidentity - -package azure - -import ( - "testing" -) - -func TestNewProviderWithIdentity_Construction(t *testing.T) { - // DefaultAzureCredential construction itself does not require any env vars; - // failures surface only on the first GetToken call. Verify we get a - // non-nil provider back with a token source wired in. - p, err := NewProviderWithIdentity("https://example.openai.azure.com", "", "ua-test") - if err != nil { - t.Fatalf("NewProviderWithIdentity() error = %v", err) - } - if p == nil { - t.Fatal("NewProviderWithIdentity() returned nil provider") - } - if p.tokenSource == nil { - t.Fatal("provider.tokenSource should be set") - } - if p.apiKey != "" { - t.Errorf("provider.apiKey = %q, want empty", p.apiKey) - } -} - -func TestNewProviderWithIdentityAndTimeout_Construction(t *testing.T) { - p, err := NewProviderWithIdentityAndTimeout("https://example.openai.azure.com", "", "ua-test", 30) - if err != nil { - t.Fatalf("NewProviderWithIdentityAndTimeout() error = %v", err) - } - if p == nil { - t.Fatal("returned nil provider") - } - if p.httpClient.Timeout.Seconds() != 30 { - t.Errorf("timeout = %v, want 30s", p.httpClient.Timeout) - } -} diff --git a/pkg/providers/azure/provider.go b/pkg/providers/azure/provider.go deleted file mode 100644 index fdbbf4a3..00000000 --- a/pkg/providers/azure/provider.go +++ /dev/null @@ -1,213 +0,0 @@ -package azure - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strings" - "time" - - "github.com/openai/openai-go/v3" - "github.com/openai/openai-go/v3/responses" - - "github.com/sipeed/picoclaw/pkg/providers/common" - orc "github.com/sipeed/picoclaw/pkg/providers/openai_responses_common" - "github.com/sipeed/picoclaw/pkg/providers/protocoltypes" -) - -type ( - LLMResponse = protocoltypes.LLMResponse - Message = protocoltypes.Message - ToolDefinition = protocoltypes.ToolDefinition -) - -const ( - defaultRequestTimeout = common.DefaultRequestTimeout - responsesAPIPath = "openai/v1/responses" -) - -// Provider implements the LLM provider interface for Azure OpenAI endpoints. -// It handles Azure-specific authentication (Bearer token), URL construction -// (Responses API), and request/response formatting. -type Provider struct { - apiKey string - apiBase string - httpClient *http.Client - userAgent string - tokenSource func(ctx context.Context) (string, error) -} - -// Option configures the Azure Provider. -type Option func(*Provider) - -// WithRequestTimeout sets the HTTP request timeout. -func WithRequestTimeout(timeout time.Duration) Option { - return func(p *Provider) { - if timeout > 0 { - p.httpClient.Timeout = timeout - } - } -} - -// WithUserAgent sets the User-Agent header for requests. -func WithUserAgent(userAgent string) Option { - return func(p *Provider) { - p.userAgent = userAgent - } -} - -// WithTokenSource sets a callback that returns a bearer token per request. -// When set, it takes precedence over the static api key. -func WithTokenSource(ts func(ctx context.Context) (string, error)) Option { - return func(p *Provider) { - p.tokenSource = ts - } -} - -// NewProvider creates a new Azure OpenAI provider. -func NewProvider(apiKey, apiBase, proxy, userAgent string, opts ...Option) *Provider { - p := &Provider{ - apiKey: apiKey, - apiBase: strings.TrimRight(apiBase, "/"), - userAgent: userAgent, - httpClient: common.NewHTTPClient(proxy), - } - - for _, opt := range opts { - if opt != nil { - opt(p) - } - } - - return p -} - -// NewProviderWithTimeout creates a new Azure OpenAI provider with a custom request timeout in seconds. -func NewProviderWithTimeout(apiKey, apiBase, proxy, userAgent string, requestTimeoutSeconds int) *Provider { - return NewProvider( - apiKey, apiBase, proxy, userAgent, - WithRequestTimeout(time.Duration(requestTimeoutSeconds)*time.Second), - ) -} - -// NewProviderWithTokenSource creates a new Azure OpenAI provider that obtains its -// bearer token from the supplied callback on every request. Used for Entra ID auth -// where tokens are short-lived and refreshed by the underlying credential. -func NewProviderWithTokenSource( - apiBase, proxy, userAgent string, - tokenSource func(ctx context.Context) (string, error), - opts ...Option, -) *Provider { - p := &Provider{ - apiBase: strings.TrimRight(apiBase, "/"), - userAgent: userAgent, - httpClient: common.NewHTTPClient(proxy), - tokenSource: tokenSource, - } - - for _, opt := range opts { - if opt != nil { - opt(p) - } - } - - return p -} - -// Chat sends a request to the Azure OpenAI Responses API endpoint. -// The model parameter is passed in the request body. -func (p *Provider) Chat( - ctx context.Context, - messages []Message, - tools []ToolDefinition, - model string, - options map[string]any, -) (*LLMResponse, error) { - if p.apiBase == "" { - return nil, fmt.Errorf("Azure API base not configured") - } - - requestURL, err := url.JoinPath(p.apiBase, responsesAPIPath) - if err != nil { - return nil, fmt.Errorf("failed to build Azure request URL: %w", err) - } - - input, instructions := orc.TranslateMessages(messages) - - requestBody := responses.ResponseNewParams{ - Model: model, - Input: responses.ResponseNewParamsInputUnion{ - OfInputItemList: input, - }, - Store: openai.Opt(false), - } - - if instructions != "" { - requestBody.Instructions = openai.Opt(instructions) - } - - if len(tools) > 0 { - enableWebSearch, _ := options["native_search"].(bool) - requestBody.Tools = orc.TranslateTools(tools, enableWebSearch) - requestBody.ToolChoice = responses.ResponseNewParamsToolChoiceUnion{ - OfToolChoiceMode: openai.Opt(responses.ToolChoiceOptionsAuto), - } - } - - if maxTokens, ok := common.AsInt(options["max_tokens"]); ok { - requestBody.MaxOutputTokens = openai.Opt(int64(maxTokens)) - } - - if temperature, ok := common.AsFloat(options["temperature"]); ok { - requestBody.Temperature = openai.Opt(temperature) - } - - if cacheKey, ok := options["prompt_cache_key"].(string); ok && cacheKey != "" { - requestBody.PromptCacheKey = openai.Opt(cacheKey) - } - - jsonData, err := json.Marshal(requestBody) - if err != nil { - return nil, fmt.Errorf("failed to marshal request: %w", err) - } - - req, err := http.NewRequestWithContext(ctx, "POST", requestURL, bytes.NewReader(jsonData)) - if err != nil { - return nil, fmt.Errorf("failed to create request: %w", err) - } - - req.Header.Set("Content-Type", "application/json") - switch { - case p.tokenSource != nil: - tok, tokErr := p.tokenSource(ctx) - if tokErr != nil { - return nil, fmt.Errorf("acquiring azure identity token: %w", tokErr) - } - req.Header.Set("Authorization", "Bearer "+tok) - case p.apiKey != "": - req.Header.Set("Authorization", "Bearer "+p.apiKey) - } - if p.userAgent != "" { - req.Header.Set("User-Agent", p.userAgent) - } - - resp, err := p.httpClient.Do(req) - if err != nil { - return nil, fmt.Errorf("failed to send request: %w", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, common.HandleErrorResponse(resp, p.apiBase) - } - - return orc.ParseResponseBody(resp.Body) -} - -// GetDefaultModel returns an empty string as Azure deployments are user-configured. -func (p *Provider) GetDefaultModel() string { - return "" -} diff --git a/pkg/providers/azure/provider_test.go b/pkg/providers/azure/provider_test.go deleted file mode 100644 index b39c956f..00000000 --- a/pkg/providers/azure/provider_test.go +++ /dev/null @@ -1,484 +0,0 @@ -package azure - -import ( - "context" - "encoding/json" - "errors" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" - - "github.com/sipeed/picoclaw/pkg/providers/protocoltypes" -) - -// writeValidResponse writes a minimal valid Responses API response. -func writeValidResponse(w http.ResponseWriter) { - resp := map[string]any{ - "id": "resp_test", - "object": "response", - "status": "completed", - "output": []map[string]any{ - { - "type": "message", - "content": []map[string]any{ - {"type": "output_text", "text": "ok"}, - }, - }, - }, - "usage": map[string]any{ - "input_tokens": 5, - "output_tokens": 2, - "total_tokens": 7, - "input_tokens_details": map[string]any{"cached_tokens": 0}, - "output_tokens_details": map[string]any{"reasoning_tokens": 0}, - }, - } - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(resp) -} - -func TestProviderChat_AzureURLConstruction(t *testing.T) { - var capturedPath string - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - capturedPath = r.URL.Path - writeValidResponse(w) - })) - defer server.Close() - - p := NewProvider("test-key", server.URL, "", "") - _, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "my-gpt5-deployment", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - - wantPath := "/openai/v1/responses" - if capturedPath != wantPath { - t.Errorf("URL path = %q, want %q", capturedPath, wantPath) - } -} - -func TestProviderChat_AzureAuthHeader(t *testing.T) { - var capturedAuth string - var capturedAPIKey string - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - capturedAuth = r.Header.Get("Authorization") - capturedAPIKey = r.Header.Get("Api-Key") - writeValidResponse(w) - })) - defer server.Close() - - p := NewProvider("test-azure-key", server.URL, "", "") - _, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "deployment", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - - if capturedAuth != "Bearer test-azure-key" { - t.Errorf("Authorization header = %q, want %q", capturedAuth, "Bearer test-azure-key") - } - if capturedAPIKey != "" { - t.Errorf("Api-Key header should be empty, got %q", capturedAPIKey) - } -} - -func TestProviderChat_AzureRequestBodyContainsModel(t *testing.T) { - var requestBody map[string]any - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - json.NewDecoder(r.Body).Decode(&requestBody) - writeValidResponse(w) - })) - defer server.Close() - - p := NewProvider("test-key", server.URL, "", "") - _, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "my-deployment", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - - if requestBody["model"] != "my-deployment" { - t.Errorf("model = %v, want %q", requestBody["model"], "my-deployment") - } -} - -func TestProviderChat_AzureUsesMaxOutputTokens(t *testing.T) { - var requestBody map[string]any - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - json.NewDecoder(r.Body).Decode(&requestBody) - writeValidResponse(w) - })) - defer server.Close() - - p := NewProvider("test-key", server.URL, "", "") - _, err := p.Chat( - t.Context(), - []Message{{Role: "user", Content: "hi"}}, - nil, - "deployment", - map[string]any{"max_tokens": 2048}, - ) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - - if requestBody["max_output_tokens"] == nil { - t.Error("request body should contain 'max_output_tokens'") - } - if _, exists := requestBody["max_tokens"]; exists { - t.Error("request body should not contain 'max_tokens'") - } - if _, exists := requestBody["max_completion_tokens"]; exists { - t.Error("request body should not contain 'max_completion_tokens'") - } -} - -func TestProviderChat_AzureStoreIsFalse(t *testing.T) { - var requestBody map[string]any - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - json.NewDecoder(r.Body).Decode(&requestBody) - writeValidResponse(w) - })) - defer server.Close() - - p := NewProvider("test-key", server.URL, "", "") - _, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "deployment", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - - if requestBody["store"] != false { - t.Errorf("store = %v, want false", requestBody["store"]) - } -} - -func TestProviderChat_AzureHTTPError(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized) - })) - defer server.Close() - - p := NewProvider("bad-key", server.URL, "", "") - _, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "deployment", nil) - if err == nil { - t.Fatal("expected error, got nil") - } -} - -func TestProviderChat_AzureRateLimitError(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusTooManyRequests) - w.Write([]byte(`{"error":{"message":"Rate limit exceeded","type":"rate_limit_error"}}`)) - })) - defer server.Close() - - p := NewProvider("test-key", server.URL, "", "") - _, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "deployment", nil) - if err == nil { - t.Fatal("expected error for 429, got nil") - } - if !strings.Contains(err.Error(), "429") { - t.Errorf("error should contain status code 429, got: %v", err) - } -} - -func TestProviderChat_AzureServerError(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{"error":{"message":"Internal server error","type":"server_error"}}`)) - })) - defer server.Close() - - p := NewProvider("test-key", server.URL, "", "") - _, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "deployment", nil) - if err == nil { - t.Fatal("expected error for 500, got nil") - } - if !strings.Contains(err.Error(), "500") { - t.Errorf("error should contain status code 500, got: %v", err) - } -} - -func TestProviderChat_AzureParseTextOutput(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - resp := map[string]any{ - "id": "resp_1", - "object": "response", - "status": "completed", - "output": []map[string]any{ - { - "type": "message", - "content": []map[string]any{ - {"type": "output_text", "text": "Hello there!"}, - }, - }, - }, - "usage": map[string]any{ - "input_tokens": 10, "output_tokens": 5, "total_tokens": 15, - "input_tokens_details": map[string]any{"cached_tokens": 0}, - "output_tokens_details": map[string]any{"reasoning_tokens": 0}, - }, - } - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(resp) - })) - defer server.Close() - - p := NewProvider("test-key", server.URL, "", "") - out, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "deployment", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - if out.Content != "Hello there!" { - t.Errorf("Content = %q, want %q", out.Content, "Hello there!") - } - if out.FinishReason != "stop" { - t.Errorf("FinishReason = %q, want %q", out.FinishReason, "stop") - } - if out.Usage.TotalTokens != 15 { - t.Errorf("TotalTokens = %d, want 15", out.Usage.TotalTokens) - } -} - -func TestProviderChat_AzureParseToolCalls(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - resp := map[string]any{ - "id": "resp_2", - "object": "response", - "status": "completed", - "output": []map[string]any{ - { - "type": "function_call", - "call_id": "call_1", - "name": "get_weather", - "arguments": `{"city":"Seattle"}`, - }, - }, - "usage": map[string]any{ - "input_tokens": 10, "output_tokens": 8, "total_tokens": 18, - "input_tokens_details": map[string]any{"cached_tokens": 0}, - "output_tokens_details": map[string]any{"reasoning_tokens": 0}, - }, - } - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(resp) - })) - defer server.Close() - - p := NewProvider("test-key", server.URL, "", "") - out, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "weather?"}}, nil, "deployment", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - if len(out.ToolCalls) != 1 { - t.Fatalf("len(ToolCalls) = %d, want 1", len(out.ToolCalls)) - } - if out.ToolCalls[0].Name != "get_weather" { - t.Errorf("ToolCalls[0].Name = %q, want %q", out.ToolCalls[0].Name, "get_weather") - } - if out.FinishReason != "tool_calls" { - t.Errorf("FinishReason = %q, want %q", out.FinishReason, "tool_calls") - } -} - -func TestProvider_AzureEmptyAPIBase(t *testing.T) { - p := NewProvider("test-key", "", "", "") - _, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "deployment", nil) - if err == nil { - t.Fatal("expected error for empty API base") - } -} - -func TestProvider_AzureRequestTimeoutDefault(t *testing.T) { - p := NewProvider("test-key", "https://example.com", "", "") - if p.httpClient.Timeout != defaultRequestTimeout { - t.Errorf("timeout = %v, want %v", p.httpClient.Timeout, defaultRequestTimeout) - } -} - -func TestProvider_AzureRequestTimeoutOverride(t *testing.T) { - p := NewProvider("test-key", "https://example.com", "", "", WithRequestTimeout(300*time.Second)) - if p.httpClient.Timeout != 300*time.Second { - t.Errorf("timeout = %v, want %v", p.httpClient.Timeout, 300*time.Second) - } -} - -func TestProvider_AzureNewProviderWithTimeout(t *testing.T) { - p := NewProviderWithTimeout("test-key", "https://example.com", "", "", 180) - if p.httpClient.Timeout != 180*time.Second { - t.Errorf("timeout = %v, want %v", p.httpClient.Timeout, 180*time.Second) - } -} - -func TestProviderChat_AzureNativeWebSearchInjection(t *testing.T) { - var requestBody map[string]any - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - json.NewDecoder(r.Body).Decode(&requestBody) - writeValidResponse(w) - })) - defer server.Close() - - tools := []ToolDefinition{ - { - Type: "function", - Function: protocoltypes.ToolFunctionDefinition{ - Name: "web_search", - Description: "local web search", - Parameters: map[string]any{"type": "object"}, - }, - }, - { - Type: "function", - Function: protocoltypes.ToolFunctionDefinition{ - Name: "read_file", - Description: "read a file", - Parameters: map[string]any{"type": "object"}, - }, - }, - } - - p := NewProvider("test-key", server.URL, "", "") - - // With native_search=true: user-defined web_search should be replaced by built-in - _, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, tools, "deployment", - map[string]any{"native_search": true}) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - - toolsAny, ok := requestBody["tools"].([]any) - if !ok { - t.Fatal("request body should contain 'tools' array") - } - if len(toolsAny) != 2 { - t.Fatalf("len(tools) = %d, want 2 (read_file + web_search builtin)", len(toolsAny)) - } - - // First tool should be read_file (user-defined web_search was skipped) - firstTool, _ := toolsAny[0].(map[string]any) - if firstTool["name"] != "read_file" { - t.Errorf("first tool name = %v, want %q", firstTool["name"], "read_file") - } - - // Second tool should be built-in web_search - secondTool, _ := toolsAny[1].(map[string]any) - if secondTool["type"] != "web_search" { - t.Errorf("second tool type = %v, want %q", secondTool["type"], "web_search") - } -} - -func TestProviderChat_AzureNoNativeWebSearch(t *testing.T) { - var requestBody map[string]any - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - json.NewDecoder(r.Body).Decode(&requestBody) - writeValidResponse(w) - })) - defer server.Close() - - tools := []ToolDefinition{ - { - Type: "function", - Function: protocoltypes.ToolFunctionDefinition{ - Name: "web_search", - Description: "local web search", - Parameters: map[string]any{"type": "object"}, - }, - }, - } - - p := NewProvider("test-key", server.URL, "", "") - - // Without native_search: user-defined web_search should be kept as-is - _, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, tools, "deployment", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - - toolsAny, ok := requestBody["tools"].([]any) - if !ok { - t.Fatal("request body should contain 'tools' array") - } - if len(toolsAny) != 1 { - t.Fatalf("len(tools) = %d, want 1", len(toolsAny)) - } - - // Should be the user-defined function tool, not built-in - tool, _ := toolsAny[0].(map[string]any) - if tool["type"] != "function" { - t.Errorf("tool type = %v, want %q", tool["type"], "function") - } -} - -func TestProviderChat_AzureTokenSourceHeader(t *testing.T) { - var capturedAuth string - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - capturedAuth = r.Header.Get("Authorization") - writeValidResponse(w) - })) - defer server.Close() - - ts := func(ctx context.Context) (string, error) { - return "fake-entra-token", nil - } - p := NewProviderWithTokenSource(server.URL, "", "", ts) - _, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "deployment", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - if capturedAuth != "Bearer fake-entra-token" { - t.Errorf("Authorization header = %q, want %q", capturedAuth, "Bearer fake-entra-token") - } -} - -func TestProviderChat_AzureTokenSourceError(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - writeValidResponse(w) - })) - defer server.Close() - - wantErr := errors.New("creds gone") - ts := func(ctx context.Context) (string, error) { - return "", wantErr - } - p := NewProviderWithTokenSource(server.URL, "", "", ts) - _, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "deployment", nil) - if err == nil { - t.Fatal("expected error from token source") - } - if !strings.Contains(err.Error(), "creds gone") { - t.Errorf("error %q should wrap original token source error", err.Error()) - } -} - -func TestProviderChat_AzureTokenSourcePrecedence(t *testing.T) { - var capturedAuth string - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - capturedAuth = r.Header.Get("Authorization") - writeValidResponse(w) - })) - defer server.Close() - - ts := func(ctx context.Context) (string, error) { - return "from-token-source", nil - } - // Provider with both an api_key AND a token source: token source must win. - p := NewProvider("static-api-key", server.URL, "", "", WithTokenSource(ts)) - _, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "deployment", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - if capturedAuth != "Bearer from-token-source" { - t.Errorf("Authorization header = %q, want token-source value", capturedAuth) - } -} diff --git a/pkg/providers/bedrock/provider_bedrock.go b/pkg/providers/bedrock/provider_bedrock.go deleted file mode 100644 index 14fe288c..00000000 --- a/pkg/providers/bedrock/provider_bedrock.go +++ /dev/null @@ -1,833 +0,0 @@ -//go:build bedrock - -// PicoClaw - Ultra-lightweight personal AI agent -// License: MIT -// -// Copyright (c) 2026 PicoClaw contributors - -// Package bedrock implements the LLM provider interface for AWS Bedrock. -// It uses the Bedrock Runtime Converse API for unified access to multiple -// model families (Claude, Llama, Mistral, etc.) with tool/function calling support. -package bedrock - -import ( - "context" - "encoding/base64" - "encoding/json" - "fmt" - "log" - "math" - "strings" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/config" - "github.com/aws/aws-sdk-go-v2/service/bedrockruntime" - "github.com/aws/aws-sdk-go-v2/service/bedrockruntime/document" - "github.com/aws/aws-sdk-go-v2/service/bedrockruntime/types" - - "github.com/sipeed/picoclaw/pkg/providers/common" - "github.com/sipeed/picoclaw/pkg/providers/protocoltypes" -) - -type ( - ToolCall = protocoltypes.ToolCall - FunctionCall = protocoltypes.FunctionCall - LLMResponse = protocoltypes.LLMResponse - UsageInfo = protocoltypes.UsageInfo - Message = protocoltypes.Message - ToolDefinition = protocoltypes.ToolDefinition - ToolFunctionDefinition = protocoltypes.ToolFunctionDefinition -) - -// Provider implements the LLM provider interface for AWS Bedrock. -type Provider struct { - client *bedrockruntime.Client - region string - requestTimeout time.Duration -} - -// Option configures the Bedrock Provider. -type Option func(*providerConfig) - -type providerConfig struct { - region string - profile string - baseEndpoint string - requestTimeout time.Duration -} - -// WithRegion sets the AWS region for Bedrock requests. -func WithRegion(region string) Option { - return func(c *providerConfig) { - c.region = region - } -} - -// WithProfile sets the AWS profile to use for credentials. -func WithProfile(profile string) Option { - return func(c *providerConfig) { - c.profile = profile - } -} - -// WithBaseEndpoint sets a custom Bedrock endpoint URL. -// Example: https://bedrock-runtime.us-east-1.amazonaws.com -func WithBaseEndpoint(endpoint string) Option { - return func(c *providerConfig) { - c.baseEndpoint = endpoint - } -} - -// WithRequestTimeout sets the timeout for Bedrock API requests. -func WithRequestTimeout(timeout time.Duration) Option { - return func(c *providerConfig) { - c.requestTimeout = timeout - } -} - -// NewProvider creates a new AWS Bedrock provider. -// It uses the default AWS credential chain (env vars, shared config, IAM roles, etc.). -func NewProvider(ctx context.Context, opts ...Option) (*Provider, error) { - pc := &providerConfig{} - for _, opt := range opts { - opt(pc) - } - - // Build AWS config options - var configOpts []func(*config.LoadOptions) error - - if pc.region != "" { - configOpts = append(configOpts, config.WithRegion(pc.region)) - } - - if pc.profile != "" { - configOpts = append(configOpts, config.WithSharedConfigProfile(pc.profile)) - } - - // Load AWS config with automatic credential discovery - cfg, err := config.LoadDefaultConfig(ctx, configOpts...) - if err != nil { - return nil, fmt.Errorf("loading AWS config: %w", err) - } - - // Validate region is set - required for Bedrock request signing - if cfg.Region == "" { - return nil, fmt.Errorf( - "AWS region not configured: set AWS_REGION, AWS_DEFAULT_REGION, or use WithRegion option", - ) - } - - // Build client options - var clientOpts []func(*bedrockruntime.Options) - if pc.baseEndpoint != "" { - clientOpts = append(clientOpts, func(o *bedrockruntime.Options) { - o.BaseEndpoint = aws.String(pc.baseEndpoint) - }) - } - - client := bedrockruntime.NewFromConfig(cfg, clientOpts...) - - return &Provider{ - client: client, - region: cfg.Region, - requestTimeout: pc.requestTimeout, - }, nil -} - -// converseParams holds the shared request parameters for Converse and ConverseStream. -type converseParams struct { - messages []types.Message - system []types.SystemContentBlock - inferenceConfig *types.InferenceConfiguration - toolConfig *types.ToolConfiguration -} - -// modelDeprecatesTemperature reports whether the given Bedrock model rejects the -// temperature inference parameter. Newer Claude models (Opus 4.8 and later) treat -// temperature as deprecated and return a ValidationException if it is supplied: -// -// ValidationException: The model returned the following errors: -// temperature is deprecated for this model. -// -// The match is intentionally loose: Bedrock model IDs and inference-profile ARNs -// embed the model name (e.g. "us.anthropic.claude-opus-4-8-20260514-v1:0"), so a -// substring check covers both bare IDs and region-prefixed inference profiles. -func modelDeprecatesTemperature(model string) bool { - m := strings.ToLower(model) - return strings.Contains(m, "claude-opus-4-8") -} - -func buildConverseParams(messages []Message, tools []ToolDefinition, model string, options map[string]any) converseParams { - bedrockMessages, systemPrompts := convertMessages(messages) - - var inferenceConfig *types.InferenceConfiguration - - if maxTokens, ok := common.AsInt(options["max_tokens"]); ok && maxTokens > 0 { - if inferenceConfig == nil { - inferenceConfig = &types.InferenceConfiguration{} - } - if maxTokens > math.MaxInt32 { - maxTokens = math.MaxInt32 - } - inferenceConfig.MaxTokens = aws.Int32(int32(maxTokens)) - } - - if temp, ok := common.AsFloat(options["temperature"]); ok { - if modelDeprecatesTemperature(model) { - log.Printf("bedrock: temperature dropped because model %q no longer supports it", model) - } else { - if inferenceConfig == nil { - inferenceConfig = &types.InferenceConfiguration{} - } - inferenceConfig.Temperature = aws.Float32(float32(temp)) - } - } - - var toolConfig *types.ToolConfiguration - if len(tools) > 0 { - tc := convertTools(tools) - if len(tc.Tools) > 0 { - toolConfig = tc - } - } - - return converseParams{ - messages: bedrockMessages, - system: systemPrompts, - inferenceConfig: inferenceConfig, - toolConfig: toolConfig, - } -} - -// Chat sends messages to AWS Bedrock using the Converse API. -func (p *Provider) Chat( - ctx context.Context, - messages []Message, - tools []ToolDefinition, - model string, - options map[string]any, -) (*LLMResponse, error) { - effectiveTimeout := p.requestTimeout - if effectiveTimeout <= 0 { - effectiveTimeout = common.DefaultRequestTimeout - } - if _, hasDeadline := ctx.Deadline(); !hasDeadline { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, effectiveTimeout) - defer cancel() - } - - params := buildConverseParams(messages, tools, model, options) - input := &bedrockruntime.ConverseInput{ - ModelId: aws.String(model), - Messages: params.messages, - InferenceConfig: params.inferenceConfig, - ToolConfig: params.toolConfig, - } - if len(params.system) > 0 { - input.System = params.system - } - - output, err := p.client.Converse(ctx, input) - if err != nil { - if isSSOTokenError(err) { - return nil, fmt.Errorf( - "bedrock converse: AWS credentials may have expired. If using AWS SSO, run 'aws sso login' to refresh: %w", - err, - ) - } - return nil, fmt.Errorf("bedrock converse: %w", err) - } - - return parseResponse(output) -} - -// ChatStream sends messages to AWS Bedrock using the ConverseStream API. -// It streams the accumulated text so far via the onChunk callback and returns the complete response. -func (p *Provider) ChatStream( - ctx context.Context, - messages []Message, - tools []ToolDefinition, - model string, - options map[string]any, - onChunk func(accumulated string), -) (*LLMResponse, error) { - if p.requestTimeout > 0 { - if _, hasDeadline := ctx.Deadline(); !hasDeadline { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, p.requestTimeout) - defer cancel() - } - } - - params := buildConverseParams(messages, tools, model, options) - input := &bedrockruntime.ConverseStreamInput{ - ModelId: aws.String(model), - Messages: params.messages, - InferenceConfig: params.inferenceConfig, - ToolConfig: params.toolConfig, - } - if len(params.system) > 0 { - input.System = params.system - } - - output, err := p.client.ConverseStream(ctx, input) - if err != nil { - if isSSOTokenError(err) { - return nil, fmt.Errorf( - "bedrock conversestream: AWS credentials may have expired. If using AWS SSO, run 'aws sso login' to refresh: %w", - err, - ) - } - return nil, fmt.Errorf("bedrock conversestream: %w", err) - } - - return parseStreamResponse(ctx, output.GetStream(), onChunk) -} - -// converseStreamReader abstracts the Bedrock event stream so parseStreamResponse -// can be unit-tested with a mock event source. -type converseStreamReader interface { - Events() <-chan types.ConverseStreamOutput - Err() error - Close() error -} - -// parseStreamResponse processes the ConverseStream event stream and accumulates the response. -func parseStreamResponse( - ctx context.Context, - stream converseStreamReader, - onChunk func(accumulated string), -) (resp *LLMResponse, err error) { - if stream == nil { - return nil, fmt.Errorf("bedrock conversestream: nil event stream") - } - defer func() { - if closeErr := stream.Close(); closeErr != nil { - if err == nil { - err = fmt.Errorf("bedrock conversestream: close event stream: %w", closeErr) - } else { - log.Printf("bedrock conversestream: close event stream: %v", closeErr) - } - } - }() - - var textContent strings.Builder - finishReason := "stop" - var usage *UsageInfo - toolCalls := make([]ToolCall, 0) - - // Track active tool use blocks by index - type toolAccum struct { - id string - name string - argsJSON strings.Builder - } - activeTools := map[int]*toolAccum{} - - events := stream.Events() - for { - select { - case <-ctx.Done(): - return nil, ctx.Err() - case event, ok := <-events: - if !ok { - // Stream closed - goto done - } - - switch e := event.(type) { - case *types.ConverseStreamOutputMemberContentBlockStart: - // New content block starting - if toolUse, ok := e.Value.Start.(*types.ContentBlockStartMemberToolUse); ok { - activeTools[int(aws.ToInt32(e.Value.ContentBlockIndex))] = &toolAccum{ - id: aws.ToString(toolUse.Value.ToolUseId), - name: aws.ToString(toolUse.Value.Name), - } - } - - case *types.ConverseStreamOutputMemberContentBlockDelta: - // Content delta - switch delta := e.Value.Delta.(type) { - case *types.ContentBlockDeltaMemberText: - textContent.WriteString(delta.Value) - if onChunk != nil { - onChunk(textContent.String()) - } - case *types.ContentBlockDeltaMemberToolUse: - idx := int(aws.ToInt32(e.Value.ContentBlockIndex)) - if tool, exists := activeTools[idx]; exists { - tool.argsJSON.WriteString(aws.ToString(delta.Value.Input)) - } - } - - case *types.ConverseStreamOutputMemberContentBlockStop: - // Content block finished - finalize tool if it was a tool use - idx := int(aws.ToInt32(e.Value.ContentBlockIndex)) - if tool, exists := activeTools[idx]; exists { - args := make(map[string]any) - argsStr := tool.argsJSON.String() - if argsStr != "" { - if err := json.Unmarshal([]byte(argsStr), &args); err != nil { - log.Printf("bedrock: stream: failed to parse tool arguments for %q: %v", tool.name, err) - args = map[string]any{"raw": argsStr} - } - } - funcArgs := argsStr - if argsJSON, marshalErr := json.Marshal(args); marshalErr == nil { - funcArgs = string(argsJSON) - } - toolCalls = append(toolCalls, ToolCall{ - ID: tool.id, - Name: tool.name, - Arguments: args, - Function: &FunctionCall{ - Name: tool.name, - Arguments: funcArgs, - }, - }) - delete(activeTools, idx) - } - - case *types.ConverseStreamOutputMemberMessageStop: - // Message complete - switch e.Value.StopReason { - case types.StopReasonToolUse: - finishReason = "tool_calls" - case types.StopReasonMaxTokens: - finishReason = "length" - case types.StopReasonEndTurn: - finishReason = "stop" - case types.StopReasonStopSequence: - finishReason = "stop" - case types.StopReasonContentFiltered: - finishReason = "content_filter" - default: - finishReason = "stop" - } - - case *types.ConverseStreamOutputMemberMetadata: - // Usage metadata - if e.Value.Usage != nil { - usage = &UsageInfo{ - PromptTokens: int(aws.ToInt32(e.Value.Usage.InputTokens)), - CompletionTokens: int(aws.ToInt32(e.Value.Usage.OutputTokens)), - TotalTokens: int( - aws.ToInt32(e.Value.Usage.InputTokens), - ) + int( - aws.ToInt32(e.Value.Usage.OutputTokens), - ), - } - } - } - } - } - -done: - if err := stream.Err(); err != nil { - return nil, fmt.Errorf("bedrock conversestream: %w", err) - } - - return &LLMResponse{ - Content: textContent.String(), - ToolCalls: toolCalls, - FinishReason: finishReason, - Usage: usage, - }, nil -} - -// GetDefaultModel returns an empty string as Bedrock models are user-configured. -func (p *Provider) GetDefaultModel() string { - return "" -} - -// Region returns the AWS region configured for this Provider. -func (p *Provider) Region() string { - return p.region -} - -// convertMessages converts internal messages to Bedrock Converse format. -// Returns the conversation messages and any system prompts separately. -// Note: Bedrock requires all tool results for a given assistant turn to be in a single -// user message with multiple ToolResultBlock content blocks. This function merges -// consecutive tool result messages accordingly. -func convertMessages(messages []Message) ([]types.Message, []types.SystemContentBlock) { - var bedrockMessages []types.Message - var systemPrompts []types.SystemContentBlock - - // Helper to check if a message is a tool result - isToolResult := func(msg Message) bool { - return (msg.Role == "tool" || (msg.Role == "user" && msg.ToolCallID != "")) && msg.ToolCallID != "" - } - - // Helper to create a tool result content block - makeToolResultBlock := func(msg Message) types.ContentBlock { - return &types.ContentBlockMemberToolResult{ - Value: types.ToolResultBlock{ - ToolUseId: aws.String(msg.ToolCallID), - Content: []types.ToolResultContentBlock{ - &types.ToolResultContentBlockMemberText{ - Value: msg.Content, - }, - }, - }, - } - } - - i := 0 - for i < len(messages) { - msg := messages[i] - - switch { - case msg.Role == "system": - // System messages go to the System field - systemPrompts = append(systemPrompts, &types.SystemContentBlockMemberText{ - Value: msg.Content, - }) - i++ - - case isToolResult(msg): - // Collect all consecutive tool results into a single user message - // Bedrock requires all tool results for a turn in one message - var toolResultBlocks []types.ContentBlock - for i < len(messages) && isToolResult(messages[i]) { - toolResultBlocks = append(toolResultBlocks, makeToolResultBlock(messages[i])) - i++ - } - bedrockMessages = append(bedrockMessages, types.Message{ - Role: types.ConversationRoleUser, - Content: toolResultBlocks, - }) - - case msg.Role == "user": - // Regular user message (no ToolCallID) - content := buildUserContent(msg) - bedrockMessages = append(bedrockMessages, types.Message{ - Role: types.ConversationRoleUser, - Content: content, - }) - i++ - - case msg.Role == "assistant": - content := buildAssistantContent(msg) - bedrockMessages = append(bedrockMessages, types.Message{ - Role: types.ConversationRoleAssistant, - Content: content, - }) - i++ - - case msg.Role == "tool" && msg.ToolCallID == "": - // Tool message without ToolCallID - treat as regular user message - content := buildUserContent(msg) - bedrockMessages = append(bedrockMessages, types.Message{ - Role: types.ConversationRoleUser, - Content: content, - }) - i++ - - default: - // Unknown role - skip - i++ - } - } - - return bedrockMessages, systemPrompts -} - -// buildUserContent builds Bedrock content blocks for a user message. -func buildUserContent(msg Message) []types.ContentBlock { - var content []types.ContentBlock - - // Add text content - if msg.Content != "" { - content = append(content, &types.ContentBlockMemberText{ - Value: msg.Content, - }) - } - - // Add images from Media field - for _, mediaURL := range msg.Media { - if strings.HasPrefix(mediaURL, "data:image/") { - // Parse data URL: data:image/jpeg;base64, - parts := strings.SplitN(mediaURL, ",", 2) - if len(parts) != 2 { - continue - } - - // Extract media type from "data:image/jpeg;base64" - mediaType := "" - header := parts[0] - if idx := strings.Index(header, "/"); idx != -1 { - end := strings.Index(header[idx:], ";") - if end == -1 { - end = len(header) - idx - } - mediaType = header[idx+1 : idx+end] - } - - // Verify this is base64 encoded - if !strings.Contains(header, ";base64") { - continue // Skip non-base64 encoded data - } - - // Map media type to Bedrock format - var format types.ImageFormat - switch mediaType { - case "jpeg", "jpg": - format = types.ImageFormatJpeg - case "png": - format = types.ImageFormatPng - case "gif": - format = types.ImageFormatGif - case "webp": - format = types.ImageFormatWebp - default: - continue // Skip unsupported formats - } - - // Check size before decoding to prevent excessive memory allocation - // Bedrock has a ~20MB request limit; cap decoded images at 10MB - const maxImageSize = 10 * 1024 * 1024 - decodedLen := base64.StdEncoding.DecodedLen(len(parts[1])) - if decodedLen > maxImageSize { - log.Printf("bedrock: skipping image exceeding size limit (%d bytes > %d)", decodedLen, maxImageSize) - continue - } - - // Decode base64 data - imageData, err := base64.StdEncoding.DecodeString(parts[1]) - if err != nil { - log.Printf("bedrock: failed to decode base64 image data: %v", err) - continue - } - - content = append(content, &types.ContentBlockMemberImage{ - Value: types.ImageBlock{ - Format: format, - Source: &types.ImageSourceMemberBytes{ - Value: imageData, - }, - }, - }) - } - } - - // Bedrock requires at least one content block; add empty text if needed - if len(content) == 0 { - content = append(content, &types.ContentBlockMemberText{Value: ""}) - } - - return content -} - -// buildAssistantContent builds Bedrock content blocks for an assistant message. -func buildAssistantContent(msg Message) []types.ContentBlock { - var content []types.ContentBlock - - // Add text content if present - if msg.Content != "" { - content = append(content, &types.ContentBlockMemberText{ - Value: msg.Content, - }) - } - - // Add tool use blocks - for _, tc := range msg.ToolCalls { - // Validate tool call ID - Bedrock requires non-empty ToolUseId - if strings.TrimSpace(tc.ID) == "" { - log.Printf("bedrock: skipping tool call with empty ID (name: %q)", tc.Name) - continue - } - - // Resolve tool name: prefer tc.Name, fallback to tc.Function.Name - // (tc.Name/tc.Arguments are json:"-" and may be empty when from JSON) - toolName := tc.Name - if toolName == "" && tc.Function != nil { - toolName = tc.Function.Name - } - if strings.TrimSpace(toolName) == "" { - continue - } - - // Resolve arguments: prefer tc.Arguments, fallback to parsing tc.Function.Arguments - args := tc.Arguments - if args == nil && tc.Function != nil && tc.Function.Arguments != "" { - if err := json.Unmarshal([]byte(tc.Function.Arguments), &args); err != nil { - log.Printf("bedrock: failed to parse Function.Arguments for tool %q: %v", toolName, err) - args = map[string]any{} - } - } - if args == nil { - args = map[string]any{} - } - - // Convert arguments to a Bedrock document using NewLazyDocument - inputDoc := document.NewLazyDocument(args) - - content = append(content, &types.ContentBlockMemberToolUse{ - Value: types.ToolUseBlock{ - ToolUseId: aws.String(tc.ID), - Name: aws.String(toolName), - Input: inputDoc, - }, - }) - } - - // Bedrock requires at least one content block; add empty text if needed - if len(content) == 0 { - content = append(content, &types.ContentBlockMemberText{Value: ""}) - } - - return content -} - -// convertTools converts tool definitions to Bedrock format. -func convertTools(tools []ToolDefinition) *types.ToolConfiguration { - bedrockTools := make([]types.Tool, 0, len(tools)) - - for _, tool := range tools { - // Skip tools with empty names - if strings.TrimSpace(tool.Function.Name) == "" { - continue - } - - // Ensure parameters is not nil - default to minimal object schema - params := tool.Function.Parameters - if params == nil { - params = map[string]any{ - "type": "object", - "properties": map[string]any{}, - } - } - - // Convert parameters schema to a Bedrock document - inputSchema := document.NewLazyDocument(params) - - bedrockTools = append(bedrockTools, &types.ToolMemberToolSpec{ - Value: types.ToolSpecification{ - Name: aws.String(tool.Function.Name), - Description: aws.String(tool.Function.Description), - InputSchema: &types.ToolInputSchemaMemberJson{ - Value: inputSchema, - }, - }, - }) - } - - return &types.ToolConfiguration{ - Tools: bedrockTools, - } -} - -// parseResponse converts Bedrock Converse output to LLMResponse. -func parseResponse(output *bedrockruntime.ConverseOutput) (*LLMResponse, error) { - var content strings.Builder - toolCalls := make([]ToolCall, 0) - - // Process output content blocks - if output.Output != nil { - if msgOutput, ok := output.Output.(*types.ConverseOutputMemberMessage); ok { - for _, block := range msgOutput.Value.Content { - switch b := block.(type) { - case *types.ContentBlockMemberText: - content.WriteString(b.Value) - - case *types.ContentBlockMemberToolUse: - // Unmarshal the document interface to a map - args := make(map[string]any) - if b.Value.Input != nil { - if err := b.Value.Input.UnmarshalSmithyDocument(&args); err != nil { - log.Printf("bedrock: failed to unmarshal tool input for tool %q (id %q): %v", - aws.ToString(b.Value.Name), - aws.ToString(b.Value.ToolUseId), - err, - ) - args = make(map[string]any) - } - } - - // Serialize arguments to JSON string for FunctionCall - argsJSON, err := json.Marshal(args) - if err != nil { - log.Printf("bedrock: failed to marshal tool arguments for tool %q (id %q): %v", - aws.ToString(b.Value.Name), - aws.ToString(b.Value.ToolUseId), - err, - ) - argsJSON = []byte("{}") - } - - toolCalls = append(toolCalls, ToolCall{ - ID: aws.ToString(b.Value.ToolUseId), - Name: aws.ToString(b.Value.Name), - Arguments: args, - Function: &FunctionCall{ - Name: aws.ToString(b.Value.Name), - Arguments: string(argsJSON), - }, - }) - } - } - } - } - - // Map stop reason - finishReason := "stop" - switch output.StopReason { - case types.StopReasonToolUse: - finishReason = "tool_calls" - case types.StopReasonMaxTokens: - finishReason = "length" - case types.StopReasonEndTurn: - finishReason = "stop" - case types.StopReasonStopSequence: - finishReason = "stop" - case types.StopReasonContentFiltered: - finishReason = "content_filter" - } - - // Build usage info - var usage *UsageInfo - if output.Usage != nil { - usage = &UsageInfo{ - PromptTokens: int(aws.ToInt32(output.Usage.InputTokens)), - CompletionTokens: int(aws.ToInt32(output.Usage.OutputTokens)), - TotalTokens: int(aws.ToInt32(output.Usage.InputTokens)) + int(aws.ToInt32(output.Usage.OutputTokens)), - } - } - - return &LLMResponse{ - Content: content.String(), - ToolCalls: toolCalls, - FinishReason: finishReason, - Usage: usage, - }, nil -} - -// isSSOTokenError checks if the error is related to expired or invalid AWS SSO tokens. -// This helps provide actionable guidance when SSO credentials need to be refreshed. -// Only matches SSO-specific error patterns to avoid misclassifying other AWS credential errors. -func isSSOTokenError(err error) bool { - if err == nil { - return false - } - lower := strings.ToLower(err.Error()) - - // Check for specific SSO token expiration/refresh-related error patterns (case-insensitive) - // Avoid matching generic patterns that could match non-SSO AWS errors (e.g., STS ExpiredToken) - if strings.Contains(lower, "refresh cached sso token") { - return true - } - if strings.Contains(lower, "read cached sso token") { - return true - } - if strings.Contains(lower, "sso oidc") { - return true - } - if strings.Contains(lower, "invalidgrantexception") { - return true - } - - return false -} diff --git a/pkg/providers/bedrock/provider_bedrock_test.go b/pkg/providers/bedrock/provider_bedrock_test.go deleted file mode 100644 index a06a93c9..00000000 --- a/pkg/providers/bedrock/provider_bedrock_test.go +++ /dev/null @@ -1,923 +0,0 @@ -//go:build bedrock - -// PicoClaw - Ultra-lightweight personal AI agent -// License: MIT -// -// Copyright (c) 2026 PicoClaw contributors - -package bedrock - -import ( - "context" - "fmt" - "testing" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/bedrockruntime" - "github.com/aws/aws-sdk-go-v2/service/bedrockruntime/document" - "github.com/aws/aws-sdk-go-v2/service/bedrockruntime/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/sipeed/picoclaw/pkg/providers/protocoltypes" -) - -func TestConvertMessages_SystemPrompts(t *testing.T) { - messages := []Message{ - {Role: "system", Content: "You are a helpful assistant."}, - {Role: "user", Content: "Hello"}, - } - - bedrockMsgs, systemPrompts := convertMessages(messages) - - assert.Len(t, systemPrompts, 1) - assert.Len(t, bedrockMsgs, 1) - - // Check system prompt - textBlock, ok := systemPrompts[0].(*types.SystemContentBlockMemberText) - require.True(t, ok) - assert.Equal(t, "You are a helpful assistant.", textBlock.Value) - - // Check user message - assert.Equal(t, types.ConversationRoleUser, bedrockMsgs[0].Role) -} - -func TestConvertMessages_UserMessage(t *testing.T) { - messages := []Message{ - {Role: "user", Content: "What is 2+2?"}, - } - - bedrockMsgs, systemPrompts := convertMessages(messages) - - assert.Empty(t, systemPrompts) - assert.Len(t, bedrockMsgs, 1) - assert.Equal(t, types.ConversationRoleUser, bedrockMsgs[0].Role) - - textBlock, ok := bedrockMsgs[0].Content[0].(*types.ContentBlockMemberText) - require.True(t, ok) - assert.Equal(t, "What is 2+2?", textBlock.Value) -} - -func TestConvertMessages_AssistantMessage(t *testing.T) { - messages := []Message{ - {Role: "assistant", Content: "The answer is 4."}, - } - - bedrockMsgs, _ := convertMessages(messages) - - assert.Len(t, bedrockMsgs, 1) - assert.Equal(t, types.ConversationRoleAssistant, bedrockMsgs[0].Role) - - textBlock, ok := bedrockMsgs[0].Content[0].(*types.ContentBlockMemberText) - require.True(t, ok) - assert.Equal(t, "The answer is 4.", textBlock.Value) -} - -func TestConvertMessages_ToolResult(t *testing.T) { - messages := []Message{ - {Role: "tool", Content: "Result from tool", ToolCallID: "call_123"}, - } - - bedrockMsgs, _ := convertMessages(messages) - - assert.Len(t, bedrockMsgs, 1) - assert.Equal(t, types.ConversationRoleUser, bedrockMsgs[0].Role) - - toolResult, ok := bedrockMsgs[0].Content[0].(*types.ContentBlockMemberToolResult) - require.True(t, ok) - assert.Equal(t, "call_123", aws.ToString(toolResult.Value.ToolUseId)) -} - -func TestConvertMessages_MultipleToolResultsMerged(t *testing.T) { - // When an assistant makes multiple tool calls, all tool results must be - // merged into a single user message for Bedrock - messages := []Message{ - {Role: "user", Content: "What's the weather in NYC and LA?"}, - { - Role: "assistant", - Content: "Let me check both cities.", - ToolCalls: []protocoltypes.ToolCall{ - {ID: "call_nyc", Name: "get_weather", Arguments: map[string]any{"city": "NYC"}}, - {ID: "call_la", Name: "get_weather", Arguments: map[string]any{"city": "LA"}}, - }, - }, - {Role: "tool", Content: "NYC: 72°F, sunny", ToolCallID: "call_nyc"}, - {Role: "tool", Content: "LA: 85°F, clear", ToolCallID: "call_la"}, - } - - bedrockMsgs, _ := convertMessages(messages) - - // Should be: user message, assistant message, merged tool results (single user message) - assert.Len(t, bedrockMsgs, 3) - - // First message: user - assert.Equal(t, types.ConversationRoleUser, bedrockMsgs[0].Role) - - // Second message: assistant with tool calls - assert.Equal(t, types.ConversationRoleAssistant, bedrockMsgs[1].Role) - - // Third message: merged tool results in single user message - assert.Equal(t, types.ConversationRoleUser, bedrockMsgs[2].Role) - assert.Len(t, bedrockMsgs[2].Content, 2) // Both tool results in one message - - // Verify both tool results are present - result1, ok := bedrockMsgs[2].Content[0].(*types.ContentBlockMemberToolResult) - require.True(t, ok) - assert.Equal(t, "call_nyc", aws.ToString(result1.Value.ToolUseId)) - - result2, ok := bedrockMsgs[2].Content[1].(*types.ContentBlockMemberToolResult) - require.True(t, ok) - assert.Equal(t, "call_la", aws.ToString(result2.Value.ToolUseId)) -} - -func TestConvertMessages_AssistantWithToolCalls(t *testing.T) { - messages := []Message{ - { - Role: "assistant", - Content: "Let me calculate that.", - ToolCalls: []protocoltypes.ToolCall{ - { - ID: "call_456", - Name: "calculator", - Arguments: map[string]any{"expression": "2+2"}, - }, - }, - }, - } - - bedrockMsgs, _ := convertMessages(messages) - - assert.Len(t, bedrockMsgs, 1) - assert.Len(t, bedrockMsgs[0].Content, 2) // text + tool use - - // Check text content - textBlock, ok := bedrockMsgs[0].Content[0].(*types.ContentBlockMemberText) - require.True(t, ok) - assert.Equal(t, "Let me calculate that.", textBlock.Value) - - // Check tool use - toolUse, ok := bedrockMsgs[0].Content[1].(*types.ContentBlockMemberToolUse) - require.True(t, ok) - assert.Equal(t, "call_456", aws.ToString(toolUse.Value.ToolUseId)) - assert.Equal(t, "calculator", aws.ToString(toolUse.Value.Name)) -} - -func TestConvertTools_Basic(t *testing.T) { - tools := []ToolDefinition{ - { - Function: protocoltypes.ToolFunctionDefinition{ - Name: "get_weather", - Description: "Get the current weather", - Parameters: map[string]any{ - "type": "object", - "properties": map[string]any{ - "location": map[string]any{"type": "string"}, - }, - }, - }, - }, - } - - toolConfig := convertTools(tools) - - assert.NotNil(t, toolConfig) - assert.Len(t, toolConfig.Tools, 1) - - toolSpec, ok := toolConfig.Tools[0].(*types.ToolMemberToolSpec) - require.True(t, ok) - assert.Equal(t, "get_weather", aws.ToString(toolSpec.Value.Name)) - assert.Equal(t, "Get the current weather", aws.ToString(toolSpec.Value.Description)) -} - -func TestConvertTools_SkipsEmptyName(t *testing.T) { - tools := []ToolDefinition{ - { - Function: protocoltypes.ToolFunctionDefinition{ - Name: "", - Description: "Empty name tool", - }, - }, - { - Function: protocoltypes.ToolFunctionDefinition{ - Name: " ", - Description: "Whitespace name tool", - }, - }, - { - Function: protocoltypes.ToolFunctionDefinition{ - Name: "valid_tool", - Description: "Valid tool", - }, - }, - } - - toolConfig := convertTools(tools) - - assert.Len(t, toolConfig.Tools, 1) - toolSpec := toolConfig.Tools[0].(*types.ToolMemberToolSpec) - assert.Equal(t, "valid_tool", aws.ToString(toolSpec.Value.Name)) -} - -func TestConvertTools_NilParameters(t *testing.T) { - tools := []ToolDefinition{ - { - Function: protocoltypes.ToolFunctionDefinition{ - Name: "simple_tool", - Description: "A tool with no parameters", - Parameters: nil, - }, - }, - } - - toolConfig := convertTools(tools) - - assert.Len(t, toolConfig.Tools, 1) - // Should not panic and should create a valid tool -} - -func TestBuildUserContent_TextOnly(t *testing.T) { - msg := Message{Content: "Hello world"} - - content := buildUserContent(msg) - - assert.Len(t, content, 1) - textBlock, ok := content[0].(*types.ContentBlockMemberText) - require.True(t, ok) - assert.Equal(t, "Hello world", textBlock.Value) -} - -func TestBuildUserContent_WithImage(t *testing.T) { - // Base64-encoded 1x1 PNG (the provider doesn't validate image correctness, - // it just verifies the format and base64 decoding works) - b64Data := "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGNgYAAAAAMAASsJTYQAAAAASUVORK5CYII=" - - msg := Message{ - Content: "Look at this image", - Media: []string{"data:image/png;base64," + b64Data}, - } - - content := buildUserContent(msg) - - assert.Len(t, content, 2) - - // Check text - textBlock, ok := content[0].(*types.ContentBlockMemberText) - require.True(t, ok) - assert.Equal(t, "Look at this image", textBlock.Value) - - // Check image - imageBlock, ok := content[1].(*types.ContentBlockMemberImage) - require.True(t, ok) - assert.Equal(t, types.ImageFormatPng, imageBlock.Value.Format) -} - -func TestBuildUserContent_SkipsInvalidBase64(t *testing.T) { - msg := Message{ - Content: "Invalid image", - Media: []string{"data:image/png;base64,not-valid-base64!!!"}, - } - - content := buildUserContent(msg) - - // Should only have text, image should be skipped - assert.Len(t, content, 1) -} - -func TestBuildUserContent_SkipsNonBase64Data(t *testing.T) { - msg := Message{ - Content: "Non-base64 image", - Media: []string{"data:image/png,raw-data-here"}, - } - - content := buildUserContent(msg) - - // Should only have text, non-base64 image should be skipped - assert.Len(t, content, 1) -} - -func TestBuildAssistantContent_SkipsEmptyToolName(t *testing.T) { - msg := Message{ - Content: "Response", - ToolCalls: []protocoltypes.ToolCall{ - {ID: "1", Name: "", Arguments: map[string]any{}}, - {ID: "2", Name: " ", Arguments: map[string]any{}}, - {ID: "3", Name: "valid", Arguments: map[string]any{}}, - }, - } - - content := buildAssistantContent(msg) - - // Should have text + 1 valid tool - assert.Len(t, content, 2) -} - -func TestBuildAssistantContent_NilArguments(t *testing.T) { - msg := Message{ - ToolCalls: []protocoltypes.ToolCall{ - {ID: "1", Name: "tool", Arguments: nil}, - }, - } - - content := buildAssistantContent(msg) - - assert.Len(t, content, 1) - toolUse, ok := content[0].(*types.ContentBlockMemberToolUse) - require.True(t, ok) - assert.NotNil(t, toolUse.Value.Input) -} - -func TestBuildAssistantContent_FunctionFallback(t *testing.T) { - // When Name/Arguments are empty (json:"-"), should fallback to Function fields - msg := Message{ - ToolCalls: []protocoltypes.ToolCall{ - { - ID: "1", - Name: "", // empty, should fallback to Function.Name - Function: &protocoltypes.FunctionCall{ - Name: "fallback_tool", - Arguments: `{"key":"value"}`, - }, - }, - }, - } - - content := buildAssistantContent(msg) - - assert.Len(t, content, 1) - toolUse, ok := content[0].(*types.ContentBlockMemberToolUse) - require.True(t, ok) - assert.Equal(t, "fallback_tool", aws.ToString(toolUse.Value.Name)) -} - -func TestParseResponse_TextOnly(t *testing.T) { - output := &bedrockruntime.ConverseOutput{ - Output: &types.ConverseOutputMemberMessage{ - Value: types.Message{ - Role: types.ConversationRoleAssistant, - Content: []types.ContentBlock{ - &types.ContentBlockMemberText{Value: "Hello!"}, - }, - }, - }, - StopReason: types.StopReasonEndTurn, - Usage: &types.TokenUsage{ - InputTokens: aws.Int32(10), - OutputTokens: aws.Int32(5), - }, - } - - resp, err := parseResponse(output) - - require.NoError(t, err) - assert.Equal(t, "Hello!", resp.Content) - assert.Equal(t, "stop", resp.FinishReason) - assert.Empty(t, resp.ToolCalls) - assert.Equal(t, 10, resp.Usage.PromptTokens) - assert.Equal(t, 5, resp.Usage.CompletionTokens) -} - -func TestParseResponse_StopReasons(t *testing.T) { - tests := []struct { - stopReason types.StopReason - expectedFinish string - }{ - {types.StopReasonEndTurn, "stop"}, - {types.StopReasonToolUse, "tool_calls"}, - {types.StopReasonMaxTokens, "length"}, - {types.StopReasonStopSequence, "stop"}, - {types.StopReasonContentFiltered, "content_filter"}, - } - - for _, tt := range tests { - t.Run(string(tt.stopReason), func(t *testing.T) { - output := &bedrockruntime.ConverseOutput{ - Output: &types.ConverseOutputMemberMessage{ - Value: types.Message{ - Content: []types.ContentBlock{ - &types.ContentBlockMemberText{Value: "test"}, - }, - }, - }, - StopReason: tt.stopReason, - } - - resp, err := parseResponse(output) - - require.NoError(t, err) - assert.Equal(t, tt.expectedFinish, resp.FinishReason) - }) - } -} - -func TestParseResponse_WithToolCalls(t *testing.T) { - // Note: document.NewLazyDocument has limitations with UnmarshalSmithyDocument in tests, - // so we test the structure extraction and verify Arguments gets populated (even if empty - // due to SDK limitations). The actual unmarshal works correctly at runtime. - toolInput := document.NewLazyDocument(map[string]any{ - "location": "San Francisco", - "unit": "celsius", - }) - - output := &bedrockruntime.ConverseOutput{ - Output: &types.ConverseOutputMemberMessage{ - Value: types.Message{ - Role: types.ConversationRoleAssistant, - Content: []types.ContentBlock{ - &types.ContentBlockMemberText{Value: "Let me check the weather."}, - &types.ContentBlockMemberToolUse{ - Value: types.ToolUseBlock{ - ToolUseId: aws.String("call_weather_123"), - Name: aws.String("get_weather"), - Input: toolInput, - }, - }, - }, - }, - }, - StopReason: types.StopReasonToolUse, - Usage: &types.TokenUsage{ - InputTokens: aws.Int32(20), - OutputTokens: aws.Int32(15), - }, - } - - resp, err := parseResponse(output) - - require.NoError(t, err) - assert.Equal(t, "Let me check the weather.", resp.Content) - assert.Equal(t, "tool_calls", resp.FinishReason) - assert.Len(t, resp.ToolCalls, 1) - - // Verify tool call ID and Name are extracted correctly - tc := resp.ToolCalls[0] - assert.Equal(t, "call_weather_123", tc.ID) - assert.Equal(t, "get_weather", tc.Name) - - // Verify Function fields are also populated - require.NotNil(t, tc.Function) - assert.Equal(t, "get_weather", tc.Function.Name) - - // Verify Arguments is not nil (content may vary due to SDK limitations in tests) - assert.NotNil(t, tc.Arguments) - - // Verify usage - assert.Equal(t, 20, resp.Usage.PromptTokens) - assert.Equal(t, 15, resp.Usage.CompletionTokens) - assert.Equal(t, 35, resp.Usage.TotalTokens) -} - -func TestParseResponse_MultipleToolCalls(t *testing.T) { - output := &bedrockruntime.ConverseOutput{ - Output: &types.ConverseOutputMemberMessage{ - Value: types.Message{ - Role: types.ConversationRoleAssistant, - Content: []types.ContentBlock{ - &types.ContentBlockMemberToolUse{ - Value: types.ToolUseBlock{ - ToolUseId: aws.String("call_1"), - Name: aws.String("tool_a"), - Input: document.NewLazyDocument(map[string]any{"arg": "value1"}), - }, - }, - &types.ContentBlockMemberToolUse{ - Value: types.ToolUseBlock{ - ToolUseId: aws.String("call_2"), - Name: aws.String("tool_b"), - Input: document.NewLazyDocument(map[string]any{"arg": "value2"}), - }, - }, - }, - }, - }, - StopReason: types.StopReasonToolUse, - } - - resp, err := parseResponse(output) - - require.NoError(t, err) - assert.Equal(t, "tool_calls", resp.FinishReason) - assert.Len(t, resp.ToolCalls, 2) - - // Verify tool call structure - assert.Equal(t, "call_1", resp.ToolCalls[0].ID) - assert.Equal(t, "tool_a", resp.ToolCalls[0].Name) - assert.NotNil(t, resp.ToolCalls[0].Arguments) - assert.NotNil(t, resp.ToolCalls[0].Function) - assert.Equal(t, "tool_a", resp.ToolCalls[0].Function.Name) - - assert.Equal(t, "call_2", resp.ToolCalls[1].ID) - assert.Equal(t, "tool_b", resp.ToolCalls[1].Name) - assert.NotNil(t, resp.ToolCalls[1].Arguments) - assert.NotNil(t, resp.ToolCalls[1].Function) - assert.Equal(t, "tool_b", resp.ToolCalls[1].Function.Name) -} - -func TestParseResponse_ToolCallWithNilInput(t *testing.T) { - output := &bedrockruntime.ConverseOutput{ - Output: &types.ConverseOutputMemberMessage{ - Value: types.Message{ - Role: types.ConversationRoleAssistant, - Content: []types.ContentBlock{ - &types.ContentBlockMemberToolUse{ - Value: types.ToolUseBlock{ - ToolUseId: aws.String("call_nil"), - Name: aws.String("no_args_tool"), - Input: nil, - }, - }, - }, - }, - }, - StopReason: types.StopReasonToolUse, - } - - resp, err := parseResponse(output) - - require.NoError(t, err) - assert.Len(t, resp.ToolCalls, 1) - assert.Equal(t, "call_nil", resp.ToolCalls[0].ID) - assert.Equal(t, "no_args_tool", resp.ToolCalls[0].Name) - // Arguments should be empty map, not nil - assert.NotNil(t, resp.ToolCalls[0].Arguments) - assert.Empty(t, resp.ToolCalls[0].Arguments) -} - -func TestIsSSOTokenError(t *testing.T) { - tests := []struct { - name string - err error - expected bool - }{ - { - name: "nil error", - err: nil, - expected: false, - }, - { - name: "generic error", - err: fmt.Errorf("connection refused"), - expected: false, - }, - { - name: "SSO config error not expiration", - err: fmt.Errorf("failed to load SSO profile: invalid SSO session"), - expected: false, - }, - { - name: "STS ExpiredToken error", - err: fmt.Errorf("ExpiredToken: The security token included in the request is expired"), - expected: false, - }, - { - name: "SSO token refresh error", - err: fmt.Errorf("refresh cached SSO token failed"), - expected: true, - }, - { - name: "InvalidGrantException", - err: fmt.Errorf("operation error SSO OIDC: CreateToken, InvalidGrantException"), - expected: true, - }, - { - name: "SSO OIDC error", - err: fmt.Errorf("operation error SSO OIDC: CreateToken, failed"), - expected: true, - }, - { - name: "full SSO error message", - err: fmt.Errorf( - "get identity: get credentials: failed to refresh cached credentials, refresh cached SSO token failed, unable to refresh SSO token", - ), - expected: true, - }, - { - name: "SSO token file missing", - err: fmt.Errorf( - "get identity: get credentials: failed to refresh cached credentials, failed to read cached SSO token file, open ~/.aws/sso/cache/abc123.json: no such file or directory", - ), - expected: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - result := isSSOTokenError(tt.err) - assert.Equal(t, tt.expected, result) - }) - } -} - -// mockStreamReader implements bedrockruntime.ConverseStreamOutputReader for testing. -type mockStreamReader struct { - ch chan types.ConverseStreamOutput - err error -} - -func (r *mockStreamReader) Events() <-chan types.ConverseStreamOutput { return r.ch } -func (r *mockStreamReader) Close() error { return nil } -func (r *mockStreamReader) Err() error { return r.err } - -func newMockStream(events []types.ConverseStreamOutput) *bedrockruntime.ConverseStreamEventStream { - ch := make(chan types.ConverseStreamOutput, len(events)) - for _, e := range events { - ch <- e - } - close(ch) - - return bedrockruntime.NewConverseStreamEventStream(func(es *bedrockruntime.ConverseStreamEventStream) { - es.Reader = &mockStreamReader{ch: ch} - }) -} - -func TestParseStreamResponse_TextOnly(t *testing.T) { - events := []types.ConverseStreamOutput{ - &types.ConverseStreamOutputMemberContentBlockDelta{ - Value: types.ContentBlockDeltaEvent{ - Delta: &types.ContentBlockDeltaMemberText{Value: "Hello "}, - ContentBlockIndex: aws.Int32(0), - }, - }, - &types.ConverseStreamOutputMemberContentBlockDelta{ - Value: types.ContentBlockDeltaEvent{ - Delta: &types.ContentBlockDeltaMemberText{Value: "World"}, - ContentBlockIndex: aws.Int32(0), - }, - }, - &types.ConverseStreamOutputMemberMessageStop{ - Value: types.MessageStopEvent{StopReason: types.StopReasonEndTurn}, - }, - &types.ConverseStreamOutputMemberMetadata{ - Value: types.ConverseStreamMetadataEvent{ - Usage: &types.TokenUsage{ - InputTokens: aws.Int32(10), - OutputTokens: aws.Int32(5), - }, - }, - }, - } - - var chunks []string - stream := newMockStream(events) - resp, err := parseStreamResponse(context.Background(), stream, func(accumulated string) { - chunks = append(chunks, accumulated) - }) - - require.NoError(t, err) - assert.Equal(t, "Hello World", resp.Content) - assert.Equal(t, "stop", resp.FinishReason) - assert.Empty(t, resp.ToolCalls) - require.NotNil(t, resp.Usage) - assert.Equal(t, 10, resp.Usage.PromptTokens) - assert.Equal(t, 5, resp.Usage.CompletionTokens) - assert.Equal(t, 15, resp.Usage.TotalTokens) - assert.Equal(t, []string{"Hello ", "Hello World"}, chunks) -} - -func TestParseStreamResponse_ToolCall(t *testing.T) { - events := []types.ConverseStreamOutput{ - &types.ConverseStreamOutputMemberContentBlockStart{ - Value: types.ContentBlockStartEvent{ - ContentBlockIndex: aws.Int32(0), - Start: &types.ContentBlockStartMemberToolUse{ - Value: types.ToolUseBlockStart{ - ToolUseId: aws.String("call_1"), - Name: aws.String("search"), - }, - }, - }, - }, - &types.ConverseStreamOutputMemberContentBlockDelta{ - Value: types.ContentBlockDeltaEvent{ - ContentBlockIndex: aws.Int32(0), - Delta: &types.ContentBlockDeltaMemberToolUse{ - Value: types.ToolUseBlockDelta{Input: aws.String(`{"q":`)}, - }, - }, - }, - &types.ConverseStreamOutputMemberContentBlockDelta{ - Value: types.ContentBlockDeltaEvent{ - ContentBlockIndex: aws.Int32(0), - Delta: &types.ContentBlockDeltaMemberToolUse{ - Value: types.ToolUseBlockDelta{Input: aws.String(`"test"}`)}, - }, - }, - }, - &types.ConverseStreamOutputMemberContentBlockStop{ - Value: types.ContentBlockStopEvent{ContentBlockIndex: aws.Int32(0)}, - }, - &types.ConverseStreamOutputMemberMessageStop{ - Value: types.MessageStopEvent{StopReason: types.StopReasonToolUse}, - }, - } - - stream := newMockStream(events) - resp, err := parseStreamResponse(context.Background(), stream, nil) - - require.NoError(t, err) - assert.Equal(t, "tool_calls", resp.FinishReason) - require.Len(t, resp.ToolCalls, 1) - assert.Equal(t, "call_1", resp.ToolCalls[0].ID) - assert.Equal(t, "search", resp.ToolCalls[0].Name) - assert.Equal(t, map[string]any{"q": "test"}, resp.ToolCalls[0].Arguments) - require.NotNil(t, resp.ToolCalls[0].Function) - assert.Equal(t, "search", resp.ToolCalls[0].Function.Name) - assert.Equal(t, `{"q":"test"}`, resp.ToolCalls[0].Function.Arguments) -} - -func TestParseStreamResponse_TextAndToolCall(t *testing.T) { - events := []types.ConverseStreamOutput{ - &types.ConverseStreamOutputMemberContentBlockDelta{ - Value: types.ContentBlockDeltaEvent{ - ContentBlockIndex: aws.Int32(0), - Delta: &types.ContentBlockDeltaMemberText{Value: "Let me search that."}, - }, - }, - &types.ConverseStreamOutputMemberContentBlockStart{ - Value: types.ContentBlockStartEvent{ - ContentBlockIndex: aws.Int32(1), - Start: &types.ContentBlockStartMemberToolUse{ - Value: types.ToolUseBlockStart{ - ToolUseId: aws.String("call_2"), - Name: aws.String("web"), - }, - }, - }, - }, - &types.ConverseStreamOutputMemberContentBlockDelta{ - Value: types.ContentBlockDeltaEvent{ - ContentBlockIndex: aws.Int32(1), - Delta: &types.ContentBlockDeltaMemberToolUse{ - Value: types.ToolUseBlockDelta{Input: aws.String(`{"url":"https://example.com"}`)}, - }, - }, - }, - &types.ConverseStreamOutputMemberContentBlockStop{ - Value: types.ContentBlockStopEvent{ContentBlockIndex: aws.Int32(1)}, - }, - &types.ConverseStreamOutputMemberMessageStop{ - Value: types.MessageStopEvent{StopReason: types.StopReasonToolUse}, - }, - } - - var chunks []string - stream := newMockStream(events) - resp, err := parseStreamResponse(context.Background(), stream, func(accumulated string) { - chunks = append(chunks, accumulated) - }) - - require.NoError(t, err) - assert.Equal(t, "Let me search that.", resp.Content) - assert.Equal(t, "tool_calls", resp.FinishReason) - require.Len(t, resp.ToolCalls, 1) - assert.Equal(t, "web", resp.ToolCalls[0].Name) - assert.Equal(t, []string{"Let me search that."}, chunks) -} - -func TestParseStreamResponse_ContextCancelled(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - cancel() - - // Use an unbuffered channel with no events so ctx.Done() is the only ready case. - ch := make(chan types.ConverseStreamOutput) - - stream := bedrockruntime.NewConverseStreamEventStream(func(es *bedrockruntime.ConverseStreamEventStream) { - es.Reader = &mockStreamReader{ch: ch} - }) - - _, err := parseStreamResponse(ctx, stream, nil) - assert.ErrorIs(t, err, context.Canceled) -} - -func TestParseStreamResponse_InvalidToolJSON(t *testing.T) { - events := []types.ConverseStreamOutput{ - &types.ConverseStreamOutputMemberContentBlockStart{ - Value: types.ContentBlockStartEvent{ - ContentBlockIndex: aws.Int32(0), - Start: &types.ContentBlockStartMemberToolUse{ - Value: types.ToolUseBlockStart{ - ToolUseId: aws.String("call_bad"), - Name: aws.String("broken"), - }, - }, - }, - }, - &types.ConverseStreamOutputMemberContentBlockDelta{ - Value: types.ContentBlockDeltaEvent{ - ContentBlockIndex: aws.Int32(0), - Delta: &types.ContentBlockDeltaMemberToolUse{ - Value: types.ToolUseBlockDelta{Input: aws.String(`{not valid json`)}, - }, - }, - }, - &types.ConverseStreamOutputMemberContentBlockStop{ - Value: types.ContentBlockStopEvent{ContentBlockIndex: aws.Int32(0)}, - }, - &types.ConverseStreamOutputMemberMessageStop{ - Value: types.MessageStopEvent{StopReason: types.StopReasonToolUse}, - }, - } - - stream := newMockStream(events) - resp, err := parseStreamResponse(context.Background(), stream, nil) - - require.NoError(t, err) - require.Len(t, resp.ToolCalls, 1) - assert.Equal(t, map[string]any{"raw": `{not valid json`}, resp.ToolCalls[0].Arguments) - assert.JSONEq(t, `{"raw":"{not valid json"}`, resp.ToolCalls[0].Function.Arguments) -} - -func TestParseStreamResponse_DefaultFinishReason(t *testing.T) { - events := []types.ConverseStreamOutput{ - &types.ConverseStreamOutputMemberContentBlockDelta{ - Value: types.ContentBlockDeltaEvent{ - Delta: &types.ContentBlockDeltaMemberText{Value: "partial"}, - ContentBlockIndex: aws.Int32(0), - }, - }, - } - - stream := newMockStream(events) - resp, err := parseStreamResponse(context.Background(), stream, nil) - - require.NoError(t, err) - assert.Equal(t, "stop", resp.FinishReason) -} - -func TestParseStreamResponse_NilStream(t *testing.T) { - _, err := parseStreamResponse(context.Background(), nil, nil) - require.Error(t, err) - assert.Contains(t, err.Error(), "nil event stream") -} - -func TestParseStreamResponse_StopReasons(t *testing.T) { - tests := []struct { - reason types.StopReason - expected string - }{ - {types.StopReasonEndTurn, "stop"}, - {types.StopReasonMaxTokens, "length"}, - {types.StopReasonToolUse, "tool_calls"}, - {types.StopReasonStopSequence, "stop"}, - {types.StopReasonContentFiltered, "content_filter"}, - } - - for _, tt := range tests { - t.Run(string(tt.reason), func(t *testing.T) { - events := []types.ConverseStreamOutput{ - &types.ConverseStreamOutputMemberMessageStop{ - Value: types.MessageStopEvent{StopReason: tt.reason}, - }, - } - stream := newMockStream(events) - resp, err := parseStreamResponse(context.Background(), stream, nil) - require.NoError(t, err) - assert.Equal(t, tt.expected, resp.FinishReason) - }) - } -} - -func TestModelDeprecatesTemperature(t *testing.T) { - tests := []struct { - name string - model string - want bool - }{ - {"opus 4.8 bare id", "claude-opus-4-8-20260514-v1:0", true}, - {"opus 4.8 inference profile", "us.anthropic.claude-opus-4-8-20260514-v1:0", true}, - {"opus 4.8 mixed case", "US.Anthropic.Claude-Opus-4-8", true}, - {"opus 4.7 unaffected", "us.anthropic.claude-opus-4-7-20250101-v1:0", false}, - {"sonnet unaffected", "us.anthropic.claude-sonnet-4-6", false}, - {"empty", "", false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - assert.Equal(t, tt.want, modelDeprecatesTemperature(tt.model)) - }) - } -} - -func TestBuildConverseParams_DropsTemperatureForDeprecatedModel(t *testing.T) { - options := map[string]any{ - "temperature": 0.7, - "max_tokens": 1024, - } - - params := buildConverseParams(nil, nil, "us.anthropic.claude-opus-4-8-20260514-v1:0", options) - - require.NotNil(t, params.inferenceConfig, "max_tokens should still populate inference config") - assert.Nil(t, params.inferenceConfig.Temperature, "temperature must be omitted for opus 4.8") - require.NotNil(t, params.inferenceConfig.MaxTokens) - assert.Equal(t, int32(1024), *params.inferenceConfig.MaxTokens) -} - -func TestBuildConverseParams_KeepsTemperatureForSupportedModel(t *testing.T) { - options := map[string]any{ - "temperature": 0.7, - } - - params := buildConverseParams(nil, nil, "us.anthropic.claude-opus-4-7-20250101-v1:0", options) - - require.NotNil(t, params.inferenceConfig) - require.NotNil(t, params.inferenceConfig.Temperature) - assert.InDelta(t, 0.7, float64(*params.inferenceConfig.Temperature), 0.0001) -} diff --git a/pkg/providers/bedrock/provider_stub.go b/pkg/providers/bedrock/provider_stub.go deleted file mode 100644 index 894d9f2c..00000000 --- a/pkg/providers/bedrock/provider_stub.go +++ /dev/null @@ -1,73 +0,0 @@ -//go:build !bedrock - -// PicoClaw - Ultra-lightweight personal AI agent -// License: MIT -// -// Copyright (c) 2026 PicoClaw contributors - -// Package bedrock provides a stub implementation when built without the bedrock tag. -// To enable AWS Bedrock support, build with: go build -tags bedrock -package bedrock - -import ( - "context" - "fmt" - "time" - - "github.com/sipeed/picoclaw/pkg/providers/protocoltypes" -) - -type ( - LLMResponse = protocoltypes.LLMResponse - Message = protocoltypes.Message - ToolDefinition = protocoltypes.ToolDefinition -) - -// Provider is a stub that returns an error when Bedrock support is not compiled in. -type Provider struct{} - -// Option is a no-op when Bedrock is not enabled. -type Option func(*providerConfig) - -type providerConfig struct{} - -// WithRegion is a no-op when Bedrock is not enabled. -func WithRegion(region string) Option { - return func(c *providerConfig) {} -} - -// WithProfile is a no-op when Bedrock is not enabled. -func WithProfile(profile string) Option { - return func(c *providerConfig) {} -} - -// WithBaseEndpoint is a no-op when Bedrock is not enabled. -func WithBaseEndpoint(endpoint string) Option { - return func(c *providerConfig) {} -} - -// WithRequestTimeout is a no-op when Bedrock is not enabled. -func WithRequestTimeout(timeout time.Duration) Option { - return func(c *providerConfig) {} -} - -// NewProvider returns an error indicating Bedrock support is not compiled in. -func NewProvider(ctx context.Context, opts ...Option) (*Provider, error) { - return nil, fmt.Errorf("bedrock provider not available: build with -tags bedrock to enable AWS Bedrock support") -} - -// Chat returns an error - this should never be called since NewProvider fails. -func (p *Provider) Chat( - ctx context.Context, - messages []Message, - tools []ToolDefinition, - model string, - options map[string]any, -) (*LLMResponse, error) { - return nil, fmt.Errorf("bedrock provider not available: build with -tags bedrock to enable AWS Bedrock support") -} - -// GetDefaultModel returns an empty string. -func (p *Provider) GetDefaultModel() string { - return "" -} diff --git a/pkg/providers/bedrock/provider_stub_test.go b/pkg/providers/bedrock/provider_stub_test.go deleted file mode 100644 index 50ec8340..00000000 --- a/pkg/providers/bedrock/provider_stub_test.go +++ /dev/null @@ -1,35 +0,0 @@ -//go:build !bedrock - -// PicoClaw - Ultra-lightweight personal AI agent -// License: MIT -// -// Copyright (c) 2026 PicoClaw contributors - -package bedrock - -import ( - "context" - "strings" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestNewProvider_ReturnsStubError(t *testing.T) { - provider, err := NewProvider(context.Background()) - - assert.Nil(t, provider) - require.Error(t, err) - assert.True(t, strings.Contains(err.Error(), "build with -tags bedrock"), - "error should mention build tag requirement, got: %s", err.Error()) -} - -func TestNewProvider_WithOptions_ReturnsStubError(t *testing.T) { - provider, err := NewProvider(context.Background(), WithRegion("us-west-2"), WithProfile("test")) - - assert.Nil(t, provider) - require.Error(t, err) - assert.True(t, strings.Contains(err.Error(), "build with -tags bedrock"), - "error should mention build tag requirement, got: %s", err.Error()) -} diff --git a/pkg/providers/cli/claude_cli_provider.go b/pkg/providers/cli/claude_cli_provider.go deleted file mode 100644 index 62851ca3..00000000 --- a/pkg/providers/cli/claude_cli_provider.go +++ /dev/null @@ -1,205 +0,0 @@ -package cliprovider - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "os/exec" - "strings" - - "github.com/sipeed/picoclaw/pkg/isolation" -) - -// ClaudeCliProvider implements LLMProvider using the claude CLI as a subprocess. -type ClaudeCliProvider struct { - command string - workspace string -} - -// NewClaudeCliProvider creates a new Claude CLI provider. -func NewClaudeCliProvider(workspace string) *ClaudeCliProvider { - return &ClaudeCliProvider{ - command: "claude", - workspace: workspace, - } -} - -// Chat implements LLMProvider.Chat by executing the claude CLI. -func (p *ClaudeCliProvider) Chat( - ctx context.Context, messages []Message, tools []ToolDefinition, model string, options map[string]any, -) (*LLMResponse, error) { - systemPrompt := p.buildSystemPrompt(messages, tools) - prompt := p.messagesToPrompt(messages) - - args := []string{"-p", "--output-format", "json", "--dangerously-skip-permissions", "--no-chrome"} - if systemPrompt != "" { - args = append(args, "--system-prompt", systemPrompt) - } - if model != "" && model != "claude-code" { - args = append(args, "--model", model) - } - args = append(args, "-") // read from stdin - - cmd := exec.CommandContext(ctx, p.command, args...) - if p.workspace != "" { - cmd.Dir = p.workspace - } - cmd.Stdin = bytes.NewReader([]byte(prompt)) - - var stdout, stderr bytes.Buffer - cmd.Stdout = &stdout - cmd.Stderr = &stderr - - // Execute the CLI through the shared isolation wrapper so external provider - // processes honor the configured isolation policy. - if err := isolation.Run(cmd); err != nil { - stderrStr := strings.TrimSpace(stderr.String()) - stdoutStr := strings.TrimSpace(stdout.String()) - switch { - case stderrStr != "" && stdoutStr != "": - return nil, fmt.Errorf("claude cli error: %w\nstderr: %s\nstdout: %s", err, stderrStr, stdoutStr) - case stderrStr != "": - return nil, fmt.Errorf("claude cli error: %s", stderrStr) - case stdoutStr != "": - return nil, fmt.Errorf("claude cli error: %w\noutput: %s", err, stdoutStr) - default: - return nil, fmt.Errorf("claude cli error: %w", err) - } - } - - return p.parseClaudeCliResponse(stdout.String()) -} - -// GetDefaultModel returns the default model identifier. -func (p *ClaudeCliProvider) GetDefaultModel() string { - return "claude-code" -} - -// messagesToPrompt converts messages to a CLI-compatible prompt string. -func (p *ClaudeCliProvider) messagesToPrompt(messages []Message) string { - var parts []string - - for _, msg := range messages { - switch msg.Role { - case "system": - // handled via --system-prompt flag - case "user": - parts = append(parts, "User: "+msg.Content) - case "assistant": - parts = append(parts, "Assistant: "+msg.Content) - case "tool": - parts = append(parts, fmt.Sprintf("[Tool Result for %s]: %s", msg.ToolCallID, msg.Content)) - } - } - - // Simplify single user message - if len(parts) == 1 && strings.HasPrefix(parts[0], "User: ") { - return strings.TrimPrefix(parts[0], "User: ") - } - - return strings.Join(parts, "\n") -} - -// buildSystemPrompt combines system messages and tool definitions. -func (p *ClaudeCliProvider) buildSystemPrompt(messages []Message, tools []ToolDefinition) string { - var parts []string - - for _, msg := range messages { - if msg.Role == "system" { - parts = append(parts, msg.Content) - } - } - - if len(tools) > 0 { - parts = append(parts, buildCLIToolsPrompt(tools)) - } - - return strings.Join(parts, "\n\n") -} - -// parseClaudeCliResponse parses the JSON output from the claude CLI. -func (p *ClaudeCliProvider) parseClaudeCliResponse(output string) (*LLMResponse, error) { - var resp claudeCliJSONResponse - if err := json.Unmarshal([]byte(output), &resp); err != nil { - return nil, fmt.Errorf("failed to parse claude cli response: %w", err) - } - - if resp.IsError { - return nil, fmt.Errorf("claude cli returned error: %s", resp.Result) - } - - toolCalls := p.extractToolCalls(resp.Result) - - finishReason := "stop" - content := resp.Result - if len(toolCalls) > 0 { - finishReason = "tool_calls" - content = p.stripToolCallsJSON(resp.Result) - } - - var usage *UsageInfo - if resp.Usage.InputTokens > 0 || resp.Usage.OutputTokens > 0 { - usage = &UsageInfo{ - PromptTokens: resp.Usage.InputTokens + resp.Usage.CacheCreationInputTokens + resp.Usage.CacheReadInputTokens, - CompletionTokens: resp.Usage.OutputTokens, - TotalTokens: resp.Usage.InputTokens + resp.Usage.CacheCreationInputTokens + resp.Usage.CacheReadInputTokens + resp.Usage.OutputTokens, - } - } - - return &LLMResponse{ - Content: strings.TrimSpace(content), - ToolCalls: toolCalls, - FinishReason: finishReason, - Usage: usage, - }, nil -} - -// extractToolCalls delegates to the shared extractToolCallsFromText function. -func (p *ClaudeCliProvider) extractToolCalls(text string) []ToolCall { - return extractToolCallsFromText(text) -} - -// stripToolCallsJSON delegates to the shared stripToolCallsFromText function. -func (p *ClaudeCliProvider) stripToolCallsJSON(text string) string { - return stripToolCallsFromText(text) -} - -// findMatchingBrace finds the index after the closing brace matching the opening brace at pos. -func findMatchingBrace(text string, pos int) int { - depth := 0 - for i := pos; i < len(text); i++ { - if text[i] == '{' { - depth++ - } else if text[i] == '}' { - depth-- - if depth == 0 { - return i + 1 - } - } - } - return pos -} - -// claudeCliJSONResponse represents the JSON output from the claude CLI. -// Matches the real claude CLI v2.x output format. -type claudeCliJSONResponse struct { - Type string `json:"type"` - Subtype string `json:"subtype"` - IsError bool `json:"is_error"` - Result string `json:"result"` - SessionID string `json:"session_id"` - TotalCostUSD float64 `json:"total_cost_usd"` - DurationMS int `json:"duration_ms"` - DurationAPI int `json:"duration_api_ms"` - NumTurns int `json:"num_turns"` - Usage claudeCliUsageInfo `json:"usage"` -} - -// claudeCliUsageInfo represents token usage from the claude CLI response. -type claudeCliUsageInfo struct { - InputTokens int `json:"input_tokens"` - OutputTokens int `json:"output_tokens"` - CacheCreationInputTokens int `json:"cache_creation_input_tokens"` - CacheReadInputTokens int `json:"cache_read_input_tokens"` -} diff --git a/pkg/providers/cli/claude_cli_provider_integration_test.go b/pkg/providers/cli/claude_cli_provider_integration_test.go deleted file mode 100644 index cdfe7060..00000000 --- a/pkg/providers/cli/claude_cli_provider_integration_test.go +++ /dev/null @@ -1,124 +0,0 @@ -//go:build integration - -package cliprovider - -import ( - "context" - exec "os/exec" - "strings" - "testing" - "time" -) - -// TestIntegration_RealClaudeCLI tests the ClaudeCliProvider with a real claude CLI. -// Run with: go test -tags=integration ./pkg/providers/... -func TestIntegration_RealClaudeCLI(t *testing.T) { - // Check if claude CLI is available - path, err := exec.LookPath("claude") - if err != nil { - t.Skip("claude CLI not found in PATH, skipping integration test") - } - t.Logf("Using claude CLI at: %s", path) - - p := NewClaudeCliProvider(t.TempDir()) - - ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) - defer cancel() - - resp, err := p.Chat(ctx, []Message{ - {Role: "user", Content: "Respond with only the word 'pong'. Nothing else."}, - }, nil, "", nil) - if err != nil { - t.Fatalf("Chat() with real CLI error = %v", err) - } - - // Verify response structure - if resp.Content == "" { - t.Error("Content is empty") - } - if resp.FinishReason != "stop" { - t.Errorf("FinishReason = %q, want %q", resp.FinishReason, "stop") - } - if resp.Usage == nil { - t.Error("Usage should not be nil from real CLI") - } else { - if resp.Usage.PromptTokens == 0 { - t.Error("PromptTokens should be > 0") - } - if resp.Usage.CompletionTokens == 0 { - t.Error("CompletionTokens should be > 0") - } - t.Logf("Usage: prompt=%d, completion=%d, total=%d", - resp.Usage.PromptTokens, resp.Usage.CompletionTokens, resp.Usage.TotalTokens) - } - - t.Logf("Response content: %q", resp.Content) - - // Loose check - should contain "pong" somewhere (model might capitalize or add punctuation) - if !strings.Contains(strings.ToLower(resp.Content), "pong") { - t.Errorf("Content = %q, expected to contain 'pong'", resp.Content) - } -} - -func TestIntegration_RealClaudeCLI_WithSystemPrompt(t *testing.T) { - if _, err := exec.LookPath("claude"); err != nil { - t.Skip("claude CLI not found in PATH") - } - - p := NewClaudeCliProvider(t.TempDir()) - - ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) - defer cancel() - - resp, err := p.Chat(ctx, []Message{ - {Role: "system", Content: "You are a calculator. Only respond with numbers. No text."}, - {Role: "user", Content: "What is 2+2?"}, - }, nil, "", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - - t.Logf("Response: %q", resp.Content) - - if !strings.Contains(resp.Content, "4") { - t.Errorf("Content = %q, expected to contain '4'", resp.Content) - } -} - -func TestIntegration_RealClaudeCLI_ParsesRealJSON(t *testing.T) { - if _, err := exec.LookPath("claude"); err != nil { - t.Skip("claude CLI not found in PATH") - } - - // Run claude directly and verify our parser handles real output - cmd := exec.Command("claude", "-p", "--output-format", "json", - "--dangerously-skip-permissions", "--no-chrome", "--no-session-persistence", "-") - cmd.Stdin = strings.NewReader("Say hi") - cmd.Dir = t.TempDir() - - output, err := cmd.Output() - if err != nil { - t.Fatalf("claude CLI failed: %v", err) - } - - t.Logf("Raw CLI output: %s", string(output)) - - // Verify our parser can handle real output - p := NewClaudeCliProvider("") - resp, err := p.parseClaudeCliResponse(string(output)) - if err != nil { - t.Fatalf("parseClaudeCliResponse() failed on real CLI output: %v", err) - } - - if resp.Content == "" { - t.Error("parsed Content is empty") - } - if resp.FinishReason != "stop" { - t.Errorf("FinishReason = %q, want stop", resp.FinishReason) - } - if resp.Usage == nil { - t.Error("Usage should not be nil") - } - - t.Logf("Parsed: content=%q, finish=%s, usage=%+v", resp.Content, resp.FinishReason, resp.Usage) -} diff --git a/pkg/providers/cli/claude_cli_provider_test.go b/pkg/providers/cli/claude_cli_provider_test.go deleted file mode 100644 index ddef84ff..00000000 --- a/pkg/providers/cli/claude_cli_provider_test.go +++ /dev/null @@ -1,907 +0,0 @@ -package cliprovider - -import ( - "context" - "fmt" - "os" - "path/filepath" - "runtime" - "strings" - "testing" - "time" -) - -// --- Compile-time interface check --- - -var _ LLMProvider = (*ClaudeCliProvider)(nil) - -// --- Helper: create mock CLI scripts --- - -// createMockCLI creates a temporary script that simulates the claude CLI. -// Uses files for stdout/stderr to avoid shell quoting issues with JSON. -func createMockCLI(t *testing.T, stdout, stderr string, exitCode int) string { - t.Helper() - if runtime.GOOS == "windows" { - t.Skip("mock CLI scripts not supported on Windows") - } - - dir := t.TempDir() - - if stdout != "" { - if err := os.WriteFile(filepath.Join(dir, "stdout.txt"), []byte(stdout), 0o644); err != nil { - t.Fatal(err) - } - } - if stderr != "" { - if err := os.WriteFile(filepath.Join(dir, "stderr.txt"), []byte(stderr), 0o644); err != nil { - t.Fatal(err) - } - } - - var sb strings.Builder - sb.WriteString("#!/bin/sh\n") - if stderr != "" { - sb.WriteString(fmt.Sprintf("cat '%s/stderr.txt' >&2\n", dir)) - } - if stdout != "" { - sb.WriteString(fmt.Sprintf("cat '%s/stdout.txt'\n", dir)) - } - sb.WriteString(fmt.Sprintf("exit %d\n", exitCode)) - - script := filepath.Join(dir, "claude") - if err := os.WriteFile(script, []byte(sb.String()), 0o755); err != nil { - t.Fatal(err) - } - return script -} - -// createSlowMockCLI creates a script that sleeps before responding (for context cancellation tests). -func createSlowMockCLI(t *testing.T, sleepSeconds int) string { - t.Helper() - if runtime.GOOS == "windows" { - t.Skip("mock CLI scripts not supported on Windows") - } - - dir := t.TempDir() - script := filepath.Join(dir, "claude") - content := fmt.Sprintf("#!/bin/sh\nsleep %d\necho '{\"type\":\"result\",\"result\":\"late\"}'\n", sleepSeconds) - if err := os.WriteFile(script, []byte(content), 0o755); err != nil { - t.Fatal(err) - } - return script -} - -// createArgCaptureCLI creates a script that captures CLI args to a file, then outputs JSON. -func createArgCaptureCLI(t *testing.T, argsFile string) string { - t.Helper() - if runtime.GOOS == "windows" { - t.Skip("mock CLI scripts not supported on Windows") - } - - dir := t.TempDir() - script := filepath.Join(dir, "claude") - content := fmt.Sprintf(`#!/bin/sh -echo "$@" > '%s' -cat <<'EOFMOCK' -{"type":"result","result":"ok","session_id":"test"} -EOFMOCK -`, argsFile) - if err := os.WriteFile(script, []byte(content), 0o755); err != nil { - t.Fatal(err) - } - return script -} - -// --- Constructor tests --- - -func TestNewClaudeCliProvider(t *testing.T) { - p := NewClaudeCliProvider("/test/workspace") - if p == nil { - t.Fatal("NewClaudeCliProvider returned nil") - } - if p.workspace != "/test/workspace" { - t.Errorf("workspace = %q, want %q", p.workspace, "/test/workspace") - } - if p.command != "claude" { - t.Errorf("command = %q, want %q", p.command, "claude") - } -} - -func TestNewClaudeCliProvider_EmptyWorkspace(t *testing.T) { - p := NewClaudeCliProvider("") - if p.workspace != "" { - t.Errorf("workspace = %q, want empty", p.workspace) - } -} - -// --- GetDefaultModel tests --- - -func TestClaudeCliProvider_GetDefaultModel(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - if got := p.GetDefaultModel(); got != "claude-code" { - t.Errorf("GetDefaultModel() = %q, want %q", got, "claude-code") - } -} - -// --- Chat() tests --- - -func TestChat_Success(t *testing.T) { - mockJSON := `{"type":"result","subtype":"success","is_error":false,"result":"Hello from mock!","session_id":"sess_123","total_cost_usd":0.005,"duration_ms":200,"duration_api_ms":150,"num_turns":1,"usage":{"input_tokens":10,"output_tokens":5,"cache_creation_input_tokens":100,"cache_read_input_tokens":0}}` - script := createMockCLI(t, mockJSON, "", 0) - - p := NewClaudeCliProvider(t.TempDir()) - p.command = script - - resp, err := p.Chat(context.Background(), []Message{ - {Role: "user", Content: "Hello"}, - }, nil, "", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - if resp.Content != "Hello from mock!" { - t.Errorf("Content = %q, want %q", resp.Content, "Hello from mock!") - } - if resp.FinishReason != "stop" { - t.Errorf("FinishReason = %q, want %q", resp.FinishReason, "stop") - } - if len(resp.ToolCalls) != 0 { - t.Errorf("ToolCalls len = %d, want 0", len(resp.ToolCalls)) - } - if resp.Usage == nil { - t.Fatal("Usage should not be nil") - } - if resp.Usage.PromptTokens != 110 { // 10 + 100 + 0 - t.Errorf("PromptTokens = %d, want 110", resp.Usage.PromptTokens) - } - if resp.Usage.CompletionTokens != 5 { - t.Errorf("CompletionTokens = %d, want 5", resp.Usage.CompletionTokens) - } - if resp.Usage.TotalTokens != 115 { // 110 + 5 - t.Errorf("TotalTokens = %d, want 115", resp.Usage.TotalTokens) - } -} - -func TestChat_IsErrorResponse(t *testing.T) { - mockJSON := `{"type":"result","subtype":"error","is_error":true,"result":"Rate limit exceeded","session_id":"s1","total_cost_usd":0}` - script := createMockCLI(t, mockJSON, "", 0) - - p := NewClaudeCliProvider(t.TempDir()) - p.command = script - - _, err := p.Chat(context.Background(), []Message{ - {Role: "user", Content: "Hello"}, - }, nil, "", nil) - - if err == nil { - t.Fatal("Chat() expected error when is_error=true") - } - if !strings.Contains(err.Error(), "Rate limit exceeded") { - t.Errorf("error = %q, want to contain 'Rate limit exceeded'", err.Error()) - } -} - -func TestChat_WithToolCallsInResponse(t *testing.T) { - mockJSON := `{"type":"result","subtype":"success","is_error":false,"result":"Checking weather.\n{\"tool_calls\":[{\"id\":\"call_1\",\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"arguments\":\"{\\\"location\\\":\\\"NYC\\\"}\"}}]}","session_id":"s1","total_cost_usd":0.01,"usage":{"input_tokens":5,"output_tokens":20,"cache_creation_input_tokens":0,"cache_read_input_tokens":0}}` - script := createMockCLI(t, mockJSON, "", 0) - - p := NewClaudeCliProvider(t.TempDir()) - p.command = script - - resp, err := p.Chat(context.Background(), []Message{ - {Role: "user", Content: "What's the weather?"}, - }, nil, "", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - if resp.FinishReason != "tool_calls" { - t.Errorf("FinishReason = %q, want %q", resp.FinishReason, "tool_calls") - } - if len(resp.ToolCalls) != 1 { - t.Fatalf("ToolCalls len = %d, want 1", len(resp.ToolCalls)) - } - if resp.ToolCalls[0].Name != "get_weather" { - t.Errorf("ToolCalls[0].Name = %q, want %q", resp.ToolCalls[0].Name, "get_weather") - } - if resp.ToolCalls[0].Arguments["location"] != "NYC" { - t.Errorf("ToolCalls[0].Arguments[location] = %v, want NYC", resp.ToolCalls[0].Arguments["location"]) - } -} - -func TestChat_StderrError(t *testing.T) { - script := createMockCLI(t, "", "Error: rate limited", 1) - - p := NewClaudeCliProvider(t.TempDir()) - p.command = script - - _, err := p.Chat(context.Background(), []Message{ - {Role: "user", Content: "Hello"}, - }, nil, "", nil) - - if err == nil { - t.Fatal("Chat() expected error") - } - if !strings.Contains(err.Error(), "rate limited") { - t.Errorf("error = %q, want to contain 'rate limited'", err.Error()) - } -} - -func TestChat_NonZeroExitNoStderr(t *testing.T) { - script := createMockCLI(t, "", "", 1) - - p := NewClaudeCliProvider(t.TempDir()) - p.command = script - - _, err := p.Chat(context.Background(), []Message{ - {Role: "user", Content: "Hello"}, - }, nil, "", nil) - - if err == nil { - t.Fatal("Chat() expected error for non-zero exit") - } - if !strings.Contains(err.Error(), "claude cli error") { - t.Errorf("error = %q, want to contain 'claude cli error'", err.Error()) - } -} - -func TestChat_CommandNotFound(t *testing.T) { - p := NewClaudeCliProvider(t.TempDir()) - p.command = "/nonexistent/claude-binary-that-does-not-exist" - - _, err := p.Chat(context.Background(), []Message{ - {Role: "user", Content: "Hello"}, - }, nil, "", nil) - - if err == nil { - t.Fatal("Chat() expected error for missing command") - } -} - -func TestChat_InvalidResponseJSON(t *testing.T) { - script := createMockCLI(t, "not valid json at all", "", 0) - - p := NewClaudeCliProvider(t.TempDir()) - p.command = script - - _, err := p.Chat(context.Background(), []Message{ - {Role: "user", Content: "Hello"}, - }, nil, "", nil) - - if err == nil { - t.Fatal("Chat() expected error for invalid JSON") - } - if !strings.Contains(err.Error(), "failed to parse claude cli response") { - t.Errorf("error = %q, want to contain 'failed to parse claude cli response'", err.Error()) - } -} - -func TestChat_ContextCancellation(t *testing.T) { - script := createSlowMockCLI(t, 2) // sleep 2s - - p := NewClaudeCliProvider(t.TempDir()) - p.command = script - - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) - defer cancel() - - start := time.Now() - _, err := p.Chat(ctx, []Message{ - {Role: "user", Content: "Hello"}, - }, nil, "", nil) - elapsed := time.Since(start) - - if err == nil { - t.Fatal("Chat() expected error on context cancellation") - } - // Should fail well before the full 2s sleep completes - if elapsed > 3*time.Second { - t.Errorf("Chat() took %v, expected to fail faster via context cancellation", elapsed) - } -} - -func TestChat_PassesSystemPromptFlag(t *testing.T) { - argsFile := filepath.Join(t.TempDir(), "args.txt") - script := createArgCaptureCLI(t, argsFile) - - p := NewClaudeCliProvider(t.TempDir()) - p.command = script - - _, err := p.Chat(context.Background(), []Message{ - {Role: "system", Content: "Be helpful."}, - {Role: "user", Content: "Hi"}, - }, nil, "", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - - argsBytes, err := os.ReadFile(argsFile) - if err != nil { - t.Fatalf("failed to read args file: %v", err) - } - args := string(argsBytes) - if !strings.Contains(args, "--system-prompt") { - t.Errorf("CLI args missing --system-prompt, got: %s", args) - } -} - -func TestChat_PassesModelFlag(t *testing.T) { - argsFile := filepath.Join(t.TempDir(), "args.txt") - script := createArgCaptureCLI(t, argsFile) - - p := NewClaudeCliProvider(t.TempDir()) - p.command = script - - _, err := p.Chat(context.Background(), []Message{ - {Role: "user", Content: "Hi"}, - }, nil, "claude-sonnet-4.6", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - - argsBytes, _ := os.ReadFile(argsFile) - args := string(argsBytes) - if !strings.Contains(args, "--model") { - t.Errorf("CLI args missing --model, got: %s", args) - } - if !strings.Contains(args, "claude-sonnet-4.6") { - t.Errorf("CLI args missing model name, got: %s", args) - } -} - -func TestChat_SkipsModelFlagForClaudeCode(t *testing.T) { - argsFile := filepath.Join(t.TempDir(), "args.txt") - script := createArgCaptureCLI(t, argsFile) - - p := NewClaudeCliProvider(t.TempDir()) - p.command = script - - _, err := p.Chat(context.Background(), []Message{ - {Role: "user", Content: "Hi"}, - }, nil, "claude-code", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - - argsBytes, _ := os.ReadFile(argsFile) - args := string(argsBytes) - if strings.Contains(args, "--model") { - t.Errorf("CLI args should NOT contain --model for claude-code, got: %s", args) - } -} - -func TestChat_SkipsModelFlagForEmptyModel(t *testing.T) { - argsFile := filepath.Join(t.TempDir(), "args.txt") - script := createArgCaptureCLI(t, argsFile) - - p := NewClaudeCliProvider(t.TempDir()) - p.command = script - - _, err := p.Chat(context.Background(), []Message{ - {Role: "user", Content: "Hi"}, - }, nil, "", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - - argsBytes, _ := os.ReadFile(argsFile) - args := string(argsBytes) - if strings.Contains(args, "--model") { - t.Errorf("CLI args should NOT contain --model for empty model, got: %s", args) - } -} - -func TestChat_EmptyWorkspaceDoesNotSetDir(t *testing.T) { - mockJSON := `{"type":"result","result":"ok","session_id":"s"}` - script := createMockCLI(t, mockJSON, "", 0) - - p := NewClaudeCliProvider("") - p.command = script - - resp, err := p.Chat(context.Background(), []Message{ - {Role: "user", Content: "Hello"}, - }, nil, "", nil) - if err != nil { - t.Fatalf("Chat() with empty workspace error = %v", err) - } - if resp.Content != "ok" { - t.Errorf("Content = %q, want %q", resp.Content, "ok") - } -} - -// --- messagesToPrompt tests --- - -func TestMessagesToPrompt_SingleUser(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - messages := []Message{ - {Role: "user", Content: "Hello"}, - } - got := p.messagesToPrompt(messages) - want := "Hello" - if got != want { - t.Errorf("messagesToPrompt() = %q, want %q", got, want) - } -} - -func TestMessagesToPrompt_Conversation(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - messages := []Message{ - {Role: "user", Content: "Hi"}, - {Role: "assistant", Content: "Hello!"}, - {Role: "user", Content: "How are you?"}, - } - got := p.messagesToPrompt(messages) - want := "User: Hi\nAssistant: Hello!\nUser: How are you?" - if got != want { - t.Errorf("messagesToPrompt() = %q, want %q", got, want) - } -} - -func TestMessagesToPrompt_WithSystemMessage(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - messages := []Message{ - {Role: "system", Content: "You are helpful."}, - {Role: "user", Content: "Hello"}, - } - got := p.messagesToPrompt(messages) - want := "Hello" - if got != want { - t.Errorf("messagesToPrompt() = %q, want %q", got, want) - } -} - -func TestMessagesToPrompt_WithToolResults(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - messages := []Message{ - {Role: "user", Content: "What's the weather?"}, - {Role: "tool", Content: `{"temp": 72}`, ToolCallID: "call_123"}, - } - got := p.messagesToPrompt(messages) - if !strings.Contains(got, "[Tool Result for call_123]") { - t.Errorf("messagesToPrompt() missing tool result marker, got %q", got) - } - if !strings.Contains(got, `{"temp": 72}`) { - t.Errorf("messagesToPrompt() missing tool result content, got %q", got) - } -} - -func TestMessagesToPrompt_EmptyMessages(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - got := p.messagesToPrompt(nil) - if got != "" { - t.Errorf("messagesToPrompt(nil) = %q, want empty", got) - } -} - -func TestMessagesToPrompt_OnlySystemMessages(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - messages := []Message{ - {Role: "system", Content: "System 1"}, - {Role: "system", Content: "System 2"}, - } - got := p.messagesToPrompt(messages) - if got != "" { - t.Errorf("messagesToPrompt() with only system msgs = %q, want empty", got) - } -} - -// --- buildSystemPrompt tests --- - -func TestBuildSystemPrompt_NoSystemNoTools(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - messages := []Message{ - {Role: "user", Content: "Hi"}, - } - got := p.buildSystemPrompt(messages, nil) - if got != "" { - t.Errorf("buildSystemPrompt() = %q, want empty", got) - } -} - -func TestBuildSystemPrompt_SystemOnly(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - messages := []Message{ - {Role: "system", Content: "You are helpful."}, - {Role: "user", Content: "Hi"}, - } - got := p.buildSystemPrompt(messages, nil) - if got != "You are helpful." { - t.Errorf("buildSystemPrompt() = %q, want %q", got, "You are helpful.") - } -} - -func TestBuildSystemPrompt_MultipleSystemMessages(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - messages := []Message{ - {Role: "system", Content: "You are helpful."}, - {Role: "system", Content: "Be concise."}, - {Role: "user", Content: "Hi"}, - } - got := p.buildSystemPrompt(messages, nil) - if !strings.Contains(got, "You are helpful.") { - t.Error("missing first system message") - } - if !strings.Contains(got, "Be concise.") { - t.Error("missing second system message") - } - // Should be joined with double newline - want := "You are helpful.\n\nBe concise." - if got != want { - t.Errorf("buildSystemPrompt() = %q, want %q", got, want) - } -} - -func TestBuildSystemPrompt_WithTools(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - messages := []Message{ - {Role: "system", Content: "You are helpful."}, - } - tools := []ToolDefinition{ - { - Type: "function", - Function: ToolFunctionDefinition{ - Name: "get_weather", - Description: "Get weather for a location", - Parameters: map[string]any{ - "type": "object", - "properties": map[string]any{ - "location": map[string]any{"type": "string"}, - }, - }, - }, - }, - } - got := p.buildSystemPrompt(messages, tools) - if !strings.Contains(got, "You are helpful.") { - t.Error("buildSystemPrompt() missing system message") - } - if !strings.Contains(got, "get_weather") { - t.Error("buildSystemPrompt() missing tool definition") - } - if !strings.Contains(got, "Available Tools") { - t.Error("buildSystemPrompt() missing tools header") - } -} - -func TestBuildSystemPrompt_ToolsOnlyNoSystem(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - tools := []ToolDefinition{ - { - Type: "function", - Function: ToolFunctionDefinition{ - Name: "test_tool", - Description: "A test tool", - }, - }, - } - got := p.buildSystemPrompt(nil, tools) - if !strings.Contains(got, "test_tool") { - t.Error("should include tool definitions even without system messages") - } -} - -// --- buildToolsPrompt tests --- - -func TestBuildToolsPrompt_SkipsNonFunction(t *testing.T) { - tools := []ToolDefinition{ - {Type: "other", Function: ToolFunctionDefinition{Name: "skip_me"}}, - {Type: "function", Function: ToolFunctionDefinition{Name: "include_me", Description: "Included"}}, - } - got := buildCLIToolsPrompt(tools) - if strings.Contains(got, "skip_me") { - t.Error("buildToolsPrompt() should skip non-function tools") - } - if !strings.Contains(got, "include_me") { - t.Error("buildToolsPrompt() should include function tools") - } -} - -func TestBuildToolsPrompt_NoDescription(t *testing.T) { - tools := []ToolDefinition{ - {Type: "function", Function: ToolFunctionDefinition{Name: "bare_tool"}}, - } - got := buildCLIToolsPrompt(tools) - if !strings.Contains(got, "bare_tool") { - t.Error("should include tool name") - } - if strings.Contains(got, "Description:") { - t.Error("should not include Description: line when empty") - } -} - -func TestBuildToolsPrompt_NoParameters(t *testing.T) { - tools := []ToolDefinition{ - {Type: "function", Function: ToolFunctionDefinition{ - Name: "no_params_tool", - Description: "A tool with no parameters", - }}, - } - got := buildCLIToolsPrompt(tools) - if strings.Contains(got, "Parameters:") { - t.Error("should not include Parameters: section when nil") - } -} - -// --- parseClaudeCliResponse tests --- - -func TestParseClaudeCliResponse_TextOnly(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - output := `{"type":"result","subtype":"success","is_error":false,"result":"Hello, world!","session_id":"abc123","total_cost_usd":0.01,"duration_ms":500,"usage":{"input_tokens":10,"output_tokens":20,"cache_creation_input_tokens":0,"cache_read_input_tokens":0}}` - - resp, err := p.parseClaudeCliResponse(output) - if err != nil { - t.Fatalf("parseClaudeCliResponse() error = %v", err) - } - if resp.Content != "Hello, world!" { - t.Errorf("Content = %q, want %q", resp.Content, "Hello, world!") - } - if resp.FinishReason != "stop" { - t.Errorf("FinishReason = %q, want %q", resp.FinishReason, "stop") - } - if len(resp.ToolCalls) != 0 { - t.Errorf("ToolCalls = %d, want 0", len(resp.ToolCalls)) - } - if resp.Usage == nil { - t.Fatal("Usage should not be nil") - } - if resp.Usage.PromptTokens != 10 { - t.Errorf("PromptTokens = %d, want 10", resp.Usage.PromptTokens) - } - if resp.Usage.CompletionTokens != 20 { - t.Errorf("CompletionTokens = %d, want 20", resp.Usage.CompletionTokens) - } -} - -func TestParseClaudeCliResponse_EmptyResult(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - output := `{"type":"result","subtype":"success","is_error":false,"result":"","session_id":"abc"}` - - resp, err := p.parseClaudeCliResponse(output) - if err != nil { - t.Fatalf("error = %v", err) - } - if resp.Content != "" { - t.Errorf("Content = %q, want empty", resp.Content) - } - if resp.FinishReason != "stop" { - t.Errorf("FinishReason = %q, want %q", resp.FinishReason, "stop") - } -} - -func TestParseClaudeCliResponse_IsError(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - output := `{"type":"result","subtype":"error","is_error":true,"result":"Something went wrong","session_id":"abc"}` - - _, err := p.parseClaudeCliResponse(output) - if err == nil { - t.Fatal("expected error when is_error=true") - } - if !strings.Contains(err.Error(), "Something went wrong") { - t.Errorf("error = %q, want to contain 'Something went wrong'", err.Error()) - } -} - -func TestParseClaudeCliResponse_NoUsage(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - output := `{"type":"result","subtype":"success","is_error":false,"result":"hi","session_id":"s"}` - - resp, err := p.parseClaudeCliResponse(output) - if err != nil { - t.Fatalf("error = %v", err) - } - if resp.Usage != nil { - t.Errorf("Usage should be nil when no tokens, got %+v", resp.Usage) - } -} - -func TestParseClaudeCliResponse_InvalidJSON(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - _, err := p.parseClaudeCliResponse("not json") - if err == nil { - t.Fatal("expected error for invalid JSON") - } - if !strings.Contains(err.Error(), "failed to parse claude cli response") { - t.Errorf("error = %q, want to contain 'failed to parse claude cli response'", err.Error()) - } -} - -func TestParseClaudeCliResponse_WithToolCalls(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - output := `{"type":"result","subtype":"success","is_error":false,"result":"Let me check.\n{\"tool_calls\":[{\"id\":\"call_1\",\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"arguments\":\"{\\\"location\\\":\\\"Tokyo\\\"}\"}}]}","session_id":"abc123","total_cost_usd":0.01}` - - resp, err := p.parseClaudeCliResponse(output) - if err != nil { - t.Fatalf("error = %v", err) - } - if resp.FinishReason != "tool_calls" { - t.Errorf("FinishReason = %q, want %q", resp.FinishReason, "tool_calls") - } - if len(resp.ToolCalls) != 1 { - t.Fatalf("ToolCalls = %d, want 1", len(resp.ToolCalls)) - } - tc := resp.ToolCalls[0] - if tc.Name != "get_weather" { - t.Errorf("Name = %q, want %q", tc.Name, "get_weather") - } - if tc.Function == nil { - t.Fatal("Function is nil") - } - if tc.Function.Name != "get_weather" { - t.Errorf("Function.Name = %q, want %q", tc.Function.Name, "get_weather") - } - if tc.Arguments["location"] != "Tokyo" { - t.Errorf("Arguments[location] = %v, want Tokyo", tc.Arguments["location"]) - } - if strings.Contains(resp.Content, "tool_calls") { - t.Errorf("Content should not contain tool_calls JSON, got %q", resp.Content) - } - if resp.Content != "Let me check." { - t.Errorf("Content = %q, want %q", resp.Content, "Let me check.") - } -} - -func TestParseClaudeCliResponse_WhitespaceResult(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - output := `{"type":"result","subtype":"success","is_error":false,"result":" hello \n ","session_id":"s"}` - - resp, err := p.parseClaudeCliResponse(output) - if err != nil { - t.Fatalf("error = %v", err) - } - if resp.Content != "hello" { - t.Errorf("Content = %q, want %q (should be trimmed)", resp.Content, "hello") - } -} - -// --- extractToolCalls tests --- - -func TestExtractToolCalls_NoToolCalls(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - got := p.extractToolCalls("Just a regular response.") - if len(got) != 0 { - t.Errorf("extractToolCalls() = %d, want 0", len(got)) - } -} - -func TestExtractToolCalls_WithToolCalls(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - text := `Here's the result: -{"tool_calls":[{"id":"call_1","type":"function","function":{"name":"test","arguments":"{}"}}]}` - - got := p.extractToolCalls(text) - if len(got) != 1 { - t.Fatalf("extractToolCalls() = %d, want 1", len(got)) - } - if got[0].ID != "call_1" { - t.Errorf("ID = %q, want %q", got[0].ID, "call_1") - } - if got[0].Name != "test" { - t.Errorf("Name = %q, want %q", got[0].Name, "test") - } - if got[0].Type != "function" { - t.Errorf("Type = %q, want %q", got[0].Type, "function") - } -} - -func TestExtractToolCalls_InvalidJSON(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - got := p.extractToolCalls(`{"tool_calls":invalid}`) - if len(got) != 0 { - t.Errorf("extractToolCalls() with invalid JSON = %d, want 0", len(got)) - } -} - -func TestExtractToolCalls_MultipleToolCalls(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - text := `{"tool_calls":[{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"/tmp/test\"}"}},{"id":"call_2","type":"function","function":{"name":"write_file","arguments":"{\"path\":\"/tmp/out\",\"content\":\"hello\"}"}}]}` - - got := p.extractToolCalls(text) - if len(got) != 2 { - t.Fatalf("extractToolCalls() = %d, want 2", len(got)) - } - if got[0].Name != "read_file" { - t.Errorf("[0].Name = %q, want %q", got[0].Name, "read_file") - } - if got[1].Name != "write_file" { - t.Errorf("[1].Name = %q, want %q", got[1].Name, "write_file") - } - // Verify arguments were parsed - if got[0].Arguments["path"] != "/tmp/test" { - t.Errorf("[0].Arguments[path] = %v, want /tmp/test", got[0].Arguments["path"]) - } - if got[1].Arguments["content"] != "hello" { - t.Errorf("[1].Arguments[content] = %v, want hello", got[1].Arguments["content"]) - } -} - -func TestExtractToolCalls_UnmatchedBrace(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - got := p.extractToolCalls(`{"tool_calls":[{"id":"call_1"`) - if len(got) != 0 { - t.Errorf("extractToolCalls() with unmatched brace = %d, want 0", len(got)) - } -} - -func TestExtractToolCalls_ToolCallArgumentsParsing(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - text := `{"tool_calls":[{"id":"c1","type":"function","function":{"name":"fn","arguments":"{\"num\":42,\"flag\":true,\"name\":\"test\"}"}}]}` - - got := p.extractToolCalls(text) - if len(got) != 1 { - t.Fatalf("len = %d, want 1", len(got)) - } - // Verify different argument types - if got[0].Arguments["num"] != float64(42) { - t.Errorf("Arguments[num] = %v (%T), want 42", got[0].Arguments["num"], got[0].Arguments["num"]) - } - if got[0].Arguments["flag"] != true { - t.Errorf("Arguments[flag] = %v, want true", got[0].Arguments["flag"]) - } - if got[0].Arguments["name"] != "test" { - t.Errorf("Arguments[name] = %v, want test", got[0].Arguments["name"]) - } - // Verify raw arguments string is preserved in FunctionCall - if got[0].Function.Arguments == "" { - t.Error("Function.Arguments should contain raw JSON string") - } -} - -// --- stripToolCallsJSON tests --- - -func TestStripToolCallsJSON(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - text := `Let me check the weather. -{"tool_calls":[{"id":"call_1","type":"function","function":{"name":"test","arguments":"{}"}}]} -Done.` - - got := p.stripToolCallsJSON(text) - if strings.Contains(got, "tool_calls") { - t.Errorf("should remove tool_calls JSON, got %q", got) - } - if !strings.Contains(got, "Let me check the weather.") { - t.Errorf("should keep text before, got %q", got) - } - if !strings.Contains(got, "Done.") { - t.Errorf("should keep text after, got %q", got) - } -} - -func TestStripToolCallsJSON_NoToolCalls(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - text := "Just regular text." - got := p.stripToolCallsJSON(text) - if got != text { - t.Errorf("stripToolCallsJSON() = %q, want %q", got, text) - } -} - -func TestStripToolCallsJSON_OnlyToolCalls(t *testing.T) { - p := NewClaudeCliProvider("/workspace") - text := `{"tool_calls":[{"id":"c1","type":"function","function":{"name":"fn","arguments":"{}"}}]}` - got := p.stripToolCallsJSON(text) - if got != "" { - t.Errorf("stripToolCallsJSON() = %q, want empty", got) - } -} - -// --- findMatchingBrace tests --- - -func TestFindMatchingBrace(t *testing.T) { - tests := []struct { - text string - pos int - want int - }{ - {`{"a":1}`, 0, 7}, - {`{"a":{"b":2}}`, 0, 13}, - {`text {"a":1} more`, 5, 12}, - {`{unclosed`, 0, 0}, // no match returns pos - {`{}`, 0, 2}, // empty object - {`{{{}}}`, 0, 6}, // deeply nested - {`{"a":"b{c}d"}`, 0, 13}, // braces in strings (simplified matcher) - } - for _, tt := range tests { - got := findMatchingBrace(tt.text, tt.pos) - if got != tt.want { - t.Errorf("findMatchingBrace(%q, %d) = %d, want %d", tt.text, tt.pos, got, tt.want) - } - } -} diff --git a/pkg/providers/cli/codex_cli_credentials.go b/pkg/providers/cli/codex_cli_credentials.go deleted file mode 100644 index 95e28909..00000000 --- a/pkg/providers/cli/codex_cli_credentials.go +++ /dev/null @@ -1,86 +0,0 @@ -package cliprovider - -import ( - "encoding/json" - "fmt" - "os" - "path/filepath" - "time" -) - -// CodexHomeEnvVar is the environment variable that overrides the Codex CLI -// home directory when resolving the codex auth.json credentials file. -// Default: ~/.codex -const CodexHomeEnvVar = "CODEX_HOME" - -// CodexCliAuth represents the ~/.codex/auth.json file structure. -type CodexCliAuth struct { - Tokens struct { - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` - AccountID string `json:"account_id"` - } `json:"tokens"` -} - -// ReadCodexCliCredentials reads OAuth tokens from the Codex CLI's auth.json file. -// Expiry is estimated as file modification time + 1 hour (same approach as moltbot). -func ReadCodexCliCredentials() (accessToken, accountID string, expiresAt time.Time, err error) { - authPath, err := resolveCodexAuthPath() - if err != nil { - return "", "", time.Time{}, err - } - - data, err := os.ReadFile(authPath) - if err != nil { - return "", "", time.Time{}, fmt.Errorf("reading %s: %w", authPath, err) - } - - var auth CodexCliAuth - if err = json.Unmarshal(data, &auth); err != nil { - return "", "", time.Time{}, fmt.Errorf("parsing %s: %w", authPath, err) - } - - if auth.Tokens.AccessToken == "" { - return "", "", time.Time{}, fmt.Errorf("no access_token in %s", authPath) - } - - stat, err := os.Stat(authPath) - if err != nil { - expiresAt = time.Now().Add(time.Hour) - } else { - expiresAt = stat.ModTime().Add(time.Hour) - } - - return auth.Tokens.AccessToken, auth.Tokens.AccountID, expiresAt, nil -} - -// CreateCodexCliTokenSource creates a token source that reads from ~/.codex/auth.json. -// This allows the existing CodexProvider to reuse Codex CLI credentials. -func CreateCodexCliTokenSource() func() (string, string, error) { - return func() (string, string, error) { - token, accountID, expiresAt, err := ReadCodexCliCredentials() - if err != nil { - return "", "", fmt.Errorf("reading codex cli credentials: %w", err) - } - - if time.Now().After(expiresAt) { - return "", "", fmt.Errorf( - "codex cli credentials expired (auth.json last modified > 1h ago). Run: codex login", - ) - } - - return token, accountID, nil - } -} - -func resolveCodexAuthPath() (string, error) { - codexHome := os.Getenv(CodexHomeEnvVar) - if codexHome == "" { - home, err := os.UserHomeDir() - if err != nil { - return "", fmt.Errorf("getting home dir: %w", err) - } - codexHome = filepath.Join(home, ".codex") - } - return filepath.Join(codexHome, "auth.json"), nil -} diff --git a/pkg/providers/cli/codex_cli_credentials_test.go b/pkg/providers/cli/codex_cli_credentials_test.go deleted file mode 100644 index abad6e24..00000000 --- a/pkg/providers/cli/codex_cli_credentials_test.go +++ /dev/null @@ -1,185 +0,0 @@ -package cliprovider - -import ( - "os" - "path/filepath" - "testing" - "time" -) - -func TestReadCodexCliCredentials_Valid(t *testing.T) { - tmpDir := t.TempDir() - authPath := filepath.Join(tmpDir, "auth.json") - - authJSON := `{ - "tokens": { - "access_token": "test-access-token", - "refresh_token": "test-refresh-token", - "account_id": "org-test123" - } - }` - if err := os.WriteFile(authPath, []byte(authJSON), 0o600); err != nil { - t.Fatal(err) - } - - t.Setenv("CODEX_HOME", tmpDir) - - token, accountID, expiresAt, err := ReadCodexCliCredentials() - if err != nil { - t.Fatalf("ReadCodexCliCredentials() error: %v", err) - } - if token != "test-access-token" { - t.Errorf("token = %q, want %q", token, "test-access-token") - } - if accountID != "org-test123" { - t.Errorf("accountID = %q, want %q", accountID, "org-test123") - } - // Expiry should be within ~1 hour from now (file was just written) - if expiresAt.Before(time.Now()) { - t.Errorf("expiresAt = %v, should be in the future", expiresAt) - } - if expiresAt.After(time.Now().Add(2 * time.Hour)) { - t.Errorf("expiresAt = %v, should be within ~1 hour", expiresAt) - } -} - -// readCodexCliCredentialsErr calls ReadCodexCliCredentials and returns only the -// error, for tests that only need to assert on failure. -func readCodexCliCredentialsErr() error { - _, _, _, err := ReadCodexCliCredentials() //nolint:dogsled - return err -} - -func TestReadCodexCliCredentials_MissingFile(t *testing.T) { - tmpDir := t.TempDir() - t.Setenv("CODEX_HOME", tmpDir) - - if err := readCodexCliCredentialsErr(); err == nil { - t.Fatal("expected error for missing auth.json") - } -} - -func TestReadCodexCliCredentials_EmptyToken(t *testing.T) { - tmpDir := t.TempDir() - authPath := filepath.Join(tmpDir, "auth.json") - - authJSON := `{"tokens": {"access_token": "", "refresh_token": "r", "account_id": "a"}}` - if err := os.WriteFile(authPath, []byte(authJSON), 0o600); err != nil { - t.Fatal(err) - } - - t.Setenv("CODEX_HOME", tmpDir) - - if err := readCodexCliCredentialsErr(); err == nil { - t.Fatal("expected error for empty access_token") - } -} - -func TestReadCodexCliCredentials_InvalidJSON(t *testing.T) { - tmpDir := t.TempDir() - authPath := filepath.Join(tmpDir, "auth.json") - - if err := os.WriteFile(authPath, []byte("not json"), 0o600); err != nil { - t.Fatal(err) - } - - t.Setenv("CODEX_HOME", tmpDir) - - if err := readCodexCliCredentialsErr(); err == nil { - t.Fatal("expected error for invalid JSON") - } -} - -func TestReadCodexCliCredentials_NoAccountID(t *testing.T) { - tmpDir := t.TempDir() - authPath := filepath.Join(tmpDir, "auth.json") - - authJSON := `{"tokens": {"access_token": "tok123", "refresh_token": "ref456"}}` - if err := os.WriteFile(authPath, []byte(authJSON), 0o600); err != nil { - t.Fatal(err) - } - - t.Setenv("CODEX_HOME", tmpDir) - - token, accountID, _, err := ReadCodexCliCredentials() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if token != "tok123" { - t.Errorf("token = %q, want %q", token, "tok123") - } - if accountID != "" { - t.Errorf("accountID = %q, want empty", accountID) - } -} - -func TestReadCodexCliCredentials_CodexHomeEnv(t *testing.T) { - tmpDir := t.TempDir() - customDir := filepath.Join(tmpDir, "custom-codex") - if err := os.MkdirAll(customDir, 0o755); err != nil { - t.Fatal(err) - } - - authJSON := `{"tokens": {"access_token": "custom-token", "refresh_token": "r"}}` - if err := os.WriteFile(filepath.Join(customDir, "auth.json"), []byte(authJSON), 0o600); err != nil { - t.Fatal(err) - } - - t.Setenv("CODEX_HOME", customDir) - - token, _, _, err := ReadCodexCliCredentials() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if token != "custom-token" { - t.Errorf("token = %q, want %q", token, "custom-token") - } -} - -func TestCreateCodexCliTokenSource_Valid(t *testing.T) { - tmpDir := t.TempDir() - authPath := filepath.Join(tmpDir, "auth.json") - - authJSON := `{"tokens": {"access_token": "fresh-token", "refresh_token": "r", "account_id": "acc"}}` - if err := os.WriteFile(authPath, []byte(authJSON), 0o600); err != nil { - t.Fatal(err) - } - - t.Setenv("CODEX_HOME", tmpDir) - - source := CreateCodexCliTokenSource() - token, accountID, err := source() - if err != nil { - t.Fatalf("token source error: %v", err) - } - if token != "fresh-token" { - t.Errorf("token = %q, want %q", token, "fresh-token") - } - if accountID != "acc" { - t.Errorf("accountID = %q, want %q", accountID, "acc") - } -} - -func TestCreateCodexCliTokenSource_Expired(t *testing.T) { - tmpDir := t.TempDir() - authPath := filepath.Join(tmpDir, "auth.json") - - authJSON := `{"tokens": {"access_token": "old-token", "refresh_token": "r"}}` - if err := os.WriteFile(authPath, []byte(authJSON), 0o600); err != nil { - t.Fatal(err) - } - - // Set file modification time to 2 hours ago - oldTime := time.Now().Add(-2 * time.Hour) - if err := os.Chtimes(authPath, oldTime, oldTime); err != nil { - t.Fatal(err) - } - - t.Setenv("CODEX_HOME", tmpDir) - - source := CreateCodexCliTokenSource() - _, _, err := source() - if err == nil { - t.Fatal("expected error for expired credentials") - } -} diff --git a/pkg/providers/cli/codex_cli_provider.go b/pkg/providers/cli/codex_cli_provider.go deleted file mode 100644 index d1a23c32..00000000 --- a/pkg/providers/cli/codex_cli_provider.go +++ /dev/null @@ -1,227 +0,0 @@ -package cliprovider - -import ( - "bufio" - "bytes" - "context" - "encoding/json" - "fmt" - "os/exec" - "strings" - - "github.com/sipeed/picoclaw/pkg/isolation" -) - -// CodexCliProvider implements LLMProvider by wrapping the codex CLI as a subprocess. -type CodexCliProvider struct { - command string - workspace string -} - -// NewCodexCliProvider creates a new Codex CLI provider. -func NewCodexCliProvider(workspace string) *CodexCliProvider { - return &CodexCliProvider{ - command: "codex", - workspace: workspace, - } -} - -// Chat implements LLMProvider.Chat by executing the codex CLI in non-interactive mode. -func (p *CodexCliProvider) Chat( - ctx context.Context, messages []Message, tools []ToolDefinition, model string, options map[string]any, -) (*LLMResponse, error) { - if p.command == "" { - return nil, fmt.Errorf("codex command not configured") - } - - prompt := p.buildPrompt(messages, tools) - - args := []string{ - "exec", - "--json", - "--dangerously-bypass-approvals-and-sandbox", - "--skip-git-repo-check", - "--color", "never", - } - if model != "" && model != "codex-cli" { - args = append(args, "-m", model) - } - if p.workspace != "" { - args = append(args, "-C", p.workspace) - } - args = append(args, "-") // read prompt from stdin - - cmd := exec.CommandContext(ctx, p.command, args...) - cmd.Stdin = bytes.NewReader([]byte(prompt)) - - var stdout, stderr bytes.Buffer - cmd.Stdout = &stdout - cmd.Stderr = &stderr - - // Execute the CLI through the shared isolation wrapper so external provider - // processes honor the configured isolation policy. - err := isolation.Run(cmd) - - // Parse JSONL from stdout even if exit code is non-zero, - // because codex writes diagnostic noise to stderr (e.g. rollout errors) - // but still produces valid JSONL output. - if stdoutStr := stdout.String(); stdoutStr != "" { - resp, parseErr := p.parseJSONLEvents(stdoutStr) - if parseErr == nil && resp != nil && (resp.Content != "" || len(resp.ToolCalls) > 0) { - return resp, nil - } - } - - if err != nil { - if ctx.Err() == context.Canceled { - return nil, ctx.Err() - } - if stderrStr := stderr.String(); stderrStr != "" { - return nil, fmt.Errorf("codex cli error: %s", stderrStr) - } - return nil, fmt.Errorf("codex cli error: %w", err) - } - - return p.parseJSONLEvents(stdout.String()) -} - -// GetDefaultModel returns the default model identifier. -func (p *CodexCliProvider) GetDefaultModel() string { - return "codex-cli" -} - -// buildPrompt converts messages to a prompt string for the Codex CLI. -// System messages are prepended as instructions since Codex CLI has no --system-prompt flag. -func (p *CodexCliProvider) buildPrompt(messages []Message, tools []ToolDefinition) string { - var systemParts []string - var conversationParts []string - - for _, msg := range messages { - switch msg.Role { - case "system": - systemParts = append(systemParts, msg.Content) - case "user": - conversationParts = append(conversationParts, msg.Content) - case "assistant": - conversationParts = append(conversationParts, "Assistant: "+msg.Content) - case "tool": - conversationParts = append(conversationParts, - fmt.Sprintf("[Tool Result for %s]: %s", msg.ToolCallID, msg.Content)) - } - } - - var sb strings.Builder - - if len(systemParts) > 0 { - sb.WriteString("## System Instructions\n\n") - sb.WriteString(strings.Join(systemParts, "\n\n")) - sb.WriteString("\n\n## Task\n\n") - } - - if len(tools) > 0 { - sb.WriteString(buildCLIToolsPrompt(tools)) - sb.WriteString("\n\n") - } - - // Simplify single user message (no prefix) - if len(conversationParts) == 1 && len(systemParts) == 0 && len(tools) == 0 { - return conversationParts[0] - } - - sb.WriteString(strings.Join(conversationParts, "\n")) - return sb.String() -} - -// codexEvent represents a single JSONL event from `codex exec --json`. -type codexEvent struct { - Type string `json:"type"` - ThreadID string `json:"thread_id,omitempty"` - Message string `json:"message,omitempty"` - Item *codexEventItem `json:"item,omitempty"` - Usage *codexUsage `json:"usage,omitempty"` - Error *codexEventErr `json:"error,omitempty"` -} - -type codexEventItem struct { - ID string `json:"id"` - Type string `json:"type"` - Text string `json:"text,omitempty"` - Command string `json:"command,omitempty"` - Status string `json:"status,omitempty"` - ExitCode *int `json:"exit_code,omitempty"` - Output string `json:"output,omitempty"` -} - -type codexUsage struct { - InputTokens int `json:"input_tokens"` - CachedInputTokens int `json:"cached_input_tokens"` - OutputTokens int `json:"output_tokens"` -} - -type codexEventErr struct { - Message string `json:"message"` -} - -// parseJSONLEvents processes the JSONL output from codex exec --json. -func (p *CodexCliProvider) parseJSONLEvents(output string) (*LLMResponse, error) { - var contentParts []string - var usage *UsageInfo - var lastError string - - scanner := bufio.NewScanner(strings.NewReader(output)) - for scanner.Scan() { - line := strings.TrimSpace(scanner.Text()) - if line == "" { - continue - } - - var event codexEvent - if err := json.Unmarshal([]byte(line), &event); err != nil { - continue // skip malformed lines - } - - switch event.Type { - case "item.completed": - if event.Item != nil && event.Item.Type == "agent_message" && event.Item.Text != "" { - contentParts = append(contentParts, event.Item.Text) - } - case "turn.completed": - if event.Usage != nil { - promptTokens := event.Usage.InputTokens + event.Usage.CachedInputTokens - usage = &UsageInfo{ - PromptTokens: promptTokens, - CompletionTokens: event.Usage.OutputTokens, - TotalTokens: promptTokens + event.Usage.OutputTokens, - } - } - case "error": - lastError = event.Message - case "turn.failed": - if event.Error != nil { - lastError = event.Error.Message - } - } - } - - if lastError != "" && len(contentParts) == 0 { - return nil, fmt.Errorf("codex cli: %s", lastError) - } - - content := strings.Join(contentParts, "\n") - - // Extract tool calls from response text (same pattern as ClaudeCliProvider) - toolCalls := extractToolCallsFromText(content) - - finishReason := "stop" - if len(toolCalls) > 0 { - finishReason = "tool_calls" - content = stripToolCallsFromText(content) - } - - return &LLMResponse{ - Content: strings.TrimSpace(content), - ToolCalls: toolCalls, - FinishReason: finishReason, - Usage: usage, - }, nil -} diff --git a/pkg/providers/cli/codex_cli_provider_integration_test.go b/pkg/providers/cli/codex_cli_provider_integration_test.go deleted file mode 100644 index af18b8c6..00000000 --- a/pkg/providers/cli/codex_cli_provider_integration_test.go +++ /dev/null @@ -1,117 +0,0 @@ -//go:build integration - -package cliprovider - -import ( - "context" - exec "os/exec" - "strings" - "testing" - "time" -) - -// TestIntegration_RealCodexCLI tests the CodexCliProvider with a real codex CLI. -// Run with: go test -tags=integration ./pkg/providers/... -func TestIntegration_RealCodexCLI(t *testing.T) { - path, err := exec.LookPath("codex") - if err != nil { - t.Skip("codex CLI not found in PATH, skipping integration test") - } - t.Logf("Using codex CLI at: %s", path) - - p := NewCodexCliProvider(t.TempDir()) - - ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) - defer cancel() - - resp, err := p.Chat(ctx, []Message{ - {Role: "user", Content: "Respond with only the word 'pong'. Nothing else."}, - }, nil, "", nil) - if err != nil { - t.Fatalf("Chat() with real CLI error = %v", err) - } - - if resp.Content == "" { - t.Error("Content is empty") - } - if resp.FinishReason != "stop" { - t.Errorf("FinishReason = %q, want %q", resp.FinishReason, "stop") - } - if resp.Usage != nil { - t.Logf("Usage: prompt=%d, completion=%d, total=%d", - resp.Usage.PromptTokens, resp.Usage.CompletionTokens, resp.Usage.TotalTokens) - } - - t.Logf("Response content: %q", resp.Content) - - if !strings.Contains(strings.ToLower(resp.Content), "pong") { - t.Errorf("Content = %q, expected to contain 'pong'", resp.Content) - } -} - -func TestIntegration_RealCodexCLI_WithSystemPrompt(t *testing.T) { - if _, err := exec.LookPath("codex"); err != nil { - t.Skip("codex CLI not found in PATH") - } - - p := NewCodexCliProvider(t.TempDir()) - - ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) - defer cancel() - - resp, err := p.Chat(ctx, []Message{ - {Role: "system", Content: "You are a calculator. Only respond with numbers. No text."}, - {Role: "user", Content: "What is 2+2?"}, - }, nil, "", nil) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - - t.Logf("Response: %q", resp.Content) - - if !strings.Contains(resp.Content, "4") { - t.Errorf("Content = %q, expected to contain '4'", resp.Content) - } -} - -func TestIntegration_RealCodexCLI_ParsesRealJSONL(t *testing.T) { - if _, err := exec.LookPath("codex"); err != nil { - t.Skip("codex CLI not found in PATH") - } - - // Run codex directly and verify our parser handles real output - cmd := exec.Command("codex", "exec", - "--json", - "--dangerously-bypass-approvals-and-sandbox", - "--skip-git-repo-check", - "--color", "never", - "-C", t.TempDir(), - "-") - cmd.Stdin = strings.NewReader("Say hi") - - output, err := cmd.Output() - if err != nil { - // codex may write diagnostic noise to stderr but still produce valid output - if len(output) == 0 { - t.Fatalf("codex CLI failed: %v", err) - } - } - - t.Logf("Raw CLI output (first 500 chars): %s", string(output[:min(len(output), 500)])) - - // Verify our parser can handle real output - p := NewCodexCliProvider("") - resp, err := p.parseJSONLEvents(string(output)) - if err != nil { - t.Fatalf("parseJSONLEvents() failed on real CLI output: %v", err) - } - - if resp.Content == "" { - t.Error("parsed Content is empty") - } - if resp.FinishReason != "stop" { - t.Errorf("FinishReason = %q, want stop", resp.FinishReason) - } - - t.Logf("Parsed: content=%q, finish=%s, usage=%+v", resp.Content, resp.FinishReason, resp.Usage) -} diff --git a/pkg/providers/cli/codex_cli_provider_test.go b/pkg/providers/cli/codex_cli_provider_test.go deleted file mode 100644 index 8338fbc9..00000000 --- a/pkg/providers/cli/codex_cli_provider_test.go +++ /dev/null @@ -1,595 +0,0 @@ -package cliprovider - -import ( - "context" - "encoding/json" - "fmt" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "testing" -) - -// --- JSONL Event Parsing Tests --- - -func TestParseJSONLEvents_AgentMessage(t *testing.T) { - p := &CodexCliProvider{} - events := `{"type":"thread.started","thread_id":"abc-123"} -{"type":"turn.started"} -{"type":"item.completed","item":{"id":"item_1","type":"agent_message","text":"Hello from Codex!"}} -{"type":"turn.completed","usage":{"input_tokens":100,"cached_input_tokens":50,"output_tokens":20}}` - - resp, err := p.parseJSONLEvents(events) - if err != nil { - t.Fatalf("parseJSONLEvents() error: %v", err) - } - if resp.Content != "Hello from Codex!" { - t.Errorf("Content = %q, want %q", resp.Content, "Hello from Codex!") - } - if resp.FinishReason != "stop" { - t.Errorf("FinishReason = %q, want %q", resp.FinishReason, "stop") - } - if resp.Usage == nil { - t.Fatal("Usage should not be nil") - } - if resp.Usage.PromptTokens != 150 { - t.Errorf("PromptTokens = %d, want 150", resp.Usage.PromptTokens) - } - if resp.Usage.CompletionTokens != 20 { - t.Errorf("CompletionTokens = %d, want 20", resp.Usage.CompletionTokens) - } - if resp.Usage.TotalTokens != 170 { - t.Errorf("TotalTokens = %d, want 170", resp.Usage.TotalTokens) - } - if len(resp.ToolCalls) != 0 { - t.Errorf("ToolCalls should be empty, got %d", len(resp.ToolCalls)) - } -} - -func TestParseJSONLEvents_ToolCallExtraction(t *testing.T) { - p := &CodexCliProvider{} - toolCallText := `Let me read that file. -{"tool_calls":[{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"/tmp/test.txt\"}"}}]}` - // Build valid JSONL by marshaling the event - item := codexEvent{ - Type: "item.completed", - Item: &codexEventItem{ID: "item_1", Type: "agent_message", Text: toolCallText}, - } - itemJSON, _ := json.Marshal(item) - usageEvt := `{"type":"turn.completed","usage":{"input_tokens":50,"cached_input_tokens":0,"output_tokens":20}}` - events := `{"type":"turn.started"}` + "\n" + string(itemJSON) + "\n" + usageEvt - - resp, err := p.parseJSONLEvents(events) - if err != nil { - t.Fatalf("parseJSONLEvents() error: %v", err) - } - if resp.FinishReason != "tool_calls" { - t.Errorf("FinishReason = %q, want %q", resp.FinishReason, "tool_calls") - } - if len(resp.ToolCalls) != 1 { - t.Fatalf("ToolCalls count = %d, want 1", len(resp.ToolCalls)) - } - if resp.ToolCalls[0].Name != "read_file" { - t.Errorf("ToolCalls[0].Name = %q, want %q", resp.ToolCalls[0].Name, "read_file") - } - if resp.ToolCalls[0].ID != "call_1" { - t.Errorf("ToolCalls[0].ID = %q, want %q", resp.ToolCalls[0].ID, "call_1") - } - if resp.ToolCalls[0].Function.Arguments != `{"path":"/tmp/test.txt"}` { - t.Errorf("ToolCalls[0].Function.Arguments = %q", resp.ToolCalls[0].Function.Arguments) - } - // Content should have the tool call JSON stripped - if strings.Contains(resp.Content, "tool_calls") { - t.Errorf("Content should not contain tool_calls JSON, got: %q", resp.Content) - } -} - -func TestParseJSONLEvents_MultipleToolCalls(t *testing.T) { - p := &CodexCliProvider{} - toolCallText := `{"tool_calls":[{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"a.txt\"}"}},{"id":"call_2","type":"function","function":{"name":"write_file","arguments":"{\"path\":\"b.txt\",\"content\":\"hello\"}"}}]}` - item := codexEvent{ - Type: "item.completed", - Item: &codexEventItem{ID: "item_1", Type: "agent_message", Text: toolCallText}, - } - itemJSON, _ := json.Marshal(item) - events := `{"type":"turn.started"}` + "\n" + string(itemJSON) + "\n" + `{"type":"turn.completed"}` - - resp, err := p.parseJSONLEvents(events) - if err != nil { - t.Fatalf("parseJSONLEvents() error: %v", err) - } - if len(resp.ToolCalls) != 2 { - t.Fatalf("ToolCalls count = %d, want 2", len(resp.ToolCalls)) - } - if resp.ToolCalls[0].Name != "read_file" { - t.Errorf("ToolCalls[0].Name = %q, want %q", resp.ToolCalls[0].Name, "read_file") - } - if resp.ToolCalls[1].Name != "write_file" { - t.Errorf("ToolCalls[1].Name = %q, want %q", resp.ToolCalls[1].Name, "write_file") - } - if resp.FinishReason != "tool_calls" { - t.Errorf("FinishReason = %q, want %q", resp.FinishReason, "tool_calls") - } -} - -func TestParseJSONLEvents_MultipleMessages(t *testing.T) { - p := &CodexCliProvider{} - events := `{"type":"turn.started"} -{"type":"item.completed","item":{"id":"item_1","type":"agent_message","text":"First part."}} -{"type":"item.completed","item":{"id":"item_2","type":"command_execution","command":"ls","status":"completed"}} -{"type":"item.completed","item":{"id":"item_3","type":"agent_message","text":"Second part."}} -{"type":"turn.completed"}` - - resp, err := p.parseJSONLEvents(events) - if err != nil { - t.Fatalf("parseJSONLEvents() error: %v", err) - } - if resp.Content != "First part.\nSecond part." { - t.Errorf("Content = %q, want %q", resp.Content, "First part.\nSecond part.") - } -} - -func TestParseJSONLEvents_ErrorEvent(t *testing.T) { - p := &CodexCliProvider{} - events := `{"type":"thread.started","thread_id":"abc"} -{"type":"turn.started"} -{"type":"error","message":"token expired"} -{"type":"turn.failed","error":{"message":"token expired"}}` - - _, err := p.parseJSONLEvents(events) - if err == nil { - t.Fatal("expected error") - } - if !strings.Contains(err.Error(), "token expired") { - t.Errorf("error = %q, want to contain 'token expired'", err.Error()) - } -} - -func TestParseJSONLEvents_TurnFailed(t *testing.T) { - p := &CodexCliProvider{} - events := `{"type":"turn.started"} -{"type":"turn.failed","error":{"message":"rate limit exceeded"}}` - - _, err := p.parseJSONLEvents(events) - if err == nil { - t.Fatal("expected error") - } - if !strings.Contains(err.Error(), "rate limit exceeded") { - t.Errorf("error = %q, want to contain 'rate limit exceeded'", err.Error()) - } -} - -func TestParseJSONLEvents_ErrorWithContent(t *testing.T) { - p := &CodexCliProvider{} - // If there's an error but also content, return the content (partial success) - events := `{"type":"turn.started"} -{"type":"item.completed","item":{"id":"item_1","type":"agent_message","text":"Partial result."}} -{"type":"error","message":"connection reset"} -{"type":"turn.failed","error":{"message":"connection reset"}}` - - resp, err := p.parseJSONLEvents(events) - if err != nil { - t.Fatalf("should not error when content exists: %v", err) - } - if resp.Content != "Partial result." { - t.Errorf("Content = %q, want %q", resp.Content, "Partial result.") - } -} - -func TestParseJSONLEvents_EmptyOutput(t *testing.T) { - p := &CodexCliProvider{} - resp, err := p.parseJSONLEvents("") - if err != nil { - t.Fatalf("empty output should not error: %v", err) - } - if resp.Content != "" { - t.Errorf("Content = %q, want empty", resp.Content) - } -} - -func TestParseJSONLEvents_MalformedLines(t *testing.T) { - p := &CodexCliProvider{} - events := `not json at all -{"type":"item.completed","item":{"id":"item_1","type":"agent_message","text":"Good line."}} -another bad line -{"type":"turn.completed","usage":{"input_tokens":10,"output_tokens":5}}` - - resp, err := p.parseJSONLEvents(events) - if err != nil { - t.Fatalf("should skip malformed lines: %v", err) - } - if resp.Content != "Good line." { - t.Errorf("Content = %q, want %q", resp.Content, "Good line.") - } - if resp.Usage == nil || resp.Usage.TotalTokens != 15 { - t.Errorf("Usage.TotalTokens = %v, want 15", resp.Usage) - } -} - -func TestParseJSONLEvents_CommandExecution(t *testing.T) { - p := &CodexCliProvider{} - events := `{"type":"turn.started"} -{"type":"item.started","item":{"id":"item_1","type":"command_execution","command":"bash -lc ls","status":"in_progress"}} -{"type":"item.completed","item":{"id":"item_1","type":"command_execution","command":"bash -lc ls","status":"completed","exit_code":0,"output":"file1.go\nfile2.go"}} -{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"Found 2 files."}} -{"type":"turn.completed"}` - - resp, err := p.parseJSONLEvents(events) - if err != nil { - t.Fatalf("parseJSONLEvents() error: %v", err) - } - // command_execution items should be skipped; only agent_message text is returned - if resp.Content != "Found 2 files." { - t.Errorf("Content = %q, want %q", resp.Content, "Found 2 files.") - } -} - -func TestParseJSONLEvents_NoUsage(t *testing.T) { - p := &CodexCliProvider{} - events := `{"type":"turn.started"} -{"type":"item.completed","item":{"id":"item_1","type":"agent_message","text":"No usage info."}} -{"type":"turn.completed"}` - - resp, err := p.parseJSONLEvents(events) - if err != nil { - t.Fatalf("parseJSONLEvents() error: %v", err) - } - if resp.Usage != nil { - t.Errorf("Usage should be nil when turn.completed has no usage, got %+v", resp.Usage) - } -} - -// --- Prompt Building Tests --- - -func TestBuildPrompt_SystemAsInstructions(t *testing.T) { - p := &CodexCliProvider{} - messages := []Message{ - {Role: "system", Content: "You are helpful."}, - {Role: "user", Content: "Hi there"}, - } - - prompt := p.buildPrompt(messages, nil) - - if !strings.Contains(prompt, "## System Instructions") { - t.Error("prompt should contain '## System Instructions'") - } - if !strings.Contains(prompt, "You are helpful.") { - t.Error("prompt should contain system content") - } - if !strings.Contains(prompt, "## Task") { - t.Error("prompt should contain '## Task'") - } - if !strings.Contains(prompt, "Hi there") { - t.Error("prompt should contain user message") - } -} - -func TestBuildPrompt_NoSystem(t *testing.T) { - p := &CodexCliProvider{} - messages := []Message{ - {Role: "user", Content: "Just a question"}, - } - - prompt := p.buildPrompt(messages, nil) - - if strings.Contains(prompt, "## System Instructions") { - t.Error("prompt should not contain system instructions header") - } - if prompt != "Just a question" { - t.Errorf("prompt = %q, want %q", prompt, "Just a question") - } -} - -func TestBuildPrompt_WithTools(t *testing.T) { - p := &CodexCliProvider{} - messages := []Message{ - {Role: "user", Content: "Get weather"}, - } - tools := []ToolDefinition{ - { - Type: "function", - Function: ToolFunctionDefinition{ - Name: "get_weather", - Description: "Get current weather", - Parameters: map[string]any{ - "type": "object", - "properties": map[string]any{ - "city": map[string]any{"type": "string"}, - }, - }, - }, - }, - } - - prompt := p.buildPrompt(messages, tools) - - if !strings.Contains(prompt, "## Available Tools") { - t.Error("prompt should contain tools section") - } - if !strings.Contains(prompt, "get_weather") { - t.Error("prompt should contain tool name") - } - if !strings.Contains(prompt, "Get current weather") { - t.Error("prompt should contain tool description") - } -} - -func TestBuildPrompt_MultipleMessages(t *testing.T) { - p := &CodexCliProvider{} - messages := []Message{ - {Role: "user", Content: "Hello"}, - {Role: "assistant", Content: "Hi! How can I help?"}, - {Role: "user", Content: "Tell me about Go"}, - } - - prompt := p.buildPrompt(messages, nil) - - if !strings.Contains(prompt, "Hello") { - t.Error("prompt should contain first user message") - } - if !strings.Contains(prompt, "Assistant: Hi! How can I help?") { - t.Error("prompt should contain assistant message with prefix") - } - if !strings.Contains(prompt, "Tell me about Go") { - t.Error("prompt should contain second user message") - } -} - -func TestBuildPrompt_ToolResults(t *testing.T) { - p := &CodexCliProvider{} - messages := []Message{ - {Role: "user", Content: "Weather?"}, - {Role: "tool", Content: `{"temp": 72}`, ToolCallID: "call_1"}, - } - - prompt := p.buildPrompt(messages, nil) - - if !strings.Contains(prompt, "[Tool Result for call_1]") { - t.Error("prompt should contain tool result") - } - if !strings.Contains(prompt, `{"temp": 72}`) { - t.Error("prompt should contain tool result content") - } -} - -func TestBuildPrompt_SystemAndTools(t *testing.T) { - p := &CodexCliProvider{} - messages := []Message{ - {Role: "system", Content: "Be concise."}, - {Role: "user", Content: "Do something"}, - } - tools := []ToolDefinition{ - { - Type: "function", - Function: ToolFunctionDefinition{ - Name: "my_tool", - Description: "A tool", - }, - }, - } - - prompt := p.buildPrompt(messages, tools) - - // System instructions should come first - sysIdx := strings.Index(prompt, "## System Instructions") - toolIdx := strings.Index(prompt, "## Available Tools") - taskIdx := strings.Index(prompt, "## Task") - - if sysIdx == -1 || toolIdx == -1 || taskIdx == -1 { - t.Fatal("prompt should contain all sections") - } - if sysIdx >= taskIdx { - t.Error("system instructions should come before task") - } - if taskIdx >= toolIdx { - t.Error("task section should come before tools in the output") - } -} - -// --- CLI Argument Tests --- - -func TestCodexCliProvider_GetDefaultModel(t *testing.T) { - p := NewCodexCliProvider("") - if got := p.GetDefaultModel(); got != "codex-cli" { - t.Errorf("GetDefaultModel() = %q, want %q", got, "codex-cli") - } -} - -// --- Mock CLI Integration Test --- - -func createMockCodexCLI(t *testing.T, events []string) string { - t.Helper() - if runtime.GOOS == "windows" { - t.Skip("mock CLI scripts not supported on Windows") - } - tmpDir := t.TempDir() - scriptPath := filepath.Join(tmpDir, "codex") - - var sb strings.Builder - sb.WriteString("#!/bin/bash\n") - for _, event := range events { - sb.WriteString(fmt.Sprintf("echo '%s'\n", event)) - } - - if err := os.WriteFile(scriptPath, []byte(sb.String()), 0o755); err != nil { - t.Fatal(err) - } - return scriptPath -} - -func TestCodexCliProvider_MockCLI_Success(t *testing.T) { - scriptPath := createMockCodexCLI(t, []string{ - `{"type":"thread.started","thread_id":"test-123"}`, - `{"type":"turn.started"}`, - `{"type":"item.completed","item":{"id":"item_1","type":"agent_message","text":"Mock response from Codex CLI"}}`, - `{"type":"turn.completed","usage":{"input_tokens":50,"cached_input_tokens":10,"output_tokens":15}}`, - }) - - p := &CodexCliProvider{ - command: scriptPath, - workspace: "", - } - - messages := []Message{{Role: "user", Content: "Hello"}} - resp, err := p.Chat(context.Background(), messages, nil, "", nil) - if err != nil { - t.Fatalf("Chat() error: %v", err) - } - if resp.Content != "Mock response from Codex CLI" { - t.Errorf("Content = %q, want %q", resp.Content, "Mock response from Codex CLI") - } - if resp.Usage == nil { - t.Fatal("Usage should not be nil") - } - if resp.Usage.PromptTokens != 60 { - t.Errorf("PromptTokens = %d, want 60", resp.Usage.PromptTokens) - } - if resp.Usage.CompletionTokens != 15 { - t.Errorf("CompletionTokens = %d, want 15", resp.Usage.CompletionTokens) - } -} - -func TestCodexCliProvider_MockCLI_Error(t *testing.T) { - scriptPath := createMockCodexCLI(t, []string{ - `{"type":"thread.started","thread_id":"test-err"}`, - `{"type":"turn.started"}`, - `{"type":"error","message":"auth token expired"}`, - `{"type":"turn.failed","error":{"message":"auth token expired"}}`, - }) - - p := &CodexCliProvider{ - command: scriptPath, - workspace: "", - } - - messages := []Message{{Role: "user", Content: "Hello"}} - _, err := p.Chat(context.Background(), messages, nil, "", nil) - if err == nil { - t.Fatal("expected error") - } - if !strings.Contains(err.Error(), "auth token expired") { - t.Errorf("error = %q, want to contain 'auth token expired'", err.Error()) - } -} - -func TestCodexCliProvider_MockCLI_WithModel(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("mock CLI scripts not supported on Windows") - } - // Mock script that captures args to verify model flag is passed - tmpDir := t.TempDir() - scriptPath := filepath.Join(tmpDir, "codex") - script := `#!/bin/bash -# Write args to a file for verification -echo "$@" > "` + filepath.Join(tmpDir, "args.txt") + `" -echo '{"type":"item.completed","item":{"id":"1","type":"agent_message","text":"ok"}}' -echo '{"type":"turn.completed"}'` - - if err := os.WriteFile(scriptPath, []byte(script), 0o755); err != nil { - t.Fatal(err) - } - - p := &CodexCliProvider{ - command: scriptPath, - workspace: "/tmp/test-workspace", - } - - messages := []Message{{Role: "user", Content: "test"}} - _, err := p.Chat(context.Background(), messages, nil, "gpt-5.3-codex", nil) - if err != nil { - t.Fatalf("Chat() error: %v", err) - } - - // Verify the args - argsData, err := os.ReadFile(filepath.Join(tmpDir, "args.txt")) - if err != nil { - t.Fatalf("reading args: %v", err) - } - args := string(argsData) - - if !strings.Contains(args, "-m gpt-5.3-codex") { - t.Errorf("args should contain model flag, got: %s", args) - } - if !strings.Contains(args, "-C /tmp/test-workspace") { - t.Errorf("args should contain workspace flag, got: %s", args) - } - if !strings.Contains(args, "--json") { - t.Errorf("args should contain --json, got: %s", args) - } - if !strings.Contains(args, "--dangerously-bypass-approvals-and-sandbox") { - t.Errorf("args should contain bypass flag, got: %s", args) - } -} - -func TestCodexCliProvider_MockCLI_ContextCancel(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("mock CLI scripts not supported on Windows") - } - // Script that sleeps forever - tmpDir := t.TempDir() - scriptPath := filepath.Join(tmpDir, "codex") - script := "#!/bin/bash\nsleep 60" - - if err := os.WriteFile(scriptPath, []byte(script), 0o755); err != nil { - t.Fatal(err) - } - - p := &CodexCliProvider{ - command: scriptPath, - workspace: "", - } - - ctx, cancel := context.WithCancel(context.Background()) - cancel() // cancel immediately - - messages := []Message{{Role: "user", Content: "test"}} - _, err := p.Chat(ctx, messages, nil, "", nil) - if err == nil { - t.Fatal("expected error on canceled context") - } -} - -func TestCodexCliProvider_EmptyCommand(t *testing.T) { - p := &CodexCliProvider{command: ""} - - messages := []Message{{Role: "user", Content: "test"}} - _, err := p.Chat(context.Background(), messages, nil, "", nil) - if err == nil { - t.Fatal("expected error for empty command") - } -} - -// --- Integration Test (requires real codex CLI with valid auth) --- - -func TestCodexCliProvider_Integration(t *testing.T) { - if os.Getenv("PICOCLAW_INTEGRATION_TESTS") == "" { - t.Skip("skipping integration test (set PICOCLAW_INTEGRATION_TESTS=1 to enable)") - } - - // Verify codex is available - codexPath, err := exec.LookPath("codex") - if err != nil { - t.Skip("codex CLI not found in PATH") - } - - p := &CodexCliProvider{ - command: codexPath, - workspace: "", - } - - messages := []Message{ - {Role: "user", Content: "Respond with just the word 'hello' and nothing else."}, - } - - resp, err := p.Chat(context.Background(), messages, nil, "", nil) - if err != nil { - t.Fatalf("Chat() error: %v", err) - } - - lower := strings.ToLower(strings.TrimSpace(resp.Content)) - if !strings.Contains(lower, "hello") { - t.Errorf("Content = %q, expected to contain 'hello'", resp.Content) - } -} diff --git a/pkg/providers/cli/github_copilot_provider.go b/pkg/providers/cli/github_copilot_provider.go deleted file mode 100644 index d1d8a3e2..00000000 --- a/pkg/providers/cli/github_copilot_provider.go +++ /dev/null @@ -1,128 +0,0 @@ -package cliprovider - -import ( - "context" - "encoding/json" - "fmt" - "sync" - - copilot "github.com/github/copilot-sdk/go" -) - -type GitHubCopilotProvider struct { - uri string - connectMode string // "stdio" or "grpc" - - client *copilot.Client - session *copilot.Session - - mu sync.Mutex -} - -func NewGitHubCopilotProvider(uri string, connectMode string, model string) (*GitHubCopilotProvider, error) { - if connectMode == "" { - connectMode = "grpc" - } - - switch connectMode { - case "stdio": - // TODO: Implement stdio mode for GitHub Copilot provider - // See https://github.com/github/copilot-sdk/blob/main/docs/getting-started.md for details - return nil, fmt.Errorf("stdio mode not implemented for GitHub Copilot provider; please use 'grpc' mode instead") - case "grpc": - client := copilot.NewClient(&copilot.ClientOptions{ - CLIUrl: uri, - }) - if err := client.Start(context.Background()); err != nil { - return nil, fmt.Errorf( - "can't connect to Github Copilot: %w; `https://github.com/github/copilot-sdk/blob/main/docs/getting-started.md#connecting-to-an-external-cli-server` for details", - err, - ) - } - - session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{ - Model: model, - OnPermissionRequest: copilot.PermissionHandler.ApproveAll, - Hooks: &copilot.SessionHooks{}, - }) - if err != nil { - client.Stop() - return nil, fmt.Errorf("create session failed: %w", err) - } - - return &GitHubCopilotProvider{ - uri: uri, - connectMode: connectMode, - client: client, - session: session, - }, nil - default: - return nil, fmt.Errorf("unknown connect mode: %s", connectMode) - } -} - -func (p *GitHubCopilotProvider) Close() { - p.mu.Lock() - defer p.mu.Unlock() - if p.client != nil { - p.client.Stop() - p.client = nil - p.session = nil - } -} - -func (p *GitHubCopilotProvider) Chat( - ctx context.Context, - messages []Message, - tools []ToolDefinition, - model string, - options map[string]any, -) (*LLMResponse, error) { - type tempMessage struct { - Role string `json:"role"` - Content string `json:"content"` - } - out := make([]tempMessage, 0, len(messages)) - for _, msg := range messages { - out = append(out, tempMessage{ - Role: msg.Role, - Content: msg.Content, - }) - } - - fullcontent, err := json.Marshal(out) - if err != nil { - return nil, fmt.Errorf("marshal messages: %w", err) - } - p.mu.Lock() - session := p.session - p.mu.Unlock() - - if session == nil { - return nil, fmt.Errorf("provider closed") - } - - resp, err := session.SendAndWait(ctx, copilot.MessageOptions{ - Prompt: string(fullcontent), - }) - if err != nil { - return nil, fmt.Errorf("failed to send message to copilot: %w", err) - } - - if resp == nil { - return nil, fmt.Errorf("empty response from copilot") - } - if resp.Data.Content == nil { - return nil, fmt.Errorf("no content in copilot response") - } - content := *resp.Data.Content - - return &LLMResponse{ - FinishReason: "stop", - Content: content, - }, nil -} - -func (p *GitHubCopilotProvider) GetDefaultModel() string { - return "gpt-4.1" -} diff --git a/pkg/providers/cli/tool_call_extract.go b/pkg/providers/cli/tool_call_extract.go deleted file mode 100644 index f1d1886e..00000000 --- a/pkg/providers/cli/tool_call_extract.go +++ /dev/null @@ -1,72 +0,0 @@ -package cliprovider - -import ( - "encoding/json" - "strings" -) - -// extractToolCallsFromText parses tool call JSON from response text. -// Both ClaudeCliProvider and CodexCliProvider use this to extract -// tool calls that the model outputs in its response text. -func extractToolCallsFromText(text string) []ToolCall { - start := strings.Index(text, `{"tool_calls"`) - if start == -1 { - return nil - } - - end := findMatchingBrace(text, start) - if end == start { - return nil - } - - jsonStr := text[start:end] - - var wrapper struct { - ToolCalls []struct { - ID string `json:"id"` - Type string `json:"type"` - Function struct { - Name string `json:"name"` - Arguments string `json:"arguments"` - } `json:"function"` - } `json:"tool_calls"` - } - - if err := json.Unmarshal([]byte(jsonStr), &wrapper); err != nil { - return nil - } - - var result []ToolCall - for _, tc := range wrapper.ToolCalls { - var args map[string]any - json.Unmarshal([]byte(tc.Function.Arguments), &args) - - result = append(result, ToolCall{ - ID: tc.ID, - Type: tc.Type, - Name: tc.Function.Name, - Arguments: args, - Function: &FunctionCall{ - Name: tc.Function.Name, - Arguments: tc.Function.Arguments, - }, - }) - } - - return result -} - -// stripToolCallsFromText removes tool call JSON from response text. -func stripToolCallsFromText(text string) string { - start := strings.Index(text, `{"tool_calls"`) - if start == -1 { - return text - } - - end := findMatchingBrace(text, start) - if end == start { - return text - } - - return strings.TrimSpace(text[:start] + text[end:]) -} diff --git a/pkg/providers/cli/types.go b/pkg/providers/cli/types.go deleted file mode 100644 index f15897ad..00000000 --- a/pkg/providers/cli/types.go +++ /dev/null @@ -1,28 +0,0 @@ -package cliprovider - -import ( - "context" - - "github.com/sipeed/picoclaw/pkg/providers/protocoltypes" -) - -type ( - ToolCall = protocoltypes.ToolCall - FunctionCall = protocoltypes.FunctionCall - LLMResponse = protocoltypes.LLMResponse - UsageInfo = protocoltypes.UsageInfo - Message = protocoltypes.Message - ToolDefinition = protocoltypes.ToolDefinition - ToolFunctionDefinition = protocoltypes.ToolFunctionDefinition -) - -type LLMProvider interface { - Chat( - ctx context.Context, - messages []Message, - tools []ToolDefinition, - model string, - options map[string]any, - ) (*LLMResponse, error) - GetDefaultModel() string -} diff --git a/pkg/providers/cli_facade.go b/pkg/providers/cli_facade.go deleted file mode 100644 index 6580291b..00000000 --- a/pkg/providers/cli_facade.go +++ /dev/null @@ -1,40 +0,0 @@ -package providers - -import ( - "time" - - cliprovider "github.com/sipeed/picoclaw/pkg/providers/cli" -) - -type ( - ClaudeCliProvider = cliprovider.ClaudeCliProvider - CodexCliProvider = cliprovider.CodexCliProvider - CodexCliAuth = cliprovider.CodexCliAuth - GitHubCopilotProvider = cliprovider.GitHubCopilotProvider -) - -const CodexHomeEnvVar = cliprovider.CodexHomeEnvVar - -func NewClaudeCliProvider(workspace string) *ClaudeCliProvider { - return cliprovider.NewClaudeCliProvider(workspace) -} - -func NewCodexCliProvider(workspace string) *CodexCliProvider { - return cliprovider.NewCodexCliProvider(workspace) -} - -func NewGitHubCopilotProvider(uri string, connectMode string, model string) (*GitHubCopilotProvider, error) { - return cliprovider.NewGitHubCopilotProvider(uri, connectMode, model) -} - -func ReadCodexCliCredentials() (accessToken, accountID string, expiresAt time.Time, err error) { - return cliprovider.ReadCodexCliCredentials() -} - -func CreateCodexCliTokenSource() func() (string, string, error) { - return cliprovider.CreateCodexCliTokenSource() -} - -func NormalizeToolCall(tc ToolCall) ToolCall { - return cliprovider.NormalizeToolCall(tc) -} diff --git a/pkg/providers/cli_factory_test.go b/pkg/providers/cli_factory_test.go deleted file mode 100644 index b00eafb9..00000000 --- a/pkg/providers/cli_factory_test.go +++ /dev/null @@ -1,99 +0,0 @@ -package providers - -import ( - "reflect" - "testing" - - "github.com/sipeed/picoclaw/pkg/config" -) - -func testProviderWorkspace(t *testing.T, provider any) string { - t.Helper() - - v := reflect.ValueOf(provider) - if v.Kind() != reflect.Ptr || v.IsNil() { - t.Fatalf("provider = %T, want non-nil pointer", provider) - } - - field := v.Elem().FieldByName("workspace") - if !field.IsValid() || field.Kind() != reflect.String { - t.Fatalf("provider %T does not expose workspace field", provider) - } - - return field.String() -} - -func TestCreateProvider_ClaudeCli(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - {ModelName: "claude-sonnet-4.6", Model: "claude-cli/claude-sonnet-4.6", Workspace: "/test/ws"}, - } - cfg.Agents.Defaults.ModelName = "claude-sonnet-4.6" - - provider, _, err := CreateProvider(cfg) - if err != nil { - t.Fatalf("CreateProvider(claude-cli) error = %v", err) - } - - cliProvider, ok := provider.(*ClaudeCliProvider) - if !ok { - t.Fatalf("CreateProvider(claude-cli) returned %T, want *ClaudeCliProvider", provider) - } - if got := testProviderWorkspace(t, cliProvider); got != "/test/ws" { - t.Errorf("workspace = %q, want %q", got, "/test/ws") - } -} - -func TestCreateProvider_ClaudeCode(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - {ModelName: "claude-code", Model: "claude-cli/claude-code"}, - } - cfg.Agents.Defaults.ModelName = "claude-code" - - provider, _, err := CreateProvider(cfg) - if err != nil { - t.Fatalf("CreateProvider(claude-code) error = %v", err) - } - if _, ok := provider.(*ClaudeCliProvider); !ok { - t.Fatalf("CreateProvider(claude-code) returned %T, want *ClaudeCliProvider", provider) - } -} - -func TestCreateProvider_ClaudeCodec(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - {ModelName: "claudecode", Model: "claude-cli/claudecode"}, - } - cfg.Agents.Defaults.ModelName = "claudecode" - - provider, _, err := CreateProvider(cfg) - if err != nil { - t.Fatalf("CreateProvider(claudecode) error = %v", err) - } - if _, ok := provider.(*ClaudeCliProvider); !ok { - t.Fatalf("CreateProvider(claudecode) returned %T, want *ClaudeCliProvider", provider) - } -} - -func TestCreateProvider_ClaudeCliDefaultWorkspace(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - {ModelName: "claude-cli", Model: "claude-cli/claude-sonnet"}, - } - cfg.Agents.Defaults.ModelName = "claude-cli" - cfg.Agents.Defaults.Workspace = "" - - provider, _, err := CreateProvider(cfg) - if err != nil { - t.Fatalf("CreateProvider error = %v", err) - } - - cliProvider, ok := provider.(*ClaudeCliProvider) - if !ok { - t.Fatalf("returned %T, want *ClaudeCliProvider", provider) - } - if got := testProviderWorkspace(t, cliProvider); got != "." { - t.Errorf("workspace = %q, want %q (default)", got, ".") - } -} diff --git a/pkg/providers/common/google_common.go b/pkg/providers/common/google_common.go deleted file mode 100644 index 954c0c80..00000000 --- a/pkg/providers/common/google_common.go +++ /dev/null @@ -1,70 +0,0 @@ -package common - -import ( - "encoding/json" - "strings" - - "github.com/sipeed/picoclaw/pkg/providers/protocoltypes" -) - -// NormalizeStoredToolCall extracts the tool name, arguments, and thought signature -// from a stored ToolCall. It handles both the top-level fields and the nested -// Function struct used by different API formats. -func NormalizeStoredToolCall(tc protocoltypes.ToolCall) (string, map[string]any, string) { - name := tc.Name - args := tc.Arguments - thoughtSignature := "" - - if name == "" && tc.Function != nil { - name = tc.Function.Name - thoughtSignature = tc.Function.ThoughtSignature - } else if tc.Function != nil { - thoughtSignature = tc.Function.ThoughtSignature - } - - if args == nil { - args = map[string]any{} - } - - if len(args) == 0 && tc.Function != nil && tc.Function.Arguments != "" { - var parsed map[string]any - if err := json.Unmarshal([]byte(tc.Function.Arguments), &parsed); err == nil && parsed != nil { - args = parsed - } - } - - return name, args, thoughtSignature -} - -// ResolveToolResponseName returns the tool name for a given tool call ID. -// It first checks the provided name map, then falls back to inferring the -// name from the call ID format. -func ResolveToolResponseName(toolCallID string, toolCallNames map[string]string) string { - if toolCallID == "" { - return "" - } - - if name, ok := toolCallNames[toolCallID]; ok && name != "" { - return name - } - - return InferToolNameFromCallID(toolCallID) -} - -// InferToolNameFromCallID extracts a tool name from a call ID in the format -// "call__". Returns the original ID if it doesn't match. -func InferToolNameFromCallID(toolCallID string) string { - if !strings.HasPrefix(toolCallID, "call_") { - return toolCallID - } - - rest := strings.TrimPrefix(toolCallID, "call_") - if idx := strings.LastIndex(rest, "_"); idx > 0 { - candidate := rest[:idx] - if candidate != "" { - return candidate - } - } - - return toolCallID -} diff --git a/pkg/providers/common/google_common_test.go b/pkg/providers/common/google_common_test.go deleted file mode 100644 index cc013dcd..00000000 --- a/pkg/providers/common/google_common_test.go +++ /dev/null @@ -1,146 +0,0 @@ -package common - -import ( - "testing" - - "github.com/sipeed/picoclaw/pkg/providers/protocoltypes" -) - -func TestNormalizeStoredToolCall_TopLevelFields(t *testing.T) { - tc := protocoltypes.ToolCall{ - Name: "search", - Arguments: map[string]any{"q": "hello"}, - } - name, args, sig := NormalizeStoredToolCall(tc) - if name != "search" { - t.Errorf("name = %q, want %q", name, "search") - } - if args["q"] != "hello" { - t.Errorf("args[q] = %v, want %q", args["q"], "hello") - } - if sig != "" { - t.Errorf("thoughtSignature = %q, want empty", sig) - } -} - -func TestNormalizeStoredToolCall_FallsBackToFunction(t *testing.T) { - tc := protocoltypes.ToolCall{ - Function: &protocoltypes.FunctionCall{ - Name: "read_file", - Arguments: `{"path":"/tmp"}`, - ThoughtSignature: "sig123", - }, - } - name, args, sig := NormalizeStoredToolCall(tc) - if name != "read_file" { - t.Errorf("name = %q, want %q", name, "read_file") - } - if args["path"] != "/tmp" { - t.Errorf("args[path] = %v, want %q", args["path"], "/tmp") - } - if sig != "sig123" { - t.Errorf("thoughtSignature = %q, want %q", sig, "sig123") - } -} - -func TestNormalizeStoredToolCall_TopLevelNameWithFunctionSig(t *testing.T) { - tc := protocoltypes.ToolCall{ - Name: "search", - Arguments: map[string]any{"q": "hi"}, - Function: &protocoltypes.FunctionCall{ - ThoughtSignature: "thought1", - }, - } - name, _, sig := NormalizeStoredToolCall(tc) - if name != "search" { - t.Errorf("name = %q, want %q", name, "search") - } - if sig != "thought1" { - t.Errorf("thoughtSignature = %q, want %q", sig, "thought1") - } -} - -func TestNormalizeStoredToolCall_NilArgs(t *testing.T) { - tc := protocoltypes.ToolCall{Name: "test"} - _, args, _ := NormalizeStoredToolCall(tc) - if args == nil { - t.Fatal("args should not be nil") - } - if len(args) != 0 { - t.Errorf("args should be empty, got %v", args) - } -} - -func TestNormalizeStoredToolCall_EmptyArgsParseFromFunction(t *testing.T) { - tc := protocoltypes.ToolCall{ - Name: "tool", - Arguments: map[string]any{}, - Function: &protocoltypes.FunctionCall{ - Arguments: `{"key":"val"}`, - }, - } - _, args, _ := NormalizeStoredToolCall(tc) - if args["key"] != "val" { - t.Errorf("args[key] = %v, want %q", args["key"], "val") - } -} - -func TestNormalizeStoredToolCall_InvalidFunctionJSON(t *testing.T) { - tc := protocoltypes.ToolCall{ - Name: "tool", - Function: &protocoltypes.FunctionCall{ - Arguments: `not-json`, - }, - } - _, args, _ := NormalizeStoredToolCall(tc) - if len(args) != 0 { - t.Errorf("args should be empty for invalid JSON, got %v", args) - } -} - -func TestResolveToolResponseName_FromMap(t *testing.T) { - names := map[string]string{"call_1": "search"} - got := ResolveToolResponseName("call_1", names) - if got != "search" { - t.Errorf("got %q, want %q", got, "search") - } -} - -func TestResolveToolResponseName_EmptyID(t *testing.T) { - got := ResolveToolResponseName("", map[string]string{"x": "y"}) - if got != "" { - t.Errorf("got %q, want empty", got) - } -} - -func TestResolveToolResponseName_FallsBackToInfer(t *testing.T) { - got := ResolveToolResponseName("call_search_docs_999", map[string]string{}) - if got != "search_docs" { - t.Errorf("got %q, want %q", got, "search_docs") - } -} - -func TestInferToolNameFromCallID(t *testing.T) { - tests := []struct { - name string - id string - want string - }{ - {"standard format", "call_search_docs_999", "search_docs"}, - {"single name", "call_read_123", "read"}, - {"no call prefix", "some_id", "some_id"}, - {"call prefix no underscore suffix", "call_onlyname", "call_onlyname"}, - {"empty string", "", ""}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := InferToolNameFromCallID(tt.id) - if got != tt.want { - t.Errorf( - "InferToolNameFromCallID(%q) = %q, want %q", - tt.id, got, tt.want, - ) - } - }) - } -} diff --git a/pkg/providers/facade_compat_test.go b/pkg/providers/facade_compat_test.go deleted file mode 100644 index 024c36ab..00000000 --- a/pkg/providers/facade_compat_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package providers - -import ( - "testing" - - cliprovider "github.com/sipeed/picoclaw/pkg/providers/cli" - oauthprovider "github.com/sipeed/picoclaw/pkg/providers/oauth" -) - -func TestNormalizeToolCallFacadeMatchesCLIProvider(t *testing.T) { - input := ToolCall{ - ID: "call_1", - Type: "function", - Function: &FunctionCall{ - Name: "read_file", - Arguments: `{"path":"README.md"}`, - }, - } - - got := NormalizeToolCall(input) - want := cliprovider.NormalizeToolCall(input) - - if got.Name != want.Name { - t.Fatalf("Name = %q, want %q", got.Name, want.Name) - } - if got.Function == nil || want.Function == nil { - t.Fatalf("Function should not be nil: got=%v want=%v", got.Function, want.Function) - } - if got.Function.Name != want.Function.Name { - t.Fatalf("Function.Name = %q, want %q", got.Function.Name, want.Function.Name) - } - if got.Function.Arguments != want.Function.Arguments { - t.Fatalf("Function.Arguments = %q, want %q", got.Function.Arguments, want.Function.Arguments) - } - if got.Arguments["path"] != want.Arguments["path"] { - t.Fatalf("Arguments[path] = %v, want %v", got.Arguments["path"], want.Arguments["path"]) - } -} - -func TestAntigravityFacadeSignaturesRemainAvailable(t *testing.T) { - var _ func(string) (string, error) = FetchAntigravityProjectID - var _ func(string, string) ([]AntigravityModelInfo, error) = FetchAntigravityModels - var _ AntigravityModelInfo = oauthprovider.AntigravityModelInfo{} -} diff --git a/pkg/providers/factory_provider.go b/pkg/providers/factory_provider.go index c0e4a6e1..e5771448 100644 --- a/pkg/providers/factory_provider.go +++ b/pkg/providers/factory_provider.go @@ -6,16 +6,11 @@ package providers import ( - "context" "fmt" "strings" - "time" "github.com/sipeed/picoclaw/pkg/config" - anthropicmessages "github.com/sipeed/picoclaw/pkg/providers/anthropic_messages" - "github.com/sipeed/picoclaw/pkg/providers/azure" - "github.com/sipeed/picoclaw/pkg/providers/bedrock" - "github.com/sipeed/picoclaw/pkg/providers/common" + anthropicprovider "github.com/sipeed/picoclaw/pkg/providers/anthropic" ) // createClaudeAuthProvider creates a Claude provider using OAuth credentials from auth store. @@ -53,8 +48,8 @@ func createCodexAuthProvider() (LLMProvider, error) { // The returned protocol is normalized to the provider's canonical spelling. // Examples: // - Model "openai/gpt-4o" -> ("openai", "gpt-4o") -// - Model "nvidia/z-ai/glm-5.1" -> ("nvidia", "z-ai/glm-5.1") -// - Provider "nvidia", Model "z-ai/glm-5.1" -> ("nvidia", "z-ai/glm-5.1") +// - Model "openai/vendor/model" -> ("openai", "vendor/model") +// - Provider "openai", Model "vendor/model" -> ("openai", "vendor/model") // - Provider "openai", Model "openai/gpt-4o" -> ("openai", "openai/gpt-4o") // - Model "gpt-4o" -> ("openai", "gpt-4o") func ExtractProtocol(cfg *config.ModelConfig) (protocol, modelID string) { @@ -84,8 +79,7 @@ func ResolveAPIBase(cfg *config.ModelConfig) string { // CreateProviderFromConfig creates a provider based on the ModelConfig. // It uses ExtractProtocol to determine which provider to create. -// Supported protocol families include OpenAI-compatible prefixes (e.g., openai, openrouter, groq), -// Azure OpenAI, Amazon Bedrock, Anthropic (including messages), and various CLI/compatibility shims. +// Supported protocols are OpenAI (Responses and Chat Completions) and Anthropic Messages. // See the switch on protocol in this function for the authoritative list. // Returns the provider, the effective model ID from ExtractProtocol, and any error. func CreateProviderFromConfig(cfg *config.ModelConfig) (LLMProvider, string, error) { @@ -136,142 +130,6 @@ func CreateProviderFromConfig(cfg *config.ModelConfig) (LLMProvider, string, err provider.SetProviderName(protocol) return finalizeProviderFromConfig(provider, modelID, cfg) - case "azure": - // Azure OpenAI uses deployment-based URLs. Auth is Bearer token via api_key - // when set; otherwise falls back to Entra ID (DefaultAzureCredential). - if cfg.APIBase == "" { - return nil, "", fmt.Errorf( - "api_base is required for azure protocol (e.g., https://your-resource.openai.azure.com)", - ) - } - if cfg.APIKey() != "" { - return finalizeProviderFromConfig(azure.NewProviderWithTimeout( - cfg.APIKey(), - cfg.APIBase, - cfg.Proxy, - userAgent, - cfg.RequestTimeout, - ), modelID, cfg) - } - provider, err := azure.NewProviderWithIdentityAndTimeout( - cfg.APIBase, - cfg.Proxy, - userAgent, - cfg.RequestTimeout, - ) - if err != nil { - return nil, "", err - } - return finalizeProviderFromConfig(provider, modelID, cfg) - - case "bedrock": - // AWS Bedrock uses AWS SDK credentials (env vars, profiles, IAM roles, etc.) - // api_base can be: - // - A full endpoint URL: https://bedrock-runtime.us-east-1.amazonaws.com - // - A region name: us-east-1 (AWS SDK resolves endpoint automatically) - var opts []bedrock.Option - if cfg.APIBase != "" { - if !strings.Contains(cfg.APIBase, "://") { - // Treat as region: let AWS SDK resolve the correct endpoint - // (supports all AWS partitions: aws, aws-cn, aws-us-gov, etc.) - opts = append(opts, bedrock.WithRegion(cfg.APIBase)) - } else { - // Full endpoint URL provided (for custom endpoints or testing) - opts = append(opts, bedrock.WithBaseEndpoint(cfg.APIBase)) - } - } - // Use a separate timeout for AWS config loading (credential resolution can block) - initTimeout := 30 * time.Second - if cfg.RequestTimeout > 0 { - reqTimeout := time.Duration(cfg.RequestTimeout) * time.Second - // Set request timeout for API calls - opts = append(opts, bedrock.WithRequestTimeout(reqTimeout)) - // Ensure init timeout is at least as large as request timeout - if reqTimeout > initTimeout { - initTimeout = reqTimeout - } - } - ctx, cancel := context.WithTimeout(context.Background(), initTimeout) - defer cancel() - // Note: AWS_PROFILE env var is automatically used by AWS SDK - provider, err := bedrock.NewProvider(ctx, opts...) - if err != nil { - return nil, "", fmt.Errorf("creating bedrock provider: %w", err) - } - return finalizeProviderFromConfig(provider, modelID, cfg) - - case "litellm", "lmstudio", "gpt4free", "openrouter", "groq", "zhipu", "nvidia", "venice", - "nearai", "ollama", "moonshot", "shengsuanyun", "siliconflow", "deepseek", "cerebras", - "vivgrid", "volcengine", "vllm", "qwen-portal", "qwen-intl", "qwen-us", "mistral", - "avian", "longcat", "modelscope", "novita", "alibaba-coding", "zai", "mimo": - // All other OpenAI-compatible HTTP providers - if cfg.APIKey() == "" && cfg.APIBase == "" && !isEmptyAPIKeyAllowed(protocol) { - return nil, "", fmt.Errorf("api_key or api_base is required for HTTP-based protocol %q", protocol) - } - apiBase := cfg.APIBase - if apiBase == "" { - apiBase = getDefaultAPIBase(protocol) - } - provider := NewHTTPProviderWithMaxTokensFieldAndRequestTimeout( - cfg.APIKey(), - apiBase, - cfg.Proxy, - cfg.MaxTokensField, - userAgent, - cfg.RequestTimeout, - cfg.ExtraBody, - cfg.CustomHeaders, - ) - provider.SetProviderName(protocol) - return finalizeProviderFromConfig(provider, modelID, cfg) - - case "gemini": - if cfg.APIKey() == "" && cfg.APIBase == "" { - return nil, "", fmt.Errorf("api_key or api_base is required for gemini protocol (model: %s)", cfg.Model) - } - apiBase := cfg.APIBase - if apiBase == "" { - apiBase = getDefaultAPIBase(protocol) - } - return finalizeProviderFromConfig(NewGeminiProvider( - cfg.APIKey(), - apiBase, - cfg.Proxy, - userAgent, - cfg.RequestTimeout, - cfg.ExtraBody, - cfg.CustomHeaders, - ), modelID, cfg) - - case "minimax": - // Minimax requires reasoning_split: true in the request body - if cfg.APIKey() == "" && cfg.APIBase == "" { - return nil, "", fmt.Errorf("api_key or api_base is required for HTTP-based protocol %q", protocol) - } - apiBase := cfg.APIBase - if apiBase == "" { - apiBase = getDefaultAPIBase(protocol) - } - extraBody := cfg.ExtraBody - if extraBody == nil { - extraBody = make(map[string]any) - } - if _, ok := extraBody["reasoning_split"]; !ok { - extraBody["reasoning_split"] = true - } - provider := NewHTTPProviderWithMaxTokensFieldAndRequestTimeout( - cfg.APIKey(), - apiBase, - cfg.Proxy, - cfg.MaxTokensField, - userAgent, - cfg.RequestTimeout, - extraBody, - cfg.CustomHeaders, - ) - provider.SetProviderName(protocol) - return finalizeProviderFromConfig(provider, modelID, cfg) - case "anthropic": if authMethod == "oauth" || authMethod == "token" { // Use OAuth credentials from auth store @@ -281,90 +139,26 @@ func CreateProviderFromConfig(cfg *config.ModelConfig) (LLMProvider, string, err } return finalizeProviderFromConfig(provider, modelID, cfg) } - // Use API key with HTTP API - apiBase := common.NormalizeBaseURL(cfg.APIBase, "https://api.anthropic.com/v1", true) if cfg.APIKey() == "" { return nil, "", fmt.Errorf("api_key is required for anthropic protocol (model: %s)", cfg.Model) } - provider := NewHTTPProviderWithMaxTokensFieldAndRequestTimeout( + provider := anthropicprovider.NewAPIKeyProvider( cfg.APIKey(), - apiBase, + cfg.APIBase, cfg.Proxy, - cfg.MaxTokensField, userAgent, cfg.RequestTimeout, cfg.ExtraBody, cfg.CustomHeaders, ) - provider.SetProviderName(protocol) - return finalizeProviderFromConfig(provider, modelID, cfg) - - case "anthropic-messages": - // Anthropic Messages API with native format (HTTP-based, no SDK) - apiBase := cfg.APIBase - if apiBase == "" { - apiBase = "https://api.anthropic.com/v1" - } - if cfg.APIKey() == "" { - return nil, "", fmt.Errorf("api_key is required for anthropic-messages protocol (model: %s)", cfg.Model) - } - return finalizeProviderFromConfig(anthropicmessages.NewProviderWithTimeout( - cfg.APIKey(), - apiBase, - userAgent, - cfg.RequestTimeout, - ), modelID, cfg) - - case "alibaba-coding-anthropic": - // Alibaba Coding Plan with Anthropic-compatible API - apiBase := cfg.APIBase - if apiBase == "" { - apiBase = getDefaultAPIBase(protocol) - } - if cfg.APIKey() == "" { - return nil, "", fmt.Errorf("api_key is required for %q protocol (model: %s)", protocol, cfg.Model) - } - return finalizeProviderFromConfig(anthropicmessages.NewProviderWithTimeout( - cfg.APIKey(), - apiBase, - userAgent, - cfg.RequestTimeout, - ), modelID, cfg) - - case "antigravity": - return finalizeProviderFromConfig(NewAntigravityProvider(), modelID, cfg) - - case "claude-cli": - workspace := cfg.Workspace - if workspace == "" { - workspace = "." - } - return finalizeProviderFromConfig(NewClaudeCliProvider(workspace), modelID, cfg) - - case "codex-cli": - workspace := cfg.Workspace - if workspace == "" { - workspace = "." - } - return finalizeProviderFromConfig(NewCodexCliProvider(workspace), modelID, cfg) - - case "github-copilot": - apiBase := cfg.APIBase - if apiBase == "" { - apiBase = "localhost:4321" - } - connectMode := cfg.ConnectMode - if connectMode == "" { - connectMode = "grpc" - } - provider, err := NewGitHubCopilotProvider(apiBase, connectMode, modelID) - if err != nil { - return nil, "", err - } return finalizeProviderFromConfig(provider, modelID, cfg) default: - return nil, "", fmt.Errorf("unknown protocol %q in model %q", protocol, cfg.Model) + return nil, "", fmt.Errorf( + "unsupported model protocol %q in model %q; use openai or anthropic with an explicit api_base for compatible services", + protocol, + cfg.Model, + ) } } @@ -380,13 +174,7 @@ func finalizeProviderFromConfig( return wrapped, modelID, nil } -func isEmptyAPIKeyAllowed(protocol string) bool { - option, ok := providerMetadataForName(protocol) - return ok && option.EmptyAPIKeyAllowed -} - -// DefaultAPIBaseForProtocol returns the configured default API base for a protocol. -// It returns empty string if the protocol has no default base. +// DefaultAPIBaseForProtocol returns the default endpoint for a supported protocol. func DefaultAPIBaseForProtocol(protocol string) string { protocol = strings.ToLower(strings.TrimSpace(protocol)) return getDefaultAPIBase(protocol) diff --git a/pkg/providers/factory_provider_azidentity_test.go b/pkg/providers/factory_provider_azidentity_test.go deleted file mode 100644 index 98dfc211..00000000 --- a/pkg/providers/factory_provider_azidentity_test.go +++ /dev/null @@ -1,36 +0,0 @@ -//go:build azidentity - -// PicoClaw - Ultra-lightweight personal AI agent -// License: MIT -// -// Copyright (c) 2026 PicoClaw contributors - -package providers - -import ( - "testing" - - "github.com/sipeed/picoclaw/pkg/config" -) - -// With the azidentity build tag, an azure config with no api_key must succeed -// (falls back to DefaultAzureCredential). Construction does not require any -// real Azure environment — token acquisition happens on first Chat. -func TestCreateProviderFromConfig_AzureIdentityFallback(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "azure-gpt5", - Model: "azure/my-gpt5-deployment", - APIBase: "https://my-resource.openai.azure.com", - } - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "my-gpt5-deployment" { - t.Errorf("modelID = %q, want %q", modelID, "my-gpt5-deployment") - } -} diff --git a/pkg/providers/factory_provider_test.go b/pkg/providers/factory_provider_test.go index a70d3eca..74dbab15 100644 --- a/pkg/providers/factory_provider_test.go +++ b/pkg/providers/factory_provider_test.go @@ -6,7 +6,6 @@ package providers import ( - "encoding/json" "net/http" "net/http/httptest" "strings" @@ -42,12 +41,6 @@ func TestExtractProtocol(t *testing.T) { wantProtocol: "openai", wantModelID: "gpt-4o", }, - { - name: "groq with prefix", - config: &config.ModelConfig{Model: "groq/llama-3.1-70b"}, - wantProtocol: "groq", - wantModelID: "llama-3.1-70b", - }, { name: "empty string", config: &config.ModelConfig{Model: ""}, @@ -62,26 +55,20 @@ func TestExtractProtocol(t *testing.T) { }, { name: "multiple slashes", - config: &config.ModelConfig{Model: "nvidia/meta/llama-3.1-8b"}, - wantProtocol: "nvidia", + config: &config.ModelConfig{Model: "openai/meta/llama-3.1-8b"}, + wantProtocol: "openai", wantModelID: "meta/llama-3.1-8b", }, { name: "normalizes provider", - config: &config.ModelConfig{Model: "z.ai/glm-5.1"}, - wantProtocol: "zai", + config: &config.ModelConfig{Model: "gpt/glm-5.1"}, + wantProtocol: "openai", wantModelID: "glm-5.1", }, - { - name: "azure with prefix", - config: &config.ModelConfig{Model: "azure/my-gpt5-deployment"}, - wantProtocol: "azure", - wantModelID: "my-gpt5-deployment", - }, { name: "explicit provider keeps model", - config: &config.ModelConfig{Provider: "nvidia", Model: "z-ai/glm-5.1"}, - wantProtocol: "nvidia", + config: &config.ModelConfig{Provider: "openai", Model: "z-ai/glm-5.1"}, + wantProtocol: "openai", wantModelID: "z-ai/glm-5.1", }, { @@ -92,8 +79,8 @@ func TestExtractProtocol(t *testing.T) { }, { name: "explicit provider preserves aliased prefix", - config: &config.ModelConfig{Provider: "qwen", Model: "qwen/qwen-plus"}, - wantProtocol: "qwen-portal", + config: &config.ModelConfig{Provider: "gpt", Model: "qwen/qwen-plus"}, + wantProtocol: "openai", wantModelID: "qwen/qwen-plus", }, { @@ -152,7 +139,7 @@ func TestCreateProviderFromConfig_UsesExplicitProvider(t *testing.T) { cfg := &config.ModelConfig{ ModelName: "test-explicit-provider", Model: "z-ai/glm-5.1", - Provider: "nvidia", + Provider: "openai", } cfg.SetAPIKey("test-key") @@ -166,32 +153,8 @@ func TestCreateProviderFromConfig_UsesExplicitProvider(t *testing.T) { if modelID != "z-ai/glm-5.1" { t.Fatalf("modelID = %q, want z-ai/glm-5.1", modelID) } - if got := ResolveAPIBase(cfg); got != "https://integrate.api.nvidia.com/v1" { - t.Fatalf("ResolveAPIBase() = %q, want NVIDIA default API base", got) - } -} - -func TestCreateProviderFromConfig_DeepSeekSupportsThinking(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "deepseek-v4-flash", - Provider: "deepseek", - Model: "deepseek-v4-flash", - } - cfg.SetAPIKey("test-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if modelID != "deepseek-v4-flash" { - t.Fatalf("modelID = %q, want %q", modelID, "deepseek-v4-flash") - } - tc, ok := provider.(ThinkingCapable) - if !ok { - t.Fatalf("provider %T should implement ThinkingCapable for DeepSeek", provider) - } - if !tc.SupportsThinking() { - t.Fatalf("DeepSeek provider SupportsThinking() = false, want true") + if got := ResolveAPIBase(cfg); got != "https://api.openai.com/v1" { + t.Fatalf("ResolveAPIBase() = %q, want OpenAI default API base", got) } } @@ -216,375 +179,6 @@ func TestCreateProviderFromConfig_PreservesExplicitProviderPrefixedModel(t *test } } -func TestCreateProviderFromConfig_DefaultAPIBase(t *testing.T) { - tests := []struct { - name string - protocol string - }{ - {"openai", "openai"}, - {"venice", "venice"}, - {"nearai", "nearai"}, - {"groq", "groq"}, - {"novita", "novita"}, - {"openrouter", "openrouter"}, - {"cerebras", "cerebras"}, - {"vivgrid", "vivgrid"}, - {"siliconflow", "siliconflow"}, - {"qwen", "qwen"}, - {"vllm", "vllm"}, - {"deepseek", "deepseek"}, - {"ollama", "ollama"}, - {"lmstudio", "lmstudio"}, - {"gpt4free", "gpt4free"}, - {"longcat", "longcat"}, - {"modelscope", "modelscope"}, - {"mimo", "mimo"}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-" + tt.protocol, - Model: tt.protocol + "/test-model", - } - cfg.SetAPIKey("test-key") - - provider, _, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - - // Verify we got an HTTPProvider for all these protocols - if _, ok := provider.(*HTTPProvider); !ok { - t.Fatalf("expected *HTTPProvider, got %T", provider) - } - }) - } -} - -func TestGetDefaultAPIBase_LiteLLM(t *testing.T) { - if got := getDefaultAPIBase("litellm"); got != "http://localhost:4000/v1" { - t.Fatalf("getDefaultAPIBase(%q) = %q, want %q", "litellm", got, "http://localhost:4000/v1") - } -} - -func TestGetDefaultAPIBase_LMStudio(t *testing.T) { - if got := getDefaultAPIBase("lmstudio"); got != "http://localhost:1234/v1" { - t.Fatalf("getDefaultAPIBase(%q) = %q, want %q", "lmstudio", got, "http://localhost:1234/v1") - } -} - -func TestGetDefaultAPIBase_GPT4Free(t *testing.T) { - if got := getDefaultAPIBase("gpt4free"); got != "http://localhost:1337/v1" { - t.Fatalf("getDefaultAPIBase(%q) = %q, want %q", "gpt4free", got, "http://localhost:1337/v1") - } - if got := getDefaultAPIBase("g4f"); got != "http://localhost:1337/v1" { - t.Fatalf("getDefaultAPIBase(%q) = %q, want %q", "g4f", got, "http://localhost:1337/v1") - } -} - -func TestGetDefaultAPIBase_Venice(t *testing.T) { - if got := getDefaultAPIBase("venice"); got != "https://api.venice.ai/api/v1" { - t.Fatalf("getDefaultAPIBase(%q) = %q, want %q", "venice", got, "https://api.venice.ai/api/v1") - } -} - -func TestGetDefaultAPIBase_NearAI(t *testing.T) { - if got := getDefaultAPIBase("nearai"); got != "https://cloud-api.near.ai/v1" { - t.Fatalf("getDefaultAPIBase(%q) = %q, want %q", "nearai", got, "https://cloud-api.near.ai/v1") - } - if got := getDefaultAPIBase("near-ai"); got != "https://cloud-api.near.ai/v1" { - t.Fatalf("getDefaultAPIBase(%q) = %q, want %q", "near-ai", got, "https://cloud-api.near.ai/v1") - } -} - -func TestGetDefaultAPIBase_SiliconFlow(t *testing.T) { - if got := getDefaultAPIBase("siliconflow"); got != "https://api.siliconflow.cn/v1" { - t.Fatalf("getDefaultAPIBase(%q) = %q, want %q", "siliconflow", got, "https://api.siliconflow.cn/v1") - } -} - -func TestCreateProviderFromConfig_LiteLLM(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-litellm", - Model: "litellm/my-proxy-alias", - APIBase: "http://localhost:4000/v1", - } - cfg.SetAPIKey("test-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "my-proxy-alias" { - t.Errorf("modelID = %q, want %q", modelID, "my-proxy-alias") - } -} - -func TestCreateProviderFromConfig_LocalProviders(t *testing.T) { - tests := []struct { - name string - modelName string - model string - apiKey string - wantModelID string - }{ - { - name: "LMStudio with API key", - modelName: "test-lmstudio", - model: "lmstudio/openai/gpt-oss-20b", - apiKey: "test-key", - wantModelID: "openai/gpt-oss-20b", - }, - { - name: "LMStudio without API key", - modelName: "test-lmstudio", - model: "lmstudio/openai/gpt-oss-20b", - apiKey: "", - wantModelID: "openai/gpt-oss-20b", - }, - { - name: "Ollama with API key", - modelName: "test-ollama", - model: "ollama/llama3.1:8b", - apiKey: "test-key", - wantModelID: "llama3.1:8b", - }, - { - name: "Ollama without API key", - modelName: "test-ollama", - model: "ollama/llama3.1:8b", - apiKey: "", - wantModelID: "llama3.1:8b", - }, - { - name: "VLLM with API key", - modelName: "test-vllm", - model: "vllm/Qwen/Qwen3-8B", - apiKey: "test-key", - wantModelID: "Qwen/Qwen3-8B", - }, - { - name: "VLLM without API key", - modelName: "test-vllm", - model: "vllm/Qwen/Qwen3-8B", - apiKey: "", - wantModelID: "Qwen/Qwen3-8B", - }, - { - name: "GPT4Free without API key", - modelName: "test-gpt4free", - model: "gpt4free/gpt-4o-mini", - apiKey: "", - wantModelID: "gpt-4o-mini", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: tt.modelName, - Model: tt.model, - } - if tt.apiKey != "" { - cfg.SetAPIKey(tt.apiKey) - } - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != tt.wantModelID { - t.Errorf("modelID = %q, want %q", modelID, tt.wantModelID) - } - if _, ok := provider.(*HTTPProvider); !ok { - t.Fatalf("expected *HTTPProvider, got %T", provider) - } - }) - } -} - -func TestCreateProviderFromConfig_LongCat(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-longcat", - Model: "longcat/LongCat-Flash-Thinking", - APIBase: "https://api.longcat.chat/openai", - } - cfg.SetAPIKey("test-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "LongCat-Flash-Thinking" { - t.Errorf("modelID = %q, want %q", modelID, "LongCat-Flash-Thinking") - } - if _, ok := provider.(*HTTPProvider); !ok { - t.Fatalf("expected *HTTPProvider, got %T", provider) - } -} - -func TestCreateProviderFromConfig_ModelScope(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-modelscope", - Model: "modelscope/Qwen/Qwen3-235B-A22B-Instruct-2507", - APIBase: "https://api-inference.modelscope.cn/v1", - } - cfg.SetAPIKey("test-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "Qwen/Qwen3-235B-A22B-Instruct-2507" { - t.Errorf("modelID = %q, want %q", modelID, "Qwen/Qwen3-235B-A22B-Instruct-2507") - } - if _, ok := provider.(*HTTPProvider); !ok { - t.Fatalf("expected *HTTPProvider, got %T", provider) - } -} - -func TestGetDefaultAPIBase_ModelScope(t *testing.T) { - if got := getDefaultAPIBase("modelscope"); got != "https://api-inference.modelscope.cn/v1" { - t.Fatalf("getDefaultAPIBase(%q) = %q, want %q", "modelscope", got, "https://api-inference.modelscope.cn/v1") - } -} - -func TestCreateProviderFromConfig_Novita(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-novita", - Model: "novita/deepseek/deepseek-v3.2", - } - cfg.SetAPIKey("test-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "deepseek/deepseek-v3.2" { - t.Errorf("modelID = %q, want %q", modelID, "deepseek/deepseek-v3.2") - } - if _, ok := provider.(*HTTPProvider); !ok { - t.Fatalf("expected *HTTPProvider, got %T", provider) - } -} - -func TestGetDefaultAPIBase_Novita(t *testing.T) { - if got := getDefaultAPIBase("novita"); got != "https://api.novita.ai/openai" { - t.Fatalf("getDefaultAPIBase(%q) = %q, want %q", "novita", got, "https://api.novita.ai/openai") - } -} - -func TestCreateProviderFromConfig_Mimo(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-mimo", - Model: "mimo/mimo-v2-pro", - APIBase: "https://api.xiaomimimo.com/v1", - } - cfg.SetAPIKey("test-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "mimo-v2-pro" { - t.Errorf("modelID = %q, want %q", modelID, "mimo-v2-pro") - } - if _, ok := provider.(*HTTPProvider); !ok { - t.Fatalf("expected *HTTPProvider, got %T", provider) - } -} - -func TestCreateProviderFromConfig_Venice(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-venice", - Model: "venice/venice-uncensored", - } - cfg.SetAPIKey("test-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "venice-uncensored" { - t.Errorf("modelID = %q, want %q", modelID, "venice-uncensored") - } - if _, ok := provider.(*HTTPProvider); !ok { - t.Fatalf("expected *HTTPProvider, got %T", provider) - } -} - -func TestCreateProviderFromConfig_NearAI(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-nearai", - Model: "nearai/zai-org/GLM-5.1-FP8", - } - cfg.SetAPIKey("test-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "zai-org/GLM-5.1-FP8" { - t.Errorf("modelID = %q, want %q", modelID, "zai-org/GLM-5.1-FP8") - } - if _, ok := provider.(*HTTPProvider); !ok { - t.Fatalf("expected *HTTPProvider, got %T", provider) - } -} - -func TestCreateProviderFromConfig_SiliconFlow(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-siliconflow", - Model: "siliconflow/deepseek-ai/DeepSeek-V3", - } - cfg.SetAPIKey("test-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "deepseek-ai/DeepSeek-V3" { - t.Errorf("modelID = %q, want %q", modelID, "deepseek-ai/DeepSeek-V3") - } - if _, ok := provider.(*HTTPProvider); !ok { - t.Fatalf("expected *HTTPProvider, got %T", provider) - } -} - -func TestGetDefaultAPIBase_Mimo(t *testing.T) { - if got := getDefaultAPIBase("mimo"); got != "https://api.xiaomimimo.com/v1" { - t.Fatalf("getDefaultAPIBase(%q) = %q, want %q", "mimo", got, "https://api.xiaomimimo.com/v1") - } -} - func TestCreateProviderFromConfig_Anthropic(t *testing.T) { cfg := &config.ModelConfig{ ModelName: "test-anthropic", @@ -604,116 +198,6 @@ func TestCreateProviderFromConfig_Anthropic(t *testing.T) { } } -func TestCreateProviderFromConfig_Antigravity(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-antigravity", - Model: "antigravity/gemini-2.0-flash", - } - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "gemini-2.0-flash" { - t.Errorf("modelID = %q, want %q", modelID, "gemini-2.0-flash") - } -} - -func TestCreateProviderFromConfig_Gemini(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-gemini", - Model: "gemini/gemini-2.5-flash", - } - cfg.SetAPIKey("test-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "gemini-2.5-flash" { - t.Errorf("modelID = %q, want %q", modelID, "gemini-2.5-flash") - } - if _, ok := provider.(*GeminiProvider); !ok { - t.Fatalf("expected *GeminiProvider, got %T", provider) - } -} - -func TestCreateProviderFromConfig_GeminiMissingAPIKey(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-gemini-no-key", - Model: "gemini/gemini-2.5-flash", - } - - _, _, err := CreateProviderFromConfig(cfg) - if err == nil { - t.Fatal("CreateProviderFromConfig() expected error for missing gemini API key") - } -} - -func TestCreateProviderFromConfig_GeminiCustomAPIBaseWithoutKey(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-gemini-custom-base", - Model: "gemini/gemini-2.5-flash", - APIBase: "https://proxy.example.com/v1beta", - } - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "gemini-2.5-flash" { - t.Errorf("modelID = %q, want %q", modelID, "gemini-2.5-flash") - } - if _, ok := provider.(*GeminiProvider); !ok { - t.Fatalf("expected *GeminiProvider, got %T", provider) - } -} - -func TestCreateProviderFromConfig_ClaudeCLI(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-claude-cli", - Model: "claude-cli/claude-sonnet-4.6", - } - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "claude-sonnet-4.6" { - t.Errorf("modelID = %q, want %q", modelID, "claude-sonnet-4.6") - } -} - -func TestCreateProviderFromConfig_CodexCLI(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-codex-cli", - Model: "codex-cli/codex", - } - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "codex" { - t.Errorf("modelID = %q, want %q", modelID, "codex") - } -} - func TestCreateProviderFromConfig_OpenAIMixedCaseAuthMethodUsesOAuthBranch(t *testing.T) { origGetCredential := getCredential getCredential = func(provider string) (*auth.AuthCredential, error) { @@ -854,343 +338,6 @@ func TestCreateProviderFromConfig_RequestTimeoutPropagation(t *testing.T) { } } -func TestCreateProviderFromConfig_Azure(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "azure-gpt5", - Model: "azure/my-gpt5-deployment", - APIBase: "https://my-resource.openai.azure.com", - } - cfg.SetAPIKey("test-azure-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "my-gpt5-deployment" { - t.Errorf("modelID = %q, want %q", modelID, "my-gpt5-deployment") - } -} - -func TestCreateProviderFromConfig_AzureOpenAIAlias(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "azure-gpt4", - Model: "azure-openai/my-deployment", - APIBase: "https://my-resource.openai.azure.com", - } - cfg.SetAPIKey("test-azure-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "my-deployment" { - t.Errorf("modelID = %q, want %q", modelID, "my-deployment") - } -} - -func TestCreateProviderFromConfig_AzureMissingAPIKey(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "azure-gpt5", - Model: "azure/my-gpt5-deployment", - APIBase: "https://my-resource.openai.azure.com", - } - - _, _, err := CreateProviderFromConfig(cfg) - // Without api_key the factory falls back to identity auth, which in the - // default build is stubbed out and surfaces a build-tag error. With the - // azidentity tag, the call succeeds and is covered by a separate test. - if err != nil && !strings.Contains(err.Error(), "azidentity") { - t.Fatalf("CreateProviderFromConfig() unexpected error = %v", err) - } -} - -func TestCreateProviderFromConfig_AzureMissingAPIBase(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "azure-gpt5", - Model: "azure/my-gpt5-deployment", - } - cfg.SetAPIKey("test-azure-key") - - _, _, err := CreateProviderFromConfig(cfg) - if err == nil { - t.Fatal("CreateProviderFromConfig() expected error for missing API base") - } -} - -func TestCreateProviderFromConfig_QwenInternationalAlias(t *testing.T) { - tests := []struct { - name string - protocol string - }{ - {"qwen-international", "qwen-international"}, - {"dashscope-intl", "dashscope-intl"}, - {"qwen-intl", "qwen-intl"}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-" + tt.protocol, - Model: tt.protocol + "/qwen-max", - } - cfg.SetAPIKey("test-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - wantModelID := "qwen-max" - if modelID != wantModelID { - t.Errorf("modelID = %q, want %q", modelID, wantModelID) - } - if _, ok := provider.(*HTTPProvider); !ok { - t.Fatalf("expected *HTTPProvider, got %T", provider) - } - }) - } -} - -func TestCreateProviderFromConfig_QwenUSAlias(t *testing.T) { - tests := []struct { - name string - protocol string - }{ - {"qwen-us", "qwen-us"}, - {"dashscope-us", "dashscope-us"}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-" + tt.protocol, - Model: tt.protocol + "/qwen-max", - } - cfg.SetAPIKey("test-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - wantModelID := "qwen-max" - if modelID != wantModelID { - t.Errorf("modelID = %q, want %q", modelID, wantModelID) - } - if _, ok := provider.(*HTTPProvider); !ok { - t.Fatalf("expected *HTTPProvider, got %T", provider) - } - }) - } -} - -func TestCreateProviderFromConfig_CodingPlanAnthropic(t *testing.T) { - tests := []struct { - name string - protocol string - }{ - {"coding-plan-anthropic", "coding-plan-anthropic"}, - {"alibaba-coding-anthropic", "alibaba-coding-anthropic"}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - cfg := &config.ModelConfig{ - ModelName: "test-" + tt.protocol, - Model: tt.protocol + "/claude-sonnet-4-20250514", - } - cfg.SetAPIKey("test-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - wantModelID := "claude-sonnet-4-20250514" - if modelID != wantModelID { - t.Errorf("modelID = %q, want %q", modelID, wantModelID) - } - // alibaba-coding-anthropic uses Anthropic Messages provider - // Verify it's the anthropic messages provider by checking interface - var _ LLMProvider = provider - }) - } -} - -func TestGetDefaultAPIBase_CodingPlanAnthropic(t *testing.T) { - expectedURL := "https://coding-intl.dashscope.aliyuncs.com/apps/anthropic" - if got := getDefaultAPIBase("coding-plan-anthropic"); got != expectedURL { - t.Fatalf("getDefaultAPIBase(%q) = %q, want %q", "coding-plan-anthropic", got, expectedURL) - } - if got := getDefaultAPIBase("alibaba-coding-anthropic"); got != expectedURL { - t.Fatalf("getDefaultAPIBase(%q) = %q, want %q", "alibaba-coding-anthropic", got, expectedURL) - } -} - -func TestGetDefaultAPIBase_QwenIntlAliases(t *testing.T) { - expectedURL := "https://dashscope-intl.aliyuncs.com/compatible-mode/v1" - for _, protocol := range []string{"qwen-intl", "qwen-international", "dashscope-intl"} { - if got := getDefaultAPIBase(protocol); got != expectedURL { - t.Fatalf("getDefaultAPIBase(%q) = %q, want %q", protocol, got, expectedURL) - } - } -} - -func TestGetDefaultAPIBase_QwenUSAliases(t *testing.T) { - expectedURL := "https://dashscope-us.aliyuncs.com/compatible-mode/v1" - for _, protocol := range []string{"qwen-us", "dashscope-us"} { - if got := getDefaultAPIBase(protocol); got != expectedURL { - t.Fatalf("getDefaultAPIBase(%q) = %q, want %q", protocol, got, expectedURL) - } - } -} - -func TestBuildModelProviderAliasMap(t *testing.T) { - aliases := buildModelProviderAliasMap() - if len(aliases) == 0 { - t.Fatal("buildModelProviderAliasMap() returned empty map") - } - - seenAliases := make(map[string]string, len(aliases)) - for provider, option := range providerMetadataByName { - got, ok := aliases[provider] - if !ok { - t.Fatalf("canonical provider %q missing from alias map", provider) - } - if got != provider { - t.Fatalf("canonical provider %q mapped to %q", provider, got) - } - if existing, ok := seenAliases[provider]; ok { - t.Fatalf("canonical provider key %q collides with provider %q", provider, existing) - } - seenAliases[provider] = provider - for _, alias := range option.Aliases { - normalized := strings.ToLower(strings.TrimSpace(alias)) - if normalized == "" { - t.Fatalf("provider %q includes empty alias", provider) - } - if existing, ok := seenAliases[normalized]; ok && existing != provider { - t.Fatalf("alias %q for provider %q collides with provider %q", alias, provider, existing) - } - seenAliases[normalized] = provider - got, ok := aliases[normalized] - if !ok { - t.Fatalf("alias %q for provider %q missing from alias map", alias, provider) - } - if got != provider { - t.Fatalf("alias %q normalized to %q, want %q", alias, got, provider) - } - } - } -} - -func TestCreateProviderFromConfig_MinimaxInjectsReasoningSplit(t *testing.T) { - var requestBody map[string]any - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"choices":[{"message":{"content":"ok"},"finish_reason":"stop"}]}`)) - })) - defer server.Close() - - cfg := &config.ModelConfig{ - ModelName: "test-minimax", - Model: "minimax/MiniMax-M2.5", - APIBase: server.URL, - } - cfg.SetAPIKey("test-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - if provider == nil { - t.Fatal("CreateProviderFromConfig() returned nil provider") - } - if modelID != "MiniMax-M2.5" { - t.Errorf("modelID = %q, want %q", modelID, "MiniMax-M2.5") - } - - _, err = provider.Chat( - t.Context(), - []Message{{Role: "user", Content: "hi"}}, - nil, - modelID, - nil, - ) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - - // Verify reasoning_split is automatically injected - if got, ok := requestBody["reasoning_split"]; !ok || got != true { - t.Fatalf("reasoning_split = %v, want true", got) - } -} - -func TestCreateProviderFromConfig_MinimaxPreservesUserExtraBody(t *testing.T) { - var requestBody map[string]any - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"choices":[{"message":{"content":"ok"},"finish_reason":"stop"}]}`)) - })) - defer server.Close() - - cfg := &config.ModelConfig{ - ModelName: "test-minimax-custom", - Model: "minimax/MiniMax-M2.5", - APIBase: server.URL, - ExtraBody: map[string]any{"custom_field": "test"}, - } - cfg.SetAPIKey("test-key") - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err != nil { - t.Fatalf("CreateProviderFromConfig() error = %v", err) - } - - _, err = provider.Chat( - t.Context(), - []Message{{Role: "user", Content: "hi"}}, - nil, - modelID, - nil, - ) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - - // Verify reasoning_split is automatically injected - if got, ok := requestBody["reasoning_split"]; !ok || got != true { - t.Fatalf("reasoning_split = %v, want true", got) - } - // Verify user's custom field is preserved - if got, ok := requestBody["custom_field"]; !ok || got != "test" { - t.Fatalf("custom_field = %v, want test", got) - } -} - func TestCreateProviderFromConfig_CustomHeaders(t *testing.T) { var gotSource, gotAuth, gotPath string @@ -1289,13 +436,6 @@ func TestCreateProviderFromConfig_UserAgent(t *testing.T) { wantUA: defaultUA, chatOpts: map[string]any{"max_tokens": 1024}, }, - { - name: "azure default user agent", - model: "azure/my-deployment", - apiKey: "test-azure-key", - response: openaiResponsesResponse, - wantUA: defaultUA, - }, } for _, tt := range tests { @@ -1342,87 +482,12 @@ func TestCreateProviderFromConfig_UserAgent(t *testing.T) { } } -func TestCreateProviderFromConfig_Bedrock(t *testing.T) { - // Set dummy AWS env vars to make test deterministic - t.Setenv("AWS_ACCESS_KEY_ID", "test-key") - t.Setenv("AWS_SECRET_ACCESS_KEY", "test-secret") - t.Setenv("AWS_EC2_METADATA_DISABLED", "true") - // Clear profile-related env vars to avoid loading shared config - t.Setenv("AWS_PROFILE", "") - t.Setenv("AWS_DEFAULT_PROFILE", "") - t.Setenv("AWS_SDK_LOAD_CONFIG", "") - t.Setenv("AWS_SHARED_CREDENTIALS_FILE", "") - - cfg := &config.ModelConfig{ - ModelName: "bedrock-claude", - Model: "bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0", - APIBase: "us-west-2", // Region (also sets AWS region) - } - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err == nil { - // Provider created successfully (built with -tags bedrock) - if provider == nil { - t.Error("provider is nil on success") - } - if modelID != "us.anthropic.claude-sonnet-4-20250514-v1:0" { - t.Errorf("modelID = %q, want %q", modelID, "us.anthropic.claude-sonnet-4-20250514-v1:0") - } - return - } - errMsg := err.Error() - // When built without -tags bedrock, expect stub error - if strings.Contains(errMsg, "build with -tags bedrock") { - return // Expected stub error - } - // Unexpected error - fail the test - t.Errorf("unexpected error from bedrock provider: %v", err) -} - -func TestCreateProviderFromConfig_BedrockWithEndpointURL(t *testing.T) { - // Set dummy AWS env vars to make test deterministic - t.Setenv("AWS_ACCESS_KEY_ID", "test-key") - t.Setenv("AWS_SECRET_ACCESS_KEY", "test-secret") - t.Setenv("AWS_REGION", "us-east-1") // Required when using endpoint URL - t.Setenv("AWS_EC2_METADATA_DISABLED", "true") - // Clear profile-related env vars to avoid loading shared config - t.Setenv("AWS_PROFILE", "") - t.Setenv("AWS_DEFAULT_PROFILE", "") - t.Setenv("AWS_SDK_LOAD_CONFIG", "") - t.Setenv("AWS_SHARED_CREDENTIALS_FILE", "") - - cfg := &config.ModelConfig{ - ModelName: "bedrock-claude", - Model: "bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0", - APIBase: "https://bedrock-runtime.us-east-1.amazonaws.com", // Full endpoint URL - } - - provider, modelID, err := CreateProviderFromConfig(cfg) - if err == nil { - // Provider created successfully (built with -tags bedrock) - if provider == nil { - t.Error("provider is nil on success") - } - if modelID != "us.anthropic.claude-sonnet-4-20250514-v1:0" { - t.Errorf("modelID = %q, want %q", modelID, "us.anthropic.claude-sonnet-4-20250514-v1:0") - } - return - } - errMsg := err.Error() - // When built without -tags bedrock, expect stub error - if strings.Contains(errMsg, "build with -tags bedrock") { - return // Expected stub error - } - // Unexpected error - fail the test - t.Errorf("unexpected error from bedrock provider: %v", err) -} - func TestCreateProviderFromConfig_ToolSchemaTransformWrapsProvider(t *testing.T) { cfg := &config.ModelConfig{ - ModelName: "claude-cli-test", - Provider: "claude-cli", + ModelName: "anthropic-test", + Provider: "anthropic", Model: "claude-sonnet-4.6", - Workspace: t.TempDir(), + APIKeys: config.SimpleSecureStrings("test-key"), ToolSchemaTransform: "simple", } @@ -1433,17 +498,17 @@ func TestCreateProviderFromConfig_ToolSchemaTransformWrapsProvider(t *testing.T) if modelID != "claude-sonnet-4.6" { t.Fatalf("modelID = %q, want %q", modelID, "claude-sonnet-4.6") } - if _, ok := provider.(*toolSchemaTransformProvider); !ok { - t.Fatalf("provider = %T, want *toolSchemaTransformProvider", provider) + if _, ok := provider.(*toolSchemaStreamingProvider); !ok { + t.Fatalf("provider = %T, want *toolSchemaStreamingProvider", provider) } } func TestCreateProviderFromConfig_InvalidToolSchemaTransform(t *testing.T) { cfg := &config.ModelConfig{ - ModelName: "claude-cli-test", - Provider: "claude-cli", + ModelName: "anthropic-test", + Provider: "anthropic", Model: "claude-sonnet-4.6", - Workspace: t.TempDir(), + APIKeys: config.SimpleSecureStrings("test-key"), ToolSchemaTransform: "invalid", } diff --git a/pkg/providers/factory_test.go b/pkg/providers/factory_test.go index 5ffb572c..51e6b688 100644 --- a/pkg/providers/factory_test.go +++ b/pkg/providers/factory_test.go @@ -7,12 +7,12 @@ import ( "github.com/sipeed/picoclaw/pkg/config" ) -func TestCreateProviderReturnsHTTPProviderForOpenRouter(t *testing.T) { +func TestCreateProviderReturnsHTTPProviderForCompatibleEndpoint(t *testing.T) { cfg := config.DefaultConfig() cfg.Agents.Defaults.ModelName = "test-openrouter" modelCfg := &config.ModelConfig{ ModelName: "test-openrouter", - Model: "openrouter/auto", + Model: "openai/auto", APIBase: "https://openrouter.ai/api/v1", } modelCfg.SetAPIKey("sk-or-test") @@ -30,10 +30,10 @@ func TestCreateProviderReturnsHTTPProviderForOpenRouter(t *testing.T) { func TestCreateProviderResolvesRawDefaultFromProviderTemplate(t *testing.T) { cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = "openrouter/deepseek/deepseek-v3.2" + cfg.Agents.Defaults.ModelName = "openai/deepseek/deepseek-v3.2" modelCfg := &config.ModelConfig{ ModelName: "openrouter-template", - Model: "openrouter/auto", + Model: "openai/auto", APIBase: "https://openrouter.ai/api/v1", ThinkingLevel: "off", } @@ -50,7 +50,7 @@ func TestCreateProviderResolvesRawDefaultFromProviderTemplate(t *testing.T) { if modelID != "deepseek/deepseek-v3.2" { t.Fatalf("model ID = %q, want %q", modelID, "deepseek/deepseek-v3.2") } - if modelCfg.Model != "openrouter/auto" { + if modelCfg.Model != "openai/auto" { t.Fatalf("template model mutated to %q", modelCfg.Model) } resolved, err := ResolveModelConfig(cfg, cfg.Agents.Defaults.ModelName) @@ -65,37 +65,37 @@ func TestCreateProviderResolvesRawDefaultFromProviderTemplate(t *testing.T) { func TestResolveModelConfigPrefersConfiguredProviderTemplate(t *testing.T) { cfg := config.DefaultConfig() cfg.ModelList = []*config.ModelConfig{ - {ModelName: "unconfigured", Model: "openrouter/auto"}, + {ModelName: "unconfigured", Model: "openai/auto"}, { ModelName: "configured", - Model: "openrouter/other", + Model: "openai/other", APIBase: "https://openrouter.ai/api/v1", APIKeys: config.SimpleSecureStrings("sk-or-test"), }, } - resolved, err := ResolveModelConfig(cfg, "openrouter/new-model") + resolved, err := ResolveModelConfig(cfg, "openai/new-model") if err != nil { t.Fatalf("ResolveModelConfig() error = %v", err) } if resolved.APIBase != "https://openrouter.ai/api/v1" || resolved.APIKey() != "sk-or-test" { - t.Fatalf("resolved template = %#v, want configured OpenRouter entry", resolved) + t.Fatalf("resolved template = %#v, want configured compatible endpoint", resolved) } } func TestResolveModelConfigPrefersConfiguredExactRawMatch(t *testing.T) { cfg := config.DefaultConfig() cfg.ModelList = []*config.ModelConfig{ - {ModelName: "unconfigured", Provider: "openrouter", Model: "openrouter/target"}, + {ModelName: "unconfigured", Provider: "openai", Model: "openai/target"}, { ModelName: "configured", - Provider: "openrouter", - Model: "openrouter/target", + Provider: "openai", + Model: "openai/target", APIKeys: config.SimpleSecureStrings("sk-or-test"), }, } - resolved, err := ResolveModelConfig(cfg, "openrouter/target") + resolved, err := ResolveModelConfig(cfg, "openai/target") if err != nil { t.Fatalf("ResolveModelConfig() error = %v", err) } @@ -106,14 +106,14 @@ func TestResolveModelConfigPrefersConfiguredExactRawMatch(t *testing.T) { func TestResolveModelConfigUsesDefaultProviderForBareTemplate(t *testing.T) { cfg := config.DefaultConfig() - cfg.Agents.Defaults.Provider = "openrouter" + cfg.Agents.Defaults.Provider = "openai" cfg.ModelList = []*config.ModelConfig{{ ModelName: "bare-template", Model: "auto", APIKeys: config.SimpleSecureStrings("sk-or-test"), }} - resolved, err := ResolveModelConfig(cfg, "openrouter/new-model") + resolved, err := ResolveModelConfig(cfg, "openai/new-model") if err != nil { t.Fatalf("ResolveModelConfig() error = %v", err) } @@ -124,10 +124,10 @@ func TestResolveModelConfigUsesDefaultProviderForBareTemplate(t *testing.T) { func TestResolveModelConfigPreservesLegacyExactModelProvider(t *testing.T) { cfg := config.DefaultConfig() - cfg.Agents.Defaults.Provider = "openrouter" + cfg.Agents.Defaults.Provider = "openai" cfg.ModelList = []*config.ModelConfig{{ ModelName: "legacy-template", - Provider: "openrouter", + Provider: "openai", Model: "openai/gpt-4o", APIKeys: config.SimpleSecureStrings("sk-or-test"), }} @@ -136,14 +136,14 @@ func TestResolveModelConfigPreservesLegacyExactModelProvider(t *testing.T) { if err != nil { t.Fatalf("ResolveModelConfig() error = %v", err) } - if resolved.Provider != "openrouter" { + if resolved.Provider != "openai" { t.Fatalf("Provider = %q, want openrouter", resolved.Provider) } } func TestResolveModelConfigSetsDefaultProviderOnBareEntry(t *testing.T) { cfg := config.DefaultConfig() - cfg.Agents.Defaults.Provider = "openrouter" + cfg.Agents.Defaults.Provider = "openai" cfg.ModelList = []*config.ModelConfig{{ ModelName: "bare", Model: "gpt-4o", @@ -154,8 +154,8 @@ func TestResolveModelConfigSetsDefaultProviderOnBareEntry(t *testing.T) { if err != nil { t.Fatalf("ResolveModelConfig() error = %v", err) } - if resolved.Provider != "openrouter" || resolved.Model != "gpt-4o" { - t.Fatalf("resolved provider/model = %q/%q, want openrouter/gpt-4o", resolved.Provider, resolved.Model) + if resolved.Provider != "openai" || resolved.Model != "gpt-4o" { + t.Fatalf("resolved provider/model = %q/%q, want openai/gpt-4o", resolved.Provider, resolved.Model) } } @@ -185,48 +185,6 @@ func TestResolveModelConfigPrefersCustomAPIBaseTemplate(t *testing.T) { } } -func TestCreateProviderReturnsCodexCliProviderForCodexCode(t *testing.T) { - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = "test-codex" - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "test-codex", - Model: "codex-cli/codex-model", - Workspace: "/tmp/workspace", - }, - } - - provider, _, err := CreateProvider(cfg) - if err != nil { - t.Fatalf("CreateProvider() error = %v", err) - } - - if _, ok := provider.(*CodexCliProvider); !ok { - t.Fatalf("provider type = %T, want *CodexCliProvider", provider) - } -} - -func TestCreateProviderReturnsClaudeCliProviderForClaudeCli(t *testing.T) { - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = "test-claude-cli" - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "test-claude-cli", - Model: "claude-cli/claude-sonnet", - Workspace: "/tmp/workspace", - }, - } - - provider, _, err := CreateProvider(cfg) - if err != nil { - t.Fatalf("CreateProvider() error = %v", err) - } - - if _, ok := provider.(*ClaudeCliProvider); !ok { - t.Fatalf("provider type = %T, want *ClaudeCliProvider", provider) - } -} - func TestCreateProviderReturnsClaudeProviderForAnthropicOAuth(t *testing.T) { originalGetCredential := getCredential t.Cleanup(func() { getCredential = originalGetCredential }) diff --git a/pkg/providers/fallback_multikey_test.go b/pkg/providers/fallback_multikey_test.go index 10481ec6..8014b708 100644 --- a/pkg/providers/fallback_multikey_test.go +++ b/pkg/providers/fallback_multikey_test.go @@ -17,7 +17,7 @@ func TestMultiKeyFailover(t *testing.T) { Fallbacks: []string{"glm-4.7__key_1", "glm-4.7__key_2"}, } - candidates := ResolveCandidates(cfg, "zhipu") + candidates := ResolveCandidates(cfg, "openai") if len(candidates) != 3 { t.Fatalf("expected 3 candidates, got %d: %v", len(candidates), candidates) @@ -79,7 +79,7 @@ func TestMultiKeyFailoverAllFail(t *testing.T) { Fallbacks: []string{"glm-4.7__key_1", "glm-4.7__key_2"}, } - candidates := ResolveCandidates(cfg, "zhipu") + candidates := ResolveCandidates(cfg, "openai") cooldown := NewCooldownTracker() chain := NewFallbackChain(cooldown, nil) @@ -124,7 +124,7 @@ func TestMultiKeyFailoverCooldown(t *testing.T) { Fallbacks: []string{"glm-4.7__key_1"}, } - candidates := ResolveCandidates(cfg, "zhipu") + candidates := ResolveCandidates(cfg, "openai") cooldown := NewCooldownTracker() chain := NewFallbackChain(cooldown, nil) @@ -180,7 +180,7 @@ func TestMultiKeyFailoverWithFormatError(t *testing.T) { Fallbacks: []string{"glm-4.7__key_1"}, } - candidates := ResolveCandidates(cfg, "zhipu") + candidates := ResolveCandidates(cfg, "openai") cooldown := NewCooldownTracker() chain := NewFallbackChain(cooldown, nil) @@ -219,20 +219,20 @@ func TestMultiKeyFailoverWithFormatError(t *testing.T) { } // TestMultiKeyWithModelFallback tests multi-key failover combined with model fallback. -// This simulates the scenario: api_keys: ["k1", "k2"] + fallbacks: ["minimax"] +// This simulates the scenario: api_keys: ["k1", "k2"] + fallbacks: ["anthropic"] // Expected failover order: glm-4.7 (k1) → glm-4.7__key_1 (k2) → minimax func TestMultiKeyWithModelFallback(t *testing.T) { // Simulate expanded config from: - // { "model_name": "glm-4.7", "api_keys": ["k1", "k2"], "fallbacks": ["minimax"] } - // After ExpandMultiKeyModels, primaryEntry.Fallbacks = ["glm-4.7__key_1", "minimax"] - // Note: In production, "minimax" would be resolved via model lookup to "minimax/minimax" + // { "model_name": "glm-4.7", "api_keys": ["k1", "k2"], "fallbacks": ["anthropic"] } + // After ExpandMultiKeyModels, primaryEntry.Fallbacks = ["glm-4.7__key_1", "anthropic"] + // Note: In production, "anthropic" would be resolved via model lookup to "anthropic/claude-test" // In this test, we use the full format to avoid needing a lookup function. cfg := ModelConfig{ Primary: "glm-4.7", - Fallbacks: []string{"glm-4.7__key_1", "minimax/minimax"}, + Fallbacks: []string{"glm-4.7__key_1", "anthropic/claude-test"}, } - candidates := ResolveCandidates(cfg, "zhipu") + candidates := ResolveCandidates(cfg, "openai") // Should have 3 candidates: glm-4.7 (zhipu), glm-4.7__key_1 (zhipu), minimax (minimax) if len(candidates) != 3 { @@ -240,23 +240,23 @@ func TestMultiKeyWithModelFallback(t *testing.T) { } // Verify candidate order - if candidates[0].Model != "glm-4.7" || candidates[0].Provider != "zhipu" { + if candidates[0].Model != "glm-4.7" || candidates[0].Provider != "openai" { t.Errorf( - "expected first candidate to be zhipu/glm-4.7, got: %s/%s", + "expected first candidate to be openai/glm-4.7, got: %s/%s", candidates[0].Provider, candidates[0].Model, ) } - if candidates[1].Model != "glm-4.7__key_1" || candidates[1].Provider != "zhipu" { + if candidates[1].Model != "glm-4.7__key_1" || candidates[1].Provider != "openai" { t.Errorf( - "expected second candidate to be zhipu/glm-4.7__key_1, got: %s/%s", + "expected second candidate to be openai/glm-4.7__key_1, got: %s/%s", candidates[1].Provider, candidates[1].Model, ) } - if candidates[2].Model != "minimax" || candidates[2].Provider != "minimax" { + if candidates[2].Model != "claude-test" || candidates[2].Provider != "anthropic" { t.Errorf( - "expected third candidate to be minimax/minimax, got: %s/%s", + "expected third candidate to be anthropic/claude-test, got: %s/%s", candidates[2].Provider, candidates[2].Model, ) @@ -304,14 +304,14 @@ func TestMultiKeyWithModelFallback(t *testing.T) { if len(calledModels) != 3 { t.Fatalf("expected 3 called models, got %d", len(calledModels)) } - if calledModels[0] != "zhipu/glm-4.7" { - t.Errorf("expected first call to zhipu/glm-4.7, got: %s", calledModels[0]) + if calledModels[0] != "openai/glm-4.7" { + t.Errorf("expected first call to openai/glm-4.7, got: %s", calledModels[0]) } - if calledModels[1] != "zhipu/glm-4.7__key_1" { - t.Errorf("expected second call to zhipu/glm-4.7__key_1, got: %s", calledModels[1]) + if calledModels[1] != "openai/glm-4.7__key_1" { + t.Errorf("expected second call to openai/glm-4.7__key_1, got: %s", calledModels[1]) } - if calledModels[2] != "minimax/minimax" { - t.Errorf("expected third call to minimax/minimax, got: %s", calledModels[2]) + if calledModels[2] != "anthropic/claude-test" { + t.Errorf("expected third call to anthropic/claude-test, got: %s", calledModels[2]) } // Verify 2 failed attempts recorded @@ -334,7 +334,7 @@ func TestMultiKeyFailoverMixedErrors(t *testing.T) { Fallbacks: []string{"glm-4.7__key_1", "glm-4.7__key_2"}, } - candidates := ResolveCandidates(cfg, "zhipu") + candidates := ResolveCandidates(cfg, "openai") cooldown := NewCooldownTracker() chain := NewFallbackChain(cooldown, nil) diff --git a/pkg/providers/fallback_test.go b/pkg/providers/fallback_test.go index e3c17e85..c07ee7f7 100644 --- a/pkg/providers/fallback_test.go +++ b/pkg/providers/fallback_test.go @@ -74,7 +74,7 @@ func TestFallback_AllFail(t *testing.T) { candidates := []FallbackCandidate{ makeCandidate("openai", "gpt-4"), makeCandidate("anthropic", "claude"), - makeCandidate("groq", "llama"), + makeCandidate("anthropic", "llama"), } run := func(ctx context.Context, provider, model string) (*LLMResponse, error) { @@ -591,7 +591,7 @@ func TestFallbackCandidateStableKeyIncludesConfigIdentity(t *testing.T) { func TestResolveCandidates_Simple(t *testing.T) { cfg := ModelConfig{ Primary: "gpt-4", - Fallbacks: []string{"anthropic/claude-opus", "groq/llama-3"}, + Fallbacks: []string{"anthropic/claude-opus", "anthropic/claude-test"}, } candidates := ResolveCandidates(cfg, "openai") @@ -605,7 +605,7 @@ func TestResolveCandidates_Simple(t *testing.T) { if candidates[1].Provider != "anthropic" || candidates[1].Model != "claude-opus" { t.Errorf("candidate[1] = %s/%s, want anthropic/claude-opus", candidates[1].Provider, candidates[1].Model) } - if candidates[2].Provider != "groq" || candidates[2].Model != "llama-3" { + if candidates[2].Provider != "anthropic" || candidates[2].Model != "claude-test" { t.Errorf("candidate[2] = %s/%s, want groq/llama-3", candidates[2].Provider, candidates[2].Model) } } @@ -654,7 +654,7 @@ func TestResolveCandidatesWithLookup_AliasResolvesToNestedModel(t *testing.T) { lookup := func(raw string) (string, bool) { if raw == "step-3.5-flash" { - return "openrouter/stepfun/step-3.5-flash:free", true + return "openai/stepfun/step-3.5-flash:free", true } return "", false } @@ -663,7 +663,7 @@ func TestResolveCandidatesWithLookup_AliasResolvesToNestedModel(t *testing.T) { if len(candidates) != 1 { t.Fatalf("candidates = %d, want 1", len(candidates)) } - if candidates[0].Provider != "openrouter" { + if candidates[0].Provider != "openai" { t.Fatalf("provider = %q, want openrouter", candidates[0].Provider) } if candidates[0].Model != "stepfun/step-3.5-flash:free" { @@ -674,12 +674,12 @@ func TestResolveCandidatesWithLookup_AliasResolvesToNestedModel(t *testing.T) { func TestResolveCandidatesWithLookup_DeduplicateAfterLookup(t *testing.T) { cfg := ModelConfig{ Primary: "step-3.5-flash", - Fallbacks: []string{"openrouter/stepfun/step-3.5-flash:free"}, + Fallbacks: []string{"openai/stepfun/step-3.5-flash:free"}, } lookup := func(raw string) (string, bool) { if raw == "step-3.5-flash" { - return "openrouter/stepfun/step-3.5-flash:free", true + return "openai/stepfun/step-3.5-flash:free", true } return "", false } diff --git a/pkg/providers/httpapi/gemini_helpers.go b/pkg/providers/httpapi/gemini_helpers.go deleted file mode 100644 index 87cc4c08..00000000 --- a/pkg/providers/httpapi/gemini_helpers.go +++ /dev/null @@ -1,22 +0,0 @@ -package httpapi - -import "strings" - -func extractPartThoughtSignature(thoughtSignature string, thoughtSignatureSnake string) string { - if thoughtSignature != "" { - return thoughtSignature - } - if thoughtSignatureSnake != "" { - return thoughtSignatureSnake - } - return "" -} - -func extractProtocol(model string) (protocol, modelID string) { - model = strings.TrimSpace(model) - protocol, modelID, found := strings.Cut(model, "/") - if !found { - return "openai", model - } - return protocol, modelID -} diff --git a/pkg/providers/httpapi/gemini_provider.go b/pkg/providers/httpapi/gemini_provider.go deleted file mode 100644 index 338a5659..00000000 --- a/pkg/providers/httpapi/gemini_provider.go +++ /dev/null @@ -1,859 +0,0 @@ -package httpapi - -import ( - "bufio" - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "strings" - "time" - - "github.com/sipeed/picoclaw/pkg/providers/common" -) - -const ( - geminiDefaultAPIBase = "https://generativelanguage.googleapis.com/v1beta" - geminiDefaultModel = "gemini-2.0-flash" - geminiDefaultStreamingReadIdleLimit = 5 * time.Minute -) - -type GeminiProvider struct { - apiKey string - apiBase string - httpClient *http.Client - extraBody map[string]any - customHeaders map[string]string - userAgent string -} - -func NewGeminiProvider( - apiKey string, - apiBase string, - proxy string, - userAgent string, - requestTimeoutSeconds int, - extraBody map[string]any, - customHeaders map[string]string, -) *GeminiProvider { - if strings.TrimSpace(apiBase) == "" { - apiBase = geminiDefaultAPIBase - } - client := common.NewHTTPClient(proxy) - if requestTimeoutSeconds > 0 { - client.Timeout = time.Duration(requestTimeoutSeconds) * time.Second - } - - return &GeminiProvider{ - apiKey: strings.TrimSpace(apiKey), - apiBase: strings.TrimRight(strings.TrimSpace(apiBase), "/"), - httpClient: client, - extraBody: cloneAnyMap(extraBody), - customHeaders: cloneStringMap(customHeaders), - userAgent: strings.TrimSpace(userAgent), - } -} - -func (p *GeminiProvider) GetDefaultModel() string { - return geminiDefaultModel -} - -func (p *GeminiProvider) SupportsThinking() bool { - return true -} - -func (p *GeminiProvider) Chat( - ctx context.Context, - messages []Message, - tools []ToolDefinition, - model string, - options map[string]any, -) (*LLMResponse, error) { - if p.apiBase == "" { - return nil, fmt.Errorf("API base not configured") - } - - model = normalizeGeminiModel(model) - requestBody := p.buildRequestBody(messages, tools, model, options) - jsonData, err := json.Marshal(requestBody) - if err != nil { - return nil, fmt.Errorf("failed to marshal request: %w", err) - } - - url := fmt.Sprintf("%s/models/%s:generateContent", p.apiBase, model) - req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(jsonData)) - if err != nil { - return nil, fmt.Errorf("failed to create request: %w", err) - } - - p.applyHeaders(req) - - resp, err := p.httpClient.Do(req) - if err != nil { - return nil, fmt.Errorf("failed to send request: %w", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, common.HandleErrorResponse(resp, p.apiBase) - } - - var apiResp geminiGenerateContentResponse - if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil { - return nil, fmt.Errorf("failed to decode response: %w", err) - } - - return parseGeminiResponse(&apiResp), nil -} - -func (p *GeminiProvider) ChatStream( - ctx context.Context, - messages []Message, - tools []ToolDefinition, - model string, - options map[string]any, - onChunk func(accumulated string), -) (*LLMResponse, error) { - return p.ChatStreamEvents( - ctx, - messages, - tools, - model, - options, - func(chunk StreamChunk) { - if onChunk != nil && strings.TrimSpace(chunk.Content) != "" { - onChunk(chunk.Content) - } - }, - ) -} - -func (p *GeminiProvider) ChatStreamEvents( - ctx context.Context, - messages []Message, - tools []ToolDefinition, - model string, - options map[string]any, - onChunk func(StreamChunk), -) (*LLMResponse, error) { - if p.apiBase == "" { - return nil, fmt.Errorf("API base not configured") - } - - model = normalizeGeminiModel(model) - requestBody := p.buildRequestBody(messages, tools, model, options) - jsonData, err := json.Marshal(requestBody) - if err != nil { - return nil, fmt.Errorf("failed to marshal request: %w", err) - } - - url := fmt.Sprintf("%s/models/%s:streamGenerateContent?alt=sse", p.apiBase, model) - req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(jsonData)) - if err != nil { - return nil, fmt.Errorf("failed to create request: %w", err) - } - - p.applyHeaders(req) - req.Header.Set("Accept", "text/event-stream") - - // Streaming should not use a whole-request timeout; context cancellation is the guard. - streamClient := &http.Client{Transport: p.httpClient.Transport} - resp, err := streamClient.Do(req) - if err != nil { - return nil, fmt.Errorf("failed to send request: %w", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, common.HandleErrorResponse(resp, p.apiBase) - } - - return parseGeminiStreamResponse(ctx, - withGeminiStreamingReadIdleTimeout(resp.Body, - geminiDefaultStreamingReadIdleLimit), - onChunk) -} - -func withGeminiStreamingReadIdleTimeout(body io.ReadCloser, timeout time.Duration) io.ReadCloser { - if body == nil || timeout <= 0 { - return body - } - return &geminiStreamingReadIdleTimeoutBody{ - body: body, - timeout: timeout, - } -} - -type geminiStreamingReadIdleTimeoutBody struct { - body io.ReadCloser - timeout time.Duration -} - -func (b *geminiStreamingReadIdleTimeoutBody) Read(p []byte) (int, error) { - timedOut := make(chan struct{}) - timer := time.AfterFunc(b.timeout, func() { - close(timedOut) - _ = b.body.Close() - }) - n, err := b.body.Read(p) - if !timer.Stop() { - <-timedOut - return n, fmt.Errorf("gemini stream idle timeout after %s", b.timeout) - } - return n, err -} - -func (b *geminiStreamingReadIdleTimeoutBody) Close() error { - return b.body.Close() -} - -func (p *GeminiProvider) applyHeaders(req *http.Request) { - req.Header.Set("Content-Type", "application/json") - if p.apiKey != "" { - req.Header.Set("X-Goog-Api-Key", p.apiKey) - } - if p.userAgent != "" { - req.Header.Set("User-Agent", p.userAgent) - } - for k, v := range p.customHeaders { - if strings.TrimSpace(k) == "" { - continue - } - req.Header.Set(k, v) - } -} - -func (p *GeminiProvider) buildRequestBody( - messages []Message, - tools []ToolDefinition, - model string, - options map[string]any, -) map[string]any { - contents := make([]geminiContent, 0, len(messages)) - toolCallNames := make(map[string]string) - systemPrompts := make([]string, 0, 1) - - for _, msg := range messages { - switch msg.Role { - case "system": - if strings.TrimSpace(msg.Content) != "" { - systemPrompts = append(systemPrompts, msg.Content) - } - - case "user": - if msg.ToolCallID != "" { - toolName := common.ResolveToolResponseName(msg.ToolCallID, toolCallNames) - contents = append(contents, geminiContent{ - Role: "user", - Parts: []geminiPart{{ - FunctionResponse: buildGeminiFunctionResponse(toolName, msg.ToolCallID, msg.Content, msg.Media), - }}, - }) - continue - } - - parts := make([]geminiPart, 0, 1+len(msg.Media)) - if strings.TrimSpace(msg.Content) != "" { - parts = append(parts, geminiPart{Text: msg.Content}) - } - parts = append(parts, buildInlineMediaParts(msg.Media)...) - if len(parts) > 0 { - contents = append(contents, geminiContent{Role: "user", Parts: parts}) - } - - case "assistant": - content := geminiContent{Role: "model"} - if strings.TrimSpace(msg.Content) != "" { - content.Parts = append(content.Parts, geminiPart{Text: msg.Content}) - } - for _, tc := range msg.ToolCalls { - toolName, toolArgs, thoughtSignature := common.NormalizeStoredToolCall(tc) - if toolName == "" { - continue - } - if tc.ID != "" { - toolCallNames[tc.ID] = toolName - } - part := geminiPart{ - FunctionCall: &geminiFunctionCall{ - Name: toolName, - Args: toolArgs, - ID: tc.ID, - }, - } - if thoughtSignature != "" { - part.ThoughtSignature = thoughtSignature - part.ThoughtSignatureSnake = thoughtSignature - } - content.Parts = append(content.Parts, part) - } - if len(content.Parts) > 0 { - contents = append(contents, content) - } - - case "tool": - toolName := common.ResolveToolResponseName(msg.ToolCallID, toolCallNames) - contents = append(contents, geminiContent{ - Role: "user", - Parts: []geminiPart{{ - FunctionResponse: buildGeminiFunctionResponse(toolName, msg.ToolCallID, msg.Content, msg.Media), - }}, - }) - } - } - - body := map[string]any{ - "contents": contents, - } - if len(systemPrompts) > 0 { - systemParts := make([]geminiPart, 0, len(systemPrompts)) - for _, prompt := range systemPrompts { - systemParts = append(systemParts, geminiPart{Text: prompt}) - } - body["systemInstruction"] = &geminiContent{Parts: systemParts} - } - - if len(tools) > 0 { - funcDecls := make([]geminiFunctionDeclaration, 0, len(tools)) - for _, t := range tools { - if t.Type != "function" { - continue - } - funcDecls = append(funcDecls, geminiFunctionDeclaration{ - Name: t.Function.Name, - Description: t.Function.Description, - Parameters: t.Function.Parameters, - }) - } - if len(funcDecls) > 0 { - body["tools"] = []geminiTool{{FunctionDeclarations: funcDecls}} - } - } - - generationConfig := make(map[string]any) - if val, ok := options["max_tokens"]; ok { - if maxTokens, ok := val.(int); ok && maxTokens > 0 { - generationConfig["maxOutputTokens"] = maxTokens - } else if maxTokens, ok := val.(float64); ok && maxTokens > 0 { - generationConfig["maxOutputTokens"] = int(maxTokens) - } - } - if temp, ok := options["temperature"].(float64); ok { - generationConfig["temperature"] = temp - } - - if thinkingConfig := buildGeminiThinkingConfig(model, options); len(thinkingConfig) > 0 { - generationConfig["thinkingConfig"] = thinkingConfig - } - - if len(generationConfig) > 0 { - body["generationConfig"] = generationConfig - } - - for k, v := range p.extraBody { - body[k] = v - } - - return body -} - -func normalizeGeminiModel(model string) string { - model = strings.TrimSpace(model) - model = strings.TrimPrefix(model, "models/") - if strings.Contains(model, "/") { - _, modelID := extractProtocol(model) - if modelID != "" { - return modelID - } - } - if model == "" { - return geminiDefaultModel - } - return model -} - -func mapGeminiThinkingLevel(level string) string { - switch strings.ToLower(strings.TrimSpace(level)) { - case "minimal", "off": - return "minimal" - case "low": - return "low" - case "medium": - return "medium" - case "high", "xhigh", "adaptive": - return "high" - default: - return "" - } -} - -func buildGeminiThinkingConfig(model string, options map[string]any) map[string]any { - if !geminiModelSupportsThinkingConfig(model) { - return nil - } - - config := map[string]any{} - rawLevel, _ := options["thinking_level"].(string) - rawLevel = strings.ToLower(strings.TrimSpace(rawLevel)) - if rawLevel == "" { - // Align with agent-level default: unset means ThinkingOff. - rawLevel = "off" - } - - includeThoughts := rawLevel != "off" && rawLevel != "minimal" - config["includeThoughts"] = includeThoughts - - if isGemini25Model(model) { - if isGemini25ProModel(model) && (rawLevel == "off" || rawLevel == "minimal") { - // Gemini 2.5 Pro cannot disable thinking; keep model-default thinking. - return config - } - if budget, ok := mapGeminiThinkingBudget(rawLevel); ok { - config["thinkingBudget"] = budget - } - return config - } - - if isGemini3ProModel(model) && (rawLevel == "off" || rawLevel == "minimal") { - // Gemini 3.x Pro does not support minimal thinking level. - return config - } - - if thinkingLevel := mapGeminiThinkingLevel(rawLevel); thinkingLevel != "" { - config["thinkingLevel"] = thinkingLevel - } - return config -} - -func geminiModelSupportsThinkingConfig(model string) bool { - lowerModel := strings.ToLower(strings.TrimSpace(model)) - return strings.Contains(lowerModel, "gemini-3") || isGemini25Model(lowerModel) -} - -func isGemini25Model(model string) bool { - lowerModel := strings.ToLower(strings.TrimSpace(model)) - return strings.Contains(lowerModel, "gemini-2.5") || strings.Contains(lowerModel, "gemini-25") -} - -func isGemini25ProModel(model string) bool { - lowerModel := strings.ToLower(strings.TrimSpace(model)) - return isGemini25Model(lowerModel) && strings.Contains(lowerModel, "pro") -} - -func isGemini3ProModel(model string) bool { - lowerModel := strings.ToLower(strings.TrimSpace(model)) - return strings.Contains(lowerModel, "gemini-3") && strings.Contains(lowerModel, "pro") -} - -func mapGeminiThinkingBudget(level string) (int, bool) { - level = strings.ToLower(strings.TrimSpace(level)) - if level == "" { - return 0, false - } - - switch level { - case "adaptive": - return -1, true - case "minimal": - return 0, true - case "off": - return 0, true - case "low": - return 1024, true - case "medium": - return 4096, true - case "high": - return 8192, true - case "xhigh": - return 16384, true - default: - return 0, false - } -} - -func parseGeminiResponse(resp *geminiGenerateContentResponse) *LLMResponse { - contentParts := make([]string, 0) - reasoningParts := make([]string, 0) - toolCalls := make([]ToolCall, 0) - finishReason := "" - - for _, candidate := range resp.Candidates { - for _, part := range candidate.Content.Parts { - if part.Text != "" { - if part.Thought { - reasoningParts = append(reasoningParts, part.Text) - } else { - contentParts = append(contentParts, part.Text) - } - } - if part.FunctionCall != nil { - toolCalls = append(toolCalls, buildGeminiToolCall(part)) - } - } - if candidate.FinishReason != "" { - finishReason = candidate.FinishReason - } - } - - var usage *UsageInfo - if resp.UsageMetadata.TotalTokenCount > 0 { - usage = &UsageInfo{ - PromptTokens: resp.UsageMetadata.PromptTokenCount, - CompletionTokens: resp.UsageMetadata.CandidatesTokenCount, - TotalTokens: resp.UsageMetadata.TotalTokenCount, - } - } - - return &LLMResponse{ - Content: strings.Join(contentParts, ""), - ReasoningContent: strings.Join(reasoningParts, ""), - ToolCalls: toolCalls, - FinishReason: normalizeGeminiFinishReason(finishReason, len(toolCalls)), - Usage: usage, - } -} - -func parseGeminiStreamResponse( - ctx context.Context, - reader io.Reader, - onChunk func(StreamChunk), -) (*LLMResponse, error) { - var contentBuilder strings.Builder - var reasoningBuilder strings.Builder - var finishReason string - var usage *UsageInfo - - toolCallsByID := make(map[string]ToolCall) - toolCallOrder := make([]string, 0) - fallbackIndex := 0 - - scanner := bufio.NewScanner(reader) - scanner.Buffer(make([]byte, 0, 1024*1024), 10*1024*1024) - for scanner.Scan() { - if err := ctx.Err(); err != nil { - return nil, err - } - - line := scanner.Text() - if !strings.HasPrefix(line, "data: ") { - continue - } - data := strings.TrimSpace(strings.TrimPrefix(line, "data: ")) - if data == "" { - continue - } - if data == "[DONE]" { - break - } - - var chunk geminiGenerateContentResponse - if err := json.Unmarshal([]byte(data), &chunk); err != nil { - return nil, fmt.Errorf("invalid gemini stream chunk: %w", err) - } - - for _, candidate := range chunk.Candidates { - for _, part := range candidate.Content.Parts { - if part.Text != "" { - if part.Thought { - reasoningBuilder.WriteString(part.Text) - if onChunk != nil { - onChunk(StreamChunk{ReasoningContent: reasoningBuilder.String()}) - } - } else { - contentBuilder.WriteString(part.Text) - if onChunk != nil { - onChunk(StreamChunk{Content: contentBuilder.String()}) - } - } - } - if part.FunctionCall != nil { - tc := buildGeminiToolCall(part) - if strings.TrimSpace(tc.Name) == "" { - continue - } - - key := strings.TrimSpace(part.FunctionCall.ID) - if key == "" { - if len(toolCallOrder) > 0 { - lastKey := toolCallOrder[len(toolCallOrder)-1] - if lastTC, exists := toolCallsByID[lastKey]; exists && lastTC.Name == tc.Name { - key = lastKey - } - } - if key == "" { - fallbackIndex++ - key = fmt.Sprintf("%s#%d", tc.Name, fallbackIndex) - } - } - - tc.ID = key - if _, exists := toolCallsByID[key]; !exists { - toolCallOrder = append(toolCallOrder, key) - } - toolCallsByID[key] = tc - } - } - if candidate.FinishReason != "" { - finishReason = candidate.FinishReason - } - } - - if chunk.UsageMetadata.TotalTokenCount > 0 { - usage = &UsageInfo{ - PromptTokens: chunk.UsageMetadata.PromptTokenCount, - CompletionTokens: chunk.UsageMetadata.CandidatesTokenCount, - TotalTokens: chunk.UsageMetadata.TotalTokenCount, - } - } - } - - if err := scanner.Err(); err != nil { - return nil, fmt.Errorf("streaming read error: %w", err) - } - - toolCalls := make([]ToolCall, 0, len(toolCallOrder)) - for _, key := range toolCallOrder { - toolCalls = append(toolCalls, toolCallsByID[key]) - } - - return &LLMResponse{ - Content: contentBuilder.String(), - ReasoningContent: reasoningBuilder.String(), - ToolCalls: toolCalls, - FinishReason: normalizeGeminiFinishReason(finishReason, len(toolCalls)), - Usage: usage, - }, nil -} - -func normalizeGeminiFinishReason(reason string, toolCalls int) string { - if toolCalls > 0 { - return "tool_calls" - } - - switch strings.ToUpper(strings.TrimSpace(reason)) { - case "MAX_TOKENS": - return "length" - case "", "STOP": - return "stop" - default: - return strings.ToLower(strings.TrimSpace(reason)) - } -} - -func buildGeminiToolCall(part geminiPart) ToolCall { - if part.FunctionCall == nil { - return ToolCall{} - } - - args := part.FunctionCall.Args - if args == nil { - args = make(map[string]any) - } - argsJSON, _ := json.Marshal(args) - thoughtSignature := extractPartThoughtSignature(part.ThoughtSignature, part.ThoughtSignatureSnake) - - toolCall := ToolCall{ - ID: part.FunctionCall.ID, - Name: part.FunctionCall.Name, - Arguments: args, - ThoughtSignature: thoughtSignature, - Function: &FunctionCall{ - Name: part.FunctionCall.Name, - Arguments: string(argsJSON), - ThoughtSignature: thoughtSignature, - }, - } - - if thoughtSignature != "" { - toolCall.ExtraContent = &ExtraContent{ - Google: &GoogleExtra{ThoughtSignature: thoughtSignature}, - } - } - if strings.TrimSpace(toolCall.ID) == "" { - toolCall.ID = fmt.Sprintf("call_%s_%d", toolCall.Name, time.Now().UnixNano()) - } - - return toolCall -} - -func buildInlineMediaParts(media []string) []geminiPart { - parts := make([]geminiPart, 0, len(media)) - for _, mediaURL := range media { - mimeType, data, ok := parseBase64DataURL(mediaURL) - if !ok { - continue - } - parts = append(parts, geminiPart{ - InlineData: &geminiInlineData{ - MIMEType: mimeType, - Data: data, - }, - }) - } - return parts -} - -func buildGeminiFunctionResponse( - toolName string, - toolCallID string, - result string, - media []string, -) *geminiFunctionResponse { - response := &geminiFunctionResponse{ - ID: toolCallID, - Name: toolName, - Response: map[string]any{ - "result": result, - }, - } - - if parts := buildFunctionResponseMediaParts(media); len(parts) > 0 { - response.Parts = parts - } - - return response -} - -func buildFunctionResponseMediaParts(media []string) []geminiFunctionResponsePart { - parts := make([]geminiFunctionResponsePart, 0, len(media)) - for i, mediaURL := range media { - mimeType, data, ok := parseBase64DataURL(mediaURL) - if !ok { - continue - } - parts = append(parts, geminiFunctionResponsePart{ - InlineData: &geminiInlineData{ - MIMEType: mimeType, - Data: data, - DisplayName: defaultFunctionResponseDisplayName(mimeType, i+1), - }, - }) - } - return parts -} - -func defaultFunctionResponseDisplayName(mimeType string, index int) string { - suffix := "bin" - switch strings.ToLower(strings.TrimSpace(mimeType)) { - case "image/png": - suffix = "png" - case "image/jpeg": - suffix = "jpg" - case "image/webp": - suffix = "webp" - case "application/pdf": - suffix = "pdf" - case "text/plain": - suffix = "txt" - } - return fmt.Sprintf("attachment-%d.%s", index, suffix) -} - -func parseBase64DataURL(mediaURL string) (mimeType string, data string, ok bool) { - if !strings.HasPrefix(mediaURL, "data:") { - return "", "", false - } - - payload := strings.TrimPrefix(mediaURL, "data:") - header, data, found := strings.Cut(payload, ",") - if !found { - return "", "", false - } - mimeType, params, _ := strings.Cut(header, ";") - mimeType = strings.TrimSpace(mimeType) - data = strings.TrimSpace(data) - if mimeType == "" || data == "" { - return "", "", false - } - if !strings.Contains(strings.ToLower(params), "base64") { - return "", "", false - } - return mimeType, data, true -} - -func cloneAnyMap(in map[string]any) map[string]any { - if len(in) == 0 { - return nil - } - out := make(map[string]any, len(in)) - for k, v := range in { - out[k] = v - } - return out -} - -func cloneStringMap(in map[string]string) map[string]string { - if len(in) == 0 { - return nil - } - out := make(map[string]string, len(in)) - for k, v := range in { - out[k] = v - } - return out -} - -type geminiGenerateContentResponse struct { - Candidates []struct { - Content struct { - Role string `json:"role"` - Parts []geminiPart `json:"parts"` - } `json:"content"` - FinishReason string `json:"finishReason"` - } `json:"candidates"` - UsageMetadata struct { - PromptTokenCount int `json:"promptTokenCount"` - CandidatesTokenCount int `json:"candidatesTokenCount"` - TotalTokenCount int `json:"totalTokenCount"` - } `json:"usageMetadata"` -} - -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"` - ThoughtSignatureSnake string `json:"thought_signature,omitempty"` - InlineData *geminiInlineData `json:"inlineData,omitempty"` - FunctionCall *geminiFunctionCall `json:"functionCall,omitempty"` - FunctionResponse *geminiFunctionResponse `json:"functionResponse,omitempty"` -} - -type geminiInlineData struct { - MIMEType string `json:"mimeType"` - Data string `json:"data"` - DisplayName string `json:"displayName,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"` - Parts []geminiFunctionResponsePart `json:"parts,omitempty"` -} - -type geminiFunctionResponsePart struct { - InlineData *geminiInlineData `json:"inlineData,omitempty"` -} - -type geminiTool struct { - FunctionDeclarations []geminiFunctionDeclaration `json:"functionDeclarations"` -} - -type geminiFunctionDeclaration struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` - Parameters any `json:"parameters,omitempty"` -} diff --git a/pkg/providers/httpapi/gemini_provider_test.go b/pkg/providers/httpapi/gemini_provider_test.go deleted file mode 100644 index d0bb96dc..00000000 --- a/pkg/providers/httpapi/gemini_provider_test.go +++ /dev/null @@ -1,931 +0,0 @@ -package httpapi - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "net/http/httptest" - "strings" - "sync" - "testing" - "time" -) - -func TestGeminiProvider_ChatSeparatesThoughtAndToolCall(t *testing.T) { - var capturedBody map[string]any - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - t.Fatalf("method = %s, want POST", r.Method) - } - if !strings.Contains(r.URL.Path, ":generateContent") { - t.Fatalf("path = %s, expected generateContent endpoint", r.URL.Path) - } - if got := r.Header.Get("X-Goog-Api-Key"); got != "test-key" { - t.Fatalf("X-Goog-Api-Key = %q, want %q", got, "test-key") - } - if err := json.NewDecoder(r.Body).Decode(&capturedBody); err != nil { - t.Fatalf("decode request body: %v", err) - } - - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(map[string]any{ - "candidates": []any{ - map[string]any{ - "content": map[string]any{ - "role": "model", - "parts": []any{ - map[string]any{"text": "hidden", "thought": true}, - map[string]any{"text": "visible"}, - map[string]any{ - "functionCall": map[string]any{ - "id": "call_1", - "name": "search", - "args": map[string]any{"q": "hi"}, - }, - "thoughtSignature": "sig-1", - }, - }, - }, - "finishReason": "STOP", - }, - }, - "usageMetadata": map[string]any{ - "promptTokenCount": 2, - "candidatesTokenCount": 3, - "totalTokenCount": 5, - }, - }) - })) - defer server.Close() - - provider := NewGeminiProvider("test-key", server.URL, "", "picoclaw-test", 0, nil, nil) - resp, err := provider.Chat( - t.Context(), - []Message{{Role: "user", Content: "hello"}}, - nil, - "gemini-3-flash-preview", - map[string]any{"thinking_level": "high"}, - ) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - if resp.Content != "visible" { - t.Fatalf("Content = %q, want %q", resp.Content, "visible") - } - if resp.ReasoningContent != "hidden" { - t.Fatalf("ReasoningContent = %q, want %q", resp.ReasoningContent, "hidden") - } - if resp.FinishReason != "tool_calls" { - t.Fatalf("FinishReason = %q, want %q", resp.FinishReason, "tool_calls") - } - if resp.Usage == nil || resp.Usage.TotalTokens != 5 { - t.Fatalf("Usage = %#v, expected total tokens = 5", resp.Usage) - } - if len(resp.ToolCalls) != 1 { - t.Fatalf("ToolCalls len = %d, want 1", len(resp.ToolCalls)) - } - if resp.ToolCalls[0].ID != "call_1" { - t.Fatalf("ToolCall ID = %q, want %q", resp.ToolCalls[0].ID, "call_1") - } - if resp.ToolCalls[0].Name != "search" { - t.Fatalf("ToolCall Name = %q, want %q", resp.ToolCalls[0].Name, "search") - } - if resp.ToolCalls[0].ThoughtSignature != "sig-1" { - t.Fatalf("ToolCall ThoughtSignature = %q, want %q", resp.ToolCalls[0].ThoughtSignature, "sig-1") - } - if resp.ToolCalls[0].Function == nil || !strings.Contains(resp.ToolCalls[0].Function.Arguments, `"q":"hi"`) { - t.Fatalf("ToolCall Function arguments = %#v, want q=hi", resp.ToolCalls[0].Function) - } - - generationConfig, ok := capturedBody["generationConfig"].(map[string]any) - if !ok { - t.Fatalf("request missing generationConfig: %#v", capturedBody) - } - thinkingConfig, ok := generationConfig["thinkingConfig"].(map[string]any) - if !ok { - t.Fatalf("request missing thinkingConfig: %#v", generationConfig) - } - if includeThoughts, ok := thinkingConfig["includeThoughts"].(bool); !ok || !includeThoughts { - t.Fatalf("thinkingConfig.includeThoughts = %#v, want true", thinkingConfig["includeThoughts"]) - } - if got := thinkingConfig["thinkingLevel"]; got != "high" { - t.Fatalf("thinkingConfig.thinkingLevel = %#v, want %q", got, "high") - } -} - -func TestGeminiProvider_ChatStreamParsesThoughtTextAndToolCalls(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if !strings.Contains(r.URL.Path, ":streamGenerateContent") { - t.Fatalf("path = %s, expected streamGenerateContent endpoint", r.URL.Path) - } - if got := r.URL.Query().Get("alt"); got != "sse" { - t.Fatalf("alt query = %q, want %q", got, "sse") - } - - w.Header().Set("Content-Type", "text/event-stream") - flusher, ok := w.(http.Flusher) - if !ok { - t.Fatal("response writer is not flushable") - } - - chunks := []map[string]any{ - { - "candidates": []any{map[string]any{ - "content": map[string]any{ - "parts": []any{ - map[string]any{"text": "think ", "thought": true}, - map[string]any{"text": "Hello "}, - }, - }, - }}, - }, - { - "candidates": []any{map[string]any{ - "content": map[string]any{ - "parts": []any{ - map[string]any{"text": "World"}, - map[string]any{ - "functionCall": map[string]any{ - "id": "call_stream", - "name": "search", - "args": map[string]any{"q": "stream"}, - }, - }, - }, - }, - "finishReason": "STOP", - }}, - "usageMetadata": map[string]any{ - "promptTokenCount": 1, - "candidatesTokenCount": 2, - "totalTokenCount": 3, - }, - }, - } - - for _, chunk := range chunks { - raw, err := json.Marshal(chunk) - if err != nil { - t.Fatalf("marshal chunk: %v", err) - } - if _, err := fmt.Fprintf(w, "data: %s\n\n", raw); err != nil { - t.Fatalf("write chunk: %v", err) - } - flusher.Flush() - } - _, _ = fmt.Fprint(w, "data: [DONE]\n\n") - flusher.Flush() - })) - defer server.Close() - - provider := NewGeminiProvider("test-key", server.URL, "", "", 0, nil, nil) - updates := make([]string, 0) - resp, err := provider.ChatStream( - t.Context(), - []Message{{Role: "user", Content: "hello"}}, - nil, - "gemini-2.5-flash", - nil, - func(accumulated string) { - updates = append(updates, accumulated) - }, - ) - if err != nil { - t.Fatalf("ChatStream() error = %v", err) - } - if resp.Content != "Hello World" { - t.Fatalf("Content = %q, want %q", resp.Content, "Hello World") - } - if resp.ReasoningContent != "think " { - t.Fatalf("ReasoningContent = %q, want %q", resp.ReasoningContent, "think ") - } - if len(resp.ToolCalls) != 1 || resp.ToolCalls[0].ID != "call_stream" { - t.Fatalf("ToolCalls = %#v, want single call_stream", resp.ToolCalls) - } - if resp.FinishReason != "tool_calls" { - t.Fatalf("FinishReason = %q, want %q", resp.FinishReason, "tool_calls") - } - if resp.Usage == nil || resp.Usage.TotalTokens != 3 { - t.Fatalf("Usage = %#v, expected total tokens = 3", resp.Usage) - } - if len(updates) < 2 || updates[len(updates)-1] != "Hello World" { - t.Fatalf("stream updates = %#v, expected final accumulated text", updates) - } -} - -func TestGeminiProvider_ChatStreamEventsStreamsThoughtBeforeContent(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if !strings.Contains(r.URL.Path, ":streamGenerateContent") { - t.Fatalf("path = %s, expected streamGenerateContent endpoint", r.URL.Path) - } - w.Header().Set("Content-Type", "text/event-stream") - flusher, ok := w.(http.Flusher) - if !ok { - t.Fatal("response writer is not flushable") - } - - chunk := map[string]any{ - "candidates": []any{map[string]any{ - "content": map[string]any{ - "parts": []any{ - map[string]any{"text": "think", "thought": true}, - map[string]any{"text": "answer"}, - }, - }, - "finishReason": "STOP", - }}, - } - raw, err := json.Marshal(chunk) - if err != nil { - t.Fatalf("marshal chunk: %v", err) - } - _, _ = fmt.Fprintf(w, "data: %s\n\n", raw) - _, _ = fmt.Fprint(w, "data: [DONE]\n\n") - flusher.Flush() - })) - defer server.Close() - - provider := NewGeminiProvider("test-key", server.URL, "", "", 0, nil, nil) - events := make([]string, 0) - resp, err := provider.ChatStreamEvents( - t.Context(), - []Message{{Role: "user", Content: "hello"}}, - nil, - "gemini-2.5-flash", - nil, - func(chunk StreamChunk) { - if chunk.ReasoningContent != "" { - events = append(events, "reasoning:"+chunk.ReasoningContent) - } - if chunk.Content != "" { - events = append(events, "content:"+chunk.Content) - } - }, - ) - if err != nil { - t.Fatalf("ChatStreamEvents() error = %v", err) - } - if resp.Content != "answer" { - t.Fatalf("Content = %q, want %q", resp.Content, "answer") - } - if resp.ReasoningContent != "think" { - t.Fatalf("ReasoningContent = %q, want %q", resp.ReasoningContent, "think") - } - want := []string{"reasoning:think", "content:answer"} - if len(events) != len(want) { - t.Fatalf("events = %#v, want %#v", events, want) - } - for i := range want { - if events[i] != want[i] { - t.Fatalf("events = %#v, want %#v", events, want) - } - } -} - -type geminiBlockingReadCloser struct { - closeOnce sync.Once - closed chan struct{} -} - -func newGeminiBlockingReadCloser() *geminiBlockingReadCloser { - return &geminiBlockingReadCloser{closed: make(chan struct{})} -} - -func (r *geminiBlockingReadCloser) Read([]byte) (int, error) { - <-r.closed - return 0, io.ErrClosedPipe -} - -func (r *geminiBlockingReadCloser) Close() error { - r.closeOnce.Do(func() { - close(r.closed) - }) - return nil -} - -func TestGeminiStreamingReadIdleTimeoutClosesStalledBody(t *testing.T) { - body := newGeminiBlockingReadCloser() - wrapped := withGeminiStreamingReadIdleTimeout(body, 10*time.Millisecond) - - _, err := wrapped.Read(make([]byte, 1)) - if err == nil { - t.Fatal("expected stalled stream read to return an error") - } - if !strings.Contains(err.Error(), "gemini stream idle timeout") { - t.Fatalf("error = %v, want gemini stream idle timeout", err) - } -} - -func TestGeminiProvider_ChatStreamSkipsEmptyDataFrames(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/event-stream") - flusher, ok := w.(http.Flusher) - if !ok { - t.Fatal("response writer is not flushable") - } - - _, _ = fmt.Fprint(w, "data: \n\n") - flusher.Flush() - - chunk := map[string]any{ - "candidates": []any{map[string]any{ - "content": map[string]any{ - "parts": []any{map[string]any{"text": "ok"}}, - }, - "finishReason": "STOP", - }}, - } - raw, err := json.Marshal(chunk) - if err != nil { - t.Fatalf("marshal chunk: %v", err) - } - _, _ = fmt.Fprintf(w, "data: %s\n\n", raw) - flusher.Flush() - _, _ = fmt.Fprint(w, "data: [DONE]\n\n") - flusher.Flush() - })) - defer server.Close() - - provider := NewGeminiProvider("test-key", server.URL, "", "", 0, nil, nil) - resp, err := provider.ChatStream( - t.Context(), - []Message{{Role: "user", Content: "hello"}}, - nil, - "gemini-2.5-flash", - nil, - nil, - ) - if err != nil { - t.Fatalf("ChatStream() error = %v", err) - } - if resp.Content != "ok" { - t.Fatalf("Content = %q, want %q", resp.Content, "ok") - } -} - -func TestGeminiProvider_BuildRequestBody_PreservesComplexToolSchemasByDefault(t *testing.T) { - provider := NewGeminiProvider("test-key", "https://example.com/v1beta", "", "", 0, nil, nil) - schema := map[string]any{ - "type": "object", - "properties": map[string]any{ - "parent": map[string]any{ - "anyOf": []any{ - map[string]any{"$ref": "#/$defs/pageParent"}, - map[string]any{"$ref": "#/$defs/databaseParent"}, - }, - }, - }, - "$defs": map[string]any{ - "pageParent": map[string]any{ - "type": "object", - "properties": map[string]any{ - "page_id": map[string]any{"type": "string"}, - }, - "required": []any{"page_id"}, - }, - "databaseParent": map[string]any{ - "type": "object", - "properties": map[string]any{ - "database_id": map[string]any{"type": "string"}, - }, - "required": []any{"database_id"}, - }, - }, - } - - body := provider.buildRequestBody( - []Message{{Role: "user", Content: "hello"}}, - []ToolDefinition{{ - Type: "function", - Function: ToolFunctionDefinition{ - Name: "mcp_notion_create", - Description: "Create a Notion object", - Parameters: schema, - }, - }}, - "gemini-3-flash-preview", - nil, - ) - - tools, ok := body["tools"].([]geminiTool) - if !ok || len(tools) != 1 { - t.Fatalf("tools = %#v, want one geminiTool", body["tools"]) - } - got, ok := tools[0].FunctionDeclarations[0].Parameters.(map[string]any) - if !ok { - t.Fatalf("parameters = %#v, want map", tools[0].FunctionDeclarations[0].Parameters) - } - - if got["$defs"] == nil { - t.Fatalf("parameters = %#v, want raw schema with $defs preserved by default", got) - } -} - -func TestGeminiProvider_ChatStreamReturnsErrorOnInvalidDataFrame(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/event-stream") - flusher, ok := w.(http.Flusher) - if !ok { - t.Fatal("response writer is not flushable") - } - - _, _ = fmt.Fprint(w, "data: {invalid-json}\n\n") - flusher.Flush() - })) - defer server.Close() - - provider := NewGeminiProvider("test-key", server.URL, "", "", 0, nil, nil) - _, err := provider.ChatStream( - t.Context(), - []Message{{Role: "user", Content: "hello"}}, - nil, - "gemini-2.5-flash", - nil, - nil, - ) - if err == nil { - t.Fatal("ChatStream() expected error for invalid SSE data frame") - } - if !strings.Contains(err.Error(), "invalid gemini stream chunk") { - t.Fatalf("error = %v, want contains %q", err, "invalid gemini stream chunk") - } -} - -func TestGeminiProvider_BuildRequestBody_SetsBothThoughtSignatureFormats(t *testing.T) { - provider := NewGeminiProvider("test-key", "https://example.com/v1beta", "", "", 0, nil, nil) - - body := provider.buildRequestBody( - []Message{{ - Role: "assistant", - ToolCalls: []ToolCall{{ - ID: "call_1", - Name: "search", - Arguments: map[string]any{"q": "hello"}, - Function: &FunctionCall{ - Name: "search", - Arguments: `{"q":"hello"}`, - ThoughtSignature: "sig-1", - }, - }}, - }}, - nil, - "gemini-2.5-flash", - nil, - ) - - raw, err := json.Marshal(body) - if err != nil { - t.Fatalf("marshal request body: %v", err) - } - jsonBody := string(raw) - - if !strings.Contains(jsonBody, `"thoughtSignature":"sig-1"`) { - t.Fatalf("request body = %s, expected camelCase thoughtSignature", jsonBody) - } - if !strings.Contains(jsonBody, `"thought_signature":"sig-1"`) { - t.Fatalf( - "request body = %s, expected snake_case thought_signature for "+ - "Gemini 3.5 Flash Agentic compatibility", - jsonBody, - ) - } -} - -func TestGeminiProvider_ChatStreamCoalescesToolCallWithoutWireID(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/event-stream") - flusher, ok := w.(http.Flusher) - if !ok { - t.Fatal("response writer is not flushable") - } - - chunks := []map[string]any{ - { - "candidates": []any{map[string]any{ - "content": map[string]any{ - "parts": []any{ - map[string]any{ - "functionCall": map[string]any{ - "name": "search", - "args": map[string]any{"q": "first"}, - }, - }, - }, - }, - }}, - }, - { - "candidates": []any{map[string]any{ - "content": map[string]any{ - "parts": []any{ - map[string]any{ - "functionCall": map[string]any{ - "name": "search", - "args": map[string]any{"q": "second"}, - }, - }, - }, - }, - "finishReason": "STOP", - }}, - }, - } - - for _, chunk := range chunks { - raw, err := json.Marshal(chunk) - if err != nil { - t.Fatalf("marshal chunk: %v", err) - } - if _, err := fmt.Fprintf(w, "data: %s\n\n", raw); err != nil { - t.Fatalf("write chunk: %v", err) - } - flusher.Flush() - } - _, _ = fmt.Fprint(w, "data: [DONE]\n\n") - flusher.Flush() - })) - defer server.Close() - - provider := NewGeminiProvider("test-key", server.URL, "", "", 0, nil, nil) - resp, err := provider.ChatStream( - t.Context(), - []Message{{Role: "user", Content: "hello"}}, - nil, - "gemini-2.5-flash", - nil, - nil, - ) - if err != nil { - t.Fatalf("ChatStream() error = %v", err) - } - if len(resp.ToolCalls) != 1 { - t.Fatalf("ToolCalls len = %d, want 1", len(resp.ToolCalls)) - } - tc := resp.ToolCalls[0] - if tc.ID != "search#1" { - t.Fatalf("ToolCall ID = %q, want %q", tc.ID, "search#1") - } - if tc.Name != "search" { - t.Fatalf("ToolCall Name = %q, want %q", tc.Name, "search") - } - if argQ, ok := tc.Arguments["q"].(string); !ok || argQ != "second" { - t.Fatalf("ToolCall Arguments = %#v, want q=second", tc.Arguments) - } - if resp.FinishReason != "tool_calls" { - t.Fatalf("FinishReason = %q, want %q", resp.FinishReason, "tool_calls") - } -} - -func TestGeminiProvider_BuildRequestBodyIncludesMediaAndThinkingConfig(t *testing.T) { - provider := NewGeminiProvider("test-key", "https://example.com/v1beta", "", "", 0, nil, nil) - - body := provider.buildRequestBody( - []Message{{ - Role: "user", - Content: "analyze attachments", - Media: []string{ - "data:application/pdf;base64,UEZERGF0YQ==", - "data:image/png;base64,aW1hZ2VEYXRh", - }, - }}, - nil, - "gemini-3-flash-preview", - map[string]any{ - "thinking_level": "low", - "max_tokens": 128, - "temperature": 0.2, - }, - ) - - contents, ok := body["contents"].([]geminiContent) - if !ok || len(contents) != 1 { - t.Fatalf("contents = %#v, want one gemini content", body["contents"]) - } - parts := contents[0].Parts - mimeSet := map[string]bool{} - for _, part := range parts { - if part.InlineData != nil { - mimeSet[part.InlineData.MIMEType] = true - } - } - if !mimeSet["application/pdf"] { - t.Fatalf("inline media missing application/pdf: %#v", parts) - } - if !mimeSet["image/png"] { - t.Fatalf("inline media missing image/png: %#v", parts) - } - - generationConfig, ok := body["generationConfig"].(map[string]any) - if !ok { - t.Fatalf("generationConfig = %#v, want map", body["generationConfig"]) - } - if got := generationConfig["maxOutputTokens"]; got != 128 { - t.Fatalf("maxOutputTokens = %#v, want 128", got) - } - if got := generationConfig["temperature"]; got != 0.2 { - t.Fatalf("temperature = %#v, want 0.2", got) - } - thinkingConfig, ok := generationConfig["thinkingConfig"].(map[string]any) - if !ok { - t.Fatalf("thinkingConfig = %#v, want map", generationConfig["thinkingConfig"]) - } - if includeThoughts, ok := thinkingConfig["includeThoughts"].(bool); !ok || !includeThoughts { - t.Fatalf("includeThoughts = %#v, want true", thinkingConfig["includeThoughts"]) - } - if got := thinkingConfig["thinkingLevel"]; got != "low" { - t.Fatalf("thinkingLevel = %#v, want %q", got, "low") - } -} - -func TestGeminiProvider_BuildRequestBody_UsesThinkingBudgetForGemini25(t *testing.T) { - provider := NewGeminiProvider("test-key", "https://example.com/v1beta", "", "", 0, nil, nil) - body := provider.buildRequestBody( - []Message{{Role: "user", Content: "hello"}}, - nil, - "gemini-2.5-flash", - map[string]any{"thinking_level": "medium"}, - ) - - generationConfig, ok := body["generationConfig"].(map[string]any) - if !ok { - t.Fatalf("generationConfig = %#v, want map", body["generationConfig"]) - } - thinkingConfig, ok := generationConfig["thinkingConfig"].(map[string]any) - if !ok { - t.Fatalf("thinkingConfig = %#v, want map", generationConfig["thinkingConfig"]) - } - if got := thinkingConfig["thinkingBudget"]; got != 4096 { - t.Fatalf("thinkingBudget = %#v, want 4096", got) - } - if _, hasLevel := thinkingConfig["thinkingLevel"]; hasLevel { - t.Fatalf("thinkingLevel should not be set for Gemini 2.5: %#v", thinkingConfig) - } -} - -func TestGeminiProvider_BuildRequestBody_OmitsThinkingConfigForGemini20(t *testing.T) { - provider := NewGeminiProvider("test-key", "https://example.com/v1beta", "", "", 0, nil, nil) - body := provider.buildRequestBody( - []Message{{Role: "user", Content: "hello"}}, - nil, - "gemini-2.0-flash-exp", - map[string]any{"thinking_level": "high"}, - ) - - if _, ok := body["generationConfig"]; ok { - t.Fatalf("generationConfig should be omitted for Gemini 2.0 when only thinking_level is set: %#v", body) - } -} - -func TestGeminiProvider_BuildRequestBody_DefaultsThinkingOffForGemini25(t *testing.T) { - provider := NewGeminiProvider("test-key", "https://example.com/v1beta", "", "", 0, nil, nil) - body := provider.buildRequestBody( - []Message{{Role: "user", Content: "hello"}}, - nil, - "gemini-2.5-flash", - nil, - ) - - generationConfig, ok := body["generationConfig"].(map[string]any) - if !ok { - t.Fatalf("generationConfig = %#v, want map", body["generationConfig"]) - } - thinkingConfig, ok := generationConfig["thinkingConfig"].(map[string]any) - if !ok { - t.Fatalf("thinkingConfig = %#v, want map", generationConfig["thinkingConfig"]) - } - if got := thinkingConfig["thinkingBudget"]; got != 0 { - t.Fatalf("thinkingBudget = %#v, want 0 for default/off", got) - } - if includeThoughts, ok := thinkingConfig["includeThoughts"].(bool); !ok || includeThoughts { - t.Fatalf("includeThoughts = %#v, want false for default/off", thinkingConfig["includeThoughts"]) - } -} - -func TestGeminiProvider_BuildRequestBody_DefaultsThinkingOffForGemini3(t *testing.T) { - provider := NewGeminiProvider("test-key", "https://example.com/v1beta", "", "", 0, nil, nil) - body := provider.buildRequestBody( - []Message{{Role: "user", Content: "hello"}}, - nil, - "gemini-3-flash-preview", - nil, - ) - - generationConfig, ok := body["generationConfig"].(map[string]any) - if !ok { - t.Fatalf("generationConfig = %#v, want map", body["generationConfig"]) - } - thinkingConfig, ok := generationConfig["thinkingConfig"].(map[string]any) - if !ok { - t.Fatalf("thinkingConfig = %#v, want map", generationConfig["thinkingConfig"]) - } - if got := thinkingConfig["thinkingLevel"]; got != "minimal" { - t.Fatalf("thinkingLevel = %#v, want minimal for default/off", got) - } - if includeThoughts, ok := thinkingConfig["includeThoughts"].(bool); !ok || includeThoughts { - t.Fatalf("includeThoughts = %#v, want false for default/off", thinkingConfig["includeThoughts"]) - } -} - -func TestGeminiProvider_BuildRequestBody_DefaultsThinkingOffForGemini25Pro(t *testing.T) { - provider := NewGeminiProvider("test-key", "https://example.com/v1beta", "", "", 0, nil, nil) - body := provider.buildRequestBody( - []Message{{Role: "user", Content: "hello"}}, - nil, - "gemini-2.5-pro", - nil, - ) - - generationConfig, ok := body["generationConfig"].(map[string]any) - if !ok { - t.Fatalf("generationConfig = %#v, want map", body["generationConfig"]) - } - thinkingConfig, ok := generationConfig["thinkingConfig"].(map[string]any) - if !ok { - t.Fatalf("thinkingConfig = %#v, want map", generationConfig["thinkingConfig"]) - } - if includeThoughts, ok := thinkingConfig["includeThoughts"].(bool); !ok || includeThoughts { - t.Fatalf("includeThoughts = %#v, want false for default/off", thinkingConfig["includeThoughts"]) - } - if _, hasBudget := thinkingConfig["thinkingBudget"]; hasBudget { - t.Fatalf("thinkingBudget should be omitted for Gemini 2.5 Pro default/off: %#v", thinkingConfig) - } -} - -func TestGeminiProvider_BuildRequestBody_DefaultsThinkingOffForGemini31Pro(t *testing.T) { - provider := NewGeminiProvider("test-key", "https://example.com/v1beta", "", "", 0, nil, nil) - body := provider.buildRequestBody( - []Message{{Role: "user", Content: "hello"}}, - nil, - "gemini-3.1-pro", - nil, - ) - - generationConfig, ok := body["generationConfig"].(map[string]any) - if !ok { - t.Fatalf("generationConfig = %#v, want map", body["generationConfig"]) - } - thinkingConfig, ok := generationConfig["thinkingConfig"].(map[string]any) - if !ok { - t.Fatalf("thinkingConfig = %#v, want map", generationConfig["thinkingConfig"]) - } - if includeThoughts, ok := thinkingConfig["includeThoughts"].(bool); !ok || includeThoughts { - t.Fatalf("includeThoughts = %#v, want false for default/off", thinkingConfig["includeThoughts"]) - } - if _, hasLevel := thinkingConfig["thinkingLevel"]; hasLevel { - t.Fatalf("thinkingLevel should be omitted for Gemini 3.1 Pro default/off: %#v", thinkingConfig) - } -} - -func TestGeminiProvider_BuildRequestBody_PreservesMultipleSystemMessages(t *testing.T) { - provider := NewGeminiProvider("test-key", "https://example.com/v1beta", "", "", 0, nil, nil) - body := provider.buildRequestBody( - []Message{ - {Role: "system", Content: "You are helpful."}, - {Role: "system", Content: "Be concise."}, - {Role: "user", Content: "hello"}, - }, - nil, - "gemini-3-flash-preview", - nil, - ) - - systemInstruction, ok := body["systemInstruction"].(*geminiContent) - if !ok || systemInstruction == nil { - t.Fatalf("systemInstruction = %#v, want *geminiContent", body["systemInstruction"]) - } - if len(systemInstruction.Parts) != 2 { - t.Fatalf("systemInstruction.Parts len = %d, want 2", len(systemInstruction.Parts)) - } - if systemInstruction.Parts[0].Text != "You are helpful." || systemInstruction.Parts[1].Text != "Be concise." { - t.Fatalf("systemInstruction.Parts = %#v, want ordered system prompts", systemInstruction.Parts) - } -} - -func TestGeminiProvider_BuildRequestBody_PreservesToolResponseMedia(t *testing.T) { - provider := NewGeminiProvider("test-key", "https://example.com/v1beta", "", "", 0, nil, nil) - body := provider.buildRequestBody( - []Message{ - { - Role: "assistant", - ToolCalls: []ToolCall{{ - ID: "call_1", - Name: "load_image", - Arguments: map[string]any{"path": "demo.png"}, - }}, - }, - { - Role: "tool", - ToolCallID: "call_1", - Content: "tool result", - Media: []string{ - "data:image/png;base64,aW1hZ2VEYXRh", - "data:application/pdf;base64,UEZERGF0YQ==", - }, - }, - }, - nil, - "gemini-3-flash-preview", - nil, - ) - - contents, ok := body["contents"].([]geminiContent) - if !ok || len(contents) != 2 { - t.Fatalf("contents = %#v, want two content entries", body["contents"]) - } - parts := contents[1].Parts - if len(parts) != 1 || parts[0].FunctionResponse == nil { - t.Fatalf("tool response part = %#v, want functionResponse", parts) - } - response := parts[0].FunctionResponse - if response.Name != "load_image" { - t.Fatalf("functionResponse.Name = %q, want %q", response.Name, "load_image") - } - if response.Response["result"] != "tool result" { - t.Fatalf("functionResponse.Response = %#v, want result=tool result", response.Response) - } - if len(response.Parts) != 2 { - t.Fatalf("functionResponse.Parts len = %d, want 2", len(response.Parts)) - } -} - -func TestGeminiProvider_ChatAllowsCustomAuthHeaderWithoutAPIKey(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if got := r.Header.Get("Authorization"); got != "Bearer test-token" { - t.Fatalf("Authorization = %q, want %q", got, "Bearer test-token") - } - if got := r.Header.Get("X-Goog-Api-Key"); got != "" { - t.Fatalf("X-Goog-Api-Key = %q, want empty", got) - } - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(map[string]any{ - "candidates": []any{ - map[string]any{ - "content": map[string]any{ - "parts": []any{map[string]any{"text": "ok"}}, - }, - "finishReason": "STOP", - }, - }, - }) - })) - defer server.Close() - - provider := NewGeminiProvider( - "", - server.URL, - "", - "", - 0, - nil, - map[string]string{"Authorization": "Bearer test-token"}, - ) - - resp, err := provider.Chat( - t.Context(), - []Message{{Role: "user", Content: "hello"}}, - nil, - "gemini-2.5-flash", - nil, - ) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - if resp.Content != "ok" { - t.Fatalf("Content = %q, want %q", resp.Content, "ok") - } -} - -func TestGeminiProvider_ChatAllowsMissingAPIKeyForCustomAPIBase(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if got := r.Header.Get("X-Goog-Api-Key"); got != "" { - t.Fatalf("X-Goog-Api-Key = %q, want empty", got) - } - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(map[string]any{ - "candidates": []any{ - map[string]any{ - "content": map[string]any{"parts": []any{map[string]any{"text": "ok"}}}, - "finishReason": "STOP", - }, - }, - }) - })) - defer server.Close() - - provider := NewGeminiProvider("", server.URL, "", "", 0, nil, nil) - resp, err := provider.Chat( - t.Context(), - []Message{{Role: "user", Content: "hello"}}, - nil, - "gemini-2.5-flash", - nil, - ) - if err != nil { - t.Fatalf("Chat() error = %v", err) - } - if resp.Content != "ok" { - t.Fatalf("Content = %q, want %q", resp.Content, "ok") - } -} diff --git a/pkg/providers/httpapi_facade.go b/pkg/providers/httpapi_facade.go index fea92dc4..498e3655 100644 --- a/pkg/providers/httpapi_facade.go +++ b/pkg/providers/httpapi_facade.go @@ -3,22 +3,9 @@ package providers import httpapi "github.com/sipeed/picoclaw/pkg/providers/httpapi" type ( - GeminiProvider = httpapi.GeminiProvider - HTTPProvider = httpapi.HTTPProvider + HTTPProvider = httpapi.HTTPProvider ) -func NewGeminiProvider( - apiKey string, - apiBase string, - proxy string, - userAgent string, - requestTimeoutSeconds int, - extraBody map[string]any, - customHeaders map[string]string, -) *GeminiProvider { - return httpapi.NewGeminiProvider(apiKey, apiBase, proxy, userAgent, requestTimeoutSeconds, extraBody, customHeaders) -} - func NewHTTPProvider(apiKey, apiBase, proxy string) *HTTPProvider { return httpapi.NewHTTPProvider(apiKey, apiBase, proxy) } diff --git a/pkg/providers/legacy_provider.go b/pkg/providers/legacy_provider.go index 9c35c081..b2b43299 100644 --- a/pkg/providers/legacy_provider.go +++ b/pkg/providers/legacy_provider.go @@ -135,7 +135,7 @@ func modelConfigTemplateScore(modelCfg *config.ModelConfig, defaultProvider stri } } } - if strings.TrimSpace(modelCfg.AuthMethod) != "" || strings.TrimSpace(modelCfg.ConnectMode) != "" { + if strings.TrimSpace(modelCfg.AuthMethod) != "" { score += 8 } if modelCfg.Enabled { @@ -161,11 +161,6 @@ func CreateProvider(cfg *config.Config) (LLMProvider, string, error) { return nil, "", fmt.Errorf("model %q not found in model_list: %w", model, err) } - // Inject global workspace if not set in model config - if modelCfg.Workspace == "" { - modelCfg.Workspace = cfg.WorkspacePath() - } - // Use factory to create provider provider, modelID, err := CreateProviderFromConfig(modelCfg) if err != nil { diff --git a/pkg/providers/model_ref_test.go b/pkg/providers/model_ref_test.go index 57438a44..82e5a723 100644 --- a/pkg/providers/model_ref_test.go +++ b/pkg/providers/model_ref_test.go @@ -62,31 +62,10 @@ func TestNormalizeProvider(t *testing.T) { }{ {"OpenAI", "openai"}, {"ANTHROPIC", "anthropic"}, - {"z.ai", "zai"}, - {"z-ai", "zai"}, - {"Z.AI", "zai"}, - {"qwen", "qwen-portal"}, {"gpt", "openai"}, {"claude", "anthropic"}, - {"glm", "zhipu"}, - {"google", "gemini"}, - {"google-antigravity", "antigravity"}, - {"groq", "groq"}, - {"azure-openai", "azure"}, - {"claudecli", "claude-cli"}, - {"codexcli", "codex-cli"}, - {"copilot", "github-copilot"}, - {"g4f", "gpt4free"}, - // Alibaba Coding Plan aliases - {"alibaba-coding", "alibaba-coding"}, - {"coding-plan", "alibaba-coding"}, - {"qwen-coding", "alibaba-coding"}, - {"alibaba-coding-anthropic", "alibaba-coding-anthropic"}, - {"coding-plan-anthropic", "alibaba-coding-anthropic"}, - // Qwen international aliases - {"qwen-international", "qwen-intl"}, - {"dashscope-intl", "qwen-intl"}, - {"dashscope-us", "qwen-us"}, + {"anthropic-messages", "anthropic"}, + {"unsupported", "unsupported"}, {"", ""}, } @@ -107,7 +86,7 @@ func TestModelKey(t *testing.T) { {"openai", "gpt-4", "openai/gpt-4"}, {"Anthropic", "Claude-Opus", "anthropic/claude-opus"}, {"claude", "sonnet", "anthropic/sonnet"}, - {"z.ai", "Model-X", "zai/model-x"}, + {"GPT", "Model-X", "openai/model-x"}, } for _, tt := range tests { @@ -119,12 +98,12 @@ func TestModelKey(t *testing.T) { } func TestParseModelRef_ProviderNormalization(t *testing.T) { - ref := ParseModelRef("Z.AI/model-x", "default") + ref := ParseModelRef("GPT/model-x", "default") if ref == nil { t.Fatal("expected non-nil ref") } - if ref.Provider != "zai" { - t.Errorf("provider = %q, want zai", ref.Provider) + if ref.Provider != "openai" { + t.Errorf("provider = %q, want openai", ref.Provider) } } @@ -163,16 +142,3 @@ func TestParseModelRef_UnknownPrefixPreservesEmptyDefaultProvider(t *testing.T) t.Fatalf("model = %q, want full original model ID", ref.Model) } } - -func TestParseModelRef_KnownNonSelectableProvider(t *testing.T) { - ref := ParseModelRef("bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0", "openai") - if ref == nil { - t.Fatal("expected non-nil ref") - } - if ref.Provider != "bedrock" { - t.Fatalf("provider = %q, want bedrock", ref.Provider) - } - if ref.Model != "us.anthropic.claude-sonnet-4-20250514-v1:0" { - t.Fatalf("model = %q, want preserved bedrock model ID", ref.Model) - } -} diff --git a/pkg/providers/oauth/antigravity_provider.go b/pkg/providers/oauth/antigravity_provider.go deleted file mode 100644 index abf1e4bd..00000000 --- a/pkg/providers/oauth/antigravity_provider.go +++ /dev/null @@ -1,691 +0,0 @@ -package oauthprovider - -import ( - "bufio" - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "math/rand" - "net/http" - "strings" - "time" - - "github.com/sipeed/picoclaw/pkg/auth" - "github.com/sipeed/picoclaw/pkg/logger" - "github.com/sipeed/picoclaw/pkg/providers/common" -) - -const ( - antigravityBaseURL = "https://cloudcode-pa.googleapis.com" - antigravityDefaultModel = "gemini-3-flash" - antigravityUserAgent = "antigravity" - antigravityXGoogClient = "google-cloud-sdk vscode_cloudshelleditor/0.1" - antigravityVersion = "1.15.8" -) - -// AntigravityProvider implements LLMProvider using Google's Cloud Code Assist (Antigravity) API. -// This provider authenticates via Google OAuth and provides access to models like Claude and Gemini -// through Google's infrastructure. -type AntigravityProvider struct { - tokenSource func() (string, string, error) // Returns (accessToken, projectID, error) - httpClient *http.Client -} - -// NewAntigravityProvider creates a new Antigravity provider using stored auth credentials. -func NewAntigravityProvider() *AntigravityProvider { - return &AntigravityProvider{ - tokenSource: createAntigravityTokenSource(), - httpClient: &http.Client{ - Timeout: 120 * time.Second, - }, - } -} - -// Chat implements LLMProvider.Chat using the Cloud Code Assist v1internal API. -// The v1internal endpoint wraps the standard Gemini request in an envelope with -// project, model, request, requestType, userAgent, and requestId fields. -func (p *AntigravityProvider) Chat( - ctx context.Context, - messages []Message, - tools []ToolDefinition, - model string, - options map[string]any, -) (*LLMResponse, error) { - accessToken, projectID, err := p.tokenSource() - if err != nil { - return nil, fmt.Errorf("antigravity auth: %w", err) - } - - if model == "" || model == "antigravity" || model == "google-antigravity" { - model = antigravityDefaultModel - } - // Strip provider prefixes if present - model = strings.TrimPrefix(model, "google-antigravity/") - model = strings.TrimPrefix(model, "antigravity/") - - logger.DebugCF("provider.antigravity", "Starting chat", map[string]any{ - "model": model, - "project": projectID, - "requestId": fmt.Sprintf("agent-%d-%s", time.Now().UnixMilli(), randomString(9)), - }) - - // Build the inner Gemini-format request - innerRequest := p.buildRequest(messages, tools, model, options) - - // Wrap in v1internal envelope (matches pi-ai SDK format) - envelope := map[string]any{ - "project": projectID, - "model": model, - "request": innerRequest, - "requestType": "agent", - "userAgent": antigravityUserAgent, - "requestId": fmt.Sprintf("agent-%d-%s", time.Now().UnixMilli(), randomString(9)), - } - - bodyBytes, err := json.Marshal(envelope) - if err != nil { - return nil, fmt.Errorf("marshaling request: %w", err) - } - - // Build API URL — uses Cloud Code Assist v1internal streaming endpoint - apiURL := fmt.Sprintf("%s/v1internal:streamGenerateContent?alt=sse", antigravityBaseURL) - - req, err := http.NewRequestWithContext(ctx, "POST", apiURL, bytes.NewReader(bodyBytes)) - if err != nil { - return nil, fmt.Errorf("creating request: %w", err) - } - - // Headers matching the pi-ai SDK antigravity format - clientMetadata, _ := json.Marshal(map[string]string{ - "ideType": "IDE_UNSPECIFIED", - "platform": "PLATFORM_UNSPECIFIED", - "pluginType": "GEMINI", - }) - req.Header.Set("Authorization", "Bearer "+accessToken) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Accept", "text/event-stream") - req.Header.Set("User-Agent", fmt.Sprintf("antigravity/%s linux/amd64", antigravityVersion)) - req.Header.Set("X-Goog-Api-Client", antigravityXGoogClient) - req.Header.Set("Client-Metadata", string(clientMetadata)) - - resp, err := p.httpClient.Do(req) - if err != nil { - return nil, fmt.Errorf("antigravity API call: %w", err) - } - defer resp.Body.Close() - - respBody, err := io.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("reading response: %w", err) - } - - if resp.StatusCode != http.StatusOK { - logger.ErrorCF("provider.antigravity", "API call failed", map[string]any{ - "status_code": resp.StatusCode, - "response": string(respBody), - "model": model, - }) - - return nil, p.parseAntigravityError(resp.StatusCode, respBody) - } - - // Response is always SSE from streamGenerateContent — each line is "data: {...}" - // with a "response" wrapper containing the standard Gemini response - llmResp, err := p.parseSSEResponse(string(respBody)) - if err != nil { - return nil, err - } - - // Check for empty response (some models might return valid success but empty text) - if llmResp.Content == "" && len(llmResp.ToolCalls) == 0 { - return nil, fmt.Errorf( - "antigravity: model returned an empty response (this model might be invalid or restricted)", - ) - } - - return llmResp, nil -} - -// GetDefaultModel returns the default model identifier. -func (p *AntigravityProvider) GetDefaultModel() string { - return antigravityDefaultModel -} - -// --- Request building --- - -type antigravityRequest struct { - Contents []antigravityContent `json:"contents"` - Tools []antigravityTool `json:"tools,omitempty"` - SystemPrompt *antigravitySystemPrompt `json:"systemInstruction,omitempty"` - Config *antigravityGenConfig `json:"generationConfig,omitempty"` -} - -type antigravityContent struct { - Role string `json:"role"` - Parts []antigravityPart `json:"parts"` -} - -type antigravityPart struct { - Text string `json:"text,omitempty"` - ThoughtSignature string `json:"thoughtSignature,omitempty"` - ThoughtSignatureSnake string `json:"thought_signature,omitempty"` - FunctionCall *antigravityFunctionCall `json:"functionCall,omitempty"` - FunctionResponse *antigravityFunctionResponse `json:"functionResponse,omitempty"` -} - -type antigravityFunctionCall struct { - Name string `json:"name"` - Args map[string]any `json:"args"` -} - -type antigravityFunctionResponse struct { - Name string `json:"name"` - Response map[string]any `json:"response"` -} - -type antigravityTool struct { - FunctionDeclarations []antigravityFuncDecl `json:"functionDeclarations"` -} - -type antigravityFuncDecl struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` - Parameters any `json:"parameters,omitempty"` -} - -type antigravitySystemPrompt struct { - Parts []antigravityPart `json:"parts"` -} - -type antigravityGenConfig struct { - MaxOutputTokens int `json:"maxOutputTokens,omitempty"` - Temperature float64 `json:"temperature,omitempty"` -} - -func (p *AntigravityProvider) buildRequest( - messages []Message, - tools []ToolDefinition, - model string, - options map[string]any, -) antigravityRequest { - req := antigravityRequest{} - toolCallNames := make(map[string]string) - - // Build contents from messages - for _, msg := range messages { - switch msg.Role { - case "system": - req.SystemPrompt = &antigravitySystemPrompt{ - Parts: []antigravityPart{{Text: msg.Content}}, - } - case "user": - if msg.ToolCallID != "" { - toolName := common.ResolveToolResponseName(msg.ToolCallID, toolCallNames) - // Tool result - req.Contents = append(req.Contents, antigravityContent{ - Role: "user", - Parts: []antigravityPart{{ - FunctionResponse: &antigravityFunctionResponse{ - Name: toolName, - Response: map[string]any{ - "result": msg.Content, - }, - }, - }}, - }) - } else { - req.Contents = append(req.Contents, antigravityContent{ - Role: "user", - Parts: []antigravityPart{{Text: msg.Content}}, - }) - } - case "assistant": - content := antigravityContent{ - Role: "model", - } - if msg.Content != "" { - content.Parts = append(content.Parts, antigravityPart{Text: msg.Content}) - } - for _, tc := range msg.ToolCalls { - toolName, toolArgs, thoughtSignature := common.NormalizeStoredToolCall(tc) - if toolName == "" { - logger.WarnCF( - "provider.antigravity", - "Skipping tool call with empty name in history", - map[string]any{ - "tool_call_id": tc.ID, - }, - ) - continue - } - if tc.ID != "" { - toolCallNames[tc.ID] = toolName - } - content.Parts = append(content.Parts, antigravityPart{ - ThoughtSignature: thoughtSignature, - ThoughtSignatureSnake: thoughtSignature, - FunctionCall: &antigravityFunctionCall{ - Name: toolName, - Args: toolArgs, - }, - }) - } - if len(content.Parts) > 0 { - req.Contents = append(req.Contents, content) - } - case "tool": - toolName := common.ResolveToolResponseName(msg.ToolCallID, toolCallNames) - req.Contents = append(req.Contents, antigravityContent{ - Role: "user", - Parts: []antigravityPart{{ - FunctionResponse: &antigravityFunctionResponse{ - Name: toolName, - Response: map[string]any{ - "result": msg.Content, - }, - }, - }}, - }) - } - } - - // Build tools - if len(tools) > 0 { - var funcDecls []antigravityFuncDecl - for _, t := range tools { - if t.Type != "function" { - continue - } - funcDecls = append(funcDecls, antigravityFuncDecl{ - Name: t.Function.Name, - Description: t.Function.Description, - Parameters: t.Function.Parameters, - }) - } - if len(funcDecls) > 0 { - req.Tools = []antigravityTool{{FunctionDeclarations: funcDecls}} - } - } - - // Generation config - config := &antigravityGenConfig{} - if val, ok := options["max_tokens"]; ok { - if maxTokens, ok := val.(int); ok && maxTokens > 0 { - config.MaxOutputTokens = maxTokens - } else if maxTokens, ok := val.(float64); ok && maxTokens > 0 { - config.MaxOutputTokens = int(maxTokens) - } - } - if temp, ok := options["temperature"].(float64); ok { - config.Temperature = temp - } - if config.MaxOutputTokens > 0 || config.Temperature > 0 { - req.Config = config - } - - return req -} - -// --- Response parsing --- - -type antigravityJSONResponse struct { - Candidates []struct { - Content struct { - Parts []struct { - Text string `json:"text,omitempty"` - Thought bool `json:"thought,omitempty"` - ThoughtSignature string `json:"thoughtSignature,omitempty"` - ThoughtSignatureSnake string `json:"thought_signature,omitempty"` - FunctionCall *antigravityFunctionCall `json:"functionCall,omitempty"` - } `json:"parts"` - Role string `json:"role"` - } `json:"content"` - FinishReason string `json:"finishReason"` - } `json:"candidates"` - UsageMetadata struct { - PromptTokenCount int `json:"promptTokenCount"` - CandidatesTokenCount int `json:"candidatesTokenCount"` - TotalTokenCount int `json:"totalTokenCount"` - } `json:"usageMetadata"` -} - -func (p *AntigravityProvider) parseSSEResponse(body string) (*LLMResponse, error) { - var contentParts []string - var reasoningParts []string - var toolCalls []ToolCall - var usage *UsageInfo - var finishReason string - - scanner := bufio.NewScanner(strings.NewReader(body)) - for scanner.Scan() { - line := scanner.Text() - if !strings.HasPrefix(line, "data: ") { - continue - } - data := strings.TrimPrefix(line, "data: ") - if data == "[DONE]" { - break - } - - // v1internal SSE wraps the Gemini response in a "response" field - var sseChunk struct { - Response antigravityJSONResponse `json:"response"` - } - if err := json.Unmarshal([]byte(data), &sseChunk); err != nil { - continue - } - resp := sseChunk.Response - - for _, candidate := range resp.Candidates { - for _, part := range candidate.Content.Parts { - if part.Text != "" { - if part.Thought { - reasoningParts = append(reasoningParts, part.Text) - } else { - contentParts = append(contentParts, part.Text) - } - } - if part.FunctionCall != nil { - argumentsJSON, _ := json.Marshal(part.FunctionCall.Args) - toolCalls = append(toolCalls, ToolCall{ - ID: fmt.Sprintf("call_%s_%d", part.FunctionCall.Name, time.Now().UnixNano()), - Name: part.FunctionCall.Name, - Arguments: part.FunctionCall.Args, - Function: &FunctionCall{ - Name: part.FunctionCall.Name, - Arguments: string(argumentsJSON), - ThoughtSignature: extractPartThoughtSignature( - part.ThoughtSignature, - part.ThoughtSignatureSnake, - ), - }, - }) - } - } - if candidate.FinishReason != "" { - finishReason = candidate.FinishReason - } - } - - if resp.UsageMetadata.TotalTokenCount > 0 { - usage = &UsageInfo{ - PromptTokens: resp.UsageMetadata.PromptTokenCount, - CompletionTokens: resp.UsageMetadata.CandidatesTokenCount, - TotalTokens: resp.UsageMetadata.TotalTokenCount, - } - } - } - - mappedFinish := "stop" - if len(toolCalls) > 0 { - mappedFinish = "tool_calls" - } - if finishReason == "MAX_TOKENS" { - mappedFinish = "length" - } - - return &LLMResponse{ - Content: strings.Join(contentParts, ""), - ReasoningContent: strings.Join(reasoningParts, ""), - ToolCalls: toolCalls, - FinishReason: mappedFinish, - Usage: usage, - }, nil -} - -func extractPartThoughtSignature(thoughtSignature string, thoughtSignatureSnake string) string { - if thoughtSignature != "" { - return thoughtSignature - } - if thoughtSignatureSnake != "" { - return thoughtSignatureSnake - } - return "" -} - -// --- Token source --- - -func createAntigravityTokenSource() func() (string, string, error) { - return func() (string, string, error) { - cred, err := auth.GetCredential("google-antigravity") - if err != nil { - return "", "", fmt.Errorf("loading auth credentials: %w", err) - } - if cred == nil { - return "", "", fmt.Errorf( - "no credentials for google-antigravity. Run: picoclaw auth login --provider google-antigravity", - ) - } - - // Refresh if needed - if cred.NeedsRefresh() && cred.RefreshToken != "" { - oauthCfg := auth.GoogleAntigravityOAuthConfig() - refreshed, err := auth.RefreshAccessToken(cred, oauthCfg) - if err != nil { - return "", "", fmt.Errorf("refreshing token: %w", err) - } - refreshed.Email = cred.Email - if refreshed.ProjectID == "" { - refreshed.ProjectID = cred.ProjectID - } - if err := auth.SetCredential("google-antigravity", refreshed); err != nil { - return "", "", fmt.Errorf("saving refreshed token: %w", err) - } - cred = refreshed - } - - if cred.IsExpired() { - return "", "", fmt.Errorf( - "antigravity credentials expired. Run: picoclaw auth login --provider google-antigravity", - ) - } - - projectID := cred.ProjectID - if projectID == "" { - // Try to fetch project ID from API - fetchedID, err := FetchAntigravityProjectID(cred.AccessToken) - if err != nil { - logger.WarnCF("provider.antigravity", "Could not fetch project ID, using fallback", map[string]any{ - "error": err.Error(), - }) - projectID = "rising-fact-p41fc" // Default fallback (same as OpenCode) - } else { - projectID = fetchedID - cred.ProjectID = projectID - _ = auth.SetCredential("google-antigravity", cred) - } - } - - return cred.AccessToken, projectID, nil - } -} - -// FetchAntigravityProjectID retrieves the Google Cloud project ID from the loadCodeAssist endpoint. -func FetchAntigravityProjectID(accessToken string) (string, error) { - reqBody, _ := json.Marshal(map[string]any{ - "metadata": map[string]any{ - "ideType": "IDE_UNSPECIFIED", - "platform": "PLATFORM_UNSPECIFIED", - "pluginType": "GEMINI", - }, - }) - - req, err := http.NewRequest("POST", antigravityBaseURL+"/v1internal:loadCodeAssist", bytes.NewReader(reqBody)) - if err != nil { - return "", err - } - req.Header.Set("Authorization", "Bearer "+accessToken) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("User-Agent", antigravityUserAgent) - req.Header.Set("X-Goog-Api-Client", antigravityXGoogClient) - - client := &http.Client{Timeout: 15 * time.Second} - resp, err := client.Do(req) - if err != nil { - return "", err - } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return "", fmt.Errorf("reading loadCodeAssist response: %w", err) - } - if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf("loadCodeAssist failed: %s", string(body)) - } - - var result struct { - CloudAICompanionProject string `json:"cloudaicompanionProject"` - } - if err := json.Unmarshal(body, &result); err != nil { - return "", err - } - - if result.CloudAICompanionProject == "" { - return "", fmt.Errorf("no project ID in loadCodeAssist response") - } - - return result.CloudAICompanionProject, nil -} - -// FetchAntigravityModels fetches available models from the Cloud Code Assist API. -func FetchAntigravityModels(accessToken, projectID string) ([]AntigravityModelInfo, error) { - reqBody, _ := json.Marshal(map[string]any{ - "project": projectID, - }) - - req, err := http.NewRequest("POST", antigravityBaseURL+"/v1internal:fetchAvailableModels", bytes.NewReader(reqBody)) - if err != nil { - return nil, err - } - req.Header.Set("Authorization", "Bearer "+accessToken) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("User-Agent", antigravityUserAgent) - req.Header.Set("X-Goog-Api-Client", antigravityXGoogClient) - - client := &http.Client{Timeout: 15 * time.Second} - resp, err := client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("reading fetchAvailableModels response: %w", err) - } - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf( - "fetchAvailableModels failed (HTTP %d): %s", - resp.StatusCode, - truncateString(string(body), 200), - ) - } - - var result struct { - Models map[string]struct { - DisplayName string `json:"displayName"` - QuotaInfo struct { - RemainingFraction any `json:"remainingFraction"` - ResetTime string `json:"resetTime"` - IsExhausted bool `json:"isExhausted"` - } `json:"quotaInfo"` - } `json:"models"` - } - if err := json.Unmarshal(body, &result); err != nil { - return nil, fmt.Errorf("parsing models response: %w", err) - } - - var models []AntigravityModelInfo - for id, info := range result.Models { - models = append(models, AntigravityModelInfo{ - ID: id, - DisplayName: info.DisplayName, - IsExhausted: info.QuotaInfo.IsExhausted, - }) - } - - // Ensure gemini-3-flash-preview and gemini-3-flash are in the list if they aren't already - hasFlashPreview := false - hasFlash := false - for _, m := range models { - if m.ID == "gemini-3-flash-preview" { - hasFlashPreview = true - } - if m.ID == "gemini-3-flash" { - hasFlash = true - } - } - if !hasFlashPreview { - models = append(models, AntigravityModelInfo{ - ID: "gemini-3-flash-preview", - DisplayName: "Gemini 3 Flash (Preview)", - }) - } - if !hasFlash { - models = append(models, AntigravityModelInfo{ - ID: "gemini-3-flash", - DisplayName: "Gemini 3 Flash", - }) - } - - return models, nil -} - -type AntigravityModelInfo struct { - ID string `json:"id"` - DisplayName string `json:"display_name"` - IsExhausted bool `json:"is_exhausted"` -} - -// --- Helpers --- - -func truncateString(s string, maxLen int) string { - if len(s) <= maxLen { - return s - } - return s[:maxLen] + "..." -} - -func randomString(n int) string { - const letters = "abcdefghijklmnopqrstuvwxyz0123456789" - b := make([]byte, n) - for i := range b { - b[i] = letters[rand.Intn(len(letters))] - } - return string(b) -} - -func (p *AntigravityProvider) parseAntigravityError(statusCode int, body []byte) error { - var errResp struct { - Error struct { - Code int `json:"code"` - Message string `json:"message"` - Status string `json:"status"` - Details []map[string]any `json:"details"` - } `json:"error"` - } - - if err := json.Unmarshal(body, &errResp); err != nil { - return fmt.Errorf("antigravity API error (HTTP %d): %s", statusCode, truncateString(string(body), 500)) - } - - msg := errResp.Error.Message - if statusCode == 429 { - // Try to extract quota reset info - for _, detail := range errResp.Error.Details { - if typeVal, ok := detail["@type"].(string); ok && strings.HasSuffix(typeVal, "ErrorInfo") { - if metadata, ok := detail["metadata"].(map[string]any); ok { - if delay, ok := metadata["quotaResetDelay"].(string); ok { - return fmt.Errorf("antigravity rate limit exceeded: %s (reset in %s)", msg, delay) - } - } - } - } - return fmt.Errorf("antigravity rate limit exceeded: %s", msg) - } - - return fmt.Errorf("antigravity API error (%s): %s", errResp.Error.Status, msg) -} diff --git a/pkg/providers/oauth/antigravity_provider_test.go b/pkg/providers/oauth/antigravity_provider_test.go deleted file mode 100644 index d85e47df..00000000 --- a/pkg/providers/oauth/antigravity_provider_test.go +++ /dev/null @@ -1,142 +0,0 @@ -package oauthprovider - -import ( - "testing" -) - -func TestBuildRequestUsesFunctionFieldsWhenToolCallNameMissing(t *testing.T) { - p := &AntigravityProvider{} - - messages := []Message{ - { - Role: "assistant", - ToolCalls: []ToolCall{{ - ID: "call_read_file_123", - Function: &FunctionCall{ - Name: "read_file", - Arguments: `{"path":"README.md"}`, - }, - }}, - }, - { - Role: "tool", - ToolCallID: "call_read_file_123", - Content: "ok", - }, - } - - req := p.buildRequest(messages, nil, "", nil) - if len(req.Contents) != 2 { - t.Fatalf("expected 2 contents, got %d", len(req.Contents)) - } - - modelPart := req.Contents[0].Parts[0] - if modelPart.FunctionCall == nil { - t.Fatal("expected functionCall in assistant message") - } - if modelPart.FunctionCall.Name != "read_file" { - t.Fatalf("expected functionCall name read_file, got %q", modelPart.FunctionCall.Name) - } - if got := modelPart.FunctionCall.Args["path"]; got != "README.md" { - t.Fatalf("expected functionCall args[path] to be README.md, got %v", got) - } - - toolPart := req.Contents[1].Parts[0] - if toolPart.FunctionResponse == nil { - t.Fatal("expected functionResponse in tool message") - } - if toolPart.FunctionResponse.Name != "read_file" { - t.Fatalf("expected functionResponse name read_file, got %q", toolPart.FunctionResponse.Name) - } -} - -func TestParseSSEResponse_SplitsThoughtAndVisibleContent(t *testing.T) { - p := &AntigravityProvider{} - body := "data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"hidden reasoning\",\"thought\":true},{\"text\":\"visible answer\"}],\"role\":\"model\"},\"finishReason\":\"STOP\"}],\"usageMetadata\":{\"promptTokenCount\":8,\"candidatesTokenCount\":17,\"totalTokenCount\":216}}}\n" + - "data: [DONE]\n" - - resp, err := p.parseSSEResponse(body) - if err != nil { - t.Fatalf("parseSSEResponse() error = %v", err) - } - - if resp.Content != "visible answer" { - t.Fatalf("Content = %q, want %q", resp.Content, "visible answer") - } - if resp.ReasoningContent != "hidden reasoning" { - t.Fatalf("ReasoningContent = %q, want %q", resp.ReasoningContent, "hidden reasoning") - } - if resp.FinishReason != "stop" { - t.Fatalf("FinishReason = %q, want %q", resp.FinishReason, "stop") - } - if resp.Usage == nil || resp.Usage.TotalTokens != 216 { - t.Fatalf("Usage.TotalTokens = %v, want %d", resp.Usage, 216) - } -} - -func TestBuildRequest_PreservesComplexToolSchemasByDefault(t *testing.T) { - p := &AntigravityProvider{} - schema := map[string]any{ - "type": "object", - "properties": map[string]any{ - "parent": map[string]any{ - "anyOf": []any{ - map[string]any{"$ref": "#/$defs/pageParent"}, - map[string]any{"$ref": "#/$defs/databaseParent"}, - }, - }, - "icon": map[string]any{ - "anyOf": []any{ - map[string]any{"type": "null"}, - map[string]any{"$ref": "#/$defs/emoji"}, - }, - }, - }, - "$defs": map[string]any{ - "pageParent": map[string]any{ - "type": "object", - "properties": map[string]any{ - "page_id": map[string]any{"type": "string"}, - }, - "required": []any{"page_id"}, - }, - "databaseParent": map[string]any{ - "type": "object", - "properties": map[string]any{ - "database_id": map[string]any{"type": "string"}, - }, - "required": []any{"database_id"}, - }, - "emoji": map[string]any{ - "type": "string", - "pattern": "^:[a-z_]+:$", - }, - }, - } - - req := p.buildRequest( - []Message{{Role: "user", Content: "hello"}}, - []ToolDefinition{{ - Type: "function", - Function: ToolFunctionDefinition{ - Name: "mcp_notion_create", - Description: "Create a Notion object", - Parameters: schema, - }, - }}, - "gemini-3-flash", - nil, - ) - - if len(req.Tools) != 1 || len(req.Tools[0].FunctionDeclarations) != 1 { - t.Fatalf("request tools = %#v, want one function declaration", req.Tools) - } - - got, ok := req.Tools[0].FunctionDeclarations[0].Parameters.(map[string]any) - if !ok { - t.Fatalf("parameters = %#v, want map", req.Tools[0].FunctionDeclarations[0].Parameters) - } - if got["$defs"] == nil { - t.Fatalf("parameters = %#v, want raw schema with $defs preserved by default", got) - } -} diff --git a/pkg/providers/oauth_facade.go b/pkg/providers/oauth_facade.go index c1411777..d699c568 100644 --- a/pkg/providers/oauth_facade.go +++ b/pkg/providers/oauth_facade.go @@ -5,16 +5,10 @@ import ( ) type ( - AntigravityProvider = oauthprovider.AntigravityProvider - AntigravityModelInfo = oauthprovider.AntigravityModelInfo - ClaudeProvider = oauthprovider.ClaudeProvider - CodexProvider = oauthprovider.CodexProvider + ClaudeProvider = oauthprovider.ClaudeProvider + CodexProvider = oauthprovider.CodexProvider ) -func NewAntigravityProvider() *AntigravityProvider { - return oauthprovider.NewAntigravityProvider() -} - func NewClaudeProvider(token string) *ClaudeProvider { return oauthprovider.NewClaudeProvider(token) } @@ -43,14 +37,6 @@ func NewCodexProviderWithTokenSource( return oauthprovider.NewCodexProviderWithTokenSource(token, accountID, tokenSource) } -func FetchAntigravityProjectID(accessToken string) (string, error) { - return oauthprovider.FetchAntigravityProjectID(accessToken) -} - -func FetchAntigravityModels(accessToken, projectID string) ([]AntigravityModelInfo, error) { - return oauthprovider.FetchAntigravityModels(accessToken, projectID) -} - func createClaudeTokenSource() func() (string, error) { return oauthprovider.CreateClaudeTokenSource(getCredential) } diff --git a/pkg/providers/provider_metadata.go b/pkg/providers/provider_metadata.go index 6690cfc8..44a15060 100644 --- a/pkg/providers/provider_metadata.go +++ b/pkg/providers/provider_metadata.go @@ -4,159 +4,13 @@ import "strings" // providerMetadata defines the shared runtime defaults and aliases for a provider. type providerMetadata struct { - DefaultAPIBase string - EmptyAPIKeyAllowed bool - Aliases []string + DefaultAPIBase string + Aliases []string } var providerMetadataByName = map[string]providerMetadata{ - "openai": { - DefaultAPIBase: "https://api.openai.com/v1", - Aliases: []string{"gpt"}, - }, - "anthropic": { - DefaultAPIBase: "https://api.anthropic.com/v1", - Aliases: []string{"claude"}, - }, - "anthropic-messages": { - DefaultAPIBase: "https://api.anthropic.com/v1", - }, - "gemini": { - DefaultAPIBase: "https://generativelanguage.googleapis.com/v1beta", - Aliases: []string{"google"}, - }, - "deepseek": { - DefaultAPIBase: "https://api.deepseek.com/v1", - }, - "openrouter": { - DefaultAPIBase: "https://openrouter.ai/api/v1", - }, - "qwen-portal": { - DefaultAPIBase: "https://dashscope.aliyuncs.com/compatible-mode/v1", - Aliases: []string{"qwen"}, - }, - "qwen-intl": { - DefaultAPIBase: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1", - Aliases: []string{"qwen-international", "dashscope-intl"}, - }, - "moonshot": { - DefaultAPIBase: "https://api.moonshot.cn/v1", - }, - "volcengine": { - DefaultAPIBase: "https://ark.cn-beijing.volces.com/api/v3", - }, - "zhipu": { - DefaultAPIBase: "https://open.bigmodel.cn/api/paas/v4", - Aliases: []string{"glm"}, - }, - "groq": { - DefaultAPIBase: "https://api.groq.com/openai/v1", - }, - "mistral": { - DefaultAPIBase: "https://api.mistral.ai/v1", - }, - "nvidia": { - DefaultAPIBase: "https://integrate.api.nvidia.com/v1", - }, - "cerebras": { - DefaultAPIBase: "https://api.cerebras.ai/v1", - }, - "azure": { - Aliases: []string{"azure-openai"}, - }, - "bedrock": { - EmptyAPIKeyAllowed: true, - }, - "github-copilot": { - DefaultAPIBase: "localhost:4321", - EmptyAPIKeyAllowed: true, - Aliases: []string{"copilot"}, - }, - "antigravity": { - EmptyAPIKeyAllowed: true, - Aliases: []string{"google-antigravity"}, - }, - "claude-cli": { - EmptyAPIKeyAllowed: true, - Aliases: []string{"claudecli"}, - }, - "codex-cli": { - EmptyAPIKeyAllowed: true, - Aliases: []string{"codexcli"}, - }, - "ollama": { - DefaultAPIBase: "http://localhost:11434/v1", - EmptyAPIKeyAllowed: true, - }, - "vllm": { - DefaultAPIBase: "http://localhost:8000/v1", - EmptyAPIKeyAllowed: true, - }, - "lmstudio": { - DefaultAPIBase: "http://localhost:1234/v1", - EmptyAPIKeyAllowed: true, - }, - "gpt4free": { - DefaultAPIBase: "http://localhost:1337/v1", - EmptyAPIKeyAllowed: true, - Aliases: []string{"g4f"}, - }, - "elevenlabs": { - DefaultAPIBase: "https://api.elevenlabs.io", - }, - "venice": { - DefaultAPIBase: "https://api.venice.ai/api/v1", - }, - "nearai": { - DefaultAPIBase: "https://cloud-api.near.ai/v1", - Aliases: []string{"near-ai", "near-ai-cloud"}, - }, - "shengsuanyun": { - DefaultAPIBase: "https://router.shengsuanyun.com/api/v1", - }, - "siliconflow": { - DefaultAPIBase: "https://api.siliconflow.cn/v1", - }, - "vivgrid": { - DefaultAPIBase: "https://api.vivgrid.com/v1", - }, - "minimax": { - DefaultAPIBase: "https://api.minimaxi.com/v1", - }, - "longcat": { - DefaultAPIBase: "https://api.longcat.chat/openai", - }, - "modelscope": { - DefaultAPIBase: "https://api-inference.modelscope.cn/v1", - }, - "mimo": { - DefaultAPIBase: "https://api.xiaomimimo.com/v1", - }, - "avian": { - DefaultAPIBase: "https://api.avian.io/v1", - }, - "zai": { - DefaultAPIBase: "https://api.z.ai/api/coding/paas/v4", - Aliases: []string{"z.ai", "z-ai"}, - }, - "alibaba-coding": { - DefaultAPIBase: "https://coding-intl.dashscope.aliyuncs.com/v1", - Aliases: []string{"coding-plan", "qwen-coding"}, - }, - "alibaba-coding-anthropic": { - DefaultAPIBase: "https://coding-intl.dashscope.aliyuncs.com/apps/anthropic", - Aliases: []string{"coding-plan-anthropic"}, - }, - "novita": { - DefaultAPIBase: "https://api.novita.ai/openai", - }, - "litellm": { - DefaultAPIBase: "http://localhost:4000/v1", - }, - "qwen-us": { - DefaultAPIBase: "https://dashscope-us.aliyuncs.com/compatible-mode/v1", - Aliases: []string{"dashscope-us"}, - }, + "openai": {DefaultAPIBase: "https://api.openai.com/v1", Aliases: []string{"gpt"}}, + "anthropic": {DefaultAPIBase: "https://api.anthropic.com/v1", Aliases: []string{"claude", "anthropic-messages"}}, } var normalizedModelProviderAliasesByName = buildModelProviderAliasMap() diff --git a/pkg/providers/supported_protocols_test.go b/pkg/providers/supported_protocols_test.go new file mode 100644 index 00000000..6608fe60 --- /dev/null +++ b/pkg/providers/supported_protocols_test.go @@ -0,0 +1,93 @@ +package providers + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/sipeed/picoclaw/pkg/config" +) + +func TestFactoryRejectsRemovedProtocols(t *testing.T) { + for _, protocol := range []string{"gemini", "azure", "bedrock", "openrouter", "deepseek", "ollama", "antigravity", "github-copilot", "claude-cli", "codex-cli"} { + t.Run(protocol, func(t *testing.T) { + cfg := &config.ModelConfig{ + Provider: protocol, + Model: "remote-model", + APIBase: "http://127.0.0.1:1/v1", + APIKeys: config.SimpleSecureStrings("test-key"), + } + _, _, err := CreateProviderFromConfig(cfg) + require.ErrorContains(t, err, "use openai or anthropic") + require.False(t, IsSupportedModelProvider(protocol)) + }) + } +} + +func TestDefaultModelsUseSupportedProtocols(t *testing.T) { + models := config.DefaultConfig().ModelList + protocols := make(map[string]bool) + for _, model := range models { + protocol, _ := ExtractProtocol(model) + require.Contains(t, []string{"openai", "anthropic"}, protocol) + protocols[protocol] = true + } + require.Len(t, protocols, 2) +} + +func TestFactoryAnthropicUsesNativeMessages(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.Equal(t, "/v1/messages", r.URL.Path) + require.Equal(t, "test-key", r.Header.Get("X-Api-Key")) + require.Empty(t, r.Header.Get("Authorization")) + require.NotEmpty(t, r.Header.Get("Anthropic-Version")) + require.Equal(t, "fork-test", r.Header.Get("User-Agent")) + require.Equal(t, "custom", r.Header.Get("X-Test")) + var body map[string]any + require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + require.Equal(t, "claude-sonnet-4-6", body["model"]) + require.Equal(t, "value", body["custom_option"]) + require.Contains(t, body, "thinking") + require.Contains(t, body, "system") + require.Len(t, body["tools"], 1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write( + []byte( + `{"id":"msg_test","type":"message","role":"assistant","model":"claude-sonnet-4-6","content":[{"type":"tool_use","id":"call_test","name":"weather","input":{"city":"成都"}}],"stop_reason":"tool_use","usage":{"input_tokens":10,"output_tokens":5}}`, + ), + ) + })) + defer server.Close() + + cfg := &config.ModelConfig{ + Provider: "anthropic", + Model: "claude-sonnet-4-6", + APIBase: server.URL + "/v1", + APIKeys: config.SimpleSecureStrings("test-key"), + RequestTimeout: 5, + UserAgent: "fork-test", + ExtraBody: map[string]any{"custom_option": "value"}, + CustomHeaders: map[string]string{"X-Test": "custom"}, + } + provider, model, err := CreateProviderFromConfig(cfg) + require.NoError(t, err) + response, err := provider.Chat(t.Context(), []Message{ + {Role: "system", Content: "Help with weather."}, + {Role: "user", Content: "成都天气"}, + }, []ToolDefinition{{Type: "function", Function: ToolFunctionDefinition{ + Name: "weather", + Parameters: map[string]any{ + "type": "object", + "properties": map[string]any{ + "city": map[string]any{"type": "string"}, + }, + }, + }}}, model, map[string]any{"max_tokens": 8192, "thinking_level": "high"}) + require.NoError(t, err) + require.Len(t, response.ToolCalls, 1) + require.Equal(t, "weather", response.ToolCalls[0].Name) + require.Equal(t, "成都", response.ToolCalls[0].Arguments["city"]) +} diff --git a/pkg/providers/cli/toolcall_utils.go b/pkg/providers/toolcall_utils.go similarity index 53% rename from pkg/providers/cli/toolcall_utils.go rename to pkg/providers/toolcall_utils.go index 1f58c9a2..881a0e09 100644 --- a/pkg/providers/cli/toolcall_utils.go +++ b/pkg/providers/toolcall_utils.go @@ -1,53 +1,6 @@ -// PicoClaw - Ultra-lightweight personal AI agent -// License: MIT -// -// Copyright (c) 2026 PicoClaw contributors +package providers -package cliprovider - -import ( - "encoding/json" - "fmt" - "strings" -) - -// buildCLIToolsPrompt creates the tool definitions section for a CLI provider system prompt. -func buildCLIToolsPrompt(tools []ToolDefinition) string { - var sb strings.Builder - - sb.WriteString("## Available Tools\n\n") - sb.WriteString("When you need to use a tool, respond with ONLY a JSON object:\n\n") - sb.WriteString("```json\n") - sb.WriteString( - `{"tool_calls":[{"id":"call_xxx","type":"function","function":{"name":"tool_name","arguments":"{...}"}}]}`, - ) - sb.WriteString("\n```\n\n") - sb.WriteString("CRITICAL: The 'arguments' field MUST be a JSON-encoded STRING.\n\n") - sb.WriteString("Escaping rules (what to type in `function.arguments`):\n") - sb.WriteString("- Use `\\n` to represent a real newline character.\n") - sb.WriteString("- Use `\\\\n` to represent a literal backslash+n sequence (`\\n`).\n") - sb.WriteString( - "- `function.arguments` is a JSON-encoded string, so quotes/backslashes must be escaped in the outer payload.\n\n", - ) - sb.WriteString("### Tool Definitions:\n\n") - - for _, tool := range tools { - if tool.Type != "function" { - continue - } - sb.WriteString(fmt.Sprintf("#### %s\n", tool.Function.Name)) - if tool.Function.Description != "" { - sb.WriteString(fmt.Sprintf("Description: %s\n", tool.Function.Description)) - } - if len(tool.Function.Parameters) > 0 { - paramsJSON, _ := json.Marshal(tool.Function.Parameters) - sb.WriteString(fmt.Sprintf("Parameters:\n```json\n%s\n```\n", string(paramsJSON))) - } - sb.WriteString("\n") - } - - return sb.String() -} +import "encoding/json" // NormalizeToolCall normalizes a ToolCall to ensure all fields are properly populated. // It handles cases where Name/Arguments might be in different locations (top-level vs Function) diff --git a/workspace/skills/picoclaw-agent/SKILL.md b/workspace/skills/picoclaw-agent/SKILL.md index c896db20..83a06231 100644 --- a/workspace/skills/picoclaw-agent/SKILL.md +++ b/workspace/skills/picoclaw-agent/SKILL.md @@ -88,7 +88,6 @@ Notes: ```bash picoclaw auth login --provider openai picoclaw auth login --provider anthropic --setup-token -picoclaw auth login --provider antigravity --device-code picoclaw auth models picoclaw auth status picoclaw auth logout --provider openai @@ -151,64 +150,11 @@ Notes: ## Providers -PicoClaw supports 30+ LLM providers through `model_list`. +PicoClaw supports two chat protocols: `openai` (Responses and Chat Completions) and `anthropic` (native Messages). -Credential patterns in PicoClaw are: +Use `model_list[].api_keys`, or the existing `picoclaw auth login --provider openai` / `anthropic` flows. For compatible services, select one of these protocols and explicitly set `api_base` and the remote `model` ID. Other vendor presets, CLI proxies, Copilot, Antigravity, Gemini, Azure and Bedrock have been removed. -- `model_list[].api_keys` for most hosted APIs -- `picoclaw auth login --provider ...` for the built-in auth helper flows (`openai`, `anthropic`, `antigravity`) -- local or self-hosted endpoints for providers like `ollama`, `lmstudio`, `vllm`, and `litellm` -- external platform credentials for providers like `bedrock`, `azure`, and `github-copilot` - -`picoclaw auth login` does **not** cover every provider. For most providers, the normal path is adding a `model_list` entry with `provider`, `model`, and `api_keys`. - -### Common Provider Matrix - -| Provider | `provider` value | Auth path in PicoClaw | -| --- | --- | --- | -| OpenAI | `openai` | OAuth helper via `picoclaw auth login --provider openai`, or `model_list[].api_keys` | -| Anthropic | `anthropic` | API key in `model_list[].api_keys`, or helper flow via `picoclaw auth login --provider anthropic` | -| Anthropic Messages API | `anthropic-messages` | API key in `model_list[].api_keys` | -| Google Gemini | `gemini` | API key in `model_list[].api_keys` | -| OpenRouter | `openrouter` | API key in `model_list[].api_keys` | -| Zhipu / GLM | `zhipu` | API key in `model_list[].api_keys` | -| DeepSeek | `deepseek` | API key in `model_list[].api_keys` | -| VolcEngine / Doubao | `volcengine` | API key in `model_list[].api_keys` | -| Qwen / DashScope | `qwen` | API key in `model_list[].api_keys` | -| Moonshot / Kimi | `moonshot` | API key in `model_list[].api_keys` | -| MiniMax | `minimax` | API key in `model_list[].api_keys` | -| Mistral | `mistral` | API key in `model_list[].api_keys` | -| Groq | `groq` | API key in `model_list[].api_keys` | -| NVIDIA NIM | `nvidia` | API key in `model_list[].api_keys` | -| Cerebras | `cerebras` | API key in `model_list[].api_keys` | -| Azure OpenAI | `azure` | `api_key` in `model_list`, or Microsoft Entra ID if built with `azidentity` support | -| AWS Bedrock | `bedrock` | AWS credentials plus Bedrock-enabled build (`go build -tags bedrock`) | -| Antigravity | `antigravity` | OAuth helper via `picoclaw auth login --provider antigravity` | -| GitHub Copilot | `github-copilot` | External Copilot gRPC endpoint, default `localhost:4321` | -| Ollama | `ollama` | Local endpoint, no API key required | -| LM Studio | `lmstudio` | Local endpoint, API key optional | -| vLLM | `vllm` | Local OpenAI-compatible endpoint | -| LiteLLM | `litellm` | Proxy endpoint and whichever credential model the proxy expects | -| Claude CLI | `claude-cli` | Local Claude CLI provider, configured by workspace/runtime | -| Codex CLI | `codex-cli` | Local Codex CLI provider, configured by workspace/runtime | - -### Additional OpenAI-Compatible Vendors - -PicoClaw also carries first-class metadata or routing support for additional vendors such as: - -- `venice` -- `vivgrid` -- `longcat` -- `modelscope` -- `mimo` -- `novita` -- `byteplus` -- `shengsuanyun` -- `avian` -- `zai-coding` -- `gpt4free` - -For the full provider matrix, default API bases, protocol families, and vendor-specific examples, read `docs/guides/providers.md`. +The legacy `anthropic-messages` spelling is an alias of `anthropic`. Model-specific HTTP headers, extra body parameters, thinking, streaming, schema transforms, multiple keys and fallback remain configurable. Speech-only services have separate selection logic and are not chat providers. ## Built-in Tool Families @@ -449,7 +395,7 @@ model_list: | Groq Whisper | `groq/whisper-large-v3-turbo` | Fast OpenAI-compatible Whisper transcription and a common default choice | | OpenAI Whisper | `openai/whisper-1` | Standard Whisper transcription through the OpenAI-compatible audio endpoint | | ElevenLabs Scribe | `provider: elevenlabs`, `model: scribe_v1` | Uses PicoClaw's dedicated ElevenLabs transcription path | -| Audio-capable chat models | `gemini/gemini-2.5-flash`, `openai/gpt-4o-audio-preview` | Multimodal audio transcription path; some model combinations are still evolving | +| Audio-capable chat models | `openai/gpt-4o-audio-preview` | Multimodal audio transcription path; some model combinations are still evolving | Detection behavior that matters: