feat(llm): introduce request-local source reference aliases
Replace raw chunk/document/KB IDs in LLM context with short cN/dN/bN/wN aliases, decode tool arguments on the way in, and expand compact <ref/> citations to the public <kb>/<web> format before user-facing output.
This commit is contained in:
@@ -0,0 +1,429 @@
|
||||
package llmreference
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// ModelOutput returns a compact, source-centric representation for the LLM.
|
||||
// The canonical ToolResult.Output remains untouched for UI, logs and storage.
|
||||
func (r *Registry) ModelOutput(result *types.ToolResult) string {
|
||||
if result == nil {
|
||||
return ""
|
||||
}
|
||||
if !result.Success {
|
||||
if result.Error != "" {
|
||||
return "Error: " + r.CompactKnownText(result.Error)
|
||||
}
|
||||
return "Error: tool call failed"
|
||||
}
|
||||
displayType := stringValue(result.Data, "display_type")
|
||||
switch displayType {
|
||||
case "grep_results":
|
||||
return r.modelKnowledgeOutput("keyword", mapsValue(result.Data["chunk_results"]), result.Output)
|
||||
case "search_results":
|
||||
return r.modelKnowledgeOutput("semantic", mapsValue(result.Data["results"]), result.Output)
|
||||
case "knowledge_chunks_list":
|
||||
return r.modelKnowledgeChunksOutput(result.Data, result.Output)
|
||||
case "document_info":
|
||||
return r.modelDocumentInfoOutput(mapsValue(result.Data["documents"]), result.Output)
|
||||
case "graph_query_results":
|
||||
return r.modelKnowledgeOutput("graph", mapsValue(result.Data["results"]), result.Output)
|
||||
case "web_search_results":
|
||||
return r.modelWebSearchOutput(mapsValue(result.Data["results"]), result.Output)
|
||||
case "web_fetch_results":
|
||||
return r.modelWebFetchOutput(mapsValue(result.Data["results"]), result.Output)
|
||||
default:
|
||||
r.registerLabeledReferences(result.Output)
|
||||
return r.CompactKnownText(result.Output)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Registry) modelDocumentInfoOutput(rows []map[string]interface{}, fallback string) string {
|
||||
if len(rows) == 0 {
|
||||
return r.CompactKnownText(fallback)
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("<documents>\n")
|
||||
count := 0
|
||||
for _, row := range rows {
|
||||
knowledgeID := stringValue(row, "knowledge_id")
|
||||
docAlias := r.RegisterDocument(knowledgeID)
|
||||
if boolValue(row, "is_faq") {
|
||||
chunkID := stringValue(row, "faq_id")
|
||||
if chunkID == "" {
|
||||
continue
|
||||
}
|
||||
title := firstNonEmpty(stringValue(row, "faq_question"), stringValue(row, "title"))
|
||||
chunkAlias := r.RegisterChunk(ChunkReference{
|
||||
ChunkID: chunkID,
|
||||
KnowledgeID: knowledgeID,
|
||||
DocumentTitle: title,
|
||||
ChunkType: "faq",
|
||||
})
|
||||
fmt.Fprintf(&b, " <document id=\"%s\" type=\"faq\">\n", escapeAttr(docAlias))
|
||||
fmt.Fprintf(&b, " <chunk id=\"%s\" type=\"faq\">\n", escapeAttr(chunkAlias))
|
||||
if title != "" {
|
||||
fmt.Fprintf(&b, " <question>%s</question>\n", escapeText(title))
|
||||
}
|
||||
for _, answer := range stringSliceValue(row["faq_answers"]) {
|
||||
fmt.Fprintf(&b, " <answer>%s</answer>\n", escapeText(answer))
|
||||
}
|
||||
b.WriteString(" </chunk>\n </document>\n")
|
||||
count++
|
||||
continue
|
||||
}
|
||||
|
||||
if docAlias == "" {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&b, " <document id=\"%s\"", escapeAttr(docAlias))
|
||||
if title := stringValue(row, "title"); title != "" {
|
||||
fmt.Fprintf(&b, " title=\"%s\"", escapeAttr(title))
|
||||
}
|
||||
if docType := stringValue(row, "type"); docType != "" {
|
||||
fmt.Fprintf(&b, " type=\"%s\"", escapeAttr(docType))
|
||||
}
|
||||
if fileType := stringValue(row, "file_type"); fileType != "" {
|
||||
fmt.Fprintf(&b, " file_type=\"%s\"", escapeAttr(fileType))
|
||||
}
|
||||
fmt.Fprintf(&b, " chunk_count=\"%d\">\n", intValue(row, "chunk_count"))
|
||||
if description := stringValue(row, "description"); description != "" {
|
||||
fmt.Fprintf(&b, " <description>%s</description>\n", escapeText(description))
|
||||
}
|
||||
b.WriteString(" </document>\n")
|
||||
count++
|
||||
}
|
||||
b.WriteString("</documents>")
|
||||
if count == 0 {
|
||||
return r.CompactKnownText(fallback)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
type modelChunk struct {
|
||||
alias string
|
||||
docAlias string
|
||||
kbAlias string
|
||||
title string
|
||||
chunkType string
|
||||
index int
|
||||
view string
|
||||
match string
|
||||
content string
|
||||
question string
|
||||
answers []string
|
||||
images []map[string]interface{}
|
||||
docRealID string
|
||||
kbRealID string
|
||||
chunkReal string
|
||||
inputOrder int
|
||||
}
|
||||
|
||||
func (r *Registry) modelKnowledgeOutput(mode string, rows []map[string]interface{}, fallback string) string {
|
||||
chunks := make([]modelChunk, 0, len(rows))
|
||||
for idx, row := range rows {
|
||||
chunkID := firstNonEmpty(stringValue(row, "chunk_id"), stringValue(row, "faq_id"), stringValue(row, "id"))
|
||||
knowledgeID := stringValue(row, "knowledge_id")
|
||||
kbID := firstNonEmpty(stringValue(row, "knowledge_base_id"), stringValue(row, "knowledge_base"))
|
||||
title := firstNonEmpty(stringValue(row, "knowledge_title"), stringValue(row, "title"))
|
||||
if chunkID == "" {
|
||||
continue
|
||||
}
|
||||
chunkType := stringValue(row, "chunk_type")
|
||||
if stringValue(row, "faq_id") != "" && chunkType == "" {
|
||||
chunkType = "faq"
|
||||
}
|
||||
chunkIndex := intValue(row, "chunk_index")
|
||||
if chunkIndex == 0 {
|
||||
chunkIndex = intValue(row, "index")
|
||||
}
|
||||
chunkAlias := r.RegisterChunk(ChunkReference{
|
||||
ChunkID: chunkID,
|
||||
KnowledgeID: knowledgeID,
|
||||
KnowledgeBaseID: kbID,
|
||||
DocumentTitle: title,
|
||||
ChunkIndex: chunkIndex,
|
||||
ChunkType: chunkType,
|
||||
})
|
||||
chunks = append(chunks, modelChunk{
|
||||
alias: chunkAlias,
|
||||
docAlias: r.RegisterDocument(knowledgeID),
|
||||
kbAlias: r.RegisterKnowledgeBase(kbID),
|
||||
title: title,
|
||||
chunkType: chunkType,
|
||||
index: chunkIndex,
|
||||
view: viewForRow(row, mode),
|
||||
match: firstNonEmpty(stringValue(row, "match_snippet"), stringValue(row, "matched_content")),
|
||||
content: stringValue(row, "content"),
|
||||
question: firstNonEmpty(stringValue(row, "faq_question"), stringValue(row, "faq_standard_question")),
|
||||
answers: stringSliceValue(row["faq_answers"]),
|
||||
images: mapsValue(row["images"]),
|
||||
docRealID: knowledgeID,
|
||||
kbRealID: kbID,
|
||||
chunkReal: chunkID,
|
||||
inputOrder: idx,
|
||||
})
|
||||
}
|
||||
if len(chunks) == 0 {
|
||||
return r.CompactKnownText(fallback)
|
||||
}
|
||||
return renderKnowledgeChunks(mode, chunks)
|
||||
}
|
||||
|
||||
func viewForRow(row map[string]interface{}, mode string) string {
|
||||
if stringValue(row, "content") != "" {
|
||||
return "full"
|
||||
}
|
||||
if mode == "deep_read" {
|
||||
return "full"
|
||||
}
|
||||
return "match"
|
||||
}
|
||||
|
||||
func (r *Registry) modelKnowledgeChunksOutput(data map[string]interface{}, fallback string) string {
|
||||
rows := mapsValue(data["chunks"])
|
||||
title := stringValue(data, "knowledge_title")
|
||||
knowledgeID := stringValue(data, "knowledge_id")
|
||||
for _, row := range rows {
|
||||
if stringValue(row, "knowledge_id") == "" {
|
||||
row["knowledge_id"] = knowledgeID
|
||||
}
|
||||
if stringValue(row, "knowledge_title") == "" {
|
||||
row["knowledge_title"] = title
|
||||
}
|
||||
}
|
||||
output := r.modelKnowledgeOutput("deep_read", rows, fallback)
|
||||
if len(rows) == 0 {
|
||||
return output
|
||||
}
|
||||
remaining := intValue(data, "total_chunks") - intValue(data, "fetched_chunks")
|
||||
if remaining > 0 {
|
||||
output = strings.TrimSuffix(output, "</retrieval>")
|
||||
output += fmt.Sprintf(" <pagination remaining=\"%d\" page=\"%d\" page_size=\"%d\" />\n</retrieval>",
|
||||
remaining, intValue(data, "page"), intValue(data, "page_size"))
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
func renderKnowledgeChunks(mode string, chunks []modelChunk) string {
|
||||
type docGroup struct {
|
||||
alias string
|
||||
kbAlias string
|
||||
title string
|
||||
chunks []modelChunk
|
||||
order int
|
||||
}
|
||||
groupsByKey := make(map[string]*docGroup)
|
||||
var groups []*docGroup
|
||||
for _, chunk := range chunks {
|
||||
key := chunk.docAlias
|
||||
if key == "" {
|
||||
key = "chunk:" + chunk.alias
|
||||
}
|
||||
group := groupsByKey[key]
|
||||
if group == nil {
|
||||
group = &docGroup{alias: chunk.docAlias, kbAlias: chunk.kbAlias, title: chunk.title, order: chunk.inputOrder}
|
||||
groupsByKey[key] = group
|
||||
groups = append(groups, group)
|
||||
}
|
||||
group.chunks = append(group.chunks, chunk)
|
||||
}
|
||||
sort.SliceStable(groups, func(i, j int) bool { return groups[i].order < groups[j].order })
|
||||
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "<retrieval type=\"knowledge\" mode=\"%s\">\n", escapeAttr(mode))
|
||||
for _, group := range groups {
|
||||
b.WriteString(" <document")
|
||||
if group.alias != "" {
|
||||
fmt.Fprintf(&b, " id=\"%s\"", escapeAttr(group.alias))
|
||||
}
|
||||
if group.kbAlias != "" {
|
||||
fmt.Fprintf(&b, " kb=\"%s\"", escapeAttr(group.kbAlias))
|
||||
}
|
||||
if group.title != "" {
|
||||
fmt.Fprintf(&b, " title=\"%s\"", escapeAttr(group.title))
|
||||
}
|
||||
b.WriteString(">\n")
|
||||
for _, chunk := range group.chunks {
|
||||
fmt.Fprintf(&b, " <chunk id=\"%s\" index=\"%d\" view=\"%s\"", chunk.alias, chunk.index, chunk.view)
|
||||
if chunk.chunkType != "" {
|
||||
fmt.Fprintf(&b, " type=\"%s\"", escapeAttr(chunk.chunkType))
|
||||
}
|
||||
b.WriteString(">\n")
|
||||
if chunk.question != "" {
|
||||
fmt.Fprintf(&b, " <question>%s</question>\n", escapeText(chunk.question))
|
||||
}
|
||||
if chunk.match != "" {
|
||||
fmt.Fprintf(&b, " <match>%s</match>\n", escapeText(chunk.match))
|
||||
}
|
||||
if chunk.content != "" {
|
||||
fmt.Fprintf(&b, " <content>%s</content>\n", escapeText(chunk.content))
|
||||
}
|
||||
for _, answer := range chunk.answers {
|
||||
fmt.Fprintf(&b, " <answer>%s</answer>\n", escapeText(answer))
|
||||
}
|
||||
for _, image := range chunk.images {
|
||||
imageURL := stringValue(image, "url")
|
||||
if imageURL == "" {
|
||||
continue
|
||||
}
|
||||
caption := stringValue(image, "caption")
|
||||
fmt.Fprintf(&b, " \n", caption, imageURL)
|
||||
}
|
||||
b.WriteString(" </chunk>\n")
|
||||
}
|
||||
b.WriteString(" </document>\n")
|
||||
}
|
||||
b.WriteString("</retrieval>")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (r *Registry) modelWebSearchOutput(rows []map[string]interface{}, fallback string) string {
|
||||
if len(rows) == 0 {
|
||||
return r.CompactKnownText(fallback)
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("<retrieval type=\"web\" mode=\"search\">\n")
|
||||
count := 0
|
||||
for _, row := range rows {
|
||||
rawURL := stringValue(row, "url")
|
||||
if rawURL == "" {
|
||||
continue
|
||||
}
|
||||
alias := r.RegisterWeb(rawURL, stringValue(row, "title"))
|
||||
fmt.Fprintf(&b, " <page id=\"%s\" title=\"%s\">\n", alias, escapeAttr(stringValue(row, "title")))
|
||||
if snippet := stringValue(row, "snippet"); snippet != "" {
|
||||
fmt.Fprintf(&b, " <match>%s</match>\n", escapeText(snippet))
|
||||
}
|
||||
if published := stringValue(row, "published_at"); published != "" {
|
||||
fmt.Fprintf(&b, " <published>%s</published>\n", escapeText(published))
|
||||
}
|
||||
b.WriteString(" </page>\n")
|
||||
count++
|
||||
}
|
||||
b.WriteString("</retrieval>")
|
||||
if count == 0 {
|
||||
return r.CompactKnownText(fallback)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (r *Registry) modelWebFetchOutput(rows []map[string]interface{}, fallback string) string {
|
||||
if len(rows) == 0 {
|
||||
return r.CompactKnownText(fallback)
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("<retrieval type=\"web\" mode=\"fetch\">\n")
|
||||
count := 0
|
||||
for _, row := range rows {
|
||||
rawURL := stringValue(row, "url")
|
||||
if rawURL == "" {
|
||||
continue
|
||||
}
|
||||
title := stringValue(row, "title")
|
||||
alias := r.RegisterWeb(rawURL, title)
|
||||
fmt.Fprintf(&b, " <page id=\"%s\"", alias)
|
||||
if title != "" {
|
||||
fmt.Fprintf(&b, " title=\"%s\"", escapeAttr(title))
|
||||
}
|
||||
b.WriteString(" view=\"full\">\n")
|
||||
if summary := stringValue(row, "summary"); summary != "" {
|
||||
fmt.Fprintf(&b, " <summary>%s</summary>\n", escapeText(summary))
|
||||
}
|
||||
if content := stringValue(row, "raw_content"); content != "" {
|
||||
fmt.Fprintf(&b, " <content>%s</content>\n", escapeText(content))
|
||||
}
|
||||
b.WriteString(" </page>\n")
|
||||
count++
|
||||
}
|
||||
b.WriteString("</retrieval>")
|
||||
if count == 0 {
|
||||
return r.CompactKnownText(fallback)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func mapsValue(value interface{}) []map[string]interface{} {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var rows []map[string]interface{}
|
||||
if err := json.Unmarshal(encoded, &rows); err != nil {
|
||||
return nil
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
func stringValue(values map[string]interface{}, key string) string {
|
||||
if values == nil {
|
||||
return ""
|
||||
}
|
||||
switch value := values[key].(type) {
|
||||
case string:
|
||||
return value
|
||||
case fmt.Stringer:
|
||||
return value.String()
|
||||
case json.Number:
|
||||
return value.String()
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func intValue(values map[string]interface{}, key string) int {
|
||||
if values == nil {
|
||||
return 0
|
||||
}
|
||||
switch value := values[key].(type) {
|
||||
case int:
|
||||
return value
|
||||
case int32:
|
||||
return int(value)
|
||||
case int64:
|
||||
return int(value)
|
||||
case float64:
|
||||
return int(value)
|
||||
case json.Number:
|
||||
result, _ := value.Int64()
|
||||
return int(result)
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func boolValue(values map[string]interface{}, key string) bool {
|
||||
if values == nil {
|
||||
return false
|
||||
}
|
||||
value, _ := values[key].(bool)
|
||||
return value
|
||||
}
|
||||
|
||||
func stringSliceValue(value interface{}) []string {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var values []string
|
||||
if err := json.Unmarshal(encoded, &values); err != nil {
|
||||
return nil
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func escapeText(value string) string {
|
||||
replacer := strings.NewReplacer("&", "&", "<", "<", ">", ">")
|
||||
return replacer.Replace(value)
|
||||
}
|
||||
@@ -0,0 +1,680 @@
|
||||
// Package llmreference keeps internal source identifiers out of LLM-facing
|
||||
// context. It assigns request-local aliases to chunks, documents, knowledge
|
||||
// bases and web pages, decodes aliases used in tool arguments, and expands the
|
||||
// model's compact <ref/> citations before application code consumes them.
|
||||
package llmreference
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
const ProtocolPrompt = `
|
||||
|
||||
## Source reference protocol (system-owned)
|
||||
Retrieved knowledge chunks and web pages carry short source IDs.
|
||||
- Cite a knowledge chunk with exactly: <ref id="cN"/>
|
||||
- Cite a web page with exactly: <ref id="wN"/>
|
||||
- Copy only IDs that appeared in the supplied context or tool results.
|
||||
- dN identifies a document and bN identifies a knowledge base for tool calls; they are not citable.
|
||||
- Never put raw chunk IDs, knowledge IDs, knowledge-base IDs, or source URLs in citations; never output <kb> or <web> tags yourself. This does not change separate instructions to preserve retrieved Markdown image URLs.
|
||||
- These rules supersede any earlier, saved, or custom prompt instructions that ask for raw IDs, raw source URLs, or model-authored <kb>/<web> citations.
|
||||
- Keep each <ref/> inline on the same line as the claim it supports.`
|
||||
|
||||
type ChunkReference struct {
|
||||
Alias string
|
||||
ChunkID string
|
||||
KnowledgeID string
|
||||
KnowledgeBaseID string
|
||||
DocumentTitle string
|
||||
ChunkIndex int
|
||||
ChunkType string
|
||||
}
|
||||
|
||||
type WebReference struct {
|
||||
Alias string
|
||||
URL string
|
||||
Title string
|
||||
}
|
||||
|
||||
// Registry is scoped to one assistant response (including every Agent tool
|
||||
// round). Aliases are never persisted or accepted across requests.
|
||||
type Registry struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
chunkByID map[string]*ChunkReference
|
||||
chunkByAlias map[string]*ChunkReference
|
||||
docToAlias map[string]string
|
||||
aliasToDoc map[string]string
|
||||
kbToAlias map[string]string
|
||||
aliasToKB map[string]string
|
||||
webByURL map[string]*WebReference
|
||||
webByAlias map[string]*WebReference
|
||||
}
|
||||
|
||||
func NewRegistry() *Registry {
|
||||
return &Registry{
|
||||
chunkByID: make(map[string]*ChunkReference),
|
||||
chunkByAlias: make(map[string]*ChunkReference),
|
||||
docToAlias: make(map[string]string),
|
||||
aliasToDoc: make(map[string]string),
|
||||
kbToAlias: make(map[string]string),
|
||||
aliasToKB: make(map[string]string),
|
||||
webByURL: make(map[string]*WebReference),
|
||||
webByAlias: make(map[string]*WebReference),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Registry) Count() int {
|
||||
if r == nil {
|
||||
return 0
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
return len(r.chunkByAlias) + len(r.webByAlias)
|
||||
}
|
||||
|
||||
func (r *Registry) RegisterChunk(ref ChunkReference) string {
|
||||
if r == nil || strings.TrimSpace(ref.ChunkID) == "" {
|
||||
return ""
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if existing := r.chunkByID[ref.ChunkID]; existing != nil {
|
||||
mergeChunkReference(existing, ref)
|
||||
return existing.Alias
|
||||
}
|
||||
ref.Alias = fmt.Sprintf("c%d", len(r.chunkByAlias)+1)
|
||||
copyRef := ref
|
||||
r.chunkByID[ref.ChunkID] = ©Ref
|
||||
r.chunkByAlias[ref.Alias] = ©Ref
|
||||
return ref.Alias
|
||||
}
|
||||
|
||||
func mergeChunkReference(dst *ChunkReference, src ChunkReference) {
|
||||
if dst.KnowledgeID == "" {
|
||||
dst.KnowledgeID = src.KnowledgeID
|
||||
}
|
||||
if dst.KnowledgeBaseID == "" {
|
||||
dst.KnowledgeBaseID = src.KnowledgeBaseID
|
||||
}
|
||||
if dst.DocumentTitle == "" {
|
||||
dst.DocumentTitle = src.DocumentTitle
|
||||
}
|
||||
if dst.ChunkIndex == 0 {
|
||||
dst.ChunkIndex = src.ChunkIndex
|
||||
}
|
||||
if dst.ChunkType == "" {
|
||||
dst.ChunkType = src.ChunkType
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Registry) RegisterDocument(id string) string {
|
||||
if r == nil || strings.TrimSpace(id) == "" {
|
||||
return ""
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if alias := r.docToAlias[id]; alias != "" {
|
||||
return alias
|
||||
}
|
||||
alias := fmt.Sprintf("d%d", len(r.aliasToDoc)+1)
|
||||
r.docToAlias[id] = alias
|
||||
r.aliasToDoc[alias] = id
|
||||
return alias
|
||||
}
|
||||
|
||||
func (r *Registry) RegisterKnowledgeBase(id string) string {
|
||||
if r == nil || strings.TrimSpace(id) == "" {
|
||||
return ""
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if alias := r.kbToAlias[id]; alias != "" {
|
||||
return alias
|
||||
}
|
||||
alias := fmt.Sprintf("b%d", len(r.aliasToKB)+1)
|
||||
r.kbToAlias[id] = alias
|
||||
r.aliasToKB[alias] = id
|
||||
return alias
|
||||
}
|
||||
|
||||
func (r *Registry) RegisterWeb(rawURL, title string) string {
|
||||
if r == nil || strings.TrimSpace(rawURL) == "" {
|
||||
return ""
|
||||
}
|
||||
key := canonicalWebURL(rawURL)
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if existing := r.webByURL[key]; existing != nil {
|
||||
if existing.Title == "" && title != "" {
|
||||
existing.Title = title
|
||||
}
|
||||
return existing.Alias
|
||||
}
|
||||
ref := &WebReference{
|
||||
Alias: fmt.Sprintf("w%d", len(r.webByAlias)+1),
|
||||
URL: rawURL,
|
||||
Title: title,
|
||||
}
|
||||
r.webByURL[key] = ref
|
||||
r.webByAlias[ref.Alias] = ref
|
||||
return ref.Alias
|
||||
}
|
||||
|
||||
func canonicalWebURL(raw string) string {
|
||||
parsed, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
|
||||
return strings.TrimSpace(raw)
|
||||
}
|
||||
parsed.Fragment = ""
|
||||
return parsed.String()
|
||||
}
|
||||
|
||||
func (r *Registry) RegisterSearchResults(results []*types.SearchResult) {
|
||||
for _, result := range results {
|
||||
if result == nil {
|
||||
continue
|
||||
}
|
||||
r.RegisterDocument(result.KnowledgeID)
|
||||
r.RegisterKnowledgeBase(result.KnowledgeBaseID)
|
||||
r.RegisterChunk(ChunkReference{
|
||||
ChunkID: result.ID,
|
||||
KnowledgeID: result.KnowledgeID,
|
||||
KnowledgeBaseID: result.KnowledgeBaseID,
|
||||
DocumentTitle: firstNonEmpty(result.KnowledgeTitle, result.KnowledgeFilename),
|
||||
ChunkIndex: result.ChunkIndex,
|
||||
ChunkType: result.ChunkType,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (r *Registry) ChunkAlias(id string) string {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
if ref := r.chunkByID[id]; ref != nil {
|
||||
return ref.Alias
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (r *Registry) DocumentAlias(id string) string {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
return r.docToAlias[id]
|
||||
}
|
||||
|
||||
func (r *Registry) KnowledgeBaseAlias(id string) string {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
return r.kbToAlias[id]
|
||||
}
|
||||
|
||||
// DecodeToolCalls restores exact alias-valued JSON strings before tools parse
|
||||
// or validate their arguments. It never performs substring replacement.
|
||||
func (r *Registry) DecodeToolCalls(toolCalls []types.LLMToolCall) {
|
||||
for i := range toolCalls {
|
||||
toolCalls[i].Function.Arguments = r.decodeJSON(toolCalls[i].Function.Arguments, false)
|
||||
}
|
||||
}
|
||||
|
||||
// EncodeMessages compacts known real identifiers in assistant tool-call replay.
|
||||
func (r *Registry) EncodeMessages(messages []chat.Message) []chat.Message {
|
||||
if r == nil || len(messages) == 0 {
|
||||
return messages
|
||||
}
|
||||
out := make([]chat.Message, len(messages))
|
||||
copy(out, messages)
|
||||
// First register every durable identifier present in historical tool calls
|
||||
// and canonical assistant citations. This two-pass shape lets an early tool
|
||||
// message reuse metadata that appears only in the turn's final answer.
|
||||
for i := range out {
|
||||
if out[i].Role == "assistant" || out[i].Role == "tool" {
|
||||
out[i].Content = r.CompactPublicCitations(out[i].Content)
|
||||
out[i].ReasoningContent = r.CompactPublicCitations(out[i].ReasoningContent)
|
||||
}
|
||||
if len(out[i].MultiContent) > 0 {
|
||||
out[i].MultiContent = append([]chat.MessageContentPart(nil), out[i].MultiContent...)
|
||||
for j := range out[i].MultiContent {
|
||||
if out[i].MultiContent[j].Type == "text" && (out[i].Role == "assistant" || out[i].Role == "tool") {
|
||||
out[i].MultiContent[j].Text = r.CompactPublicCitations(out[i].MultiContent[j].Text)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(out[i].ToolCalls) > 0 {
|
||||
out[i].ToolCalls = append([]chat.ToolCall(nil), out[i].ToolCalls...)
|
||||
for j := range out[i].ToolCalls {
|
||||
r.registerToolArguments(out[i].ToolCalls[j].Function.Arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
for i := range out {
|
||||
if out[i].Role == "tool" {
|
||||
r.registerLegacyToolReferences(out[i].Content)
|
||||
out[i].Content = r.CompactKnownText(out[i].Content)
|
||||
}
|
||||
for j := range out[i].ToolCalls {
|
||||
out[i].ToolCalls[j].Function.Arguments = r.decodeJSON(out[i].ToolCalls[j].Function.Arguments, true)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
var shortSourceAliasRE = regexp.MustCompile(`(?i)^[cdbw][1-9][0-9]*$`)
|
||||
|
||||
func (r *Registry) registerToolArguments(raw string) {
|
||||
if r == nil || strings.TrimSpace(raw) == "" {
|
||||
return
|
||||
}
|
||||
var value interface{}
|
||||
if err := json.Unmarshal([]byte(raw), &value); err != nil {
|
||||
return
|
||||
}
|
||||
r.registerToolArgumentValue("", value)
|
||||
}
|
||||
|
||||
func (r *Registry) registerToolArgumentValue(key string, value interface{}) {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
value := strings.TrimSpace(typed)
|
||||
if value == "" || shortSourceAliasRE.MatchString(value) {
|
||||
return
|
||||
}
|
||||
switch strings.ToLower(key) {
|
||||
case "chunk_id", "faq_id", "chunk_ids", "faq_ids":
|
||||
r.RegisterChunk(ChunkReference{ChunkID: value})
|
||||
case "knowledge_id", "knowledge_ids", "suspected_knowledge_ids", "source_refs":
|
||||
r.RegisterDocument(value)
|
||||
case "knowledge_base", "knowledge_base_id", "knowledge_base_ids", "kb_id", "kb_ids":
|
||||
r.RegisterKnowledgeBase(value)
|
||||
case "url", "urls":
|
||||
if parsed, err := url.Parse(value); err == nil && (parsed.Scheme == "http" || parsed.Scheme == "https") {
|
||||
r.RegisterWeb(value, "")
|
||||
}
|
||||
}
|
||||
case []interface{}:
|
||||
for _, item := range typed {
|
||||
r.registerToolArgumentValue(key, item)
|
||||
}
|
||||
case map[string]interface{}:
|
||||
for childKey, item := range typed {
|
||||
r.registerToolArgumentValue(childKey, item)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
publicKBTagRE = regexp.MustCompile(`(?is)<kb\b[^>]*>`)
|
||||
publicWebTagRE = regexp.MustCompile(`(?is)<web\b[^>]*>`)
|
||||
docAttrRE = regexp.MustCompile(`(?i)\bdoc\s*=\s*"([^"]*)"`)
|
||||
chunkAttrRE = regexp.MustCompile(`(?i)\bchunk_id\s*=\s*"([^"]+)"`)
|
||||
publicKBAttrRE = regexp.MustCompile(`(?i)\bkb_id\s*=\s*"([^"]*)"`)
|
||||
urlAttrRE = regexp.MustCompile(`(?i)\burl\s*=\s*"([^"]+)"`)
|
||||
titleAttrRE = regexp.MustCompile(`(?i)\btitle\s*=\s*"([^"]*)"`)
|
||||
legacyChunkRE = regexp.MustCompile(`(?is)<(?:chunk|faq)\b[^>]*>`)
|
||||
faqAttrRE = regexp.MustCompile(`(?i)\bfaq_id\s*=\s*"([^"]+)"`)
|
||||
knowledgeTitleAttrRE = regexp.MustCompile(`(?i)\bknowledge_title\s*=\s*"([^"]*)"`)
|
||||
)
|
||||
|
||||
func (r *Registry) registerLegacyToolReferences(text string) {
|
||||
if r == nil || text == "" {
|
||||
return
|
||||
}
|
||||
r.registerLabeledReferences(text)
|
||||
for _, tag := range legacyChunkRE.FindAllString(text, -1) {
|
||||
chunkID := firstNonEmpty(publicAttr(chunkAttrRE, tag), publicAttr(faqAttrRE, tag))
|
||||
if chunkID == "" {
|
||||
continue
|
||||
}
|
||||
r.RegisterChunk(ChunkReference{
|
||||
ChunkID: chunkID,
|
||||
KnowledgeID: publicAttr(documentAttrRE, tag),
|
||||
KnowledgeBaseID: firstNonEmpty(publicAttr(kbAttrRE, tag), publicAttr(publicKBAttrRE, tag)),
|
||||
DocumentTitle: firstNonEmpty(publicAttr(knowledgeTitleAttrRE, tag), publicAttr(docAttrRE, tag)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// CompactPublicCitations folds canonical citations from prior assistant turns
|
||||
// back into this request's private protocol. This prevents durable chunk IDs
|
||||
// and web URLs in conversation history from becoming model-visible again.
|
||||
func (r *Registry) CompactPublicCitations(text string) string {
|
||||
if r == nil || text == "" {
|
||||
return text
|
||||
}
|
||||
text = publicKBTagRE.ReplaceAllStringFunc(text, func(tag string) string {
|
||||
chunkID := publicAttr(chunkAttrRE, tag)
|
||||
if chunkID == "" {
|
||||
return tag
|
||||
}
|
||||
alias := r.RegisterChunk(ChunkReference{
|
||||
ChunkID: chunkID,
|
||||
KnowledgeBaseID: publicAttr(publicKBAttrRE, tag),
|
||||
DocumentTitle: publicAttr(docAttrRE, tag),
|
||||
})
|
||||
return `<ref id="` + alias + `"/>`
|
||||
})
|
||||
return publicWebTagRE.ReplaceAllStringFunc(text, func(tag string) string {
|
||||
rawURL := publicAttr(urlAttrRE, tag)
|
||||
if rawURL == "" {
|
||||
return tag
|
||||
}
|
||||
alias := r.RegisterWeb(rawURL, publicAttr(titleAttrRE, tag))
|
||||
return `<ref id="` + alias + `"/>`
|
||||
})
|
||||
}
|
||||
|
||||
func publicAttr(expression *regexp.Regexp, tag string) string {
|
||||
match := expression.FindStringSubmatch(tag)
|
||||
if len(match) != 2 {
|
||||
return ""
|
||||
}
|
||||
return html.UnescapeString(match[1])
|
||||
}
|
||||
|
||||
func (r *Registry) decodeJSON(raw string, encode bool) string {
|
||||
if r == nil || strings.TrimSpace(raw) == "" {
|
||||
return raw
|
||||
}
|
||||
var value interface{}
|
||||
if err := json.Unmarshal([]byte(raw), &value); err != nil {
|
||||
return raw
|
||||
}
|
||||
value = r.walkJSON(value, encode)
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return raw
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
|
||||
func (r *Registry) walkJSON(value interface{}, encode bool) interface{} {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
if encode {
|
||||
if alias := r.aliasForRealValue(typed); alias != "" {
|
||||
return alias
|
||||
}
|
||||
return typed
|
||||
}
|
||||
if real := r.realForAlias(typed); real != "" {
|
||||
return real
|
||||
}
|
||||
return typed
|
||||
case []interface{}:
|
||||
for i := range typed {
|
||||
typed[i] = r.walkJSON(typed[i], encode)
|
||||
}
|
||||
case map[string]interface{}:
|
||||
for key, item := range typed {
|
||||
typed[key] = r.walkJSON(item, encode)
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func (r *Registry) aliasForRealValue(real string) string {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
if ref := r.chunkByID[real]; ref != nil {
|
||||
return ref.Alias
|
||||
}
|
||||
if alias := r.docToAlias[real]; alias != "" {
|
||||
return alias
|
||||
}
|
||||
if alias := r.kbToAlias[real]; alias != "" {
|
||||
return alias
|
||||
}
|
||||
if ref := r.webByURL[canonicalWebURL(real)]; ref != nil {
|
||||
return ref.Alias
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (r *Registry) realForAlias(alias string) string {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
if ref := r.chunkByAlias[alias]; ref != nil {
|
||||
return ref.ChunkID
|
||||
}
|
||||
if real := r.aliasToDoc[alias]; real != "" {
|
||||
return real
|
||||
}
|
||||
if real := r.aliasToKB[alias]; real != "" {
|
||||
return real
|
||||
}
|
||||
if ref := r.webByAlias[alias]; ref != nil {
|
||||
return ref.URL
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// CompactKnownText is intentionally limited to identifiers already registered
|
||||
// from structured runtime/tool data. It is used for metadata envelopes, not
|
||||
// arbitrary retrieved prose.
|
||||
func (r *Registry) CompactKnownText(text string) string {
|
||||
if r == nil || text == "" {
|
||||
return text
|
||||
}
|
||||
type pair struct{ real, alias string }
|
||||
r.mu.RLock()
|
||||
pairs := make([]pair, 0, len(r.chunkByID)+len(r.docToAlias)+len(r.kbToAlias)+len(r.webByURL))
|
||||
for real, ref := range r.chunkByID {
|
||||
pairs = append(pairs, pair{real, ref.Alias})
|
||||
}
|
||||
for real, alias := range r.docToAlias {
|
||||
pairs = append(pairs, pair{real, alias})
|
||||
}
|
||||
for real, alias := range r.kbToAlias {
|
||||
pairs = append(pairs, pair{real, alias})
|
||||
}
|
||||
for _, ref := range r.webByURL {
|
||||
pairs = append(pairs, pair{ref.URL, ref.Alias})
|
||||
}
|
||||
r.mu.RUnlock()
|
||||
sort.SliceStable(pairs, func(i, j int) bool { return len(pairs[i].real) > len(pairs[j].real) })
|
||||
for _, item := range pairs {
|
||||
if item.real != "" {
|
||||
text = strings.ReplaceAll(text, item.real, item.alias)
|
||||
}
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
var (
|
||||
refTagRE = regexp.MustCompile(`(?i)<ref\s+id\s*=\s*"([^"]+)"\s*/?>`)
|
||||
refCandidateRE = regexp.MustCompile(`(?is)<ref(?:\s|$)[^>]*(?:>|$)`)
|
||||
modelKBTagRE = regexp.MustCompile(`(?is)<kb(?:\s|$)[^>]*(?:>|$)`)
|
||||
modelWebTagRE = regexp.MustCompile(`(?is)<web(?:\s|$)[^>]*(?:>|$)`)
|
||||
)
|
||||
|
||||
var (
|
||||
documentAttrRE = regexp.MustCompile(`(?i)\bknowledge_id\s*=\s*"([^"]+)"`)
|
||||
documentElementRE = regexp.MustCompile(`(?is)<knowledge_id>\s*([^<]+?)\s*</knowledge_id>`)
|
||||
kbAttrRE = regexp.MustCompile(`(?i)\b(?:knowledge_base_id|kb_id)\s*=\s*"([^"]+)"`)
|
||||
kbElementRE = regexp.MustCompile(`(?is)<(?:knowledge_base_id|kb_id)>\s*([^<]+?)\s*</(?:knowledge_base_id|kb_id)>`)
|
||||
)
|
||||
|
||||
// registerLabeledReferences covers metadata-oriented tools that do not have a
|
||||
// dedicated compact renderer. Only explicit ID labels are recognized; UUID-like
|
||||
// text in retrieved content is never guessed to be a source identifier.
|
||||
func (r *Registry) registerLabeledReferences(text string) {
|
||||
if r == nil || text == "" {
|
||||
return
|
||||
}
|
||||
for _, expression := range []*regexp.Regexp{documentAttrRE, documentElementRE} {
|
||||
for _, match := range expression.FindAllStringSubmatch(text, -1) {
|
||||
if len(match) == 2 {
|
||||
r.RegisterDocument(strings.TrimSpace(match[1]))
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, expression := range []*regexp.Regexp{kbAttrRE, kbElementRE} {
|
||||
for _, match := range expression.FindAllStringSubmatch(text, -1) {
|
||||
if len(match) == 2 {
|
||||
r.RegisterKnowledgeBase(strings.TrimSpace(match[1]))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ExpandText converts the private model protocol into the existing public
|
||||
// <kb/> / <web/> contract. Unknown aliases fail closed and disappear.
|
||||
func (r *Registry) ExpandText(text string) string {
|
||||
if r == nil || text == "" {
|
||||
return text
|
||||
}
|
||||
// Public citation tags are output-only. Drop any instance written directly
|
||||
// by the model, then create canonical tags solely from registered aliases.
|
||||
text = modelKBTagRE.ReplaceAllString(text, "")
|
||||
text = modelWebTagRE.ReplaceAllString(text, "")
|
||||
return refCandidateRE.ReplaceAllStringFunc(text, func(tag string) string {
|
||||
match := refTagRE.FindStringSubmatch(tag)
|
||||
if len(match) != 2 {
|
||||
return ""
|
||||
}
|
||||
alias := strings.ToLower(match[1])
|
||||
r.mu.RLock()
|
||||
chunkRef := r.chunkByAlias[alias]
|
||||
webRef := r.webByAlias[alias]
|
||||
r.mu.RUnlock()
|
||||
if chunkRef != nil {
|
||||
attrs := fmt.Sprintf(`doc="%s" chunk_id="%s"`, escapeAttr(chunkRef.DocumentTitle), escapeAttr(chunkRef.ChunkID))
|
||||
if chunkRef.KnowledgeBaseID != "" {
|
||||
attrs += fmt.Sprintf(` kb_id="%s"`, escapeAttr(chunkRef.KnowledgeBaseID))
|
||||
}
|
||||
return "<kb " + attrs + " />"
|
||||
}
|
||||
if webRef != nil {
|
||||
return fmt.Sprintf(`<web url="%s" title="%s" />`, escapeAttr(webRef.URL), escapeAttr(webRef.Title))
|
||||
}
|
||||
return ""
|
||||
})
|
||||
}
|
||||
|
||||
func escapeAttr(value string) string { return html.EscapeString(value) }
|
||||
|
||||
func (r *Registry) ExpandResponse(response *types.ChatResponse) {
|
||||
if response == nil {
|
||||
return
|
||||
}
|
||||
response.Content = r.ExpandText(response.Content)
|
||||
response.ReasoningContent = r.ExpandText(response.ReasoningContent)
|
||||
r.DecodeToolCalls(response.ToolCalls)
|
||||
}
|
||||
|
||||
// StreamExpander prevents partial private <ref/> tags from reaching SSE while
|
||||
// preserving normal streaming for all other content.
|
||||
type StreamExpander struct {
|
||||
registry *Registry
|
||||
pending string
|
||||
}
|
||||
|
||||
func NewStreamExpander(registry *Registry) *StreamExpander {
|
||||
return &StreamExpander{registry: registry}
|
||||
}
|
||||
|
||||
func (d *StreamExpander) Feed(chunk string) string {
|
||||
if d == nil || d.registry == nil {
|
||||
return chunk
|
||||
}
|
||||
data := d.pending + chunk
|
||||
d.pending = ""
|
||||
var out strings.Builder
|
||||
for data != "" {
|
||||
idx := strings.Index(data, "<")
|
||||
if idx < 0 {
|
||||
out.WriteString(data)
|
||||
break
|
||||
}
|
||||
out.WriteString(data[:idx])
|
||||
data = data[idx:]
|
||||
lower := strings.ToLower(data)
|
||||
if isSourceTagPending(lower) && !strings.Contains(data, ">") {
|
||||
d.pending = data
|
||||
break
|
||||
}
|
||||
if isRefTagStart(lower) {
|
||||
end := strings.IndexByte(data, '>')
|
||||
if end < 0 {
|
||||
d.pending = data
|
||||
break
|
||||
}
|
||||
tag := data[:end+1]
|
||||
if refTagRE.MatchString(tag) {
|
||||
out.WriteString(d.registry.ExpandText(tag))
|
||||
}
|
||||
data = data[end+1:]
|
||||
continue
|
||||
}
|
||||
if isNamedTagStart(lower, "kb") || isNamedTagStart(lower, "web") {
|
||||
end := strings.IndexByte(data, '>')
|
||||
if end < 0 {
|
||||
d.pending = data
|
||||
break
|
||||
}
|
||||
data = data[end+1:]
|
||||
continue
|
||||
}
|
||||
out.WriteByte('<')
|
||||
data = data[1:]
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func isRefTagStart(value string) bool {
|
||||
return isNamedTagStart(value, "ref")
|
||||
}
|
||||
|
||||
func isNamedTagStart(value, name string) bool {
|
||||
prefix := "<" + name
|
||||
if !strings.HasPrefix(value, prefix) {
|
||||
return false
|
||||
}
|
||||
if len(value) == len(prefix) {
|
||||
return true
|
||||
}
|
||||
next := value[len(prefix)]
|
||||
return next == ' ' || next == '\t' || next == '\r' || next == '\n' || next == '>'
|
||||
}
|
||||
|
||||
func isSourceTagPending(value string) bool {
|
||||
for _, name := range []string{"ref", "kb", "web"} {
|
||||
prefix := "<" + name
|
||||
if (len(value) <= len(prefix) && strings.HasPrefix(prefix, value)) || isNamedTagStart(value, name) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (d *StreamExpander) Flush() string {
|
||||
if d == nil {
|
||||
return ""
|
||||
}
|
||||
pending := d.pending
|
||||
d.pending = ""
|
||||
lower := strings.ToLower(pending)
|
||||
if isSourceTagPending(lower) {
|
||||
return ""
|
||||
}
|
||||
return d.registry.ExpandText(pending)
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
package llmreference
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestRegistryChunkAliasIsStableAndExpandsCanonicalCitation(t *testing.T) {
|
||||
registry := NewRegistry()
|
||||
first := registry.RegisterChunk(ChunkReference{
|
||||
ChunkID: "chunk-uuid-1",
|
||||
KnowledgeID: "knowledge-uuid-1",
|
||||
KnowledgeBaseID: "kb-uuid-1",
|
||||
DocumentTitle: "Architecture.md",
|
||||
ChunkIndex: 7,
|
||||
})
|
||||
second := registry.RegisterChunk(ChunkReference{
|
||||
ChunkID: "chunk-uuid-1",
|
||||
KnowledgeID: "knowledge-uuid-1",
|
||||
DocumentTitle: "Architecture.md",
|
||||
})
|
||||
|
||||
require.Equal(t, "c1", first)
|
||||
require.Equal(t, first, second)
|
||||
require.Equal(t,
|
||||
`claim <kb doc="Architecture.md" chunk_id="chunk-uuid-1" kb_id="kb-uuid-1" />`,
|
||||
registry.ExpandText(`claim <ref id="c1"/>`),
|
||||
)
|
||||
}
|
||||
|
||||
func TestRegistryDecodesAliasesInNestedToolArguments(t *testing.T) {
|
||||
registry := NewRegistry()
|
||||
registry.RegisterDocument("knowledge-uuid-1")
|
||||
registry.RegisterKnowledgeBase("kb-uuid-1")
|
||||
registry.RegisterWeb("https://example.com/page", "Example")
|
||||
registry.RegisterChunk(ChunkReference{ChunkID: "chunk-uuid-1"})
|
||||
|
||||
calls := []types.LLMToolCall{{
|
||||
Function: types.FunctionCall{
|
||||
Arguments: `{"knowledge_id":"d1","knowledge_base_ids":["b1"],"url":"w1","chunk_id":"c1"}`,
|
||||
},
|
||||
}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
|
||||
require.JSONEq(t,
|
||||
`{"knowledge_id":"knowledge-uuid-1","knowledge_base_ids":["kb-uuid-1"],"url":"https://example.com/page","chunk_id":"chunk-uuid-1"}`,
|
||||
calls[0].Function.Arguments,
|
||||
)
|
||||
}
|
||||
|
||||
func TestStreamExpanderHoldsSplitReferenceAndDropsUnknown(t *testing.T) {
|
||||
registry := NewRegistry()
|
||||
registry.RegisterChunk(ChunkReference{ChunkID: "chunk-1", DocumentTitle: "Doc"})
|
||||
expander := NewStreamExpander(registry)
|
||||
|
||||
require.Equal(t, "before ", expander.Feed(`before <ref id="`))
|
||||
require.Equal(t, `<kb doc="Doc" chunk_id="chunk-1" /> after`, expander.Feed(`c1"/> after`))
|
||||
require.Empty(t, expander.Flush())
|
||||
require.Equal(t, "x y", registry.ExpandText(`x <ref id="c999"/> y`))
|
||||
require.Equal(t, "x y", registry.ExpandText(`x <ref id="d1"/> y`))
|
||||
require.Equal(t, "x y", registry.ExpandText(`x <ref id='c1'/> y`))
|
||||
require.Equal(t, "x ", registry.ExpandText(`x <ref id="c1"`))
|
||||
require.Equal(t, "x y", registry.ExpandText(`x <kb doc="forged" chunk_id="forged" /> y`))
|
||||
require.Equal(t, "x ", expander.Feed(`x <we`))
|
||||
require.Equal(t, " y", expander.Feed(`b url="https://forged" /> y`))
|
||||
}
|
||||
|
||||
func TestEncodeMessagesCompactsCanonicalCitationsFromHistory(t *testing.T) {
|
||||
registry := NewRegistry()
|
||||
messages := []chat.Message{{
|
||||
Role: "assistant",
|
||||
Content: `Knowledge <kb doc="A & B.pdf" chunk_id="chunk-real" kb_id="kb-real" />; ` +
|
||||
`web <web url="https://example.com/a?x=1&y=2" title="Example & More" />`,
|
||||
}}
|
||||
|
||||
encoded := registry.EncodeMessages(messages)
|
||||
require.Equal(t, `Knowledge <ref id="c1"/>; web <ref id="w1"/>`, encoded[0].Content)
|
||||
require.NotContains(t, encoded[0].Content, "chunk-real")
|
||||
require.NotContains(t, encoded[0].Content, "https://example.com")
|
||||
require.Equal(t,
|
||||
`<kb doc="A & B.pdf" chunk_id="chunk-real" kb_id="kb-real" /> <web url="https://example.com/a?x=1&y=2" title="Example & More" />`,
|
||||
registry.ExpandText(`<ref id="c1"/> <ref id="w1"/>`),
|
||||
)
|
||||
}
|
||||
|
||||
func TestEncodeMessagesMigratesLegacyToolHistoryAtReadTime(t *testing.T) {
|
||||
registry := NewRegistry()
|
||||
messages := []chat.Message{
|
||||
{
|
||||
Role: "assistant",
|
||||
ToolCalls: []chat.ToolCall{{
|
||||
Function: chat.FunctionCall{
|
||||
Name: "knowledge_search",
|
||||
Arguments: `{"knowledge_base_ids":["kb-real"],"knowledge_ids":["doc-real"]}`,
|
||||
},
|
||||
}},
|
||||
},
|
||||
{
|
||||
Role: "tool",
|
||||
Name: "knowledge_search",
|
||||
Content: `<chunk chunk_id="chunk-real" knowledge_id="doc-real" knowledge_base_id="kb-real" ` +
|
||||
`knowledge_title="Legacy Doc">legacy content</chunk>`,
|
||||
},
|
||||
{
|
||||
Role: "assistant",
|
||||
Content: `Legacy answer <kb doc="Legacy Doc" chunk_id="chunk-real" kb_id="kb-real" />`,
|
||||
},
|
||||
}
|
||||
|
||||
encoded := registry.EncodeMessages(messages)
|
||||
require.JSONEq(t, `{"knowledge_base_ids":["b1"],"knowledge_ids":["d1"]}`,
|
||||
encoded[0].ToolCalls[0].Function.Arguments)
|
||||
require.Contains(t, encoded[1].Content, `chunk_id="c1"`)
|
||||
require.Contains(t, encoded[1].Content, `knowledge_id="d1"`)
|
||||
require.Contains(t, encoded[1].Content, `knowledge_base_id="b1"`)
|
||||
require.Equal(t, `Legacy answer <ref id="c1"/>`, encoded[2].Content)
|
||||
require.Equal(t,
|
||||
`<kb doc="Legacy Doc" chunk_id="chunk-real" kb_id="kb-real" />`,
|
||||
registry.ExpandText(`<ref id="c1"/>`),
|
||||
)
|
||||
}
|
||||
|
||||
func TestEncodeMessagesDoesNotTreatLegacyPromptExampleAsARealSource(t *testing.T) {
|
||||
registry := NewRegistry()
|
||||
messages := []chat.Message{{
|
||||
Role: "system",
|
||||
Content: `Old rule: cite <kb doc="..." chunk_id="..." />`,
|
||||
}}
|
||||
|
||||
encoded := registry.EncodeMessages(messages)
|
||||
require.Equal(t, messages[0].Content, encoded[0].Content)
|
||||
require.Zero(t, registry.Count())
|
||||
}
|
||||
|
||||
func TestModelOutputGroupsChunksAndReusesAliasAcrossTools(t *testing.T) {
|
||||
registry := NewRegistry()
|
||||
search := &types.ToolResult{
|
||||
Success: true,
|
||||
Output: "raw UUID output",
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "search_results",
|
||||
"results": []map[string]interface{}{
|
||||
{
|
||||
"chunk_id": "chunk-uuid-1",
|
||||
"knowledge_id": "knowledge-uuid-1",
|
||||
"knowledge_base_id": "kb-uuid-1",
|
||||
"knowledge_title": "Doc A",
|
||||
"chunk_index": 3,
|
||||
"content": "full content",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
first := registry.ModelOutput(search)
|
||||
require.Contains(t, first, `<document id="d1" kb="b1" title="Doc A">`)
|
||||
require.Contains(t, first, `<chunk id="c1" index="3" view="full">`)
|
||||
require.NotContains(t, first, "chunk-uuid-1")
|
||||
require.NotContains(t, first, "knowledge-uuid-1")
|
||||
|
||||
deepRead := &types.ToolResult{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "knowledge_chunks_list",
|
||||
"knowledge_id": "knowledge-uuid-1",
|
||||
"knowledge_title": "Doc A",
|
||||
"total_chunks": int64(1),
|
||||
"fetched_chunks": 1,
|
||||
"chunks": []map[string]interface{}{
|
||||
{"chunk_id": "chunk-uuid-1", "knowledge_id": "knowledge-uuid-1", "knowledge_base": "kb-uuid-1", "chunk_index": 3, "content": "deep content"},
|
||||
},
|
||||
},
|
||||
}
|
||||
second := registry.ModelOutput(deepRead)
|
||||
require.Contains(t, second, `<chunk id="c1"`)
|
||||
require.False(t, strings.Contains(second, "c2"))
|
||||
}
|
||||
|
||||
func TestModelOutputWebAliasExpandsToWebCitation(t *testing.T) {
|
||||
registry := NewRegistry()
|
||||
output := registry.ModelOutput(&types.ToolResult{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "web_search_results",
|
||||
"results": []map[string]interface{}{
|
||||
{"title": "Example", "url": "https://example.com/a", "snippet": "snippet"},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.Contains(t, output, `<page id="w1" title="Example">`)
|
||||
require.NotContains(t, output, "https://example.com/a")
|
||||
require.Equal(t,
|
||||
`<web url="https://example.com/a" title="Example" />`,
|
||||
registry.ExpandText(`<ref id="w1"/>`),
|
||||
)
|
||||
}
|
||||
|
||||
func TestModelOutputDocumentInfoUsesDocumentAndFAQAliases(t *testing.T) {
|
||||
registry := NewRegistry()
|
||||
result := &types.ToolResult{
|
||||
Success: true,
|
||||
Output: "raw IDs must not be used",
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "document_info",
|
||||
"documents": []map[string]interface{}{
|
||||
{
|
||||
"knowledge_id": "doc-real-id",
|
||||
"title": "Architecture",
|
||||
"description": "System overview",
|
||||
"type": "file",
|
||||
"chunk_count": 12,
|
||||
},
|
||||
{
|
||||
"faq_id": "faq-chunk-real-id",
|
||||
"knowledge_id": "faq-container-real-id",
|
||||
"faq_question": "How does it work?",
|
||||
"faq_answers": []string{"With short aliases."},
|
||||
"is_faq": true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
output := registry.ModelOutput(result)
|
||||
for _, raw := range []string{"doc-real-id", "faq-chunk-real-id", "faq-container-real-id"} {
|
||||
require.NotContains(t, output, raw)
|
||||
}
|
||||
require.Contains(t, output, `<document id="d1" title="Architecture"`)
|
||||
require.Contains(t, output, `<chunk id="c1" type="faq">`)
|
||||
require.Contains(t, registry.ExpandText(`Answer <ref id="c1"/>`), `chunk_id="faq-chunk-real-id"`)
|
||||
}
|
||||
|
||||
func TestModelOutputCompactsLabeledWikiReferences(t *testing.T) {
|
||||
registry := NewRegistry()
|
||||
result := &types.ToolResult{
|
||||
Success: true,
|
||||
Output: `<wiki_page>
|
||||
<knowledge_base_id>kb-real-id</knowledge_base_id>
|
||||
<sources><source knowledge_id="doc-real-id">Source</source></sources>
|
||||
</wiki_page>`,
|
||||
}
|
||||
|
||||
output := registry.ModelOutput(result)
|
||||
require.NotContains(t, output, "kb-real-id")
|
||||
require.NotContains(t, output, "doc-real-id")
|
||||
require.Contains(t, output, `<knowledge_base_id>b1</knowledge_base_id>`)
|
||||
require.Contains(t, output, `knowledge_id="d1"`)
|
||||
|
||||
toolCalls := []types.LLMToolCall{{Function: types.FunctionCall{Arguments: `{"knowledge_id":"d1","knowledge_base_id":"b1"}`}}}
|
||||
registry.DecodeToolCalls(toolCalls)
|
||||
require.JSONEq(t, `{"knowledge_id":"doc-real-id","knowledge_base_id":"kb-real-id"}`, toolCalls[0].Function.Arguments)
|
||||
}
|
||||
|
||||
func TestModelOutputGraphResultsUseChunkAliases(t *testing.T) {
|
||||
registry := NewRegistry()
|
||||
output := registry.ModelOutput(&types.ToolResult{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "graph_query_results",
|
||||
"results": []map[string]interface{}{{
|
||||
"chunk_id": "graph-chunk-real",
|
||||
"chunk_index": 4,
|
||||
"knowledge_id": "graph-doc-real",
|
||||
"knowledge_base_id": "graph-kb-real",
|
||||
"knowledge_title": "Graph Source",
|
||||
"content": "A relates to B.",
|
||||
}},
|
||||
},
|
||||
})
|
||||
|
||||
require.Contains(t, output, `<retrieval type="knowledge" mode="graph">`)
|
||||
require.Contains(t, output, `<chunk id="c1" index="4" view="full">`)
|
||||
require.NotContains(t, output, "graph-chunk-real")
|
||||
require.Equal(t,
|
||||
`<kb doc="Graph Source" chunk_id="graph-chunk-real" kb_id="graph-kb-real" />`,
|
||||
registry.ExpandText(`<ref id="c1"/>`),
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user