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
+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)
}
}