Commit f5f3d637 authored by AI-甘富林's avatar AI-甘富林

ai对话流式输出修复

parent 3c520c23
......@@ -314,18 +314,27 @@ function parseAIResponse(raw: string): GenUIResponse {
let jsonContent = raw.trim();
let textAnswer = "";
// 优先处理新格式: 纯文本 + ```json 代码块
const fencedMatch = jsonContent.match(/```(?:json)?\s*([\s\S]*?)```/);
// 优先匹配 ```json 代码块,避免把 python/javascript 等普通代码块当 JSON 解析
let fencedMatch = jsonContent.match(/```json\s*([\s\S]*?)```/);
if (fencedMatch) {
// 代码块之前的内容作为纯文本回答
textAnswer = jsonContent.substring(0, jsonContent.indexOf("```")).trim();
// ```json 代码块之前的所有内容(含普通代码块)作为纯文本回答
textAnswer = jsonContent.substring(0, jsonContent.indexOf("```json")).trim();
jsonContent = fencedMatch[1].trim();
} else {
// 兼容旧格式: 整个响应是一个 JSON 对象
// 没有 ```json 块:尝试在全文找裸 JSON 对象
// 注意:不能随便匹配 ``` 代码块,因为可能是 python/js 等非 JSON 内容
const jsonStart = jsonContent.indexOf("{");
const jsonEnd = jsonContent.lastIndexOf("}");
if (jsonStart !== -1 && jsonEnd !== -1 && jsonStart < jsonEnd) {
jsonContent = jsonContent.substring(jsonStart, jsonEnd + 1);
const candidate = jsonContent.substring(jsonStart, jsonEnd + 1);
try {
JSON.parse(candidate);
// 能解析成功才使用,否则保留全文作为 answer
jsonContent = candidate;
} catch {
// 不是有效 JSON,保留原始全文
console.log("[CozeLangchain] No valid JSON found, returning full text as answer");
}
}
}
......@@ -541,17 +550,14 @@ ${dataContext}
const streamTextContent = () => {
if (inJsonBlock || closed) return;
// 检测是否已出现 ```json 标记
// 只检测 ```json 标记,不检测其他代码块(如 ```python)。
// 普通代码块内容应该正常流式输出给前端展示。
const jsonMarker = fullText.indexOf("```json");
const jsonMarkerAlt = fullText.indexOf("```");
let textEnd = fullText.length;
if (jsonMarker !== -1) {
textEnd = jsonMarker;
inJsonBlock = true;
} else if (jsonMarkerAlt !== -1) {
textEnd = jsonMarkerAlt;
inJsonBlock = true;
}
// 发送尚未流式传输的纯文本部分
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment