diff --git a/docs/en-US/pi-runtime.md b/docs/en-US/pi-runtime.md index 987384fb..d08f9d7f 100644 --- a/docs/en-US/pi-runtime.md +++ b/docs/en-US/pi-runtime.md @@ -17,6 +17,8 @@ The launcher and self-update build prepare the worker. The new server also prepa After pulling a worker fix into a source installation, run `bash scripts/build-pi-runtime.sh` in that installation before restarting the service. If `agent_runtime.worker_path` is set, make sure it points to the rebuilt worker. Keep existing session files: the worker corrects interrupted OpenAI-compatible tool batches when preparing model requests. +Chat Completions channels outside the native OpenAI service send instructions with the `system` role. This prevents Pi from switching to an unsupported `developer` role when thinking is enabled, while preserving the configured reasoning options. Primary models, fallback models and background generation share this setting. Native OpenAI channels and the Responses/Anthropic protocols keep the SDK's role handling. + ## Configuration `agent_runtime.engine` accepts only `pi` (also the default). The former engine and dependencies have been removed. Optional `node_path`, `worker_path`, and `session_dir` control deployment. diff --git a/docs/zh-CN/pi-runtime.md b/docs/zh-CN/pi-runtime.md index c9e33c0f..ac041b70 100644 --- a/docs/zh-CN/pi-runtime.md +++ b/docs/zh-CN/pi-runtime.md @@ -29,6 +29,8 @@ agent_runtime: 模型请求使用 HTTP/1.1,遵循服务进程环境里的 `HTTP_PROXY`、`HTTPS_PROXY` 和 `NO_PROXY`。重定向只允许在原站点内跳转,避免模型凭据外传。 +非 OpenAI 官方渠道的 Chat Completions 请求使用 `system` 发送系统指令,避免启用思考后被 Pi 自动改成部分兼容接口不支持的 `developer` 角色。思考参数保持原有配置;主模型、备用模型及后台生成使用同一兼容设置。OpenAI 官方渠道和 Responses/Anthropic 原生协议保留 SDK 的角色处理。 + 新服务会在接受请求前补建缺失的匹配 Worker 并检查启动握手,因此首次从 Eino 升级时,即使旧更新器只编译 Go,也能准备运行组件。补建需要 Node.js >=22.19、npm 和锁定的 npm 依赖下载渠道;失败会阻止启动并提示修复方法。已有匹配构建包时不再安装依赖。 ## 执行边界 diff --git a/internal/multiagent/pi_model.go b/internal/multiagent/pi_model.go index ca6f767c..1e02831e 100644 --- a/internal/multiagent/pi_model.go +++ b/internal/multiagent/pi_model.go @@ -47,6 +47,15 @@ func piModelConfig(oa config.OpenAIConfig, intent *reasoning.ClientIntent, conve compat["supportsStore"] = false delete(extra, "store") } + if api == "openai-completions" { + // Pi's custom provider defaults unknown endpoints to developer messages + // when thinking is enabled. Compatible APIs may only accept system. + endpoint := oa + endpoint.BaseURL = base + if !endpoint.UsesOfficialOpenAIReasoning() { + compat["supportsDeveloperRole"] = false + } + } if oa.IsLocalContextProfile() { compat["maxTokensField"] = "max_tokens" compat["supportsStore"] = false diff --git a/internal/multiagent/pi_model_test.go b/internal/multiagent/pi_model_test.go new file mode 100644 index 00000000..18402756 --- /dev/null +++ b/internal/multiagent/pi_model_test.go @@ -0,0 +1,111 @@ +package multiagent + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "cyberstrike-ai/internal/agentruntime" + "cyberstrike-ai/internal/config" + "go.uber.org/zap" +) + +func TestPiModelInstructionRoleCompatibility(t *testing.T) { + for _, tc := range []struct { + name, provider, url, profile, model, api string + systemOnly bool + }{ + {"gateway", "openai", "https://gateway.example/v1", "auto", "fixture", "openai-completions", true}, + {"deepseek gateway", "openai", "https://gateway.example/v1", "deepseek_compat", "fixture", "openai-completions", true}, + {"local", "openai_compatible", "http://localhost:8000/v1", "auto", "fixture", "openai-completions", true}, + {"official", "openai", "https://api.openai.com/v1/", "auto", "o3", "openai-completions", false}, + {"default endpoint", "openai", "", "auto", "o3", "openai-completions", false}, + {"official with deepseek profile", "openai", "https://api.openai.com/v1", "deepseek_compat", "fixture", "openai-completions", true}, + {"responses", "openai", "https://api.openai.com/v1", "auto", "gpt-6.1-sol", "openai-responses", false}, + {"anthropic", "claude", "https://api.anthropic.com", "auto", "fixture", "anthropic-messages", false}, + } { + t.Run(tc.name, func(t *testing.T) { + oa := config.OpenAIConfig{Provider: tc.provider, BaseURL: tc.url, Model: tc.model, + Reasoning: config.OpenAIReasoningConfig{Mode: "on", Effort: "low", Profile: tc.profile}} + model := piModelConfig(oa, nil, "") + if model.API != tc.api || model.Thinking != "low" { + t.Fatalf("unexpected API or thinking: %+v", model) + } + value, set := model.Compat["supportsDeveloperRole"] + if tc.systemOnly && (!set || value != false) { + t.Fatalf("compatible endpoint must explicitly use system messages: %+v", model.Compat) + } + if !tc.systemOnly && set { + t.Fatalf("native protocol compatibility must remain SDK-controlled: %+v", model.Compat) + } + }) + } +} + +func TestPiCompatibleReasoningUsesSystemMessages(t *testing.T) { + for _, profile := range []string{"auto", "deepseek_compat"} { + for _, background := range []bool{false, true} { + name := profile + "/agent" + if background { + name = profile + "/background" + } + t.Run(name, func(t *testing.T) { + cfg := piTestConfig(t) + cfg.OpenAI.Reasoning = config.OpenAIReasoningConfig{Mode: "on", Effort: "low", Profile: profile} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body struct { + Messages []struct { + Role string + Content json.RawMessage + } + Effort string `json:"reasoning_effort"` + Thinking struct{ Type string } + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + http.Error(w, "invalid request", http.StatusBadRequest) + return + } + for _, message := range body.Messages { + if message.Role == "developer" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"message":"developer is not one of ['system', 'assistant', 'user', 'tool', 'function']","type":"invalid_request_error","param":null,"code":"invalid_parameter_error"}`)) + return + } + } + if len(body.Messages) == 0 || body.Messages[0].Role != "system" || !strings.Contains(string(body.Messages[0].Content), "instruction-role fixture") { + t.Errorf("system instruction missing: %+v", body.Messages) + } + if body.Effort != "low" || (profile == "deepseek_compat" && body.Thinking.Type != "enabled") { + t.Errorf("reasoning was not preserved: %+v", body) + } + piReply(w, "", "", nil, "role verified") + })) + defer server.Close() + cfg.OpenAI.BaseURL = server.URL + "/v1" + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + if background { + result, err := (agentruntime.Pi{WorkerPath: cfg.AgentRuntime.WorkerPath}).Run(ctx, agentruntime.Request{ + RunID: "instruction-role", GenerateOnly: true, SystemPrompt: "instruction-role fixture", + History: json.RawMessage(`[{"role":"user","content":"Say ok"}]`), + Model: piModelConfig(cfg.OpenAI, nil, ""), Tools: []agentruntime.Tool{}, MaxTurns: 1, + }, nil, nil, nil) + if err != nil || result == nil || result.Response != "role verified" || result.Status != "completed" { + t.Fatalf("result=%+v err=%v", result, err) + } + } else { + result, err := RunSingleAgent(ctx, cfg, &cfg.MultiAgent, piTestAgent(cfg, nil), nil, zap.NewNop(), "", "", "Say ok", nil, nil, nil, nil, "instruction-role fixture") + if err != nil || result == nil || result.Response != "role verified" || result.RuntimeStatus != "completed" { + t.Fatalf("result=%+v err=%v", result, err) + } + } + }) + } + } +}