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:
wizardchen
2026-07-23 18:00:35 +08:00
committed by lyingbug
parent 6c794f64cf
commit 6fb858105a
36 changed files with 877 additions and 175 deletions
+61 -20
View File
@@ -5,31 +5,72 @@ import (
"encoding/json"
)
// PromptCacheStatus distinguishes a real cache miss from providers that do not
// expose prompt-cache accounting. Treating both as zero makes fleet-level hit
// rate dashboards misleading.
type PromptCacheStatus string
const (
PromptCacheStatusUnsupported PromptCacheStatus = "unsupported"
PromptCacheStatusUnreported PromptCacheStatus = "unreported"
PromptCacheStatusMiss PromptCacheStatus = "miss"
PromptCacheStatusHit PromptCacheStatus = "hit"
)
// TokenUsage holds token consumption statistics returned by the model API.
type TokenUsage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
// CachedTokens is the subset of PromptTokens that hit a provider-side
// prompt cache. Populated from `usage.prompt_tokens_details.cached_tokens`
// in OpenAI-compatible responses.
//
// Whether this field is non-zero depends on the provider's caching mode:
//
// - Implicit caching (OpenAI, Azure OpenAI, DeepSeek, …) — automatic.
// The field populates whenever the prompt prefix matches a previous
// request within the provider's cache TTL. No client-side opt-in.
//
// - Explicit caching (Qwen on Aliyun, Anthropic Claude, …) — opt-in
// required. The caller must attach `cache_control: {"type":
// "ephemeral"}` to the relevant message or content block to make
// the provider create and read the cache. Until that opt-in is
// applied, CachedTokens stays zero even when the prompt prefix is
// otherwise byte-stable.
//
// Omitted from JSON when zero so payloads stay quiet for providers
// that never populate it.
CachedTokens int `json:"cached_tokens,omitempty"`
// CachedTokens is the legacy alias for CacheReadTokens. It remains on the
// wire for compatibility with existing API consumers.
CachedTokens int `json:"cached_tokens,omitempty"`
CacheReadTokens int `json:"cache_read_tokens,omitempty"`
CacheWriteTokens int `json:"cache_write_tokens,omitempty"`
CacheMissTokens int `json:"cache_miss_tokens,omitempty"`
CacheReported bool `json:"cache_reported"`
CacheStatus PromptCacheStatus `json:"cache_status,omitempty"`
}
// SetPromptCacheUsage normalizes provider-specific cache counters into the
// shared usage model. promptTokens remains the provider's total input-token
// count; read/write/miss are descriptive subsets and must not be added to it.
func (u *TokenUsage) SetPromptCacheUsage(read, write, miss int, reported bool) {
if u == nil {
return
}
if read < 0 {
read = 0
}
if write < 0 {
write = 0
}
if miss < 0 {
miss = 0
}
u.CachedTokens = read
u.CacheReadTokens = read
u.CacheWriteTokens = write
u.CacheMissTokens = miss
u.CacheReported = reported
switch {
case !reported:
u.CacheStatus = PromptCacheStatusUnreported
case read > 0:
u.CacheStatus = PromptCacheStatusHit
default:
u.CacheStatus = PromptCacheStatusMiss
}
}
// MarkPromptCacheUnsupported marks a provider/model path that cannot report
// provider-side prompt-cache usage.
func (u *TokenUsage) MarkPromptCacheUnsupported() {
if u == nil {
return
}
u.SetPromptCacheUsage(0, 0, 0, false)
u.CacheStatus = PromptCacheStatusUnsupported
}
// LLMToolCall represents a function/tool call from the LLM
+6
View File
@@ -45,6 +45,12 @@ const (
// concurrency governor uses this to throttle only background LLM traffic,
// leaving interactive chat latency untouched. See WithBackgroundTask.
BackgroundTaskContextKey ContextKey = "BackgroundTask"
// LLMCallPurposeContextKey labels the product-level reason for a model
// request (for example agent_round or wiki_page_modify).
LLMCallPurposeContextKey ContextKey = "LLMCallPurpose"
// LLMPromptPrefixFingerprintContextKey carries a non-sensitive hash of the
// intended reusable prompt prefix for cache diagnostics.
LLMPromptPrefixFingerprintContextKey ContextKey = "LLMPromptPrefixFingerprint"
// MCPOAuthNonInteractiveContextKey marks a request whose channel cannot
// resolve an in-conversation MCP OAuth prompt (e.g. an IM bot: there is no
// live client to click "Authorize" and call the resolve endpoint). When set,
+23
View File
@@ -183,6 +183,29 @@ func IsBackgroundTask(ctx context.Context) bool {
return v
}
// WithLLMCallMetadata annotates a provider call for cache observability. The
// fingerprint must be a hash, never raw prompt content.
func WithLLMCallMetadata(ctx context.Context, purpose, prefixFingerprint string) context.Context {
if strings.TrimSpace(purpose) != "" {
ctx = context.WithValue(ctx, LLMCallPurposeContextKey, strings.TrimSpace(purpose))
}
if strings.TrimSpace(prefixFingerprint) != "" {
ctx = context.WithValue(ctx, LLMPromptPrefixFingerprintContextKey, strings.TrimSpace(prefixFingerprint))
}
return ctx
}
// LLMCallMetadataFromContext returns the cache-observability labels attached
// by the orchestration layer.
func LLMCallMetadataFromContext(ctx context.Context) (purpose, prefixFingerprint string) {
if ctx == nil {
return "", ""
}
purpose, _ = ctx.Value(LLMCallPurposeContextKey).(string)
prefixFingerprint, _ = ctx.Value(LLMPromptPrefixFingerprintContextKey).(string)
return purpose, prefixFingerprint
}
// LanguageFromContext extracts the language locale string from ctx (e.g. "zh-CN", "en-US").
// Returns ("zh-CN", false) when the key is absent.
func LanguageFromContext(ctx context.Context) (string, bool) {
+8
View File
@@ -145,6 +145,14 @@ func TestLanguageFromContext(t *testing.T) {
}
}
func TestLLMCallMetadataContext(t *testing.T) {
ctx := WithLLMCallMetadata(context.Background(), "wiki_page_modify", "abc123")
purpose, prefix := LLMCallMetadataFromContext(ctx)
if purpose != "wiki_page_modify" || prefix != "abc123" {
t.Fatalf("metadata = (%q, %q)", purpose, prefix)
}
}
// BenchmarkLanguageLocaleName benchmarks the language name lookup
func BenchmarkLanguageLocaleName(b *testing.B) {
testCases := []string{"zh", "en", "zh-CN", "ko", "unknown"}