优化 AI 响应处理:启用 JSON mode + Zod 验证,更新知识点标签,修复 PRESERVE 问题

This commit is contained in:
wttwins
2025-12-04 22:57:30 +08:00
parent 2e072e04c4
commit b522aa9388
9 changed files with 194 additions and 101 deletions

Binary file not shown.

View File

@@ -34,8 +34,10 @@ export async function POST(req: Request) {
difficulty || 'medium'
);
// Inject the subject from the database
similarQuestion.subject = errorItemWithSubject.subject?.name || "Unknown";
// Inject the subject from the database with type safety
const validSubjects = ["数学", "物理", "化学", "生物", "英语", "语文", "历史", "地理", "政治", "其他"] as const;
const subjectName = errorItemWithSubject.subject?.name || "其他";
similarQuestion.subject = validSubjects.includes(subjectName as any) ? subjectName as typeof validSubjects[number] : "其他";
return NextResponse.json(similarQuestion);
} catch (error) {

View File

@@ -14,8 +14,10 @@ export function MarkdownRenderer({ content, className = '' }: MarkdownRendererPr
// Preprocess content to ensure proper paragraph breaks and LaTeX rendering
// Convert single line breaks to double line breaks for better readability
const processedContent = content
// Preserve existing double line breaks
.replace(/\n\n/g, '\n\n__PRESERVE__\n\n')
// First, convert literal \n sequences to actual newlines (fix for AI responses)
.replace(/\\n/g, '\n')
// Preserve existing double line breaks with a unique marker
.replace(/\n\n/g, '\n\n###PRESERVE_BREAK###\n\n')
// Convert patterns that should be new paragraphs
.replace(/([。!?;])\n(?!\n)/g, '$1\n\n') // Chinese punctuation followed by single newline
.replace(/([.!?;])\s*\n(?!\n)/g, '$1\n\n') // English punctuation followed by single newline
@@ -24,13 +26,11 @@ export function MarkdownRenderer({ content, className = '' }: MarkdownRendererPr
// Fix: Remove indentation for lines starting with circled numbers or (n) to prevent code block rendering
.replace(/\n\s+([\u2460-\u2473])/g, '\n$1')
.replace(/\n\s+(\d+\))/g, '\n$1')
// Fix: Replace literal \n sequences with actual newlines
.replace(/\\n/g, '\n')
// Fix LaTeX formulas: Ensure proper spacing around $ delimiters
// This handles cases where $ might be directly adjacent to text
.replace(/([^\s$])(\$[^$]+\$)([^\s$])/g, '$1 $2 $3')
// Restore preserved double line breaks
.replace(/\n\n__PRESERVE__\n\n/g, '\n\n');
.replace(/\n\n###PRESERVE_BREAK###\n\n/g, '\n\n');
return (
<div className={`markdown-content ${className}`}>

View File

@@ -2,6 +2,7 @@ import { GoogleGenerativeAI, GenerativeModel } from "@google/generative-ai";
import { AIService, ParsedQuestion, DifficultyLevel, AIConfig } from "./types";
import { jsonrepair } from 'jsonrepair';
import { generateAnalyzePrompt, generateSimilarQuestionPrompt } from './prompts';
import { validateParsedQuestion, safeParseParsedQuestion } from './schema';
export class GeminiProvider implements AIService {
private genAI: GoogleGenerativeAI;
@@ -92,35 +93,47 @@ export class GeminiProvider implements AIService {
}
private parseResponse(text: string): ParsedQuestion {
const jsonString = this.extractJson(text);
// Log for debugging
console.log("[DEBUG] Parsing AI response");
console.log("[DEBUG] Original text length:", text.length);
console.log("[DEBUG] Extracted JSON length:", jsonString.length);
console.log("[DEBUG] First 200 chars of extracted:", jsonString.substring(0, 200));
console.log("[Gemini] Parsing AI response, length:", text.length);
try {
// First try direct parse
const parsed = JSON.parse(jsonString) as ParsedQuestion;
console.log("[DEBUG] Direct parse succeeded");
return parsed;
// With JSON mode enabled, response should be valid JSON
const parsed = JSON.parse(text);
// Validate with Zod schema
const result = safeParseParsedQuestion(parsed);
if (result.success) {
console.log("[Gemini] ✓ Direct parse and validation succeeded");
return result.data;
} else {
console.warn("[Gemini] ⚠ Validation failed:", result.error.format());
// Try to extract JSON from potential markdown wrapping
const extracted = this.extractJson(text);
const parsedExtracted = JSON.parse(extracted);
return validateParsedQuestion(parsedExtracted);
}
} catch (error) {
console.log("[DEBUG] Direct parse failed, trying jsonrepair");
console.warn("[Gemini] ⚠ Direct parse failed, attempting extraction");
try {
// Use jsonrepair to fix the JSON
const repairedJson = jsonrepair(jsonString);
console.log("[DEBUG] JSON repaired, length:", repairedJson.length);
// Fallback: extract JSON from markdown or text
const jsonString = this.extractJson(text);
const parsed = JSON.parse(jsonString);
return validateParsedQuestion(parsed);
} catch (extractError) {
console.warn("[Gemini] ⚠ Extraction failed, trying jsonrepair");
const parsed = JSON.parse(repairedJson) as ParsedQuestion;
console.log("[DEBUG] Parse succeeded after repair");
return parsed;
} catch (repairError) {
console.error("[ERROR] JSON repair also failed:", repairError);
console.error("[ERROR] Original text (first 500 chars):", text.substring(0, 500));
console.error("[ERROR] Extracted JSON (first 500 chars):", jsonString.substring(0, 500));
throw new Error("Invalid JSON response from AI");
try {
// Last resort: use jsonrepair
const jsonString = this.extractJson(text);
const repairedJson = jsonrepair(jsonString);
const parsed = JSON.parse(repairedJson);
return validateParsedQuestion(parsed);
} catch (finalError) {
console.error("[Gemini] ✗ All parsing attempts failed");
console.error("[Gemini] Original text (first 500 chars):", text.substring(0, 500));
throw new Error("Invalid JSON response from AI: Unable to parse or validate");
}
}
}
}
@@ -129,15 +142,25 @@ export class GeminiProvider implements AIService {
const prompt = generateAnalyzePrompt(language);
try {
const result = await this.model.generateContent([
prompt,
{
inlineData: {
data: imageBase64,
mimeType: mimeType
const result = await this.model.generateContent({
contents: [
{
role: 'user',
parts: [
{ text: prompt },
{
inlineData: {
data: imageBase64,
mimeType: mimeType
}
}
]
}
],
generationConfig: {
responseMimeType: "application/json", // Enable JSON mode
}
]);
});
const response = await result.response;
const text = response.text();
@@ -154,7 +177,12 @@ export class GeminiProvider implements AIService {
const prompt = generateSimilarQuestionPrompt(language, originalQuestion, knowledgePoints, difficulty);
try {
const result = await this.model.generateContent(prompt);
const result = await this.model.generateContent({
contents: [{ role: 'user', parts: [{ text: prompt }] }],
generationConfig: {
responseMimeType: "application/json", // Enable JSON mode
}
});
const response = await result.response;
const text = response.text();

View File

@@ -2,6 +2,7 @@ import OpenAI from "openai";
import { AIService, ParsedQuestion, DifficultyLevel, AIConfig } from "./types";
import { jsonrepair } from "jsonrepair";
import { generateAnalyzePrompt, generateSimilarQuestionPrompt } from './prompts';
import { validateParsedQuestion, safeParseParsedQuestion } from './schema';
export class OpenAIProvider implements AIService {
private openai: OpenAI;
@@ -54,49 +55,47 @@ export class OpenAIProvider implements AIService {
return jsonString;
}
private cleanJson(text: string): string {
// Fix multi-line strings: Replace literal newlines inside quotes with \n
return text.replace(/"((?:[^"\\]|\\.)*)"/g, (match) => {
return match.replace(/\n/g, "\\n").replace(/\r/g, "");
});
}
private parseResponse(text: string): ParsedQuestion {
const jsonString = this.extractJson(text);
console.log("[OpenAI] Parsing AI response, length:", text.length);
try {
// First try parsing as is
return JSON.parse(jsonString) as ParsedQuestion;
// With JSON mode enabled, response should be valid JSON
const parsed = JSON.parse(text);
// Validate with Zod schema
const result = safeParseParsedQuestion(parsed);
if (result.success) {
console.log("[OpenAI] ✓ Direct parse and validation succeeded");
return result.data;
} else {
console.warn("[OpenAI] ⚠ Validation failed:", result.error.format());
// Try to extract JSON from potential markdown wrapping
const extracted = this.extractJson(text);
const parsedExtracted = JSON.parse(extracted);
return validateParsedQuestion(parsedExtracted);
}
} catch (error) {
console.warn("[OpenAI] ⚠ Direct parse failed, attempting extraction");
try {
// Try using jsonrepair
const repaired = jsonrepair(jsonString);
return JSON.parse(repaired) as ParsedQuestion;
} catch (repairError) {
// Fallback: extract JSON from markdown or text
const jsonString = this.extractJson(text);
const parsed = JSON.parse(jsonString);
return validateParsedQuestion(parsed);
} catch (extractError) {
console.warn("[OpenAI] ⚠ Extraction failed, trying jsonrepair");
try {
// Fallback to manual cleaning if repair fails
// Fix: Only escape backslashes that are NOT followed by valid JSON escape characters
// Specifically handle \u: only consider it valid if followed by 4 hex digits
let fixedJson = this.cleanJson(jsonString);
fixedJson = fixedJson.replace(/\\(?!(["\\/bfnrt]|u[0-9a-fA-F]{4}))/g, '\\\\');
return JSON.parse(fixedJson) as ParsedQuestion;
// Last resort: use jsonrepair
const jsonString = this.extractJson(text);
const repairedJson = jsonrepair(jsonString);
const parsed = JSON.parse(repairedJson);
return validateParsedQuestion(parsed);
} catch (finalError) {
console.error("JSON parse failed:", finalError);
console.error("Original text:", text);
console.error("Extracted text:", jsonString);
// Log to file for debugging
try {
const fs = require('fs');
const path = require('path');
const logPath = path.join(process.cwd(), 'debug_ai_response.log');
const logContent = `\n\n--- ${new Date().toISOString()} ---\nError: ${finalError}\nOriginal: ${text}\nExtracted: ${jsonString}\n`;
fs.appendFileSync(logPath, logContent);
} catch (e) {
console.error("Failed to write debug log:", e);
}
throw new Error("Invalid JSON response from AI");
console.error("[OpenAI] ✗ All parsing attempts failed");
console.error("[OpenAI] Original text (first 500 chars):", text.substring(0, 500));
throw new Error("Invalid JSON response from AI: Unable to parse or validate");
}
}
}

View File

@@ -48,48 +48,58 @@ export function generateAnalyzePrompt(language: 'zh' | 'en', options?: PromptOpt
5. "knowledgePoints": An array of knowledge points. STRICTLY use EXACT terms from the standard list below:
**数学标签 (Math Tags):**
- 方程: "一元一次方程", "一元二次方程", "二元一次方程组", "分式方程"
- 几何: "勾股定理", "相似三角形", "全等三角形", "圆", "三视图", "平行四边形", "矩形", "菱形"
- 函数: "二次函数", "一次函数", "反比例函数", "二次函数的图像", "二次函数的性质"
- 数值: "绝对值", "有理数", "实数", "科学计数法"
- 统计: "概率", "平均数", "中位数", "方差"
使用人教版课程大纲中的**精确标签名称**,常见标签示例:
- 七年级:"有理数", "绝对值", "有理数的加法", "一元一次方程", "解一元一次方程", "三角形三边关系"
- 八年级:"全等三角形", "全等三角形的判定", "平行四边形的性质", "勾股定理", "一次函数", "一次函数的图象和性质", "平均数", "中位数", "方差"
- 九年级:"一元二次方程", "配方法", "韦达定理", "二次函数", "二次函数顶点式", "二次函数一般式", "抛物线的顶点坐标", "圆周角定理", "切线的性质", "反比例函数", "相似三角形的判定"
**重要提示**:
- 使用精确的标签名称,例如:"二次函数一般式" 而非 "二次函数的图像"
- 使用 "三视图" 而非 "左视图"、"主视图" 或 "俯视图"
- 使用 "相似三角形的判定" 而非笼统的 "相似三角形"
- 使用 "全等三角形的判定" 以及具体判定法 "SSS", "SAS", "ASA", "AAS", "HL"
**物理标签 (Physics Tags):**
- 力学: "匀速直线运动", "变速运动", "牛顿第一定律", "牛顿第二定律", "牛顿第三定律", "力", "压强", "浮力"
- 电学: "欧姆定律", "串联电路", "并联电路", "电功率", "电功"
- 光学: "光的反射", "光的折射", "凸透镜", "凹透镜"
- 热学: "温度", "内能", "比热容", "热机效率"
暂无标准标签库,可使用通用标签如:"力学", "电学", "光学", "热学", "欧姆定律", "浮力"
**化学标签 (Chemistry Tags):**
- "化学方程式", "氧化还原反应", "酸碱盐", "中和反应", "金属", "非金属", "溶解度"
暂无标准标签库,可使用通用标签如:"化学方程式", "氧化还原反应", "酸碱盐"
**英语标签 (English Tags):**
- "语法", "词汇", "阅读理解", "完形填空", "写作", "听力", "翻译"
"语法", "词汇", "阅读理解", "完形填空", "写作", "听力", "翻译"
**其他学科 (Other Subjects):**
- If the subject is NOT Math, Physics, Chemistry, or English, you may use appropriate general tags (e.g., "历史事件", "地理常识", "古诗文").
对于语文、历史、地理等学科,使用合适的通用标签,例如:"历史事件", "地理常识", "古诗文"
**CRITICAL RULES:**
- 对于数学题目,必须从人教版课程大纲中选择精确的标签名称
- 如遇到具体知识点(如 "一元二次方程的根与系数关系"),应使用对应的标准标签(如 "韦达定理")
- 标签须与题目实际考查的知识点精准匹配
- 每题最多 5 个标签
**IMPORTANT RULES:**
- For Math/Physics/Chemistry, use EXACT matches from the list above.
- For English and other subjects, use the provided tags or relevant standard terms.
- Maximum 5 tags per question
CRITICAL FORMATTING REQUIREMENTS:
- Return ONLY the JSON object, nothing else
- Return ONLY a valid JSON object, nothing else
- Do NOT add any text before or after the JSON
- Do NOT wrap the JSON in markdown code blocks
- Do NOT add explanatory text like "The final answer is..."
- Do NOT include HTML tags (like <img>, <center>, etc.) in the extracted text
- Extract the ACTUAL text content from the image, not HTML references to the image
- Ensure all backslashes in LaTeX are properly escaped (use \\\\\\\\ instead of \\\\)
- Ensure all strings are properly escaped
- NO literal newlines in strings. Use \\\\n for newlines.
IMPORTANT:
- If the image contains a question with multiple sub-questions (like (1), (2), (3)), include ALL sub-questions in the questionText field.
- If the image contains completely separate questions (different question numbers), only analyze the first complete question with all its sub-questions.
- If the image is unclear or does not contain a question, return empty strings but valid JSON.
**Expected JSON Format:**
{
"questionText": "题目的完整文本,支持 Markdown 和 LaTeX ($formula$ 或 $$formula$$)",
"answerText": "正确答案",
"analysis": "详细解析步骤",
"subject": "数学",
"knowledgePoints": ["知识点1", "知识点2"]
}
${options?.providerHints || ''}
`;
@@ -141,10 +151,16 @@ export function generateSimilarQuestionPrompt(
4. "knowledgePoints": The knowledge points (should match input).
CRITICAL FORMATTING:
- Return ONLY the JSON object, no extra text
- Return ONLY a valid JSON object, no extra text
- Do NOT wrap in markdown code blocks
- Properly escape all backslashes in LaTeX
- No literal newlines in strings
**Expected JSON Format:**
{
"questionText": "新问题的文本(如果是选择题,包含选项 A、B、C、D)",
"answerText": "正确答案",
"analysis": "详细解析",
"knowledgePoints": ["知识点1", "知识点2"]
}
${options?.providerHints || ''}
`;

41
src/lib/ai/schema.ts Normal file
View File

@@ -0,0 +1,41 @@
import { z } from 'zod';
/**
* Zod schema for validating AI-parsed questions
* Ensures type safety and business rule compliance
*/
export const ParsedQuestionSchema = z.object({
questionText: z.string().min(1, "题目文本不能为空"),
answerText: z.string().min(1, "答案不能为空"),
analysis: z.string().min(1, "解析不能为空"),
subject: z.enum([
"数学", "物理", "化学", "生物",
"英语", "语文", "历史", "地理",
"政治", "其他"
]),
knowledgePoints: z.array(z.string()).max(5, "知识点最多 5 个"),
});
/**
* Type inference from Zod schema
* Use this type instead of manually defining ParsedQuestion
*/
export type ParsedQuestionFromSchema = z.infer<typeof ParsedQuestionSchema>;
/**
* Validates and parses AI response JSON
* @param data - Raw JSON data from AI
* @returns Validated ParsedQuestion object
* @throws ZodError if validation fails
*/
export function validateParsedQuestion(data: unknown): ParsedQuestionFromSchema {
return ParsedQuestionSchema.parse(data);
}
/**
* Safe validation that returns success/error object
* @param data - Raw JSON data from AI
*/
export function safeParseParsedQuestion(data: unknown) {
return ParsedQuestionSchema.safeParse(data);
}

View File

@@ -1,4 +1,10 @@
export interface ParsedQuestion {
// Re-export the Zod-validated type from schema.ts
export type { ParsedQuestionFromSchema as ParsedQuestion } from './schema';
import type { ParsedQuestionFromSchema } from './schema';
// Legacy interface kept for backward compatibility (deprecated)
/** @deprecated Use ParsedQuestion from schema.ts instead */
export interface ParsedQuestionLegacy {
questionText: string;
answerText: string;
analysis: string;
@@ -9,8 +15,8 @@ export interface ParsedQuestion {
export type DifficultyLevel = 'easy' | 'medium' | 'hard' | 'harder';
export interface AIService {
analyzeImage(imageBase64: string, mimeType?: string, language?: 'zh' | 'en'): Promise<ParsedQuestion>;
generateSimilarQuestion(originalQuestion: string, knowledgePoints: string[], language?: 'zh' | 'en', difficulty?: DifficultyLevel): Promise<ParsedQuestion>;
analyzeImage(imageBase64: string, mimeType?: string, language?: 'zh' | 'en'): Promise<ParsedQuestionFromSchema>;
generateSimilarQuestion(originalQuestion: string, knowledgePoints: string[], language?: 'zh' | 'en', difficulty?: DifficultyLevel): Promise<ParsedQuestionFromSchema>;
}
export interface AIConfig {

1
tsconfig.tsbuildinfo Normal file

File diff suppressed because one or more lines are too long