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:
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/common"
|
||||
appconfig "github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/llmreference"
|
||||
"github.com/Tencent/WeKnora/internal/llmresource"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
@@ -51,6 +52,7 @@ type AgentEngine struct {
|
||||
lastUsage types.TokenUsage // Token usage from the most recent LLM call
|
||||
lastSentMsgCount int // Number of messages sent in the most recent LLM call
|
||||
resourceRefs *llmresource.Registry // request-local aliases for durable resource references
|
||||
sourceRefs *llmreference.Registry // request-local chunk/document/web aliases and citations
|
||||
}
|
||||
|
||||
// ImageDescriberFunc generates a text description of an image.
|
||||
@@ -86,6 +88,7 @@ func NewAgentEngine(
|
||||
systemPromptTemplate: systemPromptTemplate,
|
||||
tokenEstimator: tokenEst,
|
||||
resourceRefs: llmresource.NewRegistry(),
|
||||
sourceRefs: llmreference.NewRegistry(),
|
||||
}
|
||||
|
||||
// Initialize memory consolidator if context window management is configured
|
||||
@@ -116,12 +119,13 @@ func (e *AgentEngine) systemPromptOptions(ctx context.Context) *BuildSystemPromp
|
||||
}
|
||||
|
||||
func (e *AgentEngine) buildSystemPrompt(ctx context.Context) string {
|
||||
return BuildSystemPromptWithOptions(
|
||||
prompt := BuildSystemPromptWithOptions(
|
||||
e.knowledgeBasesInfo,
|
||||
e.config.WebSearchEnabled,
|
||||
e.systemPromptOptions(ctx),
|
||||
e.systemPromptTemplate,
|
||||
)
|
||||
return strings.TrimRight(prompt, " \t\r\n") + llmreference.ProtocolPrompt
|
||||
}
|
||||
|
||||
// NewAgentEngineWithSkills creates a new agent engine with skills support
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/llmreference"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -69,6 +70,22 @@ func TestStreamLLMResourceAliasesRoundTrip(t *testing.T) {
|
||||
require.Equal(t, "source=res://0001", model.calls[0][0].Content)
|
||||
}
|
||||
|
||||
func TestStreamLLMChunkReferenceExpandsBeforeEmission(t *testing.T) {
|
||||
model := &mockChat{responses: []mockResponse{{chunks: []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: `answer <ref id="`},
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: `c1"/>`, Done: true},
|
||||
}}}}
|
||||
engine := newTestEngine(t, model)
|
||||
engine.sourceRefs.RegisterChunk(llmreference.ChunkReference{
|
||||
ChunkID: "chunk-1",
|
||||
KnowledgeBaseID: "kb-1",
|
||||
DocumentTitle: "Doc",
|
||||
})
|
||||
result, err := engine.streamLLMToEventBus(context.Background(), nil, nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, `answer <kb doc="Doc" chunk_id="chunk-1" kb_id="kb-1" />`, result.Content)
|
||||
}
|
||||
|
||||
func (m *mockChat) Chat(_ context.Context, _ []chat.Message, _ *chat.ChatOptions) (*types.ChatResponse, error) {
|
||||
return nil, fmt.Errorf("not implemented")
|
||||
}
|
||||
|
||||
@@ -58,9 +58,10 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(
|
||||
if searchutil.MarkdownImageRegex.MatchString(toolCall.Result.Output) {
|
||||
hasRetrievedImage = true
|
||||
}
|
||||
modelOutput := e.sourceRefs.ModelOutput(toolCall.Result)
|
||||
messages = append(messages, chat.Message{
|
||||
Role: "user",
|
||||
Content: fmt.Sprintf("Tool %s returned: %s", toolCall.Name, toolCall.Result.Output),
|
||||
Content: fmt.Sprintf("Tool %s returned: %s", toolCall.Name, modelOutput),
|
||||
})
|
||||
logger.Debugf(ctx, "[Agent][FinalAnswer] Added tool result [Step-%d][Tool-%d]: %s (output: %d chars)",
|
||||
stepIdx+1, toolIdx+1, toolCall.Name, len(toolCall.Result.Output))
|
||||
@@ -79,7 +80,7 @@ User question: %s
|
||||
|
||||
Requirements:
|
||||
1. Answer based on the actually retrieved content
|
||||
2. Cite sources by document title or name; never expose chunk_id, knowledge_id, tool names, or other internal identifiers
|
||||
2. Cite supporting knowledge chunks and web pages only with their supplied compact form: <ref id="cN"/> or <ref id="wN"/>
|
||||
3. Organize the answer in a structured format
|
||||
4. If information is insufficient, honestly state so
|
||||
5. IMPORTANT: Respond in the same language as the user's question
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
"github.com/Tencent/WeKnora/internal/common"
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/llmreference"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
@@ -374,11 +375,59 @@ func commonStringPrefix(a, b string) string {
|
||||
// (runtime_context + must_use + query). Used by Execute and finalize paths only;
|
||||
// not written to rendered_content / history.
|
||||
func (e *AgentEngine) RenderUserTurnContent(sessionID, query string) string {
|
||||
e.registerRuntimeReferences()
|
||||
runtimeCtx := buildRuntimeContextBlock(sessionID, e.knowledgeBasesInfo, e.selectedDocs)
|
||||
runtimeCtx = e.sourceRefs.CompactKnownText(runtimeCtx)
|
||||
mustUse := buildMustUseBlock(e.pinnedMCPServices, e.pinnedSkills)
|
||||
return composeUserTurnContent(runtimeCtx, mustUse, query)
|
||||
}
|
||||
|
||||
// registerRuntimeReferences makes bound KBs, pinned documents and recent
|
||||
// chunks addressable without exposing their durable IDs to the model.
|
||||
func (e *AgentEngine) registerRuntimeReferences() {
|
||||
if e == nil || e.sourceRefs == nil {
|
||||
return
|
||||
}
|
||||
for _, kb := range e.knowledgeBasesInfo {
|
||||
if kb == nil {
|
||||
continue
|
||||
}
|
||||
e.sourceRefs.RegisterKnowledgeBase(kb.ID)
|
||||
for _, doc := range kb.RecentDocs {
|
||||
e.sourceRefs.RegisterDocument(doc.KnowledgeID)
|
||||
if doc.ChunkID != "" {
|
||||
title := doc.Title
|
||||
if title == "" {
|
||||
title = doc.FileName
|
||||
}
|
||||
e.sourceRefs.RegisterChunk(llmreference.ChunkReference{
|
||||
ChunkID: doc.ChunkID,
|
||||
KnowledgeID: doc.KnowledgeID,
|
||||
KnowledgeBaseID: firstNonEmptyAgent(doc.KnowledgeBaseID, kb.ID),
|
||||
DocumentTitle: title,
|
||||
ChunkType: doc.Type,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, doc := range e.selectedDocs {
|
||||
if doc == nil {
|
||||
continue
|
||||
}
|
||||
e.sourceRefs.RegisterDocument(doc.KnowledgeID)
|
||||
e.sourceRefs.RegisterKnowledgeBase(doc.KnowledgeBaseID)
|
||||
}
|
||||
}
|
||||
|
||||
func firstNonEmptyAgent(values ...string) string {
|
||||
for _, value := range values {
|
||||
if value != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func composeUserTurnContent(parts ...string) string {
|
||||
nonEmpty := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
@@ -463,10 +512,7 @@ func (e *AgentEngine) appendToolResults(
|
||||
|
||||
// Add tool result messages (role: "tool", following OpenAI format)
|
||||
for _, toolCall := range step.ToolCalls {
|
||||
resultContent := toolCall.Result.Output
|
||||
if !toolCall.Result.Success {
|
||||
resultContent = fmt.Sprintf("Error: %s", toolCall.Result.Error)
|
||||
}
|
||||
resultContent := e.sourceRefs.ModelOutput(toolCall.Result)
|
||||
|
||||
toolMsg := chat.Message{
|
||||
Role: "tool",
|
||||
@@ -556,13 +602,13 @@ func (e *AgentEngine) buildMessagesWithLLMContext(
|
||||
}
|
||||
}
|
||||
|
||||
// Build user message with per-turn scope envelopes (current turn only).
|
||||
// Historical user messages in llmContext stay as bare Content from the DB.
|
||||
runtimeCtx := buildRuntimeContextBlock(sessionID, e.knowledgeBasesInfo, e.selectedDocs)
|
||||
mustUse := buildMustUseBlock(e.pinnedMCPServices, e.pinnedSkills)
|
||||
// Build the current user message through the same registration path used by
|
||||
// final synthesis. Calling buildRuntimeContextBlock directly here would put
|
||||
// durable bound-KB/document IDs into the first model request before the
|
||||
// request-local source registry had seen them.
|
||||
userMsg := chat.Message{
|
||||
Role: "user",
|
||||
Content: composeUserTurnContent(runtimeCtx, mustUse, currentQuery),
|
||||
Content: e.RenderUserTurnContent(sessionID, currentQuery),
|
||||
Images: imageURLs,
|
||||
}
|
||||
messages = append(messages, userMsg)
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
"github.com/Tencent/WeKnora/internal/llmreference"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -271,6 +272,38 @@ func TestRenderUserTurnContent_IncludesScopeBlocks(t *testing.T) {
|
||||
assert.Contains(t, out, "hello")
|
||||
}
|
||||
|
||||
func TestBuildMessagesWithLLMContextRegistersBoundScopeBeforeFirstModelCall(t *testing.T) {
|
||||
engine := &AgentEngine{
|
||||
sourceRefs: llmreference.NewRegistry(),
|
||||
knowledgeBasesInfo: []*KnowledgeBaseInfo{{
|
||||
ID: "kb-real-id",
|
||||
Name: "Docs",
|
||||
RecentDocs: []RecentDocInfo{{
|
||||
ChunkID: "chunk-real-id",
|
||||
KnowledgeID: "doc-real-id",
|
||||
KnowledgeBaseID: "kb-real-id",
|
||||
Title: "Guide",
|
||||
}},
|
||||
}},
|
||||
selectedDocs: []*SelectedDocumentInfo{{
|
||||
KnowledgeID: "selected-doc-real-id",
|
||||
KnowledgeBaseID: "kb-real-id",
|
||||
Title: "Selected",
|
||||
}},
|
||||
}
|
||||
|
||||
messages := engine.buildMessagesWithLLMContext("system", "question", "session", nil, nil)
|
||||
require.Len(t, messages, 2)
|
||||
userContent := messages[1].Content
|
||||
assert.Contains(t, userContent, `knowledge_base id="b1"`)
|
||||
assert.Contains(t, userContent, `knowledge_id="d1"`)
|
||||
assert.Contains(t, userContent, `knowledge_id="d2"`)
|
||||
assert.Equal(t, "c1", engine.sourceRefs.ChunkAlias("chunk-real-id"))
|
||||
assert.NotContains(t, userContent, "kb-real-id")
|
||||
assert.NotContains(t, userContent, "chunk-real-id")
|
||||
assert.NotContains(t, userContent, "doc-real-id")
|
||||
}
|
||||
|
||||
func TestBuildMustUseBlock_MultiWordServicePrefix(t *testing.T) {
|
||||
// Service "My Service" -> tools mcp_my_service_*; the prefix must be the
|
||||
// full service slug, not the first underscore segment (mcp_my_).
|
||||
|
||||
+12
-4
@@ -9,6 +9,7 @@ import (
|
||||
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
"github.com/Tencent/WeKnora/internal/common"
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/llmreference"
|
||||
"github.com/Tencent/WeKnora/internal/llmresource"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
@@ -38,6 +39,7 @@ func (e *AgentEngine) streamLLMToEventBus(
|
||||
llmCtx, llmCancel := context.WithTimeout(ctx, e.getLLMCallTimeout())
|
||||
defer llmCancel()
|
||||
|
||||
messages = e.sourceRefs.EncodeMessages(messages)
|
||||
messages = e.resourceRefs.EncodeMessages(messages)
|
||||
stream, err := e.chatModel.ChatStream(llmCtx, messages, opts)
|
||||
if err != nil {
|
||||
@@ -51,6 +53,8 @@ func (e *AgentEngine) streamLLMToEventBus(
|
||||
firstChunkTime := time.Time{}
|
||||
answerDecoder := llmresource.NewStreamDecoder(e.resourceRefs)
|
||||
thinkingDecoder := llmresource.NewStreamDecoder(e.resourceRefs)
|
||||
answerRefExpander := llmreference.NewStreamExpander(e.sourceRefs)
|
||||
thinkingRefExpander := llmreference.NewStreamExpander(e.sourceRefs)
|
||||
|
||||
for chunk := range stream {
|
||||
chunkCount++
|
||||
@@ -67,11 +71,12 @@ func (e *AgentEngine) streamLLMToEventBus(
|
||||
continue
|
||||
}
|
||||
if chunk.ResponseType == types.ResponseTypeThinking {
|
||||
chunk.Content = thinkingDecoder.Feed(chunk.Content)
|
||||
chunk.Content = thinkingRefExpander.Feed(thinkingDecoder.Feed(chunk.Content))
|
||||
} else {
|
||||
chunk.Content = answerDecoder.Feed(chunk.Content)
|
||||
chunk.Content = answerRefExpander.Feed(answerDecoder.Feed(chunk.Content))
|
||||
}
|
||||
e.resourceRefs.DecodeToolCalls(chunk.ToolCalls)
|
||||
e.sourceRefs.DecodeToolCalls(chunk.ToolCalls)
|
||||
|
||||
if chunk.Content != "" {
|
||||
isExtracted := chunk.Data != nil && chunk.Data["source"] != nil
|
||||
@@ -100,12 +105,15 @@ func (e *AgentEngine) streamLLMToEventBus(
|
||||
emitFunc(&chunk, result.Content)
|
||||
}
|
||||
}
|
||||
result.Content += answerDecoder.Flush()
|
||||
result.ReasoningContent += thinkingDecoder.Flush()
|
||||
result.Content += answerRefExpander.Feed(answerDecoder.Flush())
|
||||
result.Content += answerRefExpander.Flush()
|
||||
result.ReasoningContent += thinkingRefExpander.Feed(thinkingDecoder.Flush())
|
||||
result.ReasoningContent += thinkingRefExpander.Flush()
|
||||
// Some providers stream tool-call argument fragments but expose the
|
||||
// accumulated call in the final chunk. Decode once more after assembly so
|
||||
// aliases split across provider chunks cannot leak into tool execution.
|
||||
e.resourceRefs.DecodeToolCalls(result.ToolCalls)
|
||||
e.sourceRefs.DecodeToolCalls(result.ToolCalls)
|
||||
if orphans := e.resourceRefs.OrphanAliases(result.Content); len(orphans) > 0 {
|
||||
logger.Warnf(ctx, "[Agent][Stream] Model emitted %d unresolvable resource alias(es): %v",
|
||||
len(orphans), orphans)
|
||||
|
||||
@@ -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