fix(chat): enforce retrieved image output in answers

When retrieved context or tool results contain Markdown images, dynamically
append output requirements to system prompts and final-answer instructions.
Also normalize fullwidth image parentheses in the frontend renderer so
localized model output still renders correctly.
This commit is contained in:
wizardchen
2026-07-15 18:09:17 +08:00
committed by lyingbug
parent 951f95903b
commit fbc9db85d1
11 changed files with 264 additions and 5 deletions
+18 -1
View File
@@ -10,9 +10,19 @@ import (
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/searchutil"
"github.com/Tencent/WeKnora/internal/types"
)
func finalAnswerImageRequirement(hasRetrievedImage bool) string {
if !hasRetrievedImage {
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 ![alt](url) 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.`
}
// streamFinalAnswerToEventBus streams the final answer generation through EventBus
func (e *AgentEngine) streamFinalAnswerToEventBus(
ctx context.Context,
@@ -41,9 +51,13 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(
// Add all tool call results as context
toolResultCount := 0
hasRetrievedImage := false
for stepIdx, step := range state.RoundSteps {
for toolIdx, toolCall := range step.ToolCalls {
toolResultCount++
if searchutil.MarkdownImageRegex.MatchString(toolCall.Result.Output) {
hasRetrievedImage = true
}
messages = append(messages, chat.Message{
Role: "user",
Content: fmt.Sprintf("Tool %s returned: %s", toolCall.Name, toolCall.Result.Output),
@@ -56,6 +70,8 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(
logger.Debugf(ctx, "[Agent][FinalAnswer] Built context: %d messages, %d tool results",
len(messages), toolResultCount)
imageRequirement := finalAnswerImageRequirement(hasRetrievedImage)
// Add final answer prompt
finalPrompt := fmt.Sprintf(`Based on the above tool call results, generate a complete answer for the user's question.
@@ -67,8 +83,9 @@ Requirements:
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
%s
Now generate the final answer:`, query)
Now generate the final answer:`, query, imageRequirement)
messages = append(messages, chat.Message{
Role: "user",
@@ -0,0 +1,24 @@
package agent
import (
"strings"
"testing"
)
func TestFinalAnswerImageRequirement(t *testing.T) {
if got := finalAnswerImageRequirement(false); got != "" {
t.Fatalf("text-only tool results should not add an image requirement: %q", got)
}
got := finalAnswerImageRequirement(true)
for _, required := range []string{
"MUST include at least one relevant Markdown image",
"Preserve its complete URL exactly",
"ASCII half-width parentheses",
"silently verify",
} {
if !strings.Contains(got, required) {
t.Fatalf("expected %q in final-answer image requirement:\n%s", required, got)
}
}
}
+46
View File
@@ -0,0 +1,46 @@
package agent
import (
"strings"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/searchutil"
"github.com/Tencent/WeKnora/internal/types"
)
const agentRetrievedImageRequirementMarker = "## Retrieved Image Output Requirement"
const agentRetrievedImageSystemRequirement = `
## Retrieved Image Output Requirement
Retrieved tool results for this turn contain Markdown images. Treat images attached to retrieved passages as relevant by default.
- Unless the user explicitly requests text-only output, or every retrieved image is clearly unrelated, the final answer MUST include at least one relevant Markdown image copied verbatim from the tool results.
- Preserve the complete Markdown image syntax and URL exactly; never invent, shorten, normalize, or replace the URL.
- Use ASCII half-width parentheses exactly as ![alt](url); never use full-width ( or ).
- Place each image immediately after the paragraph it supports.
- When multiple retrieved images support different sections, distribute them across those sections instead of stopping after the first image.
- Before finishing, silently verify that the answer contains a Markdown image whenever this requirement applies.`
func stepContainsMarkdownImage(step types.AgentStep) bool {
for _, toolCall := range step.ToolCalls {
if toolCall.Result != nil &&
toolCall.Result.Success &&
searchutil.MarkdownImageRegex.MatchString(toolCall.Result.Output) {
return true
}
}
return false
}
func appendAgentRetrievedImageRequirement(messages []chat.Message) []chat.Message {
for i := range messages {
if messages[i].Role != "system" {
continue
}
if !strings.Contains(messages[i].Content, agentRetrievedImageRequirementMarker) {
messages[i].Content = strings.TrimRight(messages[i].Content, " \t\r\n") + agentRetrievedImageSystemRequirement
}
break
}
return messages
}
+7
View File
@@ -424,6 +424,13 @@ func (e *AgentEngine) appendToolResults(
messages []chat.Message,
step types.AgentStep,
) []chat.Message {
if stepContainsMarkdownImage(step) {
// Keep the requirement at system priority even when a custom Agent prompt
// replaces the built-in template. Appending it once, when image-bearing
// evidence first appears, also avoids burdening text-only turns.
messages = appendAgentRetrievedImageRequirement(messages)
}
// Add assistant message with tool calls (if any)
if step.Thought != "" || len(step.ToolCalls) > 0 || step.ReasoningContent != "" {
assistantMsg := chat.Message{
+32
View File
@@ -3,6 +3,7 @@ package agent
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
@@ -162,6 +163,37 @@ func TestAppendToolResults_PreservesReasoningContent(t *testing.T) {
})
}
func TestAppendToolResults_AddsDynamicImageRequirementToCustomSystemPrompt(t *testing.T) {
engine := &AgentEngine{}
prior := []chat.Message{
{Role: "system", Content: "Custom agent prompt."},
{Role: "user", Content: "解释流程"},
}
step := types.AgentStep{
ToolCalls: []types.ToolCall{{
ID: "call-image",
Name: "knowledge_search",
Result: &types.ToolResult{
Success: true,
Output: "结果\n![流程图](resource://AbCdEfGhIjKlMnOpQrStUv)",
},
}},
}
out := engine.appendToolResults(prior, step)
require.Len(t, out, 4)
assert.Contains(t, out[0].Content, "Custom agent prompt.")
assert.Contains(t, out[0].Content, agentRetrievedImageRequirementMarker)
assert.Contains(t, out[0].Content, "MUST include at least one relevant Markdown image")
assert.Contains(t, out[0].Content, "ASCII half-width parentheses")
assert.Equal(t, "tool", out[3].Role)
assert.Contains(t, out[3].Content, "![流程图](resource://AbCdEfGhIjKlMnOpQrStUv)")
// A later image-bearing step must not duplicate the system requirement.
out = engine.appendToolResults(out, step)
assert.Equal(t, 1, strings.Count(out[0].Content, agentRetrievedImageRequirementMarker))
}
func TestBuildRuntimeContextBlock_PinnedDocuments(t *testing.T) {
block := buildRuntimeContextBlock(
"sess-1",
@@ -11,12 +11,31 @@ import (
"github.com/Tencent/WeKnora/internal/common"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/searchutil"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
var regThinkTags = regexp.MustCompile(`(?s)<think>.*?</think>`)
const retrievedImageOutputRequirement = `
## Retrieved Image Output Requirement
The retrieved context for this turn contains Markdown images. Images attached to retrieved passages should be treated as relevant by default.
- Unless the user explicitly requests text-only output, or every retrieved image is clearly unrelated to the answer, the final answer MUST include at least one relevant Markdown image copied from the retrieved context.
- Copy the complete Markdown image syntax and its URL verbatim. Never invent, shorten, normalize, or replace the URL.
- Use ASCII half-width parentheses in image Markdown exactly as ![alt](url). Never use full-width ( or ).
- Place each image immediately after the paragraph it supports, rather than collecting images at the end.
- When multiple retrieved images support different sections of a multi-section answer, include them in their corresponding sections instead of stopping after the first image.
- Before finishing, silently verify that the answer contains a Markdown image whenever this requirement applies.`
func appendRetrievedImageOutputRequirement(systemPrompt, renderedContexts string) string {
if !searchutil.MarkdownImageRegex.MatchString(renderedContexts) {
return systemPrompt
}
return strings.TrimRight(systemPrompt, " \t\r\n") + retrievedImageOutputRequirement
}
// pipelineInfo logs pipeline info level entries.
func pipelineInfo(ctx context.Context, stage, action string, fields map[string]interface{}) {
common.PipelineInfo(ctx, stage, action, fields)
@@ -75,6 +94,7 @@ func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message {
"language": chatManage.Language,
"contexts": chatManage.RenderedContexts,
})
systemPrompt = appendRetrievedImageOutputRequirement(systemPrompt, chatManage.RenderedContexts)
chatMessages := []chat.Message{
{Role: "system", Content: systemPrompt},
@@ -0,0 +1,30 @@
package chatpipeline
import (
"strings"
"testing"
)
func TestAppendRetrievedImageOutputRequirement(t *testing.T) {
base := "Answer from retrieved evidence."
withImage := appendRetrievedImageOutputRequirement(
base,
"context\n![流程图](resource://AbCdEfGhIjKlMnOpQrStUv)",
)
for _, required := range []string{
base,
"MUST include at least one relevant Markdown image",
"Copy the complete Markdown image syntax and its URL verbatim",
"ASCII half-width parentheses",
"immediately after the paragraph it supports",
} {
if !strings.Contains(withImage, required) {
t.Fatalf("expected %q in dynamic image requirement:\n%s", required, withImage)
}
}
withoutImage := appendRetrievedImageOutputRequirement(base, "text-only retrieved context")
if withoutImage != base {
t.Fatalf("text-only context should not change the system prompt: %q", withoutImage)
}
}