feat(llm): add prompt-cache observability and wiki cache-friendly prompts
Normalize provider-specific cache counters into TokenUsage, propagate call purpose and prefix fingerprints through context for logging and Langfuse, and restructure wiki page-modify prompts with warmup/singleflight to improve prefix cache hit rates during reduce batches.
This commit is contained in:
@@ -50,8 +50,10 @@ type anthropicResponse struct {
|
||||
} `json:"content"`
|
||||
StopReason string `json:"stop_reason"`
|
||||
Usage struct {
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
CacheCreationInputTokens *int `json:"cache_creation_input_tokens"`
|
||||
CacheReadInputTokens *int `json:"cache_read_input_tokens"`
|
||||
} `json:"usage"`
|
||||
Error *struct {
|
||||
Type string `json:"type"`
|
||||
@@ -63,10 +65,10 @@ type anthropicStreamEvent struct {
|
||||
Type string `json:"type"`
|
||||
Message *struct {
|
||||
Usage 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"`
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
CacheCreationInputTokens *int `json:"cache_creation_input_tokens"`
|
||||
CacheReadInputTokens *int `json:"cache_read_input_tokens"`
|
||||
} `json:"usage"`
|
||||
} `json:"message,omitempty"`
|
||||
Delta *struct {
|
||||
@@ -75,10 +77,10 @@ type anthropicStreamEvent struct {
|
||||
StopReason string `json:"stop_reason"`
|
||||
} `json:"delta,omitempty"`
|
||||
Usage *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"`
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
CacheCreationInputTokens *int `json:"cache_creation_input_tokens"`
|
||||
CacheReadInputTokens *int `json:"cache_read_input_tokens"`
|
||||
} `json:"usage,omitempty"`
|
||||
Error *struct {
|
||||
Type string `json:"type"`
|
||||
@@ -316,14 +318,20 @@ func (c *AnthropicChat) parseResponse(resp *anthropicResponse) *types.ChatRespon
|
||||
}
|
||||
inputTokens := resp.Usage.InputTokens
|
||||
outputTokens := resp.Usage.OutputTokens
|
||||
cacheRead := valueOrZero(resp.Usage.CacheReadInputTokens)
|
||||
cacheWrite := valueOrZero(resp.Usage.CacheCreationInputTokens)
|
||||
promptTokens := inputTokens + cacheRead + cacheWrite
|
||||
usage := types.TokenUsage{
|
||||
PromptTokens: promptTokens,
|
||||
CompletionTokens: outputTokens,
|
||||
TotalTokens: promptTokens + outputTokens,
|
||||
}
|
||||
usage.SetPromptCacheUsage(cacheRead, cacheWrite, max(0, promptTokens-cacheRead),
|
||||
resp.Usage.CacheReadInputTokens != nil || resp.Usage.CacheCreationInputTokens != nil)
|
||||
return &types.ChatResponse{
|
||||
Content: strings.Join(parts, ""),
|
||||
FinishReason: resp.StopReason,
|
||||
Usage: types.TokenUsage{
|
||||
PromptTokens: inputTokens,
|
||||
CompletionTokens: outputTokens,
|
||||
TotalTokens: inputTokens + outputTokens,
|
||||
},
|
||||
Usage: usage,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -333,6 +341,9 @@ func parseAnthropicSSE(reader io.Reader) (*types.ChatResponse, error) {
|
||||
var finishReason string
|
||||
var inputTokens int
|
||||
var outputTokens int
|
||||
var cacheReadTokens int
|
||||
var cacheWriteTokens int
|
||||
var cacheReported bool
|
||||
|
||||
for {
|
||||
event, err := sseReader.ReadEvent()
|
||||
@@ -359,6 +370,11 @@ func parseAnthropicSSE(reader io.Reader) (*types.ChatResponse, error) {
|
||||
if streamEvent.Message != nil {
|
||||
inputTokens = max(inputTokens, streamEvent.Message.Usage.InputTokens)
|
||||
outputTokens = max(outputTokens, streamEvent.Message.Usage.OutputTokens)
|
||||
cacheReadTokens, cacheWriteTokens, cacheReported = mergeAnthropicCacheCounters(
|
||||
cacheReadTokens, cacheWriteTokens, cacheReported,
|
||||
streamEvent.Message.Usage.CacheReadInputTokens,
|
||||
streamEvent.Message.Usage.CacheCreationInputTokens,
|
||||
)
|
||||
}
|
||||
if streamEvent.Delta != nil {
|
||||
if streamEvent.Delta.Type == "text_delta" && streamEvent.Delta.Text != "" {
|
||||
@@ -371,17 +387,26 @@ func parseAnthropicSSE(reader io.Reader) (*types.ChatResponse, error) {
|
||||
if streamEvent.Usage != nil {
|
||||
inputTokens = max(inputTokens, streamEvent.Usage.InputTokens)
|
||||
outputTokens = max(outputTokens, streamEvent.Usage.OutputTokens)
|
||||
cacheReadTokens, cacheWriteTokens, cacheReported = mergeAnthropicCacheCounters(
|
||||
cacheReadTokens, cacheWriteTokens, cacheReported,
|
||||
streamEvent.Usage.CacheReadInputTokens,
|
||||
streamEvent.Usage.CacheCreationInputTokens,
|
||||
)
|
||||
}
|
||||
}
|
||||
promptTokens := inputTokens + cacheReadTokens + cacheWriteTokens
|
||||
usage := types.TokenUsage{
|
||||
PromptTokens: promptTokens,
|
||||
CompletionTokens: outputTokens,
|
||||
TotalTokens: promptTokens + outputTokens,
|
||||
}
|
||||
usage.SetPromptCacheUsage(cacheReadTokens, cacheWriteTokens,
|
||||
max(0, promptTokens-cacheReadTokens), cacheReported)
|
||||
|
||||
return &types.ChatResponse{
|
||||
Content: strings.Join(contentParts, ""),
|
||||
FinishReason: finishReason,
|
||||
Usage: types.TokenUsage{
|
||||
PromptTokens: inputTokens,
|
||||
CompletionTokens: outputTokens,
|
||||
TotalTokens: inputTokens + outputTokens,
|
||||
},
|
||||
Usage: usage,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -447,7 +472,10 @@ func processAnthropicStream(ctx context.Context, model string, resp *http.Respon
|
||||
return
|
||||
}
|
||||
if streamEvent.Message != nil {
|
||||
usage = mergeAnthropicUsage(usage, streamEvent.Message.Usage.InputTokens, streamEvent.Message.Usage.OutputTokens)
|
||||
usage = mergeAnthropicUsage(usage, streamEvent.Message.Usage.InputTokens,
|
||||
streamEvent.Message.Usage.OutputTokens,
|
||||
streamEvent.Message.Usage.CacheReadInputTokens,
|
||||
streamEvent.Message.Usage.CacheCreationInputTokens)
|
||||
}
|
||||
if streamEvent.Delta != nil {
|
||||
if streamEvent.Delta.StopReason != "" {
|
||||
@@ -462,17 +490,48 @@ func processAnthropicStream(ctx context.Context, model string, resp *http.Respon
|
||||
}
|
||||
}
|
||||
if streamEvent.Usage != nil {
|
||||
usage = mergeAnthropicUsage(usage, streamEvent.Usage.InputTokens, streamEvent.Usage.OutputTokens)
|
||||
usage = mergeAnthropicUsage(usage, streamEvent.Usage.InputTokens,
|
||||
streamEvent.Usage.OutputTokens,
|
||||
streamEvent.Usage.CacheReadInputTokens,
|
||||
streamEvent.Usage.CacheCreationInputTokens)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mergeAnthropicUsage(current *types.TokenUsage, inputTokens, outputTokens int) *types.TokenUsage {
|
||||
func mergeAnthropicUsage(
|
||||
current *types.TokenUsage,
|
||||
inputTokens, outputTokens int,
|
||||
cacheRead, cacheWrite *int,
|
||||
) *types.TokenUsage {
|
||||
if current == nil {
|
||||
current = &types.TokenUsage{}
|
||||
}
|
||||
current.PromptTokens = max(current.PromptTokens, inputTokens)
|
||||
read, write, reported := mergeAnthropicCacheCounters(
|
||||
current.CacheReadTokens, current.CacheWriteTokens, current.CacheReported,
|
||||
cacheRead, cacheWrite,
|
||||
)
|
||||
uncachedInput := max(0, current.PromptTokens-current.CacheReadTokens-current.CacheWriteTokens)
|
||||
uncachedInput = max(uncachedInput, inputTokens)
|
||||
current.PromptTokens = uncachedInput + read + write
|
||||
current.CompletionTokens = max(current.CompletionTokens, outputTokens)
|
||||
current.TotalTokens = current.PromptTokens + current.CompletionTokens
|
||||
current.SetPromptCacheUsage(read, write, max(0, current.PromptTokens-read), reported)
|
||||
return current
|
||||
}
|
||||
|
||||
func mergeAnthropicCacheCounters(
|
||||
currentRead, currentWrite int,
|
||||
currentReported bool,
|
||||
cacheRead, cacheWrite *int,
|
||||
) (read, write int, reported bool) {
|
||||
read = currentRead
|
||||
write = currentWrite
|
||||
reported = currentReported || cacheRead != nil || cacheWrite != nil
|
||||
if cacheRead != nil {
|
||||
read = max(read, *cacheRead)
|
||||
}
|
||||
if cacheWrite != nil {
|
||||
write = max(write, *cacheWrite)
|
||||
}
|
||||
return read, write, reported
|
||||
}
|
||||
|
||||
@@ -70,6 +70,33 @@ func TestAnthropicChat(t *testing.T) {
|
||||
assert.Equal(t, 5, resp.Usage.TotalTokens)
|
||||
}
|
||||
|
||||
func TestAnthropicChat_CacheUsage(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{
|
||||
"id":"msg_cached","type":"message","role":"assistant",
|
||||
"content":[{"type":"text","text":"hello"}],"stop_reason":"end_turn",
|
||||
"usage":{"input_tokens":24,"output_tokens":2,"cache_creation_input_tokens":100,"cache_read_input_tokens":900}
|
||||
}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
chat, err := NewAnthropicChat(&ChatConfig{
|
||||
Source: types.ModelSourceRemote, BaseURL: server.URL, ModelName: "claude-sonnet-4-5",
|
||||
APIKey: "test-key", Provider: string(provider.ProviderAnthropic),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
resp, err := chat.Chat(context.Background(), []Message{{Role: "user", Content: "Hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1024, resp.Usage.PromptTokens)
|
||||
assert.Equal(t, 900, resp.Usage.CacheReadTokens)
|
||||
assert.Equal(t, 100, resp.Usage.CacheWriteTokens)
|
||||
assert.Equal(t, 124, resp.Usage.CacheMissTokens)
|
||||
assert.True(t, resp.Usage.CacheReported)
|
||||
assert.Equal(t, types.PromptCacheStatusHit, resp.Usage.CacheStatus)
|
||||
}
|
||||
|
||||
func TestAnthropicChat_FullEndpoint(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
|
||||
@@ -145,13 +172,13 @@ func TestAnthropicChat_SSEResponse(t *testing.T) {
|
||||
assert.Equal(t, "/v1/messages", r.URL.Path)
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(`event: message_start
|
||||
data: {"type":"message_start","message":{"usage":{"input_tokens":0,"output_tokens":0}}}
|
||||
data: {"type":"message_start","message":{"usage":{"input_tokens":14,"output_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":100}}}
|
||||
|
||||
event: content_block_delta
|
||||
data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"pong"}}
|
||||
|
||||
event: message_delta
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"input_tokens":114,"output_tokens":5}}
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":5}}
|
||||
|
||||
event: message_stop
|
||||
data: {"type":"message_stop"}
|
||||
@@ -177,6 +204,8 @@ data: {"type":"message_stop"}
|
||||
assert.Equal(t, 114, resp.Usage.PromptTokens)
|
||||
assert.Equal(t, 5, resp.Usage.CompletionTokens)
|
||||
assert.Equal(t, 119, resp.Usage.TotalTokens)
|
||||
assert.Equal(t, 100, resp.Usage.CacheReadTokens)
|
||||
assert.Equal(t, 14, resp.Usage.CacheMissTokens)
|
||||
}
|
||||
|
||||
func TestAnthropicChat_ChatStream(t *testing.T) {
|
||||
@@ -189,13 +218,13 @@ func TestAnthropicChat_ChatStream(t *testing.T) {
|
||||
require.NoError(t, json.NewDecoder(r.Body).Decode(&capturedRequest))
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(`event: message_start
|
||||
data: {"type":"message_start","message":{"usage":{"input_tokens":0,"output_tokens":0}}}
|
||||
data: {"type":"message_start","message":{"usage":{"input_tokens":14,"output_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":100}}}
|
||||
|
||||
event: content_block_delta
|
||||
data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"pong"}}
|
||||
|
||||
event: message_delta
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"input_tokens":114,"output_tokens":5}}
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":5}}
|
||||
|
||||
event: message_stop
|
||||
data: {"type":"message_stop"}
|
||||
@@ -231,6 +260,8 @@ data: {"type":"message_stop"}
|
||||
assert.Equal(t, 114, chunks[1].Usage.PromptTokens)
|
||||
assert.Equal(t, 5, chunks[1].Usage.CompletionTokens)
|
||||
assert.Equal(t, 119, chunks[1].Usage.TotalTokens)
|
||||
assert.Equal(t, 100, chunks[1].Usage.CacheReadTokens)
|
||||
assert.Equal(t, 14, chunks[1].Usage.CacheMissTokens)
|
||||
}
|
||||
|
||||
func TestNewRemoteChat_AnthropicProvider(t *testing.T) {
|
||||
|
||||
@@ -25,15 +25,18 @@ func (l *langfuseChat) Chat(ctx context.Context, messages []Message, opts *ChatO
|
||||
return l.inner.Chat(ctx, messages, opts)
|
||||
}
|
||||
|
||||
purpose, prefixFingerprint := types.LLMCallMetadataFromContext(ctx)
|
||||
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
|
||||
Name: "chat.completion",
|
||||
Model: l.inner.GetModelName(),
|
||||
Input: buildLangfuseMessages(messages),
|
||||
ModelParameters: buildLangfuseModelParams(opts),
|
||||
Metadata: map[string]interface{}{
|
||||
"model_id": l.inner.GetModelID(),
|
||||
"streaming": false,
|
||||
"has_tools": opts != nil && len(opts.Tools) > 0,
|
||||
"model_id": l.inner.GetModelID(),
|
||||
"streaming": false,
|
||||
"has_tools": opts != nil && len(opts.Tools) > 0,
|
||||
"call_purpose": purpose,
|
||||
"prompt_prefix_fingerprint": prefixFingerprint,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -57,15 +60,18 @@ func (l *langfuseChat) ChatStream(ctx context.Context, messages []Message, opts
|
||||
return l.inner.ChatStream(ctx, messages, opts)
|
||||
}
|
||||
|
||||
purpose, prefixFingerprint := types.LLMCallMetadataFromContext(ctx)
|
||||
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
|
||||
Name: "chat.completion.stream",
|
||||
Model: l.inner.GetModelName(),
|
||||
Input: buildLangfuseMessages(messages),
|
||||
ModelParameters: buildLangfuseModelParams(opts),
|
||||
Metadata: map[string]interface{}{
|
||||
"model_id": l.inner.GetModelID(),
|
||||
"streaming": true,
|
||||
"has_tools": opts != nil && len(opts.Tools) > 0,
|
||||
"model_id": l.inner.GetModelID(),
|
||||
"streaming": true,
|
||||
"has_tools": opts != nil && len(opts.Tools) > 0,
|
||||
"call_purpose": purpose,
|
||||
"prompt_prefix_fingerprint": prefixFingerprint,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -211,10 +217,13 @@ func convertUsage(u *types.TokenUsage) *langfuse.TokenUsage {
|
||||
return nil
|
||||
}
|
||||
return &langfuse.TokenUsage{
|
||||
Input: u.PromptTokens,
|
||||
Output: u.CompletionTokens,
|
||||
Total: u.TotalTokens,
|
||||
Unit: "TOKENS",
|
||||
Input: u.PromptTokens,
|
||||
Output: u.CompletionTokens,
|
||||
Total: u.TotalTokens,
|
||||
CacheRead: u.CacheReadTokens,
|
||||
CacheWrite: u.CacheWriteTokens,
|
||||
CacheMiss: u.CacheMissTokens,
|
||||
Unit: "TOKENS",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -43,3 +43,16 @@ func TestBuildLangfuseMessagesReasoningContent(t *testing.T) {
|
||||
t.Fatalf("reasoning_content = %v; want chain of thought", msgs[0]["reasoning_content"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertUsageIncludesPromptCacheCounters(t *testing.T) {
|
||||
got := convertUsage(&types.TokenUsage{
|
||||
PromptTokens: 1000, CompletionTokens: 50, TotalTokens: 1050,
|
||||
CacheReadTokens: 800, CacheWriteTokens: 100, CacheMissTokens: 200,
|
||||
})
|
||||
if got == nil {
|
||||
t.Fatal("convertUsage returned nil")
|
||||
}
|
||||
if got.CacheRead != 800 || got.CacheWrite != 100 || got.CacheMiss != 200 {
|
||||
t.Fatalf("cache usage = read:%d write:%d miss:%d", got.CacheRead, got.CacheWrite, got.CacheMiss)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,8 +108,9 @@ func buildResponseToolCalls(tcs []types.LLMToolCall) []logger.LLMToolCallInfo {
|
||||
}
|
||||
|
||||
func usageString(u types.TokenUsage) string {
|
||||
return fmt.Sprintf("Prompt: %d, Completion: %d, Total: %d",
|
||||
u.PromptTokens, u.CompletionTokens, u.TotalTokens)
|
||||
return fmt.Sprintf("Prompt: %d, Completion: %d, Total: %d, CacheRead: %d, CacheWrite: %d, CacheMiss: %d, CacheStatus: %s",
|
||||
u.PromptTokens, u.CompletionTokens, u.TotalTokens, u.CacheReadTokens,
|
||||
u.CacheWriteTokens, u.CacheMissTokens, u.CacheStatus)
|
||||
}
|
||||
|
||||
// logLLMDebugCall logs a complete non-stream LLM chat call.
|
||||
|
||||
@@ -165,6 +165,7 @@ func (c *OllamaChat) Chat(ctx context.Context, messages []Message, opts *ChatOpt
|
||||
CompletionTokens: completionTokens,
|
||||
TotalTokens: promptTokens + completionTokens,
|
||||
}
|
||||
usage.MarkPromptCacheUnsupported()
|
||||
logUsage(ctx, c.modelName, &usage)
|
||||
|
||||
return &types.ChatResponse{
|
||||
@@ -260,6 +261,7 @@ func (c *OllamaChat) ChatStream(
|
||||
CompletionTokens: resp.EvalCount,
|
||||
TotalTokens: resp.PromptEvalCount + resp.EvalCount,
|
||||
}
|
||||
usage.MarkPromptCacheUnsupported()
|
||||
}
|
||||
logUsage(ctx, c.modelName, usage)
|
||||
streamChan <- types.StreamResponse{
|
||||
|
||||
@@ -26,15 +26,11 @@ func (c *RemoteAPIChat) parseCompletionResponse(resp *openai.ChatCompletionRespo
|
||||
// 为设置了 Thinking=false 但模型仍返回思考内容的情况和部分不支持Thinking=false的思考模型(例如Miniax-M2.1)提供兜底策略
|
||||
content := removeThinkingContent(choice.Message.Content)
|
||||
|
||||
usage := tokenUsageFromOpenAI(resp.Usage, c.provider)
|
||||
response := &types.ChatResponse{
|
||||
Content: content,
|
||||
FinishReason: string(choice.FinishReason),
|
||||
Usage: types.TokenUsage{
|
||||
PromptTokens: resp.Usage.PromptTokens,
|
||||
CompletionTokens: resp.Usage.CompletionTokens,
|
||||
TotalTokens: resp.Usage.TotalTokens,
|
||||
CachedTokens: cachedTokens(resp.Usage.PromptTokensDetails),
|
||||
},
|
||||
Usage: usage,
|
||||
}
|
||||
|
||||
if len(choice.Message.ToolCalls) > 0 {
|
||||
@@ -148,12 +144,8 @@ func (c *RemoteAPIChat) processStream(
|
||||
}
|
||||
|
||||
if response.Usage != nil {
|
||||
state.usage = &types.TokenUsage{
|
||||
PromptTokens: response.Usage.PromptTokens,
|
||||
CompletionTokens: response.Usage.CompletionTokens,
|
||||
TotalTokens: response.Usage.TotalTokens,
|
||||
CachedTokens: cachedTokens(response.Usage.PromptTokensDetails),
|
||||
}
|
||||
usage := tokenUsageFromOpenAI(*response.Usage, c.provider)
|
||||
state.usage = &usage
|
||||
}
|
||||
|
||||
if len(response.Choices) > 0 {
|
||||
@@ -246,12 +238,9 @@ func (c *RemoteAPIChat) processRawHTTPStream(
|
||||
}
|
||||
|
||||
if streamResp.Usage != nil {
|
||||
state.usage = &types.TokenUsage{
|
||||
PromptTokens: streamResp.Usage.PromptTokens,
|
||||
CompletionTokens: streamResp.Usage.CompletionTokens,
|
||||
TotalTokens: streamResp.Usage.TotalTokens,
|
||||
CachedTokens: cachedTokens(streamResp.Usage.PromptTokensDetails),
|
||||
}
|
||||
usage := tokenUsageFromOpenAI(*streamResp.Usage, c.provider)
|
||||
applyRawPromptCacheUsage(event.Data, &usage)
|
||||
state.usage = &usage
|
||||
}
|
||||
|
||||
if len(streamResp.Choices) > 0 {
|
||||
@@ -600,23 +589,3 @@ func (c *RemoteAPIChat) processToolCallsDelta(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// cachedTokens returns the cached prompt-token count from an OpenAI-compatible
|
||||
// usage detail block, or zero when the provider did not report one. Some
|
||||
// providers omit PromptTokensDetails entirely, so the nil guard is required.
|
||||
//
|
||||
// Note on provider semantics:
|
||||
// - Implicit-cache providers (OpenAI, Azure OpenAI, DeepSeek, …) populate
|
||||
// `cached_tokens` automatically whenever the prompt prefix matches a
|
||||
// previous request — no caller opt-in is required.
|
||||
// - Explicit-cache providers (Qwen on Aliyun, Anthropic Claude, …) only
|
||||
// populate `cached_tokens` after the caller attaches `cache_control:
|
||||
// {"type": "ephemeral"}` to the relevant message / content block. This
|
||||
// helper still returns zero for those providers until that opt-in is
|
||||
// applied upstream of the request.
|
||||
func cachedTokens(d *openai.PromptTokensDetails) int {
|
||||
if d == nil {
|
||||
return 0
|
||||
}
|
||||
return d.CachedTokens
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/provider"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/sashabaranov/go-openai"
|
||||
)
|
||||
|
||||
// FingerprintPromptPrefix returns a short, non-reversible identifier suitable
|
||||
// for logs and cache routing. Raw prompts must never be used as metric labels.
|
||||
func FingerprintPromptPrefix(parts ...string) string {
|
||||
h := sha256.New()
|
||||
for _, part := range parts {
|
||||
_, _ = h.Write([]byte(part))
|
||||
_, _ = h.Write([]byte{0})
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil))[:16]
|
||||
}
|
||||
|
||||
// PromptPrefixFingerprint hashes the stable portion common to normal chat and
|
||||
// agent requests: leading system messages plus the deterministic tool schema.
|
||||
// Dynamic conversation/user messages intentionally do not participate.
|
||||
func PromptPrefixFingerprint(messages []Message, opts *ChatOptions) string {
|
||||
type stablePrefix struct {
|
||||
System []Message `json:"system,omitempty"`
|
||||
Tools []Tool `json:"tools,omitempty"`
|
||||
}
|
||||
prefix := stablePrefix{}
|
||||
for _, message := range messages {
|
||||
if message.Role != "system" {
|
||||
break
|
||||
}
|
||||
prefix.System = append(prefix.System, message)
|
||||
}
|
||||
if opts != nil {
|
||||
prefix.Tools = opts.Tools
|
||||
}
|
||||
data, _ := json.Marshal(prefix)
|
||||
return FingerprintPromptPrefix(string(data))
|
||||
}
|
||||
|
||||
// BuildPromptCacheKey derives an opaque process-local coordination key.
|
||||
// Tenant and model identifiers are hashed rather than retained in memory.
|
||||
func BuildPromptCacheKey(tenantID uint64, modelID, purpose, prefixFingerprint string) string {
|
||||
return "wk-" + FingerprintPromptPrefix(
|
||||
fmt.Sprintf("%d", tenantID), modelID, purpose, prefixFingerprint,
|
||||
)
|
||||
}
|
||||
|
||||
func providerCacheAccountingStatus(name provider.ProviderName) types.PromptCacheStatus {
|
||||
switch name {
|
||||
case provider.ProviderOpenAI,
|
||||
provider.ProviderAzureOpenAI,
|
||||
provider.ProviderDeepSeek,
|
||||
provider.ProviderAliyun,
|
||||
provider.ProviderAnthropic:
|
||||
return types.PromptCacheStatusUnreported
|
||||
default:
|
||||
return types.PromptCacheStatusUnsupported
|
||||
}
|
||||
}
|
||||
|
||||
func tokenUsageFromOpenAI(usage openai.Usage, providerName provider.ProviderName) types.TokenUsage {
|
||||
u := types.TokenUsage{
|
||||
PromptTokens: usage.PromptTokens,
|
||||
CompletionTokens: usage.CompletionTokens,
|
||||
TotalTokens: usage.TotalTokens,
|
||||
}
|
||||
if usage.PromptTokensDetails != nil {
|
||||
read := usage.PromptTokensDetails.CachedTokens
|
||||
u.SetPromptCacheUsage(read, 0, max(0, usage.PromptTokens-read), true)
|
||||
return u
|
||||
}
|
||||
if providerCacheAccountingStatus(providerName) == types.PromptCacheStatusUnsupported {
|
||||
u.MarkPromptCacheUnsupported()
|
||||
} else {
|
||||
u.SetPromptCacheUsage(0, 0, 0, false)
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
// cachedTokens is retained as the nil-safe primitive used by older callers
|
||||
// and focused tests; normalization happens in tokenUsageFromOpenAI.
|
||||
func cachedTokens(details *openai.PromptTokensDetails) int {
|
||||
if details == nil {
|
||||
return 0
|
||||
}
|
||||
return details.CachedTokens
|
||||
}
|
||||
|
||||
type rawPromptCacheUsage struct {
|
||||
Usage struct {
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
PromptCacheHit *int `json:"prompt_cache_hit_tokens"`
|
||||
PromptCacheMiss *int `json:"prompt_cache_miss_tokens"`
|
||||
CacheReadInput *int `json:"cache_read_input_tokens"`
|
||||
CacheCreationInput *int `json:"cache_creation_input_tokens"`
|
||||
PromptTokensDetails *struct {
|
||||
CachedTokens *int `json:"cached_tokens"`
|
||||
CacheWriteTokens *int `json:"cache_write_tokens"`
|
||||
} `json:"prompt_tokens_details"`
|
||||
} `json:"usage"`
|
||||
}
|
||||
|
||||
// applyRawPromptCacheUsage captures native fields discarded by the pinned
|
||||
// OpenAI-compatible SDK (notably DeepSeek hit/miss counters).
|
||||
func applyRawPromptCacheUsage(data []byte, usage *types.TokenUsage) {
|
||||
if usage == nil || len(data) == 0 {
|
||||
return
|
||||
}
|
||||
var raw rawPromptCacheUsage
|
||||
if json.Unmarshal(data, &raw) != nil {
|
||||
return
|
||||
}
|
||||
if raw.Usage.PromptCacheHit != nil || raw.Usage.PromptCacheMiss != nil {
|
||||
read := valueOrZero(raw.Usage.PromptCacheHit)
|
||||
miss := valueOrZero(raw.Usage.PromptCacheMiss)
|
||||
usage.SetPromptCacheUsage(read, 0, miss, true)
|
||||
return
|
||||
}
|
||||
if raw.Usage.CacheReadInput != nil || raw.Usage.CacheCreationInput != nil {
|
||||
read := valueOrZero(raw.Usage.CacheReadInput)
|
||||
write := valueOrZero(raw.Usage.CacheCreationInput)
|
||||
usage.SetPromptCacheUsage(read, write, max(0, usage.PromptTokens-read), true)
|
||||
return
|
||||
}
|
||||
if details := raw.Usage.PromptTokensDetails; details != nil {
|
||||
read := valueOrZero(details.CachedTokens)
|
||||
write := valueOrZero(details.CacheWriteTokens)
|
||||
usage.SetPromptCacheUsage(read, write, max(0, usage.PromptTokens-read), true)
|
||||
}
|
||||
}
|
||||
|
||||
func valueOrZero(value *int) int {
|
||||
if value == nil {
|
||||
return 0
|
||||
}
|
||||
return *value
|
||||
}
|
||||
@@ -146,6 +146,10 @@ func (lkeapProvider) Thinking() ThinkingStrategy { return thinkingTypeField{} }
|
||||
type deepseekProvider struct{ baseProvider }
|
||||
|
||||
func (deepseekProvider) Name() provider.ProviderName { return provider.ProviderDeepSeek }
|
||||
|
||||
// Native DeepSeek cache counters are not represented by go-openai v1.41.2;
|
||||
// use the raw path so prompt_cache_hit_tokens/miss_tokens remain observable.
|
||||
func (deepseekProvider) ForceRawHTTP() bool { return true }
|
||||
func (deepseekProvider) ShapeRequest(req *openai.ChatCompletionRequest, opts *ChatOptions, _ bool) {
|
||||
if opts != nil && opts.ToolChoice != "" {
|
||||
req.ToolChoice = nil
|
||||
|
||||
@@ -147,9 +147,10 @@ func TestBuildOutbound_ShapeRequest(t *testing.T) {
|
||||
c := newOutboundChat(t, string(provider.ProviderDeepSeek), "deepseek-chat", nil)
|
||||
body, _, useRaw, err := c.buildOutbound(msgs, &ChatOptions{ToolChoice: "auto"}, false)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, useRaw)
|
||||
req := body.(*openai.ChatCompletionRequest)
|
||||
assert.Nil(t, req.ToolChoice)
|
||||
assert.True(t, useRaw)
|
||||
request, ok := body.(map[string]any)
|
||||
require.True(t, ok)
|
||||
assert.NotContains(t, request, "tool_choice")
|
||||
})
|
||||
|
||||
t.Run("moonshot pins temperature to 1", func(t *testing.T) {
|
||||
|
||||
@@ -67,6 +67,8 @@ func NewRemoteAPIChat(chatConfig *ChatConfig) (*RemoteAPIChat, error) {
|
||||
config = openai.DefaultConfig(apiKey)
|
||||
if baseURL := chatConfig.BaseURL; baseURL != "" {
|
||||
config.BaseURL = baseURL
|
||||
} else if providerName == provider.ProviderDeepSeek {
|
||||
config.BaseURL = provider.DeepSeekBaseURL
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,7 +102,7 @@ func NewRemoteAPIChat(chatConfig *ChatConfig) (*RemoteAPIChat, error) {
|
||||
modelName: modelName,
|
||||
client: openai.NewClientWithConfig(config),
|
||||
modelID: chatConfig.ModelID,
|
||||
baseURL: chatConfig.BaseURL,
|
||||
baseURL: strings.TrimRight(config.BaseURL, "/"),
|
||||
apiKey: apiKey,
|
||||
provider: providerName,
|
||||
appID: chatConfig.AppID,
|
||||
@@ -255,6 +257,7 @@ func (c *RemoteAPIChat) chatWithRawHTTP(ctx context.Context, endpoint string, cu
|
||||
return nil, err
|
||||
}
|
||||
c.applyCompletionToolCallMetadata(body, result)
|
||||
applyRawPromptCacheUsage(body, &result.Usage)
|
||||
logUsage(ctx, c.modelName, &result.Usage)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
@@ -488,6 +488,10 @@ func TestParseCompletionResponse_CachedTokens(t *testing.T) {
|
||||
assert.Equal(t, 6971, got.Usage.TotalTokens)
|
||||
assert.Equal(t, 6900, got.Usage.CachedTokens,
|
||||
"cached_tokens must mirror prompt_tokens_details.cached_tokens")
|
||||
assert.Equal(t, 6900, got.Usage.CacheReadTokens)
|
||||
assert.Equal(t, 29, got.Usage.CacheMissTokens)
|
||||
assert.True(t, got.Usage.CacheReported)
|
||||
assert.Equal(t, types.PromptCacheStatusHit, got.Usage.CacheStatus)
|
||||
})
|
||||
|
||||
t.Run("missing prompt_tokens_details yields zero cached_tokens", func(t *testing.T) {
|
||||
@@ -512,9 +516,20 @@ func TestParseCompletionResponse_CachedTokens(t *testing.T) {
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, 0, got.Usage.CachedTokens,
|
||||
"missing details must surface as zero, not panic")
|
||||
assert.False(t, got.Usage.CacheReported)
|
||||
assert.Equal(t, types.PromptCacheStatusUnsupported, got.Usage.CacheStatus)
|
||||
})
|
||||
}
|
||||
|
||||
func TestApplyRawPromptCacheUsage_DeepSeekNativeFields(t *testing.T) {
|
||||
usage := types.TokenUsage{PromptTokens: 4096, CompletionTokens: 10, TotalTokens: 4106}
|
||||
applyRawPromptCacheUsage([]byte(`{"usage":{"prompt_tokens":4096,"prompt_cache_hit_tokens":3072,"prompt_cache_miss_tokens":1024}}`), &usage)
|
||||
assert.Equal(t, 3072, usage.CacheReadTokens)
|
||||
assert.Equal(t, 1024, usage.CacheMissTokens)
|
||||
assert.True(t, usage.CacheReported)
|
||||
assert.Equal(t, types.PromptCacheStatusHit, usage.CacheStatus)
|
||||
}
|
||||
|
||||
// TestTokenUsage_CachedTokensJSONOmitempty ensures the new CachedTokens field
|
||||
// stays out of serialized payloads when it is zero. This keeps logs and API
|
||||
// responses unchanged for providers that never report cache hits.
|
||||
|
||||
@@ -14,7 +14,10 @@ func logUsage(ctx context.Context, model string, u *types.TokenUsage) {
|
||||
if u == nil {
|
||||
return
|
||||
}
|
||||
purpose, prefixFingerprint := types.LLMCallMetadataFromContext(ctx)
|
||||
logger.Infof(ctx,
|
||||
"[LLM Usage] model=%s, prompt_tokens=%d, completion_tokens=%d, total_tokens=%d, cached_tokens=%d",
|
||||
model, u.PromptTokens, u.CompletionTokens, u.TotalTokens, u.CachedTokens)
|
||||
"[LLM Usage] model=%s, purpose=%s, prompt_prefix=%s, prompt_tokens=%d, completion_tokens=%d, total_tokens=%d, cached_tokens=%d, cache_read_tokens=%d, cache_write_tokens=%d, cache_miss_tokens=%d, cache_reported=%t, cache_status=%s",
|
||||
model, purpose, prefixFingerprint, u.PromptTokens, u.CompletionTokens, u.TotalTokens,
|
||||
u.CachedTokens, u.CacheReadTokens, u.CacheWriteTokens, u.CacheMissTokens,
|
||||
u.CacheReported, u.CacheStatus)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user