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:
@@ -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  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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 ; 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
|
||||
}
|
||||
@@ -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{
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
}},
|
||||
}
|
||||
|
||||
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, "")
|
||||
|
||||
// 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",
|
||||
|
||||
Reference in New Issue
Block a user