feat(chat): implement orphan alias detection and logging in chat completion and streaming

Add functionality to detect unresolvable resource aliases emitted by the model during chat completion and streaming. Introduce logging for these orphan aliases to aid in debugging and improve the handling of resource references. Update the stream processing to ensure held aliases are flushed upon cancellation, preventing data loss. Include tests to verify the correct reporting of orphan aliases.
This commit is contained in:
wizardchen
2026-07-15 16:49:43 +08:00
committed by lyingbug
parent 6d14cc3536
commit 38c594aec3
6 changed files with 210 additions and 16 deletions
+34
View File
@@ -23,6 +23,11 @@ var storedRefRE = regexp.MustCompile(
`(?:local|minio|cos|tos|s3|oss|ks3|obs)://[^\s)\]>"']+`,
)
// aliasShapeRE matches the alias syntax produced by EncodeText. It is used only
// to spot alias-shaped tokens the model emitted that the registry cannot map
// back — either a hallucinated reference or a coincidental collision.
var aliasShapeRE = regexp.MustCompile(`res:\d{4,}`)
// Registry 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 {
@@ -120,6 +125,35 @@ func (r *Registry) DecodeToolCalls(toolCalls []types.LLMToolCall) {
}
}
// OrphanAliases returns the distinct alias-shaped tokens in an already-decoded
// string that the registry cannot resolve. A non-empty result means the model
// 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 {
if decoded == "" {
return nil
}
var orphans []string
seen := make(map[string]struct{})
for _, match := range aliasShapeRE.FindAllString(decoded, -1) {
if r != nil {
r.mu.RLock()
_, known := r.aliasToRef[match]
r.mu.RUnlock()
if known {
continue
}
}
if _, dup := seen[match]; dup {
continue
}
seen[match] = struct{}{}
orphans = append(orphans, match)
}
return orphans
}
func (r *Registry) aliases() []string {
r.mu.RLock()
defer r.mu.RUnlock()
+17
View File
@@ -41,3 +41,20 @@ func TestStreamDecoderRestoresSplitAlias(t *testing.T) {
require.Equal(t, ref+" afte", d.Feed("001 after"))
require.Equal(t, "r", d.Flush())
}
func TestOrphanAliasesReportsUnresolvableTokens(t *testing.T) {
r := NewRegistry()
ref := "resource://AbCdEfGhIjKlMnOpQrStUv"
require.Equal(t, "res:0001", r.EncodeText(ref))
// Known alias resolves and leaves no orphan once decoded.
require.Nil(t, r.OrphanAliases(r.DecodeText("see res:0001")))
// A reference the registry never assigned is reported (deduplicated).
require.Equal(t, []string{"res:0099"}, r.OrphanAliases("look at res:0099 and res:0099"))
}
func TestOrphanAliasesNilRegistry(t *testing.T) {
var r *Registry
require.Equal(t, []string{"res:0001"}, r.OrphanAliases("res:0001"))
}