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:
@@ -55,6 +55,7 @@ func (p *PluginChatCompletion) OnEvent(
|
||||
resourceRefs := llmresource.NewRegistry()
|
||||
chatMessages = sourceRefs.EncodeMessages(chatMessages)
|
||||
chatMessages = resourceRefs.EncodeMessages(chatMessages)
|
||||
ctx = withPromptCacheMetadata(ctx, chatModel, chatMessages, opt, "knowledge_qa")
|
||||
|
||||
// Call the chat model to generate response
|
||||
pipelineInfo(ctx, "Completion", "model_call", map[string]interface{}{
|
||||
|
||||
@@ -60,6 +60,7 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
|
||||
resourceRefs := llmresource.NewRegistry()
|
||||
chatMessages = sourceRefs.EncodeMessages(chatMessages)
|
||||
chatMessages = resourceRefs.EncodeMessages(chatMessages)
|
||||
ctx = withPromptCacheMetadata(ctx, chatModel, chatMessages, opt, "knowledge_qa")
|
||||
pipelineInfo(ctx, "Stream", "messages_ready", map[string]interface{}{
|
||||
"message_count": len(chatMessages),
|
||||
"system_prompt": chatMessages[0].Content,
|
||||
|
||||
@@ -113,6 +113,18 @@ func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message {
|
||||
return chatMessages
|
||||
}
|
||||
|
||||
func withPromptCacheMetadata(
|
||||
ctx context.Context,
|
||||
chatModel chat.Chat,
|
||||
messages []chat.Message,
|
||||
opts *chat.ChatOptions,
|
||||
purpose string,
|
||||
) context.Context {
|
||||
prefixFingerprint := chat.PromptPrefixFingerprint(messages, opts)
|
||||
_ = chatModel // model identity is already captured by the usage sink
|
||||
return types.WithLLMCallMetadata(ctx, purpose, prefixFingerprint)
|
||||
}
|
||||
|
||||
// AppendHistoryMessages appends prior Q&A rounds in chronological order.
|
||||
// History is already filtered and truncated upstream by the load_history plugin.
|
||||
func AppendHistoryMessages(messages []chat.Message, history []*types.History) []chat.Message {
|
||||
|
||||
@@ -119,7 +119,8 @@ If NO, leave the sql field empty.
|
||||
|
||||
Return your response in the specified JSON format.`, chatManage.Query, knowledge.ID, schema.Description())
|
||||
|
||||
response, err := chatModel.Chat(ctx, []chat.Message{
|
||||
modelCtx := types.WithLLMCallMetadata(ctx, "data_analysis_plan", "")
|
||||
response, err := chatModel.Chat(modelCtx, []chat.Message{
|
||||
{Role: "user", Content: analysisPrompt},
|
||||
}, &chat.ChatOptions{
|
||||
Temperature: 0.1,
|
||||
|
||||
@@ -184,7 +184,8 @@ func (e *Extractor) Extract(ctx context.Context, content string) (*types.GraphDa
|
||||
// logger.Debugf(ctx, "chat system: %s", generator.System(ctx))
|
||||
// logger.Debugf(ctx, "chat user: %s", generator.User(ctx, content))
|
||||
|
||||
chatResponse, err := e.chat.Chat(ctx, generator.Render(ctx, content), e.chatOpt)
|
||||
modelCtx := types.WithLLMCallMetadata(ctx, "entity_extraction", "")
|
||||
chatResponse, err := e.chat.Chat(modelCtx, generator.Render(ctx, content), e.chatOpt)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "failed to chat: %v", err)
|
||||
return nil, err
|
||||
|
||||
@@ -114,7 +114,8 @@ func (p *PluginQueryUnderstand) OnEvent(ctx context.Context,
|
||||
|
||||
// --- Call model ---
|
||||
thinking := false
|
||||
response, err := rewriteModel.Chat(ctx, []chat.Message{
|
||||
modelCtx := types.WithLLMCallMetadata(ctx, "query_rewrite", "")
|
||||
response, err := rewriteModel.Chat(modelCtx, []chat.Message{
|
||||
{Role: "system", Content: systemContent},
|
||||
userMsg,
|
||||
}, &chat.ChatOptions{
|
||||
|
||||
@@ -395,7 +395,7 @@ func (s *knowledgeService) scrubWikiPendingIngest(ctx context.Context, kbID, kno
|
||||
// actual swap happens asynchronously inside mapOneDocument (see its
|
||||
// oldPageSlugs handling) — that's where we have both the old page set and
|
||||
// the freshly extracted candidate slugs, which is exactly the information
|
||||
// the WikiPageModifyPrompt needs to do a correct replace-not-append.
|
||||
// the WikiPageModifyUserPrompt needs to do a correct replace-not-append.
|
||||
//
|
||||
// So the only thing worth doing synchronously at reparse time is keeping
|
||||
// the Redis pending list clean so the re-ingest enqueued by
|
||||
|
||||
@@ -829,7 +829,8 @@ func (s *knowledgeService) getSummary(ctx context.Context,
|
||||
"language": types.LanguageNameFromContext(ctx),
|
||||
})
|
||||
thinking := false
|
||||
summary, err := summaryModel.Chat(ctx, []chat.Message{
|
||||
modelCtx := types.WithLLMCallMetadata(ctx, "document_summary", "")
|
||||
summary, err := summaryModel.Chat(modelCtx, []chat.Message{
|
||||
{
|
||||
Role: "system",
|
||||
Content: summaryPrompt,
|
||||
@@ -1928,7 +1929,8 @@ func (s *knowledgeService) generateQuestionsWithContext(ctx context.Context,
|
||||
prompt = types.AppendCustomPromptInstructions(prompt, customInstructions, "question_generation")
|
||||
|
||||
thinking := false
|
||||
response, err := chatModel.Chat(ctx, []chat.Message{
|
||||
modelCtx := types.WithLLMCallMetadata(ctx, "question_generation", "")
|
||||
response, err := chatModel.Chat(modelCtx, []chat.Message{
|
||||
{
|
||||
Role: "user",
|
||||
Content: prompt,
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"golang.org/x/sync/singleflight"
|
||||
)
|
||||
|
||||
// ErrWikiIngestConcurrent is returned by the wiki ingest handler in Lite mode
|
||||
@@ -344,6 +345,17 @@ type wikiIngestService struct {
|
||||
// wiki:finalize:active:<kbID> lock, keeping two finalize runs for the
|
||||
// same KB from overlapping when there is no Redis.
|
||||
liteFinalizeLocks sync.Map
|
||||
// llmRequests coalesces byte-identical concurrent prompts within this
|
||||
// process. Keys include tenant and model to preserve isolation.
|
||||
llmRequests singleflight.Group
|
||||
// promptWarmups serializes only the first request for a reusable Wiki page
|
||||
// prefix. Other prefixes and already-warmed cohorts stay parallel.
|
||||
promptWarmups sync.Map
|
||||
}
|
||||
|
||||
type wikiPromptWarmup struct {
|
||||
done chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
// NewWikiIngestService creates a new wiki ingest service
|
||||
@@ -1399,7 +1411,7 @@ var wikiLinkRE = regexp.MustCompile(`\[\[([^\[\]\|\s]+)(?:\|([^\]]+))?\]\]`)
|
||||
// Background: WikiSummaryPrompt instructs the LLM to embed wiki links
|
||||
// for every extracted slug it knows about, but slug extraction happens
|
||||
// during map (parallel with summary generation) and the actual page
|
||||
// creation happens later in reduce. When reduce's WikiPageModifyPrompt
|
||||
// creation happens later in reduce. When reduce's WikiPageModifyUserPrompt
|
||||
// fails on an entity/concept slug the page never gets written — and
|
||||
// the already-persisted summary is left holding a `[[entity/foo|name]]`
|
||||
// link that 404s.
|
||||
@@ -2379,42 +2391,163 @@ func (s *wikiIngestService) generateWithTemplate(ctx context.Context, chatModel
|
||||
}
|
||||
|
||||
prompt := buf.String()
|
||||
prompt = types.AppendCustomPromptInstructions(prompt, data["CustomInstructions"], data["InstructionScope"])
|
||||
thinking := false
|
||||
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= wikiLLMMaxAttempts; attempt++ {
|
||||
response, err := chatModel.Chat(ctx, []chat.Message{
|
||||
purpose := wikiPromptPurpose(promptTpl)
|
||||
messages := []chat.Message{{Role: "user", Content: prompt}}
|
||||
if promptTpl == agent.WikiPageModifyUserPrompt {
|
||||
systemPrompt := types.AppendCustomPromptInstructions(
|
||||
agent.WikiPageModifySystemPrompt,
|
||||
maskedData["CustomInstructions"],
|
||||
maskedData["InstructionScope"],
|
||||
)
|
||||
messages = []chat.Message{
|
||||
{Role: "system", Content: systemPrompt},
|
||||
{Role: "user", Content: prompt},
|
||||
}, &chat.ChatOptions{
|
||||
Temperature: 0.3,
|
||||
Thinking: &thinking,
|
||||
})
|
||||
if err == nil {
|
||||
return unmaskImageURLs(response.Content, urlMap), nil
|
||||
}
|
||||
lastErr = err
|
||||
|
||||
// Abort immediately on non-retryable errors (4xx except 408/429,
|
||||
// parse/marshal failures, tool-side bugs, etc.). Retrying a
|
||||
// hard "invalid arguments" error just wastes the model's budget.
|
||||
if !isTransientLLMError(ctx, err) {
|
||||
return "", fmt.Errorf("LLM call failed: %w", err)
|
||||
}
|
||||
if attempt == wikiLLMMaxAttempts {
|
||||
break
|
||||
}
|
||||
|
||||
backoff := wikiLLMBackoffBase << (attempt - 1)
|
||||
logger.Warnf(ctx, "wiki ingest: LLM call failed (attempt %d/%d), retrying in %s: %v",
|
||||
attempt, wikiLLMMaxAttempts, backoff, err)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return "", fmt.Errorf("LLM call aborted during backoff: %w", ctx.Err())
|
||||
case <-time.After(backoff):
|
||||
} else {
|
||||
messages[0].Content = types.AppendCustomPromptInstructions(
|
||||
prompt, maskedData["CustomInstructions"], maskedData["InstructionScope"],
|
||||
)
|
||||
}
|
||||
thinking := false
|
||||
opts := &chat.ChatOptions{Temperature: 0.3, Thinking: &thinking}
|
||||
prefixFingerprint := chat.PromptPrefixFingerprint(messages, opts)
|
||||
warmupKey := ""
|
||||
if promptTpl == agent.WikiPageModifyUserPrompt {
|
||||
prefixFingerprint = chat.FingerprintPromptPrefix(
|
||||
messages[0].Content, maskedData["SharedSourceContexts"],
|
||||
)
|
||||
if tenantID, ok := types.TenantIDFromContext(ctx); ok {
|
||||
warmupKey = chat.BuildPromptCacheKey(
|
||||
tenantID, chatModel.GetModelID(), purpose, prefixFingerprint,
|
||||
)
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("LLM call failed after %d attempts: %w", wikiLLMMaxAttempts, lastErr)
|
||||
ctx = types.WithLLMCallMetadata(ctx, purpose, prefixFingerprint)
|
||||
|
||||
tenantID, tenantScoped := types.TenantIDFromContext(ctx)
|
||||
requestJSON, _ := json.Marshal(struct {
|
||||
Messages []chat.Message `json:"messages"`
|
||||
Options *chat.ChatOptions `json:"options"`
|
||||
}{Messages: messages, Options: opts})
|
||||
requestKey := chat.BuildPromptCacheKey(
|
||||
tenantID, chatModel.GetModelID(), "wiki_exact_request",
|
||||
chat.FingerprintPromptPrefix(string(requestJSON)),
|
||||
)
|
||||
|
||||
execute := func() (interface{}, error) {
|
||||
releaseWarmup := func() {}
|
||||
if tenantScoped && promptTpl == agent.WikiPageModifyUserPrompt && strings.TrimSpace(maskedData["SharedSourceContexts"]) != "" {
|
||||
var warmupErr error
|
||||
releaseWarmup, warmupErr = s.awaitWikiPromptWarmup(ctx, warmupKey)
|
||||
if warmupErr != nil {
|
||||
return "", warmupErr
|
||||
}
|
||||
}
|
||||
defer releaseWarmup()
|
||||
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= wikiLLMMaxAttempts; attempt++ {
|
||||
response, callErr := chatModel.Chat(ctx, messages, opts)
|
||||
if callErr == nil && response != nil {
|
||||
return response.Content, nil
|
||||
}
|
||||
if callErr == nil {
|
||||
callErr = errors.New("LLM returned nil response")
|
||||
}
|
||||
lastErr = callErr
|
||||
|
||||
if !isTransientLLMError(ctx, callErr) {
|
||||
return "", fmt.Errorf("LLM call failed: %w", callErr)
|
||||
}
|
||||
if attempt == wikiLLMMaxAttempts {
|
||||
break
|
||||
}
|
||||
|
||||
backoff := wikiLLMBackoffBase << (attempt - 1)
|
||||
logger.Warnf(ctx, "wiki ingest: LLM call failed (attempt %d/%d), retrying in %s: %v",
|
||||
attempt, wikiLLMMaxAttempts, backoff, callErr)
|
||||
timer := time.NewTimer(backoff)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return "", fmt.Errorf("LLM call aborted during backoff: %w", ctx.Err())
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("LLM call failed after %d attempts: %w", wikiLLMMaxAttempts, lastErr)
|
||||
}
|
||||
|
||||
// Missing tenant context is unexpected for production Wiki work. Fail safe
|
||||
// by skipping cross-call coalescing instead of putting unrelated requests
|
||||
// into a synthetic tenant-0 bucket.
|
||||
if !tenantScoped {
|
||||
value, executeErr := execute()
|
||||
if executeErr != nil {
|
||||
return "", executeErr
|
||||
}
|
||||
content, _ := value.(string)
|
||||
return unmaskImageURLs(content, urlMap), nil
|
||||
}
|
||||
resultCh := s.llmRequests.DoChan(requestKey, execute)
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return "", ctx.Err()
|
||||
case result := <-resultCh:
|
||||
if result.Err != nil {
|
||||
return "", result.Err
|
||||
}
|
||||
content, _ := result.Val.(string)
|
||||
return unmaskImageURLs(content, urlMap), nil
|
||||
}
|
||||
}
|
||||
|
||||
func wikiPromptPurpose(promptTpl string) string {
|
||||
switch promptTpl {
|
||||
case agent.WikiPageModifyUserPrompt:
|
||||
return "wiki_page_modify"
|
||||
case agent.WikiChunkCitationPrompt:
|
||||
return "wiki_chunk_citation"
|
||||
case agent.WikiCandidateSlugPrompt:
|
||||
return "wiki_candidate_slug"
|
||||
case agent.WikiSummaryPrompt:
|
||||
return "wiki_summary"
|
||||
case agent.WikiKnowledgeExtractPrompt:
|
||||
return "wiki_knowledge_extract"
|
||||
case agent.WikiTaxonomyPlanPrompt:
|
||||
return "wiki_taxonomy_plan"
|
||||
case agent.WikiDeduplicationPrompt:
|
||||
return "wiki_deduplication"
|
||||
case agent.WikiIndexIntroPrompt, agent.WikiIndexIntroUpdatePrompt:
|
||||
return "wiki_index_intro"
|
||||
default:
|
||||
return "wiki_generation"
|
||||
}
|
||||
}
|
||||
|
||||
func (s *wikiIngestService) awaitWikiPromptWarmup(ctx context.Context, key string) (func(), error) {
|
||||
if key == "" {
|
||||
return func() {}, nil
|
||||
}
|
||||
candidate := &wikiPromptWarmup{done: make(chan struct{})}
|
||||
actual, loaded := s.promptWarmups.LoadOrStore(key, candidate)
|
||||
entry := actual.(*wikiPromptWarmup)
|
||||
if !loaded {
|
||||
return func() {
|
||||
entry.once.Do(func() { close(entry.done) })
|
||||
// Keep the local warmed marker long enough to cover the parallel
|
||||
// reduce burst without turning it into a persistent application cache.
|
||||
time.AfterFunc(4*time.Minute, func() {
|
||||
s.promptWarmups.CompareAndDelete(key, entry)
|
||||
})
|
||||
}, nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-entry.done:
|
||||
return func() {}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// isTransientLLMError reports whether an error from the chat provider
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -4,9 +4,12 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
@@ -334,16 +337,25 @@ func TestGenerateWithTemplateMasksImageURLsBeforeLLM(t *testing.T) {
|
||||
type templateCaptureChatModel struct {
|
||||
prompt string
|
||||
response string
|
||||
messages []chat.Message
|
||||
options chat.ChatOptions
|
||||
purpose string
|
||||
prefix string
|
||||
}
|
||||
|
||||
func (m *templateCaptureChatModel) Chat(
|
||||
_ context.Context,
|
||||
ctx context.Context,
|
||||
messages []chat.Message,
|
||||
_ *chat.ChatOptions,
|
||||
opts *chat.ChatOptions,
|
||||
) (*types.ChatResponse, error) {
|
||||
if len(messages) > 0 {
|
||||
m.prompt = messages[0].Content
|
||||
}
|
||||
m.messages = append([]chat.Message(nil), messages...)
|
||||
if opts != nil {
|
||||
m.options = *opts
|
||||
}
|
||||
m.purpose, m.prefix = types.LLMCallMetadataFromContext(ctx)
|
||||
return &types.ChatResponse{Content: m.response}, nil
|
||||
}
|
||||
|
||||
@@ -358,6 +370,118 @@ func (m *templateCaptureChatModel) ChatStream(
|
||||
func (m *templateCaptureChatModel) GetModelName() string { return "capture" }
|
||||
func (m *templateCaptureChatModel) GetModelID() string { return "capture" }
|
||||
|
||||
func TestGenerateWikiPageModifyUsesCacheableMessageLayout(t *testing.T) {
|
||||
model := &templateCaptureChatModel{response: "SUMMARY: page\n# Alpha"}
|
||||
service := &wikiIngestService{}
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
|
||||
_, err := service.generateWithTemplate(ctx, model, agent.WikiPageModifyUserPrompt, map[string]string{
|
||||
"HasAdditions": "1",
|
||||
"SharedSourceContexts": "<document><context>shared source summary</context></document>\n",
|
||||
"PageSlug": "concept/alpha",
|
||||
"PageTitle": "Alpha",
|
||||
"PageType": "concept",
|
||||
"ExistingContent": "(New page)",
|
||||
"NewContent": "page-specific evidence",
|
||||
"AvailableSlugs": "concept/beta (Beta)",
|
||||
"Language": "English",
|
||||
"InstructionScope": "wiki_content",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("generateWithTemplate() error = %v", err)
|
||||
}
|
||||
if len(model.messages) != 2 || model.messages[0].Role != "system" || model.messages[1].Role != "user" {
|
||||
t.Fatalf("unexpected message layout: %#v", model.messages)
|
||||
}
|
||||
if !strings.Contains(model.messages[0].Content, "SOURCE GROUNDING & MERGE RULES") {
|
||||
t.Fatalf("system prompt missing stable rules: %q", model.messages[0].Content)
|
||||
}
|
||||
if !strings.HasPrefix(model.messages[1].Content, "<shared_source_contexts>") {
|
||||
t.Fatalf("shared source context must lead user message: %q", model.messages[1].Content)
|
||||
}
|
||||
if model.purpose != "wiki_page_modify" || model.prefix == "" {
|
||||
t.Fatalf("missing cache metadata: purpose=%q prefix=%q", model.purpose, model.prefix)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAwaitWikiPromptWarmupBlocksFollowersUntilLeaderCompletes(t *testing.T) {
|
||||
service := &wikiIngestService{}
|
||||
release, err := service.awaitWikiPromptWarmup(context.Background(), "same-prefix")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
followerDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, followErr := service.awaitWikiPromptWarmup(context.Background(), "same-prefix")
|
||||
followerDone <- followErr
|
||||
}()
|
||||
select {
|
||||
case <-followerDone:
|
||||
t.Fatal("follower passed warmup gate before leader completed")
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
release()
|
||||
select {
|
||||
case followErr := <-followerDone:
|
||||
if followErr != nil {
|
||||
t.Fatal(followErr)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("follower did not resume after leader completed")
|
||||
}
|
||||
}
|
||||
|
||||
type blockingTemplateChatModel struct {
|
||||
calls atomic.Int32
|
||||
started chan struct{}
|
||||
release chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (m *blockingTemplateChatModel) Chat(
|
||||
context.Context,
|
||||
[]chat.Message,
|
||||
*chat.ChatOptions,
|
||||
) (*types.ChatResponse, error) {
|
||||
m.calls.Add(1)
|
||||
m.once.Do(func() { close(m.started) })
|
||||
<-m.release
|
||||
return &types.ChatResponse{Content: "shared result"}, nil
|
||||
}
|
||||
|
||||
func (m *blockingTemplateChatModel) ChatStream(context.Context, []chat.Message, *chat.ChatOptions) (<-chan types.StreamResponse, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *blockingTemplateChatModel) GetModelName() string { return "blocking" }
|
||||
func (m *blockingTemplateChatModel) GetModelID() string { return "blocking" }
|
||||
|
||||
func TestGenerateWithTemplateCoalescesIdenticalConcurrentRequests(t *testing.T) {
|
||||
model := &blockingTemplateChatModel{started: make(chan struct{}), release: make(chan struct{})}
|
||||
service := &wikiIngestService{}
|
||||
result := make(chan error, 2)
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
|
||||
call := func() {
|
||||
_, err := service.generateWithTemplate(ctx, model, "same {{.Value}}", map[string]string{"Value": "input"})
|
||||
result <- err
|
||||
}
|
||||
go call()
|
||||
<-model.started
|
||||
go call()
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if got := model.calls.Load(); got != 1 {
|
||||
t.Fatalf("identical requests reached provider %d times before release", got)
|
||||
}
|
||||
close(model.release)
|
||||
for range 2 {
|
||||
if err := <-result; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if got := model.calls.Load(); got != 1 {
|
||||
t.Fatalf("identical requests reached provider %d times, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWikiIngestCleanupContextDetachedFromCancelledParent(t *testing.T) {
|
||||
parent := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(42))
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
|
||||
Reference in New Issue
Block a user