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
@@ -6,6 +6,7 @@ import {
closeDanglingStreamingEmphasis,
createChatMarkdownRenderer,
markStandaloneStrongParagraphs,
normalizeFullwidthMarkdownImageParentheses,
normalizeLegacyImageContextMarkup,
preprocessMathDelimiters,
renderChatMarkdown,
@@ -46,6 +47,56 @@ test('replaceIncompleteImageWithPlaceholder hides an unfinished streaming image'
)
})
test('normalizeFullwidthMarkdownImageParentheses repairs localized image delimiters', () => {
const ref = 'resource://yB7V7wE1gls7h9WonCDq5Q'
assert.equal(
normalizeFullwidthMarkdownImageParentheses(`![](${ref})`),
`![](${ref})`,
)
assert.equal(
normalizeFullwidthMarkdownImageParentheses(`![流程图](${ref})`),
`![流程图](${ref})`,
)
assert.equal(
normalizeFullwidthMarkdownImageParentheses(`普通中文(说明)和 ![示例](unknown://value)`),
`普通中文(说明)和 ![示例](unknown://value)`,
)
})
test('normalizeFullwidthMarkdownImageParentheses preserves literal examples in code', () => {
const code = '`![](resource://example)`\n```md\n![](resource://example)\n```'
assert.equal(normalizeFullwidthMarkdownImageParentheses(code), code)
})
test('renderChatMarkdown safely renders an image with fullwidth parentheses', () => {
const renderer = createChatMarkdownRenderer({
imageRenderer: ({ href, text }) => `<img src="${href}" alt="${text}">`,
isValidImageUrl: (href) => href.startsWith('resource://'),
})
const html = renderChatMarkdown('![](resource://yB7V7wE1gls7h9WonCDq5Q)', {
renderer,
escapeMarkdown: (text) => text,
sanitizeHtml: (value) => value,
streaming: false,
})
assert.match(html, /<img src="resource:\/\/yB7V7wE1gls7h9WonCDq5Q" alt="">/)
assert.doesNotMatch(html, /(|)/)
})
test('renderChatMarkdown hides an unfinished fullwidth-parenthesis image while streaming', () => {
const renderer = createChatMarkdownRenderer()
const html = renderChatMarkdown('before ![流程图](resource://yB7V7wE1gls7h9WonCDq5Q', {
renderer,
escapeMarkdown: (text) => text,
sanitizeHtml: (value) => value,
streaming: true,
})
assert.match(html, /streaming-image-loading/)
assert.doesNotMatch(html, /resource:\/\/|(/)
})
test('normalizeLegacyImageContextMarkup converts copied image XML to Markdown', () => {
const input = [
'before',
+29 -1
View File
@@ -84,6 +84,33 @@ const LEGACY_IMAGE_ORIGINAL_RE = /<image_original>([\s\S]*?)<\/image_original>/i
const LEGACY_IMAGE_CAPTION_RE = /<image_caption>([\s\S]*?)<\/image_caption>/i
const LEGACY_IMAGE_OCR_RE = /<image_ocr>([\s\S]*?)<\/image_ocr>/i
const COMPLETE_MARKDOWN_CODE_RE = /(```[\s\S]*?```|~~~[\s\S]*?~~~|`[^`\n]*`)/g
const IMAGE_URL_SCHEME = '(?:https?|resource|storage|local|minio|s3|cos|tos|oss|obs|ks3)'
const FULLWIDTH_IMAGE_OPEN_RE = new RegExp(`(!\\[[^\\]\\n]*\\])((?=${IMAGE_URL_SCHEME}://)`, 'gi')
const FULLWIDTH_IMAGE_CLOSE_RE = new RegExp(
`(!\\[[^\\]\\n]*\\]\\(${IMAGE_URL_SCHEME}://[^)\\n]*?))`,
'gi',
)
/**
* Repair image Markdown when a model localizes its destination parentheses:
* `![alt](resource://…)` -> `![alt](resource://…)`.
*
* The rewrite is limited to supported image URL schemes and skips code, so
* ordinary Chinese punctuation and literal Markdown examples stay unchanged.
* Normalizing an opening parenthesis before the closing one streams in also
* lets the existing incomplete-image skeleton suppress the unstable tail.
*/
export function normalizeFullwidthMarkdownImageParentheses(content: string): string {
if (!content || (!content.includes('(') && !content.includes(')'))) return content
const parts = content.split(COMPLETE_MARKDOWN_CODE_RE)
for (let i = 0; i < parts.length; i += 2) {
parts[i] = parts[i]
.replace(FULLWIDTH_IMAGE_OPEN_RE, '$1(')
.replace(FULLWIDTH_IMAGE_CLOSE_RE, '$1)')
}
return parts.join('')
}
function legacyImageField(body: string, pattern: RegExp): string {
const value = body.match(pattern)?.[1] || ''
@@ -437,7 +464,8 @@ export function renderChatMarkdown(rawMarkdown: unknown, options: RenderChatMark
)
const citationSafeText = stripIncompleteCitationTag(imageContextSafeText)
const { text: tagSafe, tags } = preserveCitationTags(citationSafeText)
const imageSafe = replaceIncompleteImageWithPlaceholder(tagSafe)
const normalizedImageMarkdown = normalizeFullwidthMarkdownImageParentheses(tagSafe)
const imageSafe = replaceIncompleteImageWithPlaceholder(normalizedImageMarkdown)
const mathSafe = preprocessMathDelimiters(imageSafe)
const restoredTags = restoreCitationTags(mathSafe, tags)
const inlineTags = joinCitationTagsToPreviousLine(restoredTags)