Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
refactor(modelcontext): fold llmresource into modelcontext as resource codec
wizardchenc01b00313b0d
diff --git a/internal/modelcontext/registry.go b/internal/modelcontext/registry.goindex 4f9e123bc..110c7786b 100644--- a/internal/modelcontext/registry.go+++ b/internal/modelcontext/registry.go@@ -15,7 +15,6 @@ import ("sort""github.com/Tencent/WeKnora/internal/llmreference"- "github.com/Tencent/WeKnora/internal/llmresource""github.com/Tencent/WeKnora/internal/models/chat""github.com/Tencent/WeKnora/internal/types")@@ -47,7 +46,7 @@ type ChunkReference = llmreference.ChunkReference// compacted to dN. Callers therefore cannot accidentally reverse the codecs.type Registry struct {sources *llmreference.Registry- resources *llmresource.Registry+ resources *resourceRegistryissues *HandleTable}@@ -55,7 +54,7 @@ type Registry struct {func NewRegistry(citationsEnabled bool) *Registry {return &Registry{sources: llmreference.NewRegistry(citationsEnabled),- resources: llmresource.NewRegistry(),+ resources: newResourceRegistry(),issues: NewHandleTable("i", 0, 1),}}@@ -174,7 +173,7 @@ func (r *Registry) StreamDecoder() *StreamDecoder {return &StreamDecoder{}}return &StreamDecoder{- resources: llmresource.NewStreamDecoder(r.resources),+ resources: newResourceStreamDecoder(r.resources),sources: llmreference.NewStreamExpander(r.sources),issues: NewHandleStreamDecoder(r.issues),orphans: &orphanResourceStreamFilter{},@@ -299,7 +298,7 @@ func (r *Registry) DecodeOutputText(text string) string {// StreamDecoder composes resource restoration and source-citation expansion// so callers cannot split handle processing or apply stages in the wrong order.type StreamDecoder struct {- resources *llmresource.StreamDecoder+ resources *resourceStreamDecodersources *llmreference.StreamExpanderissues *HandleStreamDecoderorphans *orphanResourceStreamFilterdiff --git a/internal/llmresource/registry.go b/internal/modelcontext/resources.gosimilarity index 80%rename from internal/llmresource/registry.gorename to internal/modelcontext/resources.goindex 8e2daf459..7046d75b2 100644--- a/internal/llmresource/registry.go+++ b/internal/modelcontext/resources.go@@ -1,7 +1,7 @@-// Package llmresource is the low-level durable-resource codec used by-// modelcontext. Application request lifecycles should not coordinate it-// independently from source-reference handling.-package llmresource+// resources.go is the durable-resource half of the model-context registry:+// it assigns request-local res://NNNN handles to stored resource references+// and restores them before application code consumes model output.+package modelcontextimport ("fmt"@@ -41,24 +41,24 @@ var storedRefRE = regexp.MustCompile(// back — either a hallucinated reference or a coincidental collision.var aliasShapeRE = regexp.MustCompile(`res://\d+`)-// Registry assigns low-entropy, request-local aliases to stable resource+// resourceRegistry assigns low-entropy, request-local aliases to stable resource// handles. It is safe to reuse across all rounds of one Agent execution.-type Registry struct {+type resourceRegistry struct {mu sync.RWMutexrefToAlias map[string]stringaliasToRef map[string]string}-// NewRegistry creates an empty request-local alias registry.-func NewRegistry() *Registry {- return &Registry{+// newResourceRegistry creates an empty request-local alias registry.+func newResourceRegistry() *resourceRegistry {+ return &resourceRegistry{refToAlias: make(map[string]string),aliasToRef: make(map[string]string),}}// EncodeText replaces stored references with compact, stable aliases.-func (r *Registry) EncodeText(value string) string {+func (r *resourceRegistry) EncodeText(value string) string {if r == nil || value == "" {return value}@@ -79,7 +79,7 @@ func (r *Registry) EncodeText(value string) string {}// DecodeText restores every alias currently known to the registry.-func (r *Registry) DecodeText(value string) string {+func (r *resourceRegistry) DecodeText(value string) string {if r == nil || value == "" {return value}@@ -100,7 +100,7 @@ func (r *Registry) DecodeText(value string) string {// StripOrphanAliases removes alias-shaped tokens after all known aliases have// been restored. Use this only on model output; tool arguments must retain// unknown aliases long enough for modelcontext to reject the call.-func (r *Registry) StripOrphanAliases(value string) string {+func (r *resourceRegistry) StripOrphanAliases(value string) string {if value == "" {return value}@@ -109,7 +109,7 @@ func (r *Registry) StripOrphanAliases(value string) string {// EncodeMessages returns a copied message slice with textual references// compacted. Binary/image content fields are intentionally left untouched.-func (r *Registry) EncodeMessages(messages []chat.Message) []chat.Message {+func (r *resourceRegistry) EncodeMessages(messages []chat.Message) []chat.Message {if r == nil || len(messages) == 0 {return messages}@@ -134,18 +134,8 @@ func (r *Registry) EncodeMessages(messages []chat.Message) []chat.Message {return encoded}-// DecodeResponse restores references in a non-streaming model response.-func (r *Registry) DecodeResponse(response *types.ChatResponse) {- if r == nil || response == nil {- return- }- response.Content = r.DecodeText(response.Content)- response.ReasoningContent = r.DecodeText(response.ReasoningContent)- r.DecodeToolCalls(response.ToolCalls)-}-// DecodeToolCalls restores aliases in tool-call JSON arguments.-func (r *Registry) DecodeToolCalls(toolCalls []types.LLMToolCall) {+func (r *resourceRegistry) DecodeToolCalls(toolCalls []types.LLMToolCall) {for i := range toolCalls {toolCalls[i].Function.Arguments = r.DecodeText(toolCalls[i].Function.Arguments)}@@ -156,7 +146,7 @@ func (r *Registry) DecodeToolCalls(toolCalls []types.LLMToolCall) {// emitted a reference no real resource backs (hallucination) or the user text// happened to collide with the alias syntax. Callers should log/observe these// rather than surfacing them to end users as broken links.-func (r *Registry) OrphanAliases(decoded string) []string {+func (r *resourceRegistry) OrphanAliases(decoded string) []string {if decoded == "" {return nil}@@ -180,7 +170,7 @@ func (r *Registry) OrphanAliases(decoded string) []string {return orphans}-func (r *Registry) aliases() []string {+func (r *resourceRegistry) aliases() []string {r.mu.RLock()defer r.mu.RUnlock()aliases := make([]string, 0, len(r.aliasToRef))@@ -190,21 +180,21 @@ func (r *Registry) aliases() []string {return aliases}-// StreamDecoder holds only a suffix that could be the beginning of a known+// resourceStreamDecoder holds only a suffix that could be the beginning of a known// alias, allowing aliases split across provider chunks to round-trip exactly.-type StreamDecoder struct {- registry *Registry+type resourceStreamDecoder struct {+ registry *resourceRegistrypending string}-// NewStreamDecoder creates an alias decoder for one streaming text channel.-func NewStreamDecoder(registry *Registry) *StreamDecoder {- return &StreamDecoder{registry: registry}+// newResourceStreamDecoder creates an alias decoder for one streaming text channel.+func newResourceStreamDecoder(registry *resourceRegistry) *resourceStreamDecoder {+ return &resourceStreamDecoder{registry: registry}}// Feed decodes a chunk while retaining suffixes that may complete an alias in// the next provider chunk.-func (d *StreamDecoder) Feed(chunk string) string {+func (d *resourceStreamDecoder) Feed(chunk string) string {if d == nil || d.registry == nil {return chunk}@@ -229,7 +219,7 @@ func (d *StreamDecoder) Feed(chunk string) string {}// Flush returns any buffered suffix when the provider stream closes.-func (d *StreamDecoder) Flush() string {+func (d *resourceStreamDecoder) Flush() string {if d == nil {return ""}diff --git a/internal/llmresource/registry_test.go b/internal/modelcontext/resources_test.gosimilarity index 89%rename from internal/llmresource/registry_test.gorename to internal/modelcontext/resources_test.goindex 2187651f3..90ff519a4 100644--- a/internal/llmresource/registry_test.go+++ b/internal/modelcontext/resources_test.go@@ -1,4 +1,4 @@-package llmresource+package modelcontextimport ("testing"@@ -8,7 +8,7 @@ import ()func TestRegistryRoundTripAndDeduplicate(t *testing.T) {- r := NewRegistry()+ r := newResourceRegistry()ref := "resource://AbCdEfGhIjKlMnOpQrStUv"encoded := r.EncodeText(" and " + ref)require.Equal(t, " and res://0001", encoded)@@ -16,7 +16,7 @@ func TestRegistryRoundTripAndDeduplicate(t *testing.T) {}func TestRegistryAliasesLegacyPhysicalReferencesDuringRollout(t *testing.T) {- r := NewRegistry()+ r := newResourceRegistry()ref := "storage://c0d93536-702c-4977-aa5e-fe670073c3cb/local://10000/exports/image.png"encoded := r.EncodeText("")require.Equal(t, "", encoded)@@ -24,7 +24,7 @@ func TestRegistryAliasesLegacyPhysicalReferencesDuringRollout(t *testing.T) {}func TestRegistryAliasesWikiSummarySlug(t *testing.T) {- r := NewRegistry()+ r := newResourceRegistry()slug := "summary/07a20bb1-a662-47cf-9929-06fb5d5b5b5e"// Inside a [[slug|display]] link the model must copy verbatim.encoded := r.EncodeText("see [[" + slug + "|Foo.md - Summary]]")@@ -36,14 +36,14 @@ func TestRegistryAliasesWikiSummarySlug(t *testing.T) {}func TestRegistryLeavesEntitySlugUntouched(t *testing.T) {- r := NewRegistry()+ r := newResourceRegistry()// Entity slugs are low-entropy and semantically meaningful; not aliased.entity := "[[entity/weknora-error-log|WeKnora 试错记录]]"require.Equal(t, entity, r.EncodeText(entity))}func TestRegistryEncodesMessageCopies(t *testing.T) {- r := NewRegistry()+ r := newResourceRegistry()ref := "resource://AbCdEfGhIjKlMnOpQrStUv"original := []chat.Message{{Role: "tool", Content: ref}}encoded := r.EncodeMessages(original)@@ -52,10 +52,10 @@ func TestRegistryEncodesMessageCopies(t *testing.T) {}func TestStreamDecoderRestoresSplitAlias(t *testing.T) {- r := NewRegistry()+ r := newResourceRegistry()ref := "resource://AbCdEfGhIjKlMnOpQrStUv"require.Equal(t, "res://0001", r.EncodeText(ref))- d := NewStreamDecoder(r)+ d := newResourceStreamDecoder(r)require.Equal(t, "before ", d.Feed("before res://0"))require.Equal(t, ref+" afte", d.Feed("001 after"))require.Equal(t, "r", d.Flush())@@ -63,16 +63,16 @@ func TestStreamDecoderRestoresSplitAlias(t *testing.T) {func TestStreamDecoderRestoresAliasSplitBeforeScheme(t *testing.T) {const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"- r := NewRegistry()+ r := newResourceRegistry()require.Equal(t, "res://0001", r.EncodeText(ref))- d := NewStreamDecoder(r)+ d := newResourceStreamDecoder(r)require.Equal(t, "see ", d.Feed("see re"))require.Equal(t, ref, d.Feed("s://0001"))require.Empty(t, d.Flush())}func TestOrphanAliasesReportsUnresolvableTokens(t *testing.T) {- r := NewRegistry()+ r := newResourceRegistry()ref := "resource://AbCdEfGhIjKlMnOpQrStUv"require.Equal(t, "res://0001", r.EncodeText(ref))@@ -84,11 +84,11 @@ func TestOrphanAliasesReportsUnresolvableTokens(t *testing.T) {}func TestStripOrphanAliasesRemovesIncompleteNumericHandle(t *testing.T) {- r := NewRegistry()+ r := newResourceRegistry()require.Equal(t, "broken ", r.StripOrphanAliases("broken res://1"))}func TestOrphanAliasesNilRegistry(t *testing.T) {- var r *Registry+ var r *resourceRegistryrequire.Equal(t, []string{"res://0001"}, r.OrphanAliases("res://0001"))}