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:
@@ -103,7 +103,7 @@ func buildMissingColumnSuggestion(sqlErr error, schema *TableSchema) string {
|
||||
}
|
||||
|
||||
type DataAnalysisInput struct {
|
||||
KnowledgeID string `json:"knowledge_id" jsonschema:"id of the knowledge to query"`
|
||||
KnowledgeID string `json:"knowledge_id" jsonschema:"short dN document ID to query"`
|
||||
Sql string `json:"sql" jsonschema:"SQL to be executed on knowledge"`
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ var dataSchemaTool = BaseTool{
|
||||
}
|
||||
|
||||
type DataSchemaInput struct {
|
||||
KnowledgeID string `json:"knowledge_id" jsonschema:"id of the knowledge to query"`
|
||||
KnowledgeID string `json:"knowledge_id" jsonschema:"short dN document ID to query"`
|
||||
}
|
||||
|
||||
type DataSchemaTool struct {
|
||||
|
||||
@@ -43,20 +43,20 @@ Do not use when:
|
||||
- Can check document processing status (parse_status)
|
||||
|
||||
## IDs
|
||||
- knowledge_ids: regular documents knowledges
|
||||
- faq_ids: individual FAQ entries. Returns the standard question and answers, not the container title.`,
|
||||
- knowledge_ids: regular documents, using the short dN IDs from retrieval results
|
||||
- faq_ids: individual FAQ entries, using the short cN chunk IDs. Returns the standard question and answers, not the container title.`,
|
||||
schema: json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"knowledge_ids": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" },
|
||||
"description": "Document/knowledge IDs for regular documents"
|
||||
"description": "Short dN document IDs for regular documents"
|
||||
},
|
||||
"faq_ids": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" },
|
||||
"description": "FAQ entry IDs (= chunk_id from grep_chunks). Use instead of knowledge_ids for a single FAQ Q&A."
|
||||
"description": "Short cN FAQ chunk IDs from retrieval results. Use instead of knowledge_ids for a single FAQ Q&A."
|
||||
}
|
||||
}
|
||||
}`),
|
||||
|
||||
@@ -20,7 +20,7 @@ var grepChunksTool = BaseTool{
|
||||
name: ToolGrepChunks,
|
||||
description: `Search knowledge base chunk content with a single POSIX regular expression, applied directly in the database (PostgreSQL ~* / MySQL/SQLite REGEXP, case-insensitive). Behaves like ` + "`grep -E -i`" + `.
|
||||
Pack multiple concepts into ONE regex using ` + "`|`" + ` alternation — do not call this tool repeatedly for synonyms.
|
||||
Returns matching chunks with hit counts and a <match_snippet> around the first match (each tagged with its knowledge_id and chunk_id).
|
||||
Returns matching chunks with a short cN chunk source ID, a parent dN document ID, and a <match> snippet around the first match.
|
||||
Examples:
|
||||
- Alternation (RECOMMENDED): "stardust|skyvault|psionic" (matches any of the words)
|
||||
- Multiple terms in order: "psionic.*engine" (matches both words in order)
|
||||
@@ -30,8 +30,8 @@ IMPORTANT — JSON escaping: every backslash in a regex MUST be written as \\ in
|
||||
Use this to locate candidate chunks by exact identifiers, error codes, product names, or recurring terms.
|
||||
|
||||
## Deep read after grep:
|
||||
- **FAQ hit** (chunk type faq): call list_knowledge_chunks with **faq_id** from the grep result (NOT the parent knowledge_id).
|
||||
- **Document hit**: call list_knowledge_chunks with **knowledge_id**, or get_document_info with **knowledge_ids**.`,
|
||||
- **FAQ hit** (chunk type faq): call list_knowledge_chunks with **faq_id=cN** from the grep result (NOT the parent dN document ID).
|
||||
- **Document hit**: call list_knowledge_chunks with **knowledge_id=dN**, or get_document_info with **knowledge_ids=[dN]**.`,
|
||||
schema: json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -75,7 +75,7 @@ Avoid:
|
||||
|
||||
## Output
|
||||
Returns chunks ranked by semantic similarity, reranked when applicable.
|
||||
Results represent conceptual relevance, not literal keyword overlap.`,
|
||||
Each chunk has a short cN source ID and belongs to a dN document ID. Results represent conceptual relevance, not literal keyword overlap. Use dN for document-level follow-up tool calls and cN for chunk citations.`,
|
||||
schema: json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -90,7 +90,7 @@ Results represent conceptual relevance, not literal keyword overlap.`,
|
||||
},
|
||||
"knowledge_base_ids": {
|
||||
"type": "array",
|
||||
"description": "Optional: KB IDs to search",
|
||||
"description": "Optional: bound knowledge-base IDs (the short bN values shown in runtime context)",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
@@ -16,13 +16,13 @@ var listKnowledgeChunksTool = BaseTool{
|
||||
description: `Retrieve full chunk content for a document or a single FAQ entry.
|
||||
|
||||
## Use After grep_chunks or knowledge_search:
|
||||
- **FAQ hit** (type faq): list_knowledge_chunks(faq_id="<chunk_id from search>") — reads that one FAQ entry with answers from metadata.
|
||||
- **Document hit**: list_knowledge_chunks(knowledge_id="<document id>") — pages through all chunks.
|
||||
- **FAQ hit** (type faq): list_knowledge_chunks(faq_id="cN") — reads that one FAQ chunk with answers from metadata.
|
||||
- **Document hit**: list_knowledge_chunks(knowledge_id="dN") — pages through all chunks.
|
||||
|
||||
## Parameters (provide exactly one id target):
|
||||
- faq_id (optional): FAQ entry ID from grep_chunks / knowledge_search.
|
||||
- chunk_id (optional): Single non-FAQ chunk ID (do not use for FAQ — use faq_id).
|
||||
- knowledge_id (optional): Document/knowledge ID to page through all chunks.
|
||||
- faq_id (optional): Short cN ID for an FAQ chunk from grep_chunks / knowledge_search.
|
||||
- chunk_id (optional): Short cN ID for a single non-FAQ chunk.
|
||||
- knowledge_id (optional): Short dN document ID to page through all chunks.
|
||||
- limit / offset: Only for knowledge_id paging (default limit 20, max 100).
|
||||
|
||||
## Output:
|
||||
@@ -32,15 +32,15 @@ Full chunk content. FAQ entries include <faq> with <answer> from metadata.`,
|
||||
"properties": {
|
||||
"faq_id": {
|
||||
"type": "string",
|
||||
"description": "FAQ entry ID (same as chunk_id). Use for FAQ hits instead of knowledge_id."
|
||||
"description": "Short cN FAQ chunk ID. Use for FAQ hits instead of the parent dN document ID."
|
||||
},
|
||||
"chunk_id": {
|
||||
"type": "string",
|
||||
"description": "Single chunk ID (alias of faq_id)"
|
||||
"description": "Short cN ID for one non-FAQ chunk"
|
||||
},
|
||||
"knowledge_id": {
|
||||
"type": "string",
|
||||
"description": "Document/knowledge ID to list all chunks"
|
||||
"description": "Short dN document ID to list all chunks"
|
||||
},
|
||||
"limit": {
|
||||
"type": "integer",
|
||||
|
||||
@@ -37,7 +37,7 @@ Explores relationships between entities in knowledge bases that have graph extra
|
||||
- Need exact document content → use knowledge_search
|
||||
|
||||
## Parameters
|
||||
- **knowledge_base_ids** (required): Array of knowledge base IDs (1-10). Only KBs with graph extraction configured will be effective.
|
||||
- **knowledge_base_ids** (required): Array of short bN knowledge base IDs (1-10). Only KBs with graph extraction configured will be effective.
|
||||
- **query** (required): Query content - can be entity name, relationship query, or concept search.
|
||||
|
||||
## Graph Configuration
|
||||
@@ -61,7 +61,7 @@ If KB is not configured with graph, tool will return regular search results.
|
||||
|
||||
// QueryKnowledgeGraphInput defines the input parameters for query knowledge graph tool
|
||||
type QueryKnowledgeGraphInput struct {
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids" jsonschema:"Array of knowledge base IDs to query"`
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids" jsonschema:"Array of short bN knowledge base IDs to query"`
|
||||
Query string `json:"query" jsonschema:"Query content (entity name or query text)"`
|
||||
}
|
||||
|
||||
@@ -299,14 +299,17 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
|
||||
output += fmt.Sprintf(" 🆔 chunk_id: %s\n\n", result.ID)
|
||||
|
||||
formattedResults = append(formattedResults, map[string]interface{}{
|
||||
"result_index": i + 1,
|
||||
"chunk_id": result.ID,
|
||||
"content": result.Content,
|
||||
"score": result.Score,
|
||||
"relevance_level": relevanceLevel,
|
||||
"knowledge_id": result.KnowledgeID,
|
||||
"knowledge_title": result.KnowledgeTitle,
|
||||
"match_type": FormatMatchType(result.MatchType),
|
||||
"result_index": i + 1,
|
||||
"chunk_id": result.ID,
|
||||
"chunk_index": result.ChunkIndex,
|
||||
"chunk_type": result.ChunkType,
|
||||
"content": result.Content,
|
||||
"score": result.Score,
|
||||
"relevance_level": relevanceLevel,
|
||||
"knowledge_id": result.KnowledgeID,
|
||||
"knowledge_base_id": result.KnowledgeBaseID,
|
||||
"knowledge_title": result.KnowledgeTitle,
|
||||
"match_type": FormatMatchType(result.MatchType),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -29,10 +29,10 @@ const (
|
||||
|
||||
var webFetchTool = BaseTool{
|
||||
name: ToolWebFetch,
|
||||
description: `Fetch detailed web content from previously discovered URLs and analyze it with an LLM.
|
||||
description: `Fetch detailed web content from previously discovered short wN web page IDs and analyze it with an LLM.
|
||||
|
||||
## Usage
|
||||
- Receive one or more {url, prompt} combinations
|
||||
- Receive one or more {url: "wN", prompt} combinations; the field name stays url, but its value is the short page ID
|
||||
- Fetch web page content and convert to Markdown text
|
||||
- Use prompt to call small model for analysis and summary (if model is available)
|
||||
- Return summary result and original content fragment
|
||||
@@ -45,12 +45,12 @@ var webFetchTool = BaseTool{
|
||||
|
||||
// WebFetchInput defines the input parameters for web fetch tool
|
||||
type WebFetchInput struct {
|
||||
Items []WebFetchItem `json:"items" jsonschema:"Batch fetch tasks, each containing a url and prompt"`
|
||||
Items []WebFetchItem `json:"items" jsonschema:"Batch fetch tasks, each containing a short wN web page ID and prompt"`
|
||||
}
|
||||
|
||||
// WebFetchItem represents a single web fetch task
|
||||
type WebFetchItem struct {
|
||||
URL string `json:"url" jsonschema:"URL of the web page to fetch, should come from web_search results"`
|
||||
URL string `json:"url" jsonschema:"Short wN web page ID from web_search results"`
|
||||
Prompt string `json:"prompt" jsonschema:"Prompt for analyzing the fetched web page content"`
|
||||
}
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ var webSearchTool = BaseTool{
|
||||
**Parameters**:
|
||||
- query (required): Search query string
|
||||
|
||||
**Returns**: Web search results with title, URL, snippet, and content (up to %d results)
|
||||
**Returns**: Web search results with title, short wN page ID, snippet, and content (up to %d results)
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -62,8 +62,8 @@ var webSearchTool = BaseTool{
|
||||
- Results are automatically compressed using RAG to extract relevant content
|
||||
- Search results are stored in a temporary knowledge base for the session
|
||||
- Use this tool when knowledge bases don't have the information you need
|
||||
- Results include URL, title, snippet, and content snippet (may be truncated)
|
||||
- **CRITICAL**: If content is truncated or you need full details, use **web_fetch** to fetch complete page content
|
||||
- Results include a short wN page ID, title, snippet, and content snippet (may be truncated)
|
||||
- **CRITICAL**: If content is truncated or you need full details, pass that wN value to **web_fetch** to fetch complete page content
|
||||
- Maximum %d results will be returned per search`,
|
||||
schema: utils.GenerateSchema[WebSearchInput](),
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ This will log an issue for human review or automated maintenance.`,
|
||||
"suspected_knowledge_ids": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" },
|
||||
"description": "Optional list of knowledge_ids (from the <sources> block) that you suspect are causing the pollution or error."
|
||||
"description": "Optional list of short dN document IDs from the <sources> block that you suspect are causing the pollution or error."
|
||||
}
|
||||
},
|
||||
"required": ["slug", "issue_type", "description"]
|
||||
@@ -72,7 +72,7 @@ func (t *wikiFlagIssueTool) Execute(ctx context.Context, args json.RawMessage) (
|
||||
if len(t.kbIDs) == 0 {
|
||||
return &types.ToolResult{Success: false, Error: "No knowledge bases available for issue tracking"}, nil
|
||||
}
|
||||
|
||||
|
||||
// Default to first KB ID if multiple (normally there's only one in this context)
|
||||
kbID := t.kbIDs[0]
|
||||
|
||||
@@ -102,4 +102,4 @@ func (t *wikiFlagIssueTool) Execute(ctx context.Context, args json.RawMessage) (
|
||||
Success: true,
|
||||
Output: fmt.Sprintf("Successfully flagged issue for %s. A maintenance ticket has been created for review.", slug),
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ If neither query nor range is provided, it returns the beginning of the document
|
||||
"properties": {
|
||||
"knowledge_id": {
|
||||
"type": "string",
|
||||
"description": "The ID of the source document to read"
|
||||
"description": "The short dN source document ID from the <sources> block"
|
||||
},
|
||||
"query": {
|
||||
"type": "string",
|
||||
@@ -161,12 +161,27 @@ func (t *wikiReadSourceDocTool) Execute(ctx context.Context, args json.RawMessag
|
||||
}
|
||||
|
||||
var chunksOutput strings.Builder
|
||||
formattedChunks := make([]map[string]interface{}, 0)
|
||||
totalChunks := int64(0)
|
||||
reachedMax := false
|
||||
|
||||
var prevChunk *types.Chunk
|
||||
var forceOutputNext bool
|
||||
outputtedIndices := make(map[int]bool)
|
||||
appendFormattedChunk := func(chunk *types.Chunk, content string) {
|
||||
if chunk == nil {
|
||||
return
|
||||
}
|
||||
formattedChunks = append(formattedChunks, map[string]interface{}{
|
||||
"chunk_id": chunk.ID,
|
||||
"chunk_index": chunk.ChunkIndex,
|
||||
"chunk_type": chunk.ChunkType,
|
||||
"content": content,
|
||||
"knowledge_id": knowledgeID,
|
||||
"knowledge_base": knowledge.KnowledgeBaseID,
|
||||
"knowledge_title": knowledge.Title,
|
||||
})
|
||||
}
|
||||
|
||||
for {
|
||||
pagination := &types.Pagination{
|
||||
@@ -213,6 +228,7 @@ func (t *wikiReadSourceDocTool) Execute(ctx context.Context, args json.RawMessag
|
||||
break
|
||||
}
|
||||
fmt.Fprintf(&chunksOutput, "<chunk index=\"%d\" type=\"range\">\n%s\n</chunk>\n", chunkNum, chunkContent)
|
||||
appendFormattedChunk(c, chunkContent)
|
||||
matchCount++
|
||||
continue
|
||||
}
|
||||
@@ -232,6 +248,7 @@ func (t *wikiReadSourceDocTool) Execute(ctx context.Context, args json.RawMessag
|
||||
if prevChunk != nil && !outputtedIndices[prevChunk.ChunkIndex] {
|
||||
prevContent := enrichChunkContent(prevChunk)
|
||||
fmt.Fprintf(&chunksOutput, "<chunk index=\"%d\" type=\"context_before\">\n%s\n</chunk>\n", prevChunk.ChunkIndex+1, prevContent)
|
||||
appendFormattedChunk(prevChunk, prevContent)
|
||||
outputtedIndices[prevChunk.ChunkIndex] = true
|
||||
}
|
||||
}
|
||||
@@ -242,6 +259,7 @@ func (t *wikiReadSourceDocTool) Execute(ctx context.Context, args json.RawMessag
|
||||
matchAttr = ` type="match"`
|
||||
}
|
||||
fmt.Fprintf(&chunksOutput, "<chunk index=\"%d\"%s>\n%s\n</chunk>\n", c.ChunkIndex+1, matchAttr, chunkContent)
|
||||
appendFormattedChunk(c, chunkContent)
|
||||
outputtedIndices[c.ChunkIndex] = true
|
||||
}
|
||||
|
||||
@@ -251,6 +269,7 @@ func (t *wikiReadSourceDocTool) Execute(ctx context.Context, args json.RawMessag
|
||||
} else if forceOutputNext {
|
||||
if !outputtedIndices[c.ChunkIndex] {
|
||||
fmt.Fprintf(&chunksOutput, "<chunk index=\"%d\" type=\"context_after\">\n%s\n</chunk>\n", c.ChunkIndex+1, chunkContent)
|
||||
appendFormattedChunk(c, chunkContent)
|
||||
outputtedIndices[c.ChunkIndex] = true
|
||||
}
|
||||
forceOutputNext = false
|
||||
@@ -312,5 +331,16 @@ func (t *wikiReadSourceDocTool) Execute(ctx context.Context, args json.RawMessag
|
||||
|
||||
sb.WriteString("</source_document>")
|
||||
|
||||
return &types.ToolResult{Success: true, Output: sb.String()}, nil
|
||||
return &types.ToolResult{
|
||||
Success: true,
|
||||
Output: sb.String(),
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "knowledge_chunks_list",
|
||||
"knowledge_id": knowledgeID,
|
||||
"knowledge_title": knowledge.Title,
|
||||
"total_chunks": totalChunks,
|
||||
"fetched_chunks": len(formattedChunks),
|
||||
"chunks": formattedChunks,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ func NewWikiReplaceTextTool(wikiPageService interfaces.WikiPageService, kbIDs []
|
||||
"source_refs": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "An optional list of source knowledge IDs (UUIDs only) that justify this change. If provided, these will COMPLETELY REPLACE the existing source_refs of the page."
|
||||
"description": "An optional list of short dN source document IDs that justify this change. If provided, these will COMPLETELY REPLACE the existing source_refs of the page."
|
||||
}
|
||||
},
|
||||
"required": ["slug", "old_text", "new_text"]
|
||||
|
||||
@@ -284,7 +284,7 @@ func NewWikiReadPageTool(
|
||||
ToolWikiReadPage,
|
||||
`Read one or more wiki pages by their slugs. Returns the full markdown content, metadata, and links.
|
||||
Use this to read specific wiki pages when you know their slug (e.g. "entity/acme-corp", "concept/rag").
|
||||
When the same slug exists in multiple knowledge bases, all matching pages are returned (each tagged with its knowledge_base_id). Pass "knowledge_base_id" to limit to a specific KB.`,
|
||||
When the same slug exists in multiple knowledge bases, all matching pages are returned (each tagged with its short bN knowledge_base_id). Pass that bN value in "knowledge_base_id" to limit to a specific KB.`,
|
||||
json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -295,7 +295,7 @@ When the same slug exists in multiple knowledge bases, all matching pages are re
|
||||
},
|
||||
"knowledge_base_id": {
|
||||
"type": "string",
|
||||
"description": "Optional: specific knowledge base ID. If omitted, reads the slug from every wiki KB in scope (all matches returned)."
|
||||
"description": "Optional: specific short bN knowledge base ID. If omitted, reads the slug from every wiki KB in scope (all matches returned)."
|
||||
}
|
||||
},
|
||||
"required": ["slugs"]
|
||||
@@ -576,7 +576,7 @@ func NewWikiSearchTool(
|
||||
ToolWikiSearch,
|
||||
`Search wiki pages using PostgreSQL POSIX regular expressions (~* operator, case-insensitive).
|
||||
STRONGLY PREFER using regex to search for multiple concepts at once rather than simple plain text queries.
|
||||
Returns matching pages with titles, slugs, and summaries (each tagged with its knowledge_base_id).
|
||||
Returns matching pages with titles, slugs, and summaries (each tagged with its short bN knowledge_base_id).
|
||||
Examples:
|
||||
- Alternation (RECOMMENDED): "stardust|skyvault" (matches either word)
|
||||
- Multiple terms (RECOMMENDED): "psionic.*engine" (matches both words in order)
|
||||
@@ -598,7 +598,7 @@ Use this to find relevant wiki pages when you don't know the exact slug.`,
|
||||
},
|
||||
"knowledge_base_id": {
|
||||
"type": "string",
|
||||
"description": "Optional: restrict search to a single knowledge base ID in scope."
|
||||
"description": "Optional: restrict search to a single short bN knowledge base ID in scope."
|
||||
}
|
||||
},
|
||||
"required": ["queries"]
|
||||
|
||||
@@ -56,7 +56,7 @@ func NewWikiWritePageTool(wikiPageService interfaces.WikiPageService, kbIDs []st
|
||||
"source_refs": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "A list of source knowledge IDs (UUIDs only) that contributed to this page. If provided, these will COMPLETELY REPLACE the existing source_refs of the page."
|
||||
"description": "A list of short dN source document IDs that contributed to this page. If provided, these will COMPLETELY REPLACE the existing source_refs of the page."
|
||||
}
|
||||
},
|
||||
"required": ["slug", "title", "summary", "content", "page_type"]
|
||||
|
||||
Reference in New Issue
Block a user