const response = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/api/llm/chat`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ messages }),
}
);
if (!response.ok) {
throw new Error("LLM Chat API 调用失败");
}
const data = await response.json();
logger.info("原始返回数据", { data });
const cleanContent = data.content
.replace(/```json\n?/g, '')
.replace(/```\n?/g, '')
.trim();
let fixedContent = cleanContent;
if (!cleanContent.endsWith(']')) {
const lastValidBrace = cleanContent.lastIndexOf('}');
if (lastValidBrace !== -1) {
fixedContent = cleanContent.substring(0, lastValidBrace + 1) + ']';
}
}
let parsedData;
try {
parsedData = JSON.parse(fixedContent);
} catch (e) {
logger.error("JSON 解析失败", { error: e, content: cleanContent });
try {
const arrayMatch = cleanContent.match(/\[\s*\{.*\}\s*\]/);
if (arrayMatch) {
parsedData = JSON.parse(arrayMatch[0]);
} else {
throw new Error("无法解析返回内容");
}
} catch (innerError) {
logger.error("备选解析方案也失败", { error: innerError });
throw new Error("LLM 返回格式无效");
}
}