fix(chat): use Markdown for LLM image context and normalize legacy XML

Chat and agent tool context now emits answer-ready Markdown images instead
of internal <image> XML so copied content renders safely. The frontend also
normalizes legacy XML blocks in persisted conversations during streaming.
This commit is contained in:
wizardchen
2026-07-15 17:30:16 +08:00
committed by lyingbug
parent a729bc1271
commit 951f95903b
9 changed files with 357 additions and 57 deletions
@@ -0,0 +1,46 @@
package tools
import (
"encoding/json"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
func TestLLMToolOutputsUseMarkdownImages(t *testing.T) {
imageInfo, err := json.Marshal([]types.ImageInfo{
{
URL: "resource://AbCdEfGhIjKlMnOpQrStUv",
Caption: "目标说话人提取流程图",
OCRText: "输入\n输出",
},
})
if err != nil {
t.Fatal(err)
}
chunk := &types.Chunk{
ID: "chunk-1",
ChunkIndex: 0,
ChunkType: types.ChunkTypeText,
Content: "测试阶段主要流程",
ImageInfo: string(imageInfo),
}
listOutput := (&ListKnowledgeChunksTool{}).buildOutput("knowledge-1", "测试文档", 1, 1, []*types.Chunk{chunk})
wikiOutput := enrichChunkContent(chunk)
for name, output := range map[string]string{
"list_knowledge_chunks": listOutput,
"wiki_read_source_doc": wikiOutput,
} {
t.Run(name, func(t *testing.T) {
if !strings.Contains(output, "![目标说话人提取流程图](resource://AbCdEfGhIjKlMnOpQrStUv)") {
t.Fatalf("expected Markdown image in tool output:\n%s", output)
}
if strings.Contains(output, "<image") || strings.Contains(output, "<caption>") || strings.Contains(output, "<ocr_text>") {
t.Fatalf("tool output leaked legacy image XML:\n%s", output)
}
})
}
}
+3 -7
View File
@@ -1247,14 +1247,10 @@ func (t *KnowledgeSearchTool) formatOutput(
var imageInfos []types.ImageInfo
if err := json.Unmarshal([]byte(result.ImageInfo), &imageInfos); err == nil && len(imageInfos) > 0 {
for _, img := range imageInfos {
ob.WriteString(fmt.Sprintf("<image url=\"%s\">\n", xmlEscape(img.URL)))
if img.Caption != "" {
ob.WriteString(fmt.Sprintf("<image_caption>%s</image_caption>\n", xmlEscape(img.Caption)))
if imageMarkdown := searchutil.BuildImageInfoMarkdownWithURL(img.URL, &img); imageMarkdown != "" {
ob.WriteString(imageMarkdown)
ob.WriteString("\n")
}
if img.OCRText != "" {
ob.WriteString(fmt.Sprintf("<image_ocr>%s</image_ocr>\n", xmlEscape(img.OCRText)))
}
ob.WriteString("</image>\n")
}
}
}
+6 -14
View File
@@ -412,7 +412,7 @@ func (t *ListKnowledgeChunksTool) buildOutput(
for _, c := range chunks {
if c.ChunkType == types.ChunkTypeFAQ {
writeFAQEntryXML(&b, c)
writeChunkImagesXML(&b, c)
writeChunkImagesMarkdown(&b, c)
continue
}
@@ -424,7 +424,7 @@ func (t *ListKnowledgeChunksTool) buildOutput(
c.ID, c.ChunkIndex, c.ChunkType)
}
fmt.Fprintf(&b, "<content>%s</content>\n", summarizeContent(c.Content))
writeChunkImagesXML(&b, c)
writeChunkImagesMarkdown(&b, c)
b.WriteString("</chunk>\n")
}
@@ -436,7 +436,7 @@ func (t *ListKnowledgeChunksTool) buildOutput(
return b.String()
}
func writeChunkImagesXML(b *strings.Builder, c *types.Chunk) {
func writeChunkImagesMarkdown(b *strings.Builder, c *types.Chunk) {
if c == nil || c.ImageInfo == "" {
return
}
@@ -445,18 +445,10 @@ func writeChunkImagesXML(b *strings.Builder, c *types.Chunk) {
return
}
for _, img := range imageInfos {
if img.URL != "" {
fmt.Fprintf(b, "<image url=\"%s\">\n", img.URL)
} else {
b.WriteString("<image>\n")
if imageMarkdown := searchutil.BuildImageInfoMarkdownWithURL(img.URL, &img); imageMarkdown != "" {
b.WriteString(imageMarkdown)
b.WriteString("\n")
}
if img.Caption != "" {
fmt.Fprintf(b, "<image_caption>%s</image_caption>\n", img.Caption)
}
if img.OCRText != "" {
fmt.Fprintf(b, "<image_ocr>%s</image_ocr>\n", img.OCRText)
}
b.WriteString("</image>\n")
}
}
+5 -11
View File
@@ -96,15 +96,9 @@ func enrichChunkContent(c *types.Chunk) string {
if err := json.Unmarshal([]byte(c.ImageInfo), &imgInfos); err == nil && len(imgInfos) > 0 {
var imgBuilder strings.Builder
for _, img := range imgInfos {
if img.URL != "" {
imgBuilder.WriteString(fmt.Sprintf("\n<image url=\"%s\">\n", img.URL))
if img.Caption != "" {
imgBuilder.WriteString(fmt.Sprintf("<caption>%s</caption>\n", img.Caption))
}
if img.OCRText != "" {
imgBuilder.WriteString(fmt.Sprintf("<ocr_text>%s</ocr_text>\n", img.OCRText))
}
imgBuilder.WriteString("</image>")
if imageMarkdown := searchutil.BuildImageInfoMarkdownWithURL(img.URL, &img); imageMarkdown != "" {
imgBuilder.WriteString("\n")
imgBuilder.WriteString(imageMarkdown)
}
}
content += imgBuilder.String()
@@ -163,7 +157,7 @@ func (t *wikiReadSourceDocTool) Execute(ctx context.Context, args json.RawMessag
pageSize := 100
page := 1
if hasRange {
page = (params.StartChunkIndex - 1) / pageSize + 1
page = (params.StartChunkIndex-1)/pageSize + 1
}
var chunksOutput strings.Builder
@@ -293,7 +287,7 @@ func (t *wikiReadSourceDocTool) Execute(ctx context.Context, args json.RawMessag
}
sb.WriteString(fmt.Sprintf("<total_chunks>%d</total_chunks>\n</metadata>\n", totalChunks))
if matchCount > 0 {
sb.WriteString(fmt.Sprintf("<chunks count=\"%d\">\n", matchCount))
sb.WriteString(chunksOutput.String())
+70 -17
View File
@@ -260,10 +260,15 @@ func EnrichContentWithImageInfo(content string, imageInfoJSON string) string {
return content
}
// EnrichContentWithImageInfoForChat is like EnrichContentWithImageInfo but only
// wraps Markdown images that have a matching image_info entry. This avoids
// turning every parent thumbnail into an <image> block when only a few pages
// were retrieved, and skips appending orphan image_info extras.
// EnrichContentWithImageInfoForChat enriches matching Markdown images with
// caption / OCR text while keeping the image itself as Markdown. Chat context is
// deliberately answer-ready: if a model copies a relevant image from its
// context, the copied content should still render instead of leaking the
// internal <image> XML protocol into the answer.
//
// Only images with a matching image_info entry are enriched. This avoids adding
// every parent thumbnail when only a few pages were retrieved, and skips orphan
// image_info extras.
func EnrichContentWithImageInfoForChat(content string, imageInfoJSON string) string {
var imageInfos []types.ImageInfo
if err := json.Unmarshal([]byte(imageInfoJSON), &imageInfos); err != nil {
@@ -283,29 +288,77 @@ func EnrichContentWithImageInfoForChat(content string, imageInfoJSON string) str
}
}
matches := MarkdownImageRegex.FindAllStringSubmatch(content, -1)
for _, match := range matches {
content = MarkdownImageRegex.ReplaceAllStringFunc(content, func(markdownImage string) string {
match := MarkdownImageRegex.FindStringSubmatch(markdownImage)
if len(match) < 3 {
continue
return markdownImage
}
imgURL := match[2]
imgInfo, found := imageInfoMap[imgURL]
if !found || imgInfo == nil {
continue
return markdownImage
}
inner := BuildImageInfoXML(imgInfo)
if inner == "" {
continue
metadata := buildImageInfoMarkdownMetadata(imgInfo)
if metadata == "" {
return markdownImage
}
var b strings.Builder
b.WriteString(fmt.Sprintf("<image url=\"%s\">\n", imgURL))
b.WriteString(inner)
b.WriteString("</image>")
content = strings.Replace(content, match[0], b.String(), 1)
}
return markdownImage + "\n\n" + metadata
})
return content
}
// buildImageInfoMarkdownMetadata keeps image-derived text explicit for the LLM
// without introducing a second, user-visible markup protocol. Blockquotes keep
// multiline OCR attached to its image and remain harmless if copied verbatim.
func buildImageInfoMarkdownMetadata(img *types.ImageInfo) string {
if img == nil {
return ""
}
var lines []string
if caption := strings.TrimSpace(img.Caption); caption != "" {
lines = append(lines, "**Image caption:** "+caption)
}
if ocr := strings.TrimSpace(img.OCRText); ocr != "" {
lines = append(lines, "**Image text (OCR):** "+ocr)
}
if len(lines) == 0 {
return ""
}
return "> " + strings.ReplaceAll(strings.Join(lines, "\n\n"), "\n", "\n> ")
}
// BuildImageInfoMarkdownWithURL formats one image as answer-ready Markdown for
// LLM-facing chat/tool context. The URL is intentionally preserved verbatim;
// resource and provider URLs are opaque handles resolved by the frontend.
func BuildImageInfoMarkdownWithURL(url string, img *types.ImageInfo) string {
if img == nil {
return ""
}
url = strings.TrimSpace(url)
metadata := buildImageInfoMarkdownMetadata(img)
if url == "" {
return metadata
}
alt := strings.Join(strings.Fields(img.Caption), " ")
if alt == "" {
alt = "image"
}
alt = strings.NewReplacer(
`\`, `\\`,
`[`, `\[`,
`]`, `\]`,
).Replace(alt)
image := fmt.Sprintf("![%s](%s)", alt, url)
if metadata == "" {
return image
}
return image + "\n\n" + metadata
}
// BuildImageInfoXML returns XML-tagged caption / ocr for one image.
func BuildImageInfoXML(img *types.ImageInfo) string {
var b strings.Builder
+68 -5
View File
@@ -72,17 +72,80 @@ func TestEnrichContentWithImageInfoForChat_SkipsUnmatched(t *testing.T) {
content := "![p1](u1)\n\n![p2](u2)"
raw, _ := json.Marshal([]types.ImageInfo{{URL: "u2", OCRText: "two"}})
got := EnrichContentWithImageInfoForChat(content, string(raw))
if strings.Count(got, "<image url=") != 1 {
t.Fatalf("expected one image block, got: %s", got)
if strings.Contains(got, "<image") {
t.Fatalf("chat context should not contain internal image XML: %s", got)
}
if !strings.Contains(got, "![p1](u1)") {
t.Fatalf("unmatched markdown should remain: %s", got)
}
if !strings.Contains(got, "<image_ocr>two</image_ocr>") {
if !strings.Contains(got, "![p2](u2)") {
t.Fatalf("matched markdown should remain renderable: %s", got)
}
if !strings.Contains(got, "> **Image text (OCR):** two") {
t.Fatalf("matched image should be enriched: %s", got)
}
if strings.Contains(got, "<image_original>") {
t.Fatalf("chat enrich should not duplicate markdown in image_original: %s", got)
if strings.Count(got, "![") != 2 {
t.Fatalf("chat enrich should not duplicate markdown images: %s", got)
}
}
func TestEnrichContentWithImageInfoForChat_UsesMarkdownForMultilineMetadata(t *testing.T) {
content := "before\n\n![flow](resource://AbCdEfGhIjKlMnOpQrStUv)\n\nafter"
raw, _ := json.Marshal([]types.ImageInfo{
{
URL: "resource://AbCdEfGhIjKlMnOpQrStUv",
Caption: "目标说话人提取流程图",
OCRText: "输入\n目标说话人提取\n输出",
},
})
got := EnrichContentWithImageInfoForChat(content, string(raw))
for _, want := range []string{
"![flow](resource://AbCdEfGhIjKlMnOpQrStUv)",
"> **Image caption:** 目标说话人提取流程图",
"> **Image text (OCR):** 输入",
"> 目标说话人提取",
"> 输出",
} {
if !strings.Contains(got, want) {
t.Fatalf("expected %q in enriched Markdown:\n%s", want, got)
}
}
if strings.Contains(got, "<image") {
t.Fatalf("chat context should be Markdown-only for image content: %s", got)
}
}
func TestEnrichContentWithImageInfoForChat_EnrichesRepeatedImagesOnceEach(t *testing.T) {
content := "![same](u1)\n\n![same](u1)"
raw, _ := json.Marshal([]types.ImageInfo{{URL: "u1", Caption: "same caption"}})
got := EnrichContentWithImageInfoForChat(content, string(raw))
if strings.Count(got, "![same](u1)") != 2 {
t.Fatalf("expected both Markdown images to remain: %s", got)
}
if strings.Count(got, "> **Image caption:** same caption") != 2 {
t.Fatalf("expected each image to be enriched exactly once: %s", got)
}
}
func TestBuildImageInfoMarkdownWithURL(t *testing.T) {
got := BuildImageInfoMarkdownWithURL(
"resource://AbCdEfGhIjKlMnOpQrStUv",
&types.ImageInfo{Caption: "流程图 [测试]", OCRText: "输入\n输出"},
)
for _, want := range []string{
`![流程图 \[测试\]](resource://AbCdEfGhIjKlMnOpQrStUv)`,
"> **Image caption:** 流程图 [测试]",
"> **Image text (OCR):** 输入",
"> 输出",
} {
if !strings.Contains(got, want) {
t.Fatalf("expected %q in image Markdown:\n%s", want, got)
}
}
if strings.Contains(got, "<image") {
t.Fatalf("LLM-facing image context must not use image XML: %s", got)
}
}