稳定处理大模型返回的 json

26 阅读1分钟

		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();

		// 尝试修复可能被截断的 JSON
		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 返回格式无效");
			}
		}