From 3646c1f38a7940b4367a06e5491d55c74150efb1 Mon Sep 17 00:00:00 2001 From: Sycun <165354365+Sycun@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:06:05 +0800 Subject: [PATCH] fix(pi): honor DeepSeek output budgets and report reasoning usage --- docs/en-US/token-usage-monitoring.md | 8 ++- docs/zh-CN/token-usage-monitoring.md | 7 ++ internal/multiagent/pi_integration_test.go | 78 ++++++++++++++++++++++ internal/multiagent/pi_model.go | 4 +- internal/multiagent/pi_runner.go | 16 ++++- 5 files changed, 109 insertions(+), 4 deletions(-) diff --git a/docs/en-US/token-usage-monitoring.md b/docs/en-US/token-usage-monitoring.md index 0920faf7..654c11ed 100644 --- a/docs/en-US/token-usage-monitoring.md +++ b/docs/en-US/token-usage-monitoring.md @@ -2,8 +2,14 @@ Pi reports usage; Go accumulates completed model turns and emits `agent_usage_summary` into the existing database and timeline. Local statistics are not a provider billing statement and may not cover every auxiliary HTTP request. -Prompt tokens are Pi input + cacheRead + cacheWrite. Completion tokens are output, and total is prompt + completion. Cache details are already included and must not be added again. Model-call counts reflect observed turns. Missing reasoning/cache details mean unreported data, not proven zero use. Durable assessments retain their own conservative budget ledger. +Prompt tokens are Pi input + cacheRead + cacheWrite. Completion tokens are output, and total is prompt + completion. Cache details are already included and must not be added again. The usage view shows provider-reported reasoning tokens as a subset of completion tokens. Model-call counts reflect observed turns. Missing reasoning/cache details mean unreported data, not proven zero use. Durable assessments retain their own conservative budget ledger. The dashboard and Settings usage view retain period, model and project filters. APIs are `GET /api/usage/tokens` and `GET /api/conversations/:id/token-usage`. Existing usage rows and historical timeline backfill remain compatible. Streaming updates carry deltas; complete messages are committed at message end. Implementation: `internal/multiagent/pi_runner.go` and `internal/database/model_token_usage.go`. See [Pi AI](https://github.com/earendil-works/pi/tree/v1.5.2/packages/ai). + +## DeepSeek + +In the channel’s reasoning settings, use `off` for simple Q&A and format conversions or pair `auto` with `low` to keep reasoning on at a lower effort. The official API defaults to `high` when effort is unspecified and maps `medium` to `high`. The channel sends its per-request output limit as `max_tokens`, shared by reasoning and the visible answer. Compare output tokens, reasoning tokens and the cache hit rate for the same tasks at different effort levels. [DeepSeek Thinking Mode](https://api-docs.deepseek.com/guides/thinking_mode/) · [Chat Completions](https://api-docs.deepseek.com/api/create-chat-completion/) + +The official API automatically caches reusable request prefixes. Pi orders MCP tool definitions by name so the same catalog introduces fewer prefix changes across requests. The provider reports the actual cache hits. [DeepSeek Context Caching](https://api-docs.deepseek.com/guides/kv_cache/) diff --git a/docs/zh-CN/token-usage-monitoring.md b/docs/zh-CN/token-usage-monitoring.md index 29e4fd4c..37ff0802 100644 --- a/docs/zh-CN/token-usage-monitoring.md +++ b/docs/zh-CN/token-usage-monitoring.md @@ -6,6 +6,7 @@ - 输入总量由 Pi 的 input、cacheRead、cacheWrite 相加;输出使用 output。 - 总量为输入与输出之和;缓存读取和缓存写入已经包含在输入中,不能重复叠加。 +- 供应商单独报告的推理 Token 已包含在输出中,面板单列展示。 - 模型调用次数按已观察到的轮次统计,重试会产生新的轮次。 - 未报告的细分不能推断为没有发生。推理 Token 等没有独立字段时,不根据文本长度伪造账单计数。 - 深度评估使用其持久预算账本;供应商未报告用量时采用原有保守计费策略。 @@ -17,3 +18,9 @@ 已有模型用量表保持兼容。旧时间线用量事件可作为历史记录补齐;新记录仅由原生 Pi 事件生成。原生流式消息只传输增量,完整消息在结束时提交,避免重复累计与逐块重复发送整份内容。 实现:`internal/multiagent/pi_runner.go`、`internal/database/model_token_usage.go`、前端用量页面。基础模型 usage 语义见 [Pi AI](https://github.com/earendil-works/pi/tree/v1.5.2/packages/ai)。 + +## DeepSeek + +在 AI 通道的推理设置中,可用 `off` 处理简单问答和格式转换,或用 `auto` 配合 `low` 保留低强度推理。官方接口未指定强度时默认使用 `high`,`medium` 也映射到 `high`。通道的「单次输出上限」通过 `max_tokens` 发送,推理和正文共用额度。对照面板里的输出、推理 Token 和缓存命中率,可比较相同任务在不同强度下的用量。[DeepSeek 推理模式](https://api-docs.deepseek.com/guides/thinking_mode/) · [Chat Completions](https://api-docs.deepseek.com/api/create-chat-completion/) + +官方接口自动缓存可复用的请求前缀。Pi 按名称固定 MCP 工具定义的顺序,以减少相同工具目录在请求之间的前缀变化。缓存命中以供应商返回的用量为准。[DeepSeek 上下文缓存](https://api-docs.deepseek.com/guides/kv_cache/) diff --git a/internal/multiagent/pi_integration_test.go b/internal/multiagent/pi_integration_test.go index f6ee7a91..5b060745 100644 --- a/internal/multiagent/pi_integration_test.go +++ b/internal/multiagent/pi_integration_test.go @@ -9,6 +9,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" "sync" "sync/atomic" @@ -166,6 +167,83 @@ func piReply(w http.ResponseWriter, tool, id string, args map[string]any, text s fmt.Fprint(w, "data: [DONE]\n\n") } +func TestPiDeepSeekOutputBudgetAndUsage(t *testing.T) { + for _, tc := range []struct { + profile, mode, thinking, effort string + reasoning int + }{ + {profile: "deepseek", mode: "auto", thinking: "enabled", effort: "low", reasoning: 6}, + {profile: "deepseek_compat", mode: "off", thinking: "disabled"}, + } { + t.Run(tc.profile, func(t *testing.T) { + cfg := piTestConfig(t) + cfg.OpenAI.Model = "deepseek-flash" + cfg.OpenAI.Reasoning = config.OpenAIReasoningConfig{Profile: tc.profile, Mode: tc.mode, Effort: "low"} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body struct { + MaxTokens int `json:"max_tokens"` + MaxCompletionTokens *int `json:"max_completion_tokens"` + Effort string `json:"reasoning_effort"` + Thinking struct { + Type string `json:"type"` + } `json:"thinking"` + StreamOptions struct { + IncludeUsage bool `json:"include_usage"` + } `json:"stream_options"` + Tools []struct { + Function struct { + Name string `json:"name"` + } `json:"function"` + } `json:"tools"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + http.Error(w, "invalid fixture request", http.StatusBadRequest) + return + } + if body.MaxTokens != 1024 || body.MaxCompletionTokens != nil || !body.StreamOptions.IncludeUsage { + t.Errorf("unexpected budget or usage options: %+v", body) + } + if body.Thinking.Type != tc.thinking || body.Effort != tc.effort { + t.Errorf("unexpected thinking options: %+v", body) + } + var names []string + for _, tool := range body.Tools { + names = append(names, tool.Function.Name) + } + if !slices.Equal(names, []string{"echo", "secret"}) { + t.Errorf("unexpected tool catalog: %v", names) + } + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, `data: {"id":"fixture","object":"chat.completion.chunk","model":"deepseek-flash","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}`+"\n\n") + fmt.Fprintf(w, `data: {"id":"fixture","object":"chat.completion.chunk","model":"deepseek-flash","choices":[],"usage":{"prompt_tokens":100,"prompt_cache_hit_tokens":75,"prompt_cache_miss_tokens":25,"completion_tokens":20,"completion_tokens_details":{"reasoning_tokens":%d},"total_tokens":120}}`+"\n\n", tc.reasoning) + fmt.Fprint(w, "data: [DONE]\n\n") + })) + defer server.Close() + cfg.OpenAI.BaseURL = server.URL + "/v1" + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + var usage map[string]any + result, err := RunSingleAgent(ctx, cfg, &cfg.MultiAgent, piTestAgent(cfg, nil), nil, zap.NewNop(), "", "", "Say ok", nil, nil, func(kind, _ string, data interface{}) { + if kind == "agent_usage_summary" { + usage = data.(map[string]any) + } + }, nil, "") + if err != nil || result == nil || result.Response != "ok" || result.RuntimeStatus != "completed" { + t.Fatalf("result=%+v err=%v", result, err) + } + for field, want := range map[string]int{ + "modelCalls": 1, "promptTokens": 100, "completionTokens": 20, + "cachedTokens": 75, "cacheWriteTokens": 0, "reasoningTokens": tc.reasoning, "totalTokens": 120, + } { + if usage[field] != want { + t.Errorf("%s=%v, want %d (usage=%v)", field, usage[field], want, usage) + } + } + }) + } +} + func TestPiBackgroundGenerationReturnsProposalWithoutExecutingTools(t *testing.T) { for _, provider := range []string{"openai", "claude"} { t.Run(provider, func(t *testing.T) { diff --git a/internal/multiagent/pi_model.go b/internal/multiagent/pi_model.go index b8c06fcc..f4f4b675 100644 --- a/internal/multiagent/pi_model.go +++ b/internal/multiagent/pi_model.go @@ -44,9 +44,11 @@ func piModelConfig(oa config.OpenAIConfig, intent *reasoning.ClientIntent, conve compat["maxTokensField"] = "max_tokens" compat["supportsStore"] = false } - if oa.Reasoning.ProfileEffective() == "deepseek_compat" || (oa.Reasoning.ProfileEffective() == "auto" && oa.IsDeepSeekEndpointOrModel()) { + profile := oa.Reasoning.ProfileEffective() + if api == "openai-completions" && (profile == "deepseek" || profile == "deepseek_compat" || (profile == "auto" && oa.IsDeepSeekEndpointOrModel())) { compat["thinkingFormat"] = "deepseek" compat["requiresReasoningContentOnAssistantMessages"] = true + compat["maxTokensField"] = "max_tokens" } return agentruntime.Model{Provider: provider, API: api, ID: oa.Model, BaseURL: base, APIKey: oa.APIKey, Headers: headers, ContextWindow: window, InputBudget: budget, MaxTokens: oa.MaxCompletionTokensEffective(), Thinking: thinking, ExtraFields: extra, Compat: compat} } diff --git a/internal/multiagent/pi_runner.go b/internal/multiagent/pi_runner.go index 9e639e36..ffc1fafd 100644 --- a/internal/multiagent/pi_runner.go +++ b/internal/multiagent/pi_runner.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "path/filepath" + "slices" "strings" "sync" "sync/atomic" @@ -224,6 +225,11 @@ func runPiMulti(ctx context.Context, cfg *config.Config, ma *config.MultiAgentCo func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { defs := r.ag.ToolsForRole(r.roleTools) + // MCP catalogs are backed by maps. Keep the tool prefix and the first N + // always-visible tools stable across runs with the same catalog. + slices.SortFunc(defs, func(a, b agent.Tool) int { + return strings.Compare(a.Function.Name, b.Function.Name) + }) localDefs, localNames, skillPrompt, err := r.piLocalCatalog(ctx) if err != nil { return nil, err @@ -406,7 +412,7 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { return result, err } var text, thought string - var modelCalls, promptTokens, completionTokens, cacheRead, cacheWrite int + var modelCalls, promptTokens, completionTokens, cacheRead, cacheWrite, reasoningTokens int reasonID := func() string { return fmt.Sprintf("%s-reasoning-%d", runID, iteration.Load()) } emit := func(e agentruntime.Event) { if e.Type == "compaction_end" { @@ -442,6 +448,7 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { Output int `json:"output"` CacheRead int `json:"cacheRead"` CacheWrite int `json:"cacheWrite"` + Reasoning int `json:"reasoning"` } `json:"usage"` } `json:"message"` } @@ -451,6 +458,7 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { completionTokens += d.Message.Usage.Output cacheRead += d.Message.Usage.CacheRead cacheWrite += d.Message.Usage.CacheWrite + reasoningTokens += d.Message.Usage.Reasoning } } @@ -508,7 +516,11 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { progress("reasoning_chain_stream_end", thought, map[string]any{"streamId": reasonID()}) } if modelCalls > 0 { - progress("agent_usage_summary", "Pi token usage summary", map[string]any{"model": oa.Model, "modelCalls": modelCalls, "promptTokens": promptTokens, "completionTokens": completionTokens, "totalTokens": promptTokens + completionTokens, "cachedTokens": cacheRead, "cacheWriteTokens": cacheWrite}) + progress("agent_usage_summary", "Pi token usage summary", map[string]any{ + "model": oa.Model, "modelCalls": modelCalls, + "promptTokens": promptTokens, "completionTokens": completionTokens, "totalTokens": promptTokens + completionTokens, + "cachedTokens": cacheRead, "cacheWriteTokens": cacheWrite, "reasoningTokens": reasoningTokens, + }) } if res == nil { return nil, runErr