feat(agent): add per-agent citation output toggle
Move citation protocol injection to the system layer so custom prompts no longer own citation syntax. Agents can disable inline citations while source aliases still encode and decode tool arguments correctly.
This commit is contained in:
@@ -88,7 +88,7 @@ func NewAgentEngine(
|
||||
systemPromptTemplate: systemPromptTemplate,
|
||||
tokenEstimator: tokenEst,
|
||||
resourceRefs: llmresource.NewRegistry(),
|
||||
sourceRefs: llmreference.NewRegistry(),
|
||||
sourceRefs: llmreference.NewRegistry(config.CitationsEnabled()),
|
||||
}
|
||||
|
||||
// Initialize memory consolidator if context window management is configured
|
||||
@@ -125,7 +125,7 @@ func (e *AgentEngine) buildSystemPrompt(ctx context.Context) string {
|
||||
e.systemPromptOptions(ctx),
|
||||
e.systemPromptTemplate,
|
||||
)
|
||||
return strings.TrimRight(prompt, " \t\r\n") + llmreference.ProtocolPrompt
|
||||
return strings.TrimRight(prompt, " \t\r\n") + llmreference.ProtocolPrompt(e.config.CitationsEnabled())
|
||||
}
|
||||
|
||||
// NewAgentEngineWithSkills creates a new agent engine with skills support
|
||||
|
||||
@@ -105,6 +105,23 @@ func withMaxIterations(n int) testEngineOption {
|
||||
}
|
||||
}
|
||||
|
||||
func withCitationsEnabled(enabled bool) testEngineOption {
|
||||
return func(cfg *types.AgentConfig) {
|
||||
cfg.CitationEnabled = &enabled
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSystemPromptUsesInternalCitationSetting(t *testing.T) {
|
||||
model := &mockChat{}
|
||||
enabledEngine := newTestEngine(t, model)
|
||||
require.Contains(t, enabledEngine.buildSystemPrompt(context.Background()), "Source citations are enabled")
|
||||
|
||||
disabledEngine := newTestEngine(t, model, withCitationsEnabled(false))
|
||||
prompt := disabledEngine.buildSystemPrompt(context.Background())
|
||||
require.Contains(t, prompt, "Source citations are disabled")
|
||||
require.NotContains(t, prompt, "Source citations are enabled")
|
||||
}
|
||||
|
||||
func newTestEngine(t *testing.T, chatModel chat.Chat, opts ...testEngineOption) *AgentEngine {
|
||||
t.Helper()
|
||||
cfg := &types.AgentConfig{
|
||||
|
||||
@@ -19,8 +19,8 @@ func finalAnswerImageRequirement(hasRetrievedImage bool) string {
|
||||
return ""
|
||||
}
|
||||
return `
|
||||
6. Retrieved tool results contain Markdown images. Unless the user explicitly requested text-only output or every image is clearly unrelated, the final answer MUST include at least one relevant Markdown image copied verbatim from the tool results. Preserve its complete URL exactly. Use ASCII half-width parentheses exactly as  and never use full-width ( or ). Place the image immediately after the paragraph it supports. When multiple images support different sections, distribute them across those sections instead of stopping after the first image.
|
||||
7. Before finishing, silently verify that the answer contains a Markdown image when requirement 6 applies.`
|
||||
5. Retrieved tool results contain Markdown images. Unless the user explicitly requested text-only output or every image is clearly unrelated, the final answer MUST include at least one relevant Markdown image copied verbatim from the tool results. Preserve its complete URL exactly. Use ASCII half-width parentheses exactly as  and never use full-width ( or ). Place the image immediately after the paragraph it supports. When multiple images support different sections, distribute them across those sections instead of stopping after the first image.
|
||||
6. Before finishing, silently verify that the answer contains a Markdown image when requirement 5 applies.`
|
||||
}
|
||||
|
||||
// streamFinalAnswerToEventBus streams the final answer generation through EventBus
|
||||
@@ -80,10 +80,9 @@ User question: %s
|
||||
|
||||
Requirements:
|
||||
1. Answer based on the actually retrieved content
|
||||
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
|
||||
2. Organize the answer in a structured format
|
||||
3. If information is insufficient, honestly state so
|
||||
4. IMPORTANT: Respond in the same language as the user's question
|
||||
%s
|
||||
|
||||
Now generate the final answer:`, query, imageRequirement)
|
||||
|
||||
@@ -75,7 +75,7 @@ Avoid:
|
||||
|
||||
## Output
|
||||
Returns chunks ranked by semantic similarity, reranked when applicable.
|
||||
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.`,
|
||||
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.`,
|
||||
schema: json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -11,18 +11,20 @@ import (
|
||||
|
||||
// prepareMessagesWithReferences replaces the pipeline's positional context IDs
|
||||
// with request-local chunk references in the copy sent to the model. Persisted
|
||||
// rendered_content and the public citation contract remain unchanged.
|
||||
// rendered_content remains unchanged; public citations are expanded only when
|
||||
// the request's agent setting enables them.
|
||||
func prepareMessagesWithReferences(
|
||||
ctx context.Context,
|
||||
chatManage *types.ChatManage,
|
||||
) ([]chat.Message, *llmreference.Registry) {
|
||||
refs := llmreference.NewRegistry()
|
||||
citationsEnabled := chatManage == nil || chatManage.CitationsEnabled()
|
||||
refs := llmreference.NewRegistry(citationsEnabled)
|
||||
if chatManage == nil {
|
||||
return nil, refs
|
||||
}
|
||||
messages := prepareMessagesWithHistory(chatManage)
|
||||
if len(messages) > 0 {
|
||||
messages[0].Content = strings.TrimRight(messages[0].Content, " \t\r\n") + llmreference.ProtocolPrompt
|
||||
messages[0].Content = strings.TrimRight(messages[0].Content, " \t\r\n") + llmreference.ProtocolPrompt(citationsEnabled)
|
||||
}
|
||||
if len(chatManage.MergeResult) == 0 || len(messages) == 0 {
|
||||
return messages, refs
|
||||
|
||||
@@ -30,7 +30,7 @@ func TestPrepareMessagesWithReferencesUsesChunkCentricContext(t *testing.T) {
|
||||
|
||||
messages, refs := prepareMessagesWithReferences(context.Background(), manage)
|
||||
require.Len(t, messages, 2)
|
||||
require.Contains(t, messages[0].Content, "Source reference protocol")
|
||||
require.Contains(t, messages[0].Content, "Source handling protocol")
|
||||
require.Contains(t, messages[1].Content, `<document id="d1" kb="b1" title="Doc">`)
|
||||
require.Contains(t, messages[1].Content, `<chunk id="c1" index="1" view="full">`)
|
||||
require.Contains(t, messages[1].Content, `<chunk id="c2" index="2" view="full">`)
|
||||
@@ -110,7 +110,30 @@ func TestPrepareMessagesWithReferencesCompactsHistoryWithoutCurrentRetrieval(t *
|
||||
|
||||
messages, refs := prepareMessagesWithReferences(context.Background(), manage)
|
||||
messages = refs.EncodeMessages(messages)
|
||||
require.Contains(t, messages[0].Content, "Source reference protocol")
|
||||
require.Contains(t, messages[0].Content, "Source handling protocol")
|
||||
require.Contains(t, messages[2].Content, `<ref id="w1"/>`)
|
||||
require.NotContains(t, messages[2].Content, "https://example.com/old")
|
||||
}
|
||||
|
||||
func TestPrepareMessagesWithReferencesSuppressesCitationsWhenDisabled(t *testing.T) {
|
||||
disabled := false
|
||||
manage := &types.ChatManage{
|
||||
PipelineRequest: types.PipelineRequest{
|
||||
Query: "question",
|
||||
CitationEnabled: &disabled,
|
||||
SummaryConfig: types.SummaryConfig{Prompt: "custom system prompt"},
|
||||
},
|
||||
PipelineState: types.PipelineState{
|
||||
UserContent: "question",
|
||||
MergeResult: []*types.SearchResult{{
|
||||
ID: "chunk-1", KnowledgeID: "doc-1", KnowledgeBaseID: "kb-1", KnowledgeTitle: "Doc", Content: "evidence",
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
messages, refs := prepareMessagesWithReferences(context.Background(), manage)
|
||||
require.Contains(t, messages[0].Content, "Source citations are disabled")
|
||||
require.Contains(t, messages[1].Content, `<chunk id="c1"`)
|
||||
require.NotContains(t, messages[1].Content, "chunk-1")
|
||||
require.Equal(t, "answer ", refs.ExpandText(`answer <ref id="c1"/>`))
|
||||
}
|
||||
|
||||
@@ -89,10 +89,25 @@ func TestPrepareFallbackMessagesMigratesHistoricalCitations(t *testing.T) {
|
||||
}}
|
||||
|
||||
messages, refs := prepareFallbackMessages(cm, "legacy fallback prompt")
|
||||
require.Contains(t, messages[0].Content, "Source reference protocol")
|
||||
require.Contains(t, messages[0].Content, "Source handling protocol")
|
||||
require.Equal(t, `Previous <ref id="c1"/>`, messages[2].Content)
|
||||
require.Equal(t,
|
||||
`<kb doc="Legacy" chunk_id="legacy-chunk" kb_id="legacy-kb" />`,
|
||||
refs.ExpandText(`<ref id="c1"/>`),
|
||||
)
|
||||
}
|
||||
|
||||
func TestPrepareFallbackMessagesSuppressesCitationsWhenDisabled(t *testing.T) {
|
||||
disabled := false
|
||||
cm := &types.ChatManage{PipelineRequest: types.PipelineRequest{CitationEnabled: &disabled}}
|
||||
cm.Query = "follow-up"
|
||||
cm.History = []*types.History{{
|
||||
Query: "previous",
|
||||
Answer: `Previous <kb doc="Legacy" chunk_id="legacy-chunk" />`,
|
||||
}}
|
||||
|
||||
messages, refs := prepareFallbackMessages(cm, "legacy fallback prompt")
|
||||
require.Contains(t, messages[0].Content, "Source citations are disabled")
|
||||
require.Equal(t, `Previous <ref id="c1"/>`, messages[2].Content)
|
||||
require.Equal(t, "answer ", refs.ExpandText(`answer <ref id="c1"/>`))
|
||||
}
|
||||
|
||||
@@ -229,6 +229,7 @@ func (s *sessionService) buildAgentConfig(
|
||||
MCPServices: customAgent.Config.MCPServices,
|
||||
MCPAuthWaitTimeout: customAgent.Config.MCPAuthWaitTimeout,
|
||||
Thinking: customAgent.Config.Thinking,
|
||||
CitationEnabled: customAgent.Config.CitationEnabled,
|
||||
RetrieveKBOnlyWhenMentioned: customAgent.Config.RetrieveKBOnlyWhenMentioned,
|
||||
LLMCallTimeout: customAgent.Config.LLMCallTimeout,
|
||||
RetainRetrievalHistory: customAgent.Config.RetainRetrievalHistory,
|
||||
|
||||
@@ -995,11 +995,12 @@ func prepareFallbackMessages(
|
||||
promptContent string,
|
||||
) ([]chat.Message, *llmreference.Registry) {
|
||||
messages := buildFallbackMessages(chatManage, promptContent)
|
||||
refs := llmreference.NewRegistry()
|
||||
citationsEnabled := chatManage == nil || chatManage.CitationsEnabled()
|
||||
refs := llmreference.NewRegistry(citationsEnabled)
|
||||
if len(messages) > 0 && messages[0].Role == "system" {
|
||||
messages[0].Content = strings.TrimRight(messages[0].Content, " \t\r\n") + llmreference.ProtocolPrompt
|
||||
messages[0].Content = strings.TrimRight(messages[0].Content, " \t\r\n") + llmreference.ProtocolPrompt(citationsEnabled)
|
||||
} else {
|
||||
messages = append([]chat.Message{{Role: "system", Content: strings.TrimSpace(llmreference.ProtocolPrompt)}}, messages...)
|
||||
messages = append([]chat.Message{{Role: "system", Content: strings.TrimSpace(llmreference.ProtocolPrompt(citationsEnabled))}}, messages...)
|
||||
}
|
||||
return refs.EncodeMessages(messages), refs
|
||||
}
|
||||
@@ -1184,7 +1185,7 @@ func (s *sessionService) consumeFallbackStream(
|
||||
// `references` SSE event. Must run before CHAT_COMPLETION_STREAM so citations
|
||||
// arrive while the connection is still open (complete closes the stream).
|
||||
func emitKnowledgeReferencesEvent(ctx context.Context, chatManage *types.ChatManage) {
|
||||
if chatManage == nil || chatManage.EventBus == nil || len(chatManage.MergeResult) == 0 {
|
||||
if chatManage == nil || !chatManage.CitationsEnabled() || chatManage.EventBus == nil || len(chatManage.MergeResult) == 0 {
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "Emitting references event with %d results (pre-answer)", len(chatManage.MergeResult))
|
||||
@@ -1205,6 +1206,9 @@ func (s *sessionService) emitFallbackAnswer(ctx context.Context, chatManage *typ
|
||||
if chatManage.EventBus == nil {
|
||||
return
|
||||
}
|
||||
if !chatManage.CitationsEnabled() {
|
||||
content = llmreference.NewRegistry(false).ExpandText(content)
|
||||
}
|
||||
|
||||
fallbackID := generateEventID("fallback")
|
||||
if err := chatManage.EventBus.Emit(ctx, types.Event{
|
||||
|
||||
@@ -52,6 +52,31 @@ type stubModelService struct {
|
||||
modelsByID map[string]*types.Model
|
||||
}
|
||||
|
||||
func TestEmitKnowledgeReferencesEventHonorsCitationSetting(t *testing.T) {
|
||||
bus := event.NewEventBus()
|
||||
emitted := 0
|
||||
bus.On(event.EventAgentReferences, func(context.Context, event.Event) error {
|
||||
emitted++
|
||||
return nil
|
||||
})
|
||||
disabled := false
|
||||
cm := &types.ChatManage{
|
||||
PipelineRequest: types.PipelineRequest{CitationEnabled: &disabled},
|
||||
PipelineState: types.PipelineState{
|
||||
MergeResult: []*types.SearchResult{{ID: "chunk-1"}},
|
||||
},
|
||||
PipelineContext: types.PipelineContext{EventBus: bus.AsEventBusInterface()},
|
||||
}
|
||||
|
||||
emitKnowledgeReferencesEvent(context.Background(), cm)
|
||||
require.Zero(t, emitted)
|
||||
|
||||
enabled := true
|
||||
cm.CitationEnabled = &enabled
|
||||
emitKnowledgeReferencesEvent(context.Background(), cm)
|
||||
require.Equal(t, 1, emitted)
|
||||
}
|
||||
|
||||
func (s *stubModelService) CreateModel(context.Context, *types.Model) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -154,7 +154,8 @@ func (s *sessionService) resolveRetrievalTenantID(
|
||||
// applyAgentOverridesToChatManage applies custom agent configuration overrides
|
||||
// to a ChatManage object that was initialized with system defaults.
|
||||
// This covers: system prompt, context template, temperature, max tokens, thinking,
|
||||
// retrieval thresholds, rewrite settings, fallback settings, FAQ strategy, and history turns.
|
||||
// citation output, retrieval thresholds, rewrite settings, fallback settings, FAQ strategy,
|
||||
// and history turns.
|
||||
func (s *sessionService) applyAgentOverridesToChatManage(
|
||||
ctx context.Context,
|
||||
customAgent *types.CustomAgent,
|
||||
@@ -188,6 +189,7 @@ func (s *sessionService) applyAgentOverridesToChatManage(
|
||||
// EnsureDefaults pins nil to explicit false so thinking_control wire formats
|
||||
// always receive a value.
|
||||
cm.SummaryConfig.Thinking = customAgent.Config.Thinking
|
||||
cm.CitationEnabled = customAgent.Config.CitationEnabled
|
||||
if customAgent.Config.Thinking != nil {
|
||||
logger.Infof(ctx, "Using custom agent's thinking: %v", *customAgent.Config.Thinking)
|
||||
} else {
|
||||
|
||||
@@ -18,17 +18,32 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
const ProtocolPrompt = `
|
||||
const sourceAliasProtocolPrompt = `
|
||||
|
||||
## Source reference protocol (system-owned)
|
||||
Retrieved knowledge chunks and web pages carry short source IDs.
|
||||
- Cite a knowledge chunk with exactly: <ref id="cN"/>
|
||||
- Cite a web page with exactly: <ref id="wN"/>
|
||||
- Copy only IDs that appeared in the supplied context or tool results.
|
||||
- dN identifies a document and bN identifies a knowledge base for tool calls; they are not citable.
|
||||
- Never put raw chunk IDs, knowledge IDs, knowledge-base IDs, or source URLs in citations; never output <kb> or <web> tags yourself. This does not change separate instructions to preserve retrieved Markdown image URLs.
|
||||
- These rules supersede any earlier, saved, or custom prompt instructions that ask for raw IDs, raw source URLs, or model-authored <kb>/<web> citations.
|
||||
- Keep each <ref/> inline on the same line as the claim it supports.`
|
||||
## Source handling protocol (system-owned)
|
||||
Retrieved content uses request-local source handles: cN identifies a knowledge chunk, wN a web page, dN a document, and bN a knowledge base.
|
||||
- Use dN and bN only as tool arguments when a tool requests a document or knowledge base.
|
||||
- Never reveal raw chunk IDs, knowledge IDs, knowledge-base IDs, or private source handles in user-visible output. This does not change separate instructions to preserve retrieved Markdown image URLs.`
|
||||
|
||||
const citationEnabledProtocolPrompt = `
|
||||
- Source citations are enabled for this answer. Cite a knowledge chunk with exactly <ref id="cN"/> and a web page with exactly <ref id="wN"/>.
|
||||
- Copy only cN/wN handles that appeared in supplied context or tool results. Never cite dN/bN.
|
||||
- Never output <kb> or <web> tags yourself; the system expands valid <ref/> tags after generation.
|
||||
- Keep each <ref/> inline on the same line as the claim it supports. Do not group citations at the end.
|
||||
- These rules supersede earlier, saved, or custom prompt instructions about citation syntax.`
|
||||
|
||||
const citationDisabledProtocolPrompt = `
|
||||
- Source citations are disabled for this answer. Do not output <ref>, <kb>, <web>, raw source URLs, or source-handle citations.
|
||||
- These rules supersede earlier, saved, or custom prompt instructions that require source citations.`
|
||||
|
||||
// ProtocolPrompt returns the internal, non-user-editable source protocol for a
|
||||
// model call. Citation formatting stays out of custom and template prompts.
|
||||
func ProtocolPrompt(citationsEnabled bool) string {
|
||||
if citationsEnabled {
|
||||
return sourceAliasProtocolPrompt + citationEnabledProtocolPrompt
|
||||
}
|
||||
return sourceAliasProtocolPrompt + citationDisabledProtocolPrompt
|
||||
}
|
||||
|
||||
type ChunkReference struct {
|
||||
Alias string
|
||||
@@ -51,6 +66,8 @@ type WebReference struct {
|
||||
type Registry struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
citationsEnabled bool
|
||||
|
||||
chunkByID map[string]*ChunkReference
|
||||
chunkByAlias map[string]*ChunkReference
|
||||
docToAlias map[string]string
|
||||
@@ -61,16 +78,21 @@ type Registry struct {
|
||||
webByAlias map[string]*WebReference
|
||||
}
|
||||
|
||||
func NewRegistry() *Registry {
|
||||
func NewRegistry(citationsEnabled ...bool) *Registry {
|
||||
enabled := true
|
||||
if len(citationsEnabled) > 0 {
|
||||
enabled = citationsEnabled[0]
|
||||
}
|
||||
return &Registry{
|
||||
chunkByID: make(map[string]*ChunkReference),
|
||||
chunkByAlias: make(map[string]*ChunkReference),
|
||||
docToAlias: make(map[string]string),
|
||||
aliasToDoc: make(map[string]string),
|
||||
kbToAlias: make(map[string]string),
|
||||
aliasToKB: make(map[string]string),
|
||||
webByURL: make(map[string]*WebReference),
|
||||
webByAlias: make(map[string]*WebReference),
|
||||
citationsEnabled: enabled,
|
||||
chunkByID: make(map[string]*ChunkReference),
|
||||
chunkByAlias: make(map[string]*ChunkReference),
|
||||
docToAlias: make(map[string]string),
|
||||
aliasToDoc: make(map[string]string),
|
||||
kbToAlias: make(map[string]string),
|
||||
aliasToKB: make(map[string]string),
|
||||
webByURL: make(map[string]*WebReference),
|
||||
webByAlias: make(map[string]*WebReference),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -398,7 +420,7 @@ func (r *Registry) decodeJSON(raw string, encode bool) string {
|
||||
if err := json.Unmarshal([]byte(raw), &value); err != nil {
|
||||
return raw
|
||||
}
|
||||
value = r.walkJSON(value, encode)
|
||||
value = r.walkJSON("", value, encode)
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return raw
|
||||
@@ -406,26 +428,47 @@ func (r *Registry) decodeJSON(raw string, encode bool) string {
|
||||
return string(encoded)
|
||||
}
|
||||
|
||||
func (r *Registry) walkJSON(value interface{}, encode bool) interface{} {
|
||||
// decodableKeys mirrors the ID-bearing keys recognized by
|
||||
// registerToolArgumentValue. Alias -> real substitution on decode is restricted
|
||||
// to these keys so that free-text values (e.g. a grep/search query that happens
|
||||
// to equal "d1") are never rewritten into internal identifiers.
|
||||
var decodableKeys = map[string]struct{}{
|
||||
"chunk_id": {}, "faq_id": {}, "chunk_ids": {}, "faq_ids": {},
|
||||
"knowledge_id": {}, "knowledge_ids": {}, "suspected_knowledge_ids": {}, "source_refs": {},
|
||||
"knowledge_base": {}, "knowledge_base_id": {}, "knowledge_base_ids": {}, "kb_id": {}, "kb_ids": {},
|
||||
"url": {}, "urls": {},
|
||||
}
|
||||
|
||||
func (r *Registry) walkJSON(key string, value interface{}, encode bool) interface{} {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
if encode {
|
||||
// Encode matches on exact real identifiers (UUIDs/URLs), which do
|
||||
// not collide with prose, so it stays key-agnostic.
|
||||
if alias := r.aliasForRealValue(typed); alias != "" {
|
||||
return alias
|
||||
}
|
||||
return typed
|
||||
}
|
||||
// Decode only ID-bearing keys, and only when the value is alias-shaped,
|
||||
// so ordinary strings that coincidentally equal an alias are preserved.
|
||||
if _, ok := decodableKeys[strings.ToLower(key)]; !ok {
|
||||
return typed
|
||||
}
|
||||
if !shortSourceAliasRE.MatchString(strings.TrimSpace(typed)) {
|
||||
return typed
|
||||
}
|
||||
if real := r.realForAlias(typed); real != "" {
|
||||
return real
|
||||
}
|
||||
return typed
|
||||
case []interface{}:
|
||||
for i := range typed {
|
||||
typed[i] = r.walkJSON(typed[i], encode)
|
||||
typed[i] = r.walkJSON(key, typed[i], encode)
|
||||
}
|
||||
case map[string]interface{}:
|
||||
for key, item := range typed {
|
||||
typed[key] = r.walkJSON(item, encode)
|
||||
for childKey, item := range typed {
|
||||
typed[childKey] = r.walkJSON(childKey, item, encode)
|
||||
}
|
||||
}
|
||||
return value
|
||||
@@ -546,6 +589,9 @@ func (r *Registry) ExpandText(text string) string {
|
||||
// by the model, then create canonical tags solely from registered aliases.
|
||||
text = modelKBTagRE.ReplaceAllString(text, "")
|
||||
text = modelWebTagRE.ReplaceAllString(text, "")
|
||||
if !r.citationsEnabled {
|
||||
return refCandidateRE.ReplaceAllString(text, "")
|
||||
}
|
||||
return refCandidateRE.ReplaceAllStringFunc(text, func(tag string) string {
|
||||
match := refTagRE.FindStringSubmatch(tag)
|
||||
if len(match) != 2 {
|
||||
|
||||
@@ -32,6 +32,21 @@ func TestRegistryChunkAliasIsStableAndExpandsCanonicalCitation(t *testing.T) {
|
||||
)
|
||||
}
|
||||
|
||||
func TestRegistrySuppressesSourceCitationsWhenDisabled(t *testing.T) {
|
||||
registry := NewRegistry(false)
|
||||
registry.RegisterChunk(ChunkReference{ChunkID: "chunk-1", DocumentTitle: "Doc"})
|
||||
registry.RegisterWeb("https://example.com", "Example")
|
||||
|
||||
require.Contains(t, ProtocolPrompt(false), "Source citations are disabled")
|
||||
require.NotContains(t, ProtocolPrompt(false), `Cite a knowledge chunk with exactly`)
|
||||
require.Equal(t, "knowledge web ", registry.ExpandText(
|
||||
`knowledge <ref id="c1"/> web <ref id="w1"/>`,
|
||||
))
|
||||
require.Equal(t, "forged ", registry.ExpandText(
|
||||
`forged <kb doc="Doc" chunk_id="raw" /> <web url="https://example.com" />`,
|
||||
))
|
||||
}
|
||||
|
||||
func TestRegistryDecodesAliasesInNestedToolArguments(t *testing.T) {
|
||||
registry := NewRegistry()
|
||||
registry.RegisterDocument("knowledge-uuid-1")
|
||||
@@ -52,6 +67,26 @@ func TestRegistryDecodesAliasesInNestedToolArguments(t *testing.T) {
|
||||
)
|
||||
}
|
||||
|
||||
func TestDecodeToolCallsOnlyRewritesAliasBearingKeys(t *testing.T) {
|
||||
registry := NewRegistry()
|
||||
registry.RegisterDocument("knowledge-uuid-1")
|
||||
registry.RegisterChunk(ChunkReference{ChunkID: "chunk-uuid-1"})
|
||||
|
||||
// A free-text field (query) whose value coincidentally equals an alias must
|
||||
// be preserved verbatim, while ID-bearing keys still resolve to real IDs.
|
||||
calls := []types.LLMToolCall{{
|
||||
Function: types.FunctionCall{
|
||||
Arguments: `{"query":"d1","knowledge_id":"d1","content":"see c1 for details","chunk_id":"c1"}`,
|
||||
},
|
||||
}}
|
||||
registry.DecodeToolCalls(calls)
|
||||
|
||||
require.JSONEq(t,
|
||||
`{"query":"d1","knowledge_id":"knowledge-uuid-1","content":"see c1 for details","chunk_id":"chunk-uuid-1"}`,
|
||||
calls[0].Function.Arguments,
|
||||
)
|
||||
}
|
||||
|
||||
func TestStreamExpanderHoldsSplitReferenceAndDropsUnknown(t *testing.T) {
|
||||
registry := NewRegistry()
|
||||
registry.RegisterChunk(ChunkReference{ChunkID: "chunk-1", DocumentTitle: "Doc"})
|
||||
|
||||
@@ -38,6 +38,8 @@ type AgentConfig struct {
|
||||
MCPAuthWaitTimeout int `json:"mcp_auth_wait_timeout,omitempty"`
|
||||
// Whether to enable thinking mode (for models that support extended thinking)
|
||||
Thinking *bool `json:"thinking"`
|
||||
// Whether final answers include knowledge/web source citations. Nil defaults to true.
|
||||
CitationEnabled *bool `json:"citation_enabled"`
|
||||
// Whether to retrieve knowledge base only when explicitly mentioned with @ (default: false)
|
||||
RetrieveKBOnlyWhenMentioned bool `json:"retrieve_kb_only_when_mentioned"`
|
||||
|
||||
@@ -71,6 +73,12 @@ type AgentConfig struct {
|
||||
ParallelToolCalls bool `json:"parallel_tool_calls,omitempty"`
|
||||
}
|
||||
|
||||
// CitationsEnabled preserves citation output for legacy runtime configs that
|
||||
// predate the setting and therefore have a nil CitationEnabled value.
|
||||
func (c *AgentConfig) CitationsEnabled() bool {
|
||||
return c == nil || c.CitationEnabled == nil || *c.CitationEnabled
|
||||
}
|
||||
|
||||
// SessionAgentConfig represents session-level agent configuration
|
||||
// Sessions only store Enabled and KnowledgeBases; other configs are read from Tenant at runtime
|
||||
type SessionAgentConfig struct {
|
||||
|
||||
@@ -30,6 +30,9 @@ type PipelineRequest struct {
|
||||
FallbackStrategy FallbackStrategy `json:"fallback_strategy"`
|
||||
FallbackResponse string `json:"fallback_response"`
|
||||
FallbackPrompt string `json:"fallback_prompt"`
|
||||
// CitationEnabled controls only final knowledge/web source citations. Nil
|
||||
// defaults to true for requests and agents created before this option existed.
|
||||
CitationEnabled *bool `json:"citation_enabled,omitempty"`
|
||||
|
||||
// Rewrite parameters
|
||||
EnableRewrite bool `json:"enable_rewrite"`
|
||||
@@ -73,6 +76,11 @@ type PipelineRequest struct {
|
||||
Language string `json:"-"`
|
||||
}
|
||||
|
||||
// CitationsEnabled returns the effective citation setting for this request.
|
||||
func (c *PipelineRequest) CitationsEnabled() bool {
|
||||
return c == nil || c.CitationEnabled == nil || *c.CitationEnabled
|
||||
}
|
||||
|
||||
// QueryIntent represents the classified intent of a user query.
|
||||
type QueryIntent string
|
||||
|
||||
@@ -210,6 +218,7 @@ func (c *ChatManage) Clone() *ChatManage {
|
||||
FallbackStrategy: c.FallbackStrategy,
|
||||
FallbackResponse: c.FallbackResponse,
|
||||
FallbackPrompt: c.FallbackPrompt,
|
||||
CitationEnabled: c.CitationEnabled,
|
||||
EnableRewrite: c.EnableRewrite,
|
||||
EnableQueryExpansion: c.EnableQueryExpansion,
|
||||
RewritePromptSystem: c.RewritePromptSystem,
|
||||
|
||||
@@ -125,6 +125,9 @@ type CustomAgentConfig struct {
|
||||
MaxCompletionTokens int `yaml:"max_completion_tokens" json:"max_completion_tokens"`
|
||||
// Whether to enable thinking mode (for models that support extended thinking)
|
||||
Thinking *bool `yaml:"thinking" json:"thinking"`
|
||||
// Whether final answers include knowledge/web source citations. Nil defaults to true
|
||||
// so agents saved before this option was introduced keep their existing behavior.
|
||||
CitationEnabled *bool `yaml:"citation_enabled" json:"citation_enabled"`
|
||||
|
||||
// ===== Agent Mode Settings =====
|
||||
// Maximum iterations for ReAct loop (only for agent type)
|
||||
@@ -517,6 +520,12 @@ func (a *CustomAgent) EnsureDefaults() {
|
||||
disabled := false
|
||||
a.Config.Thinking = &disabled
|
||||
}
|
||||
// Keep citations enabled for existing agents whose persisted config predates
|
||||
// this field. An explicit false is always preserved.
|
||||
if a.Config.CitationEnabled == nil {
|
||||
enabled := true
|
||||
a.Config.CitationEnabled = &enabled
|
||||
}
|
||||
}
|
||||
|
||||
// IsAgentMode returns true if this agent uses ReAct agent mode
|
||||
|
||||
@@ -39,3 +39,18 @@ func TestEnsureDefaults_ThinkingPreservesTrue(t *testing.T) {
|
||||
t.Fatal("EnsureDefaults must not overwrite an explicit Thinking=true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureDefaults_CitationsDefaultEnabledAndPreserveFalse(t *testing.T) {
|
||||
legacy := &CustomAgent{Config: CustomAgentConfig{}}
|
||||
legacy.EnsureDefaults()
|
||||
if legacy.Config.CitationEnabled == nil || !*legacy.Config.CitationEnabled {
|
||||
t.Fatal("legacy agents must default citation output to enabled")
|
||||
}
|
||||
|
||||
disabled := false
|
||||
explicit := &CustomAgent{Config: CustomAgentConfig{CitationEnabled: &disabled}}
|
||||
explicit.EnsureDefaults()
|
||||
if explicit.Config.CitationEnabled == nil || *explicit.Config.CitationEnabled {
|
||||
t.Fatal("EnsureDefaults must preserve explicit citation_enabled=false")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user