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
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"sync"
"time"
@@ -1538,7 +1539,7 @@ func (s *wikiIngestService) mapOneDocument(
// swap: emit BOTH a "retract" (carrying the doc's PRIOR summary
// body as the old-version signal) AND the normal addition. The
// reduce stage sees HasAdditions=1 + HasRetractions=1 and the
// WikiPageModifyPrompt correctly tells the editor model to
// WikiPageModifyUserPrompt correctly tells the editor model to
// remove the old K section and add the new K section in one
// pass — giving us replace-not-append semantics that "append
// new K on top of old K" would otherwise violate.
@@ -1706,7 +1707,7 @@ func (s *wikiIngestService) extractEntitiesAndConceptsNoUpsert(
// - changed: whether the wiki page was created or updated
// - affectedType: "ingest" or "retract" — drives downstream bookkeeping
// - additionFailed: true iff the slug had entity/concept additions queued
// AND the WikiPageModifyPrompt LLM call failed, so no page exists/was
// AND the WikiPageModifyUserPrompt LLM call failed, so no page exists/was
// refreshed for it. Callers use this to sanitize dead [[slug]] links
// elsewhere (e.g. in the doc's summary page) and to drop the slug from
// the wiki log feed so users don't see a clickable entry that 404s.
@@ -1875,6 +1876,7 @@ func (s *wikiIngestService) reduceSlugUpdates(
var deletedContent strings.Builder
var relatedSlugs strings.Builder
var newContentBuilder strings.Builder
var sharedSourceContexts strings.Builder
var docTitles []string
var language string
@@ -1936,6 +1938,11 @@ func (s *wikiIngestService) reduceSlugUpdates(
// knowledge ID, so the <new_information> block can quote the chunks
// verbatim instead of relying on the short Details paraphrase.
chunkContentByID := s.resolveCitedChunks(ctx, tenantID, additions)
// A document summary is shared by every page derived from that document.
// Render a deterministic, de-duplicated block before any page-specific
// metadata so provider prefix caches can reuse it across parallel reduce
// calls.
sourceContextByRef := make(map[string]string)
for _, add := range additions {
cited := collectCitedChunkContent(add.SourceChunks, chunkContentByID)
@@ -1947,21 +1954,27 @@ func (s *wikiIngestService) reduceSlugUpdates(
// source documents, and calibrating tone (self-reported vs
// third-party authoritative) benefits from the richer context.
sourceCtx := strings.TrimSpace(add.DocSummary)
sourceCtxBlock := ""
if sourceCtx != "" {
sourceCtxBlock = fmt.Sprintf("<source_context>\n%s\n</source_context>\n", sourceCtx)
contextKey := add.SourceRef
if contextKey == "" {
contextKey = add.KnowledgeID + "\x00" + add.DocTitle
}
sourceContextByRef[contextKey] = fmt.Sprintf(
"<document>\n<title>%s</title>\n<context>\n%s\n</context>\n</document>\n",
add.DocTitle, sourceCtx,
)
}
if cited != "" {
fmt.Fprintf(&newContentBuilder,
"<document>\n<title>%s</title>\n%s<content>\n**%s**: %s\n\n%s\n</content>\n</document>\n\n",
add.DocTitle, sourceCtxBlock, add.Item.Name, add.Item.Description, cited)
"<document>\n<title>%s</title>\n<content>\n**%s**: %s\n\n%s\n</content>\n</document>\n\n",
add.DocTitle, add.Item.Name, add.Item.Description, cited)
} else {
// Fallback: no citations available (legacy path, citation pass
// failed, or bad chunk IDs were filtered out) — stick with
// the short Details summary so the page still gets real text.
fmt.Fprintf(&newContentBuilder,
"<document>\n<title>%s</title>\n%s<content>\n**%s**: %s\n\n%s\n</content>\n</document>\n\n",
add.DocTitle, sourceCtxBlock, add.Item.Name, add.Item.Description, add.Item.Details)
"<document>\n<title>%s</title>\n<content>\n**%s**: %s\n\n%s\n</content>\n</document>\n\n",
add.DocTitle, add.Item.Name, add.Item.Description, add.Item.Details)
}
docTitles = appendUnique(docTitles, add.DocTitle)
@@ -1977,6 +1990,15 @@ func (s *wikiIngestService) reduceSlugUpdates(
page.PageType = add.Type
}
}
contextKeys := make([]string, 0, len(sourceContextByRef))
for key := range sourceContextByRef {
contextKeys = append(contextKeys, key)
}
sort.Strings(contextKeys)
for _, key := range contextKeys {
sharedSourceContexts.WriteString(sourceContextByRef[key])
}
}
if len(additions) > 0 || len(retracts) > 0 {
@@ -2019,7 +2041,7 @@ func (s *wikiIngestService) reduceSlugUpdates(
pageAliases := strings.Join(page.Aliases, ", ")
var updatedContent string
updatedContent, err = s.generateWithTemplate(ctx, chatModel, agent.WikiPageModifyPrompt, map[string]string{
updatedContent, err = s.generateWithTemplate(ctx, chatModel, agent.WikiPageModifyUserPrompt, map[string]string{
"HasAdditions": hasAdditionsStr,
"HasRetractions": hasRetractionsStr,
"PageSlug": slug,
@@ -2027,6 +2049,7 @@ func (s *wikiIngestService) reduceSlugUpdates(
"PageType": pageType,
"PageAliases": pageAliases,
"ExistingContent": existingContent,
"SharedSourceContexts": sharedSourceContexts.String(),
"NewContent": newContentBuilder.String(),
"DeletedContent": deletedContent.String(),
"RemainingSourcesContent": remainingSourcesContent.String(),