feat(resource): add stable resource registry with LLM-context alias compaction
Introduce resource://<handle> as the stable application identity for stored objects, decoupling API responses, persisted rich text, and LLM prompts from physical storage paths. Adds a resource catalog service (register/resolve/bind, revocable expiring access grants), a request-local alias registry that compacts resource references while in the LLM context and restores them (including across streaming chunks), plus router, IM, chat-pipeline, and multimodal integration. Includes schema migrations (resources, resource_bindings, resource_access_grants) for sqlite, and hardens URL/output security handling.
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/llmresource"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
|
||||
@@ -49,6 +50,7 @@ type AgentEngine struct {
|
||||
memoryConsolidator *agentmemory.Consolidator // Memory consolidator for LLM-powered summarization (optional)
|
||||
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
|
||||
}
|
||||
|
||||
// ImageDescriberFunc generates a text description of an image.
|
||||
@@ -83,6 +85,7 @@ func NewAgentEngine(
|
||||
sessionID: sessionID,
|
||||
systemPromptTemplate: systemPromptTemplate,
|
||||
tokenEstimator: tokenEst,
|
||||
resourceRefs: llmresource.NewRegistry(),
|
||||
}
|
||||
|
||||
// Initialize memory consolidator if context window management is configured
|
||||
|
||||
@@ -24,16 +24,22 @@ type mockResponse struct {
|
||||
type mockChat struct {
|
||||
mu sync.Mutex
|
||||
responses []mockResponse
|
||||
calls [][]chat.Message
|
||||
callCount int
|
||||
}
|
||||
|
||||
func (m *mockChat) ChatStream(_ context.Context, _ []chat.Message, _ *chat.ChatOptions) (<-chan types.StreamResponse, error) {
|
||||
func (m *mockChat) ChatStream(
|
||||
_ context.Context,
|
||||
messages []chat.Message,
|
||||
_ *chat.ChatOptions,
|
||||
) (<-chan types.StreamResponse, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.callCount >= len(m.responses) {
|
||||
return nil, fmt.Errorf("unexpected ChatStream call #%d (only %d responses prepared)", m.callCount, len(m.responses))
|
||||
}
|
||||
resp := m.responses[m.callCount]
|
||||
m.calls = append(m.calls, append([]chat.Message(nil), messages...))
|
||||
m.callCount++
|
||||
|
||||
ch := make(chan types.StreamResponse, len(resp.chunks))
|
||||
@@ -44,6 +50,25 @@ func (m *mockChat) ChatStream(_ context.Context, _ []chat.Message, _ *chat.ChatO
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func TestStreamLLMResourceAliasesRoundTrip(t *testing.T) {
|
||||
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
model := &mockChat{responses: []mockResponse{{chunks: []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "", Done: true},
|
||||
}}}}
|
||||
engine := newTestEngine(t, model)
|
||||
result, err := engine.streamLLMToEventBus(
|
||||
context.Background(),
|
||||
[]chat.Message{{Role: "tool", Content: "source=" + ref}},
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "", result.Content)
|
||||
require.Len(t, model.calls, 1)
|
||||
require.Equal(t, "source=res:0001", model.calls[0][0].Content)
|
||||
}
|
||||
|
||||
func (m *mockChat) Chat(_ context.Context, _ []chat.Message, _ *chat.ChatOptions) (*types.ChatResponse, error) {
|
||||
return nil, fmt.Errorf("not implemented")
|
||||
}
|
||||
@@ -270,8 +295,10 @@ func TestStreamThinkingToEventBus_SplitsInlineThinkBlock(t *testing.T) {
|
||||
mock := &mockChat{
|
||||
responses: []mockResponse{
|
||||
{chunks: []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "<think>hidden reasoning</think>Visible answer.",
|
||||
Done: true, FinishReason: "stop"},
|
||||
{
|
||||
ResponseType: types.ResponseTypeAnswer, Content: "<think>hidden reasoning</think>Visible answer.",
|
||||
Done: true, FinishReason: "stop",
|
||||
},
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -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/llmresource"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
@@ -37,6 +38,7 @@ func (e *AgentEngine) streamLLMToEventBus(
|
||||
llmCtx, llmCancel := context.WithTimeout(ctx, e.getLLMCallTimeout())
|
||||
defer llmCancel()
|
||||
|
||||
messages = e.resourceRefs.EncodeMessages(messages)
|
||||
stream, err := e.chatModel.ChatStream(llmCtx, messages, opts)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[Agent][Stream] Failed to start LLM stream: %v", err)
|
||||
@@ -47,6 +49,8 @@ func (e *AgentEngine) streamLLMToEventBus(
|
||||
chunkCount := 0
|
||||
responseTypeCounts := make(map[string]int)
|
||||
firstChunkTime := time.Time{}
|
||||
answerDecoder := llmresource.NewStreamDecoder(e.resourceRefs)
|
||||
thinkingDecoder := llmresource.NewStreamDecoder(e.resourceRefs)
|
||||
|
||||
for chunk := range stream {
|
||||
chunkCount++
|
||||
@@ -62,6 +66,12 @@ func (e *AgentEngine) streamLLMToEventBus(
|
||||
result.StreamError = chunk.Content
|
||||
continue
|
||||
}
|
||||
if chunk.ResponseType == types.ResponseTypeThinking {
|
||||
chunk.Content = thinkingDecoder.Feed(chunk.Content)
|
||||
} else {
|
||||
chunk.Content = answerDecoder.Feed(chunk.Content)
|
||||
}
|
||||
e.resourceRefs.DecodeToolCalls(chunk.ToolCalls)
|
||||
|
||||
if chunk.Content != "" {
|
||||
isExtracted := chunk.Data != nil && chunk.Data["source"] != nil
|
||||
@@ -90,6 +100,12 @@ func (e *AgentEngine) streamLLMToEventBus(
|
||||
emitFunc(&chunk, result.Content)
|
||||
}
|
||||
}
|
||||
result.Content += answerDecoder.Flush()
|
||||
result.ReasoningContent += thinkingDecoder.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)
|
||||
|
||||
// Stream diagnostic summary: helps identify non-streaming patterns
|
||||
streamDuration := time.Duration(0)
|
||||
|
||||
Reference in New Issue
Block a user