mirror of
https://github.com/massbug/judge4c.git
synced 2025-05-17 23:12:23 +00:00
feat(ai-improve): 添加题目详情并优化代码结构
-增加了获取题目详情的功能,如果提供了 problemId - 重构了代码,使其更具可读性和可维护性 - 添加了注释,以提高代码的可理解性 - 优化了提示词,以获得更好的 AI 优化建议
This commit is contained in:
parent
fabdb7c17a
commit
ebea5c986e
@ -1,42 +1,75 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
OptimizeCodeInput,
|
OptimizeCodeInput,
|
||||||
OptimizeCodeOutput,
|
OptimizeCodeOutput,
|
||||||
OptimizeCodeOutputSchema
|
OptimizeCodeOutputSchema,
|
||||||
} from "@/types/ai-improve";
|
} from "@/types/ai-improve";
|
||||||
import { openai } from "@/lib/ai";
|
import { openai } from "@/lib/ai";
|
||||||
import { CoreMessage, generateText } from "ai";
|
import { CoreMessage, generateText } from "ai";
|
||||||
|
import { prisma } from "@/lib/prisma"; // Prisma客户端
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 调用AI优化代码
|
||||||
|
* @param input 包含代码、错误信息、题目ID的输入
|
||||||
|
* @returns 优化后的代码和说明
|
||||||
|
*/
|
||||||
export const optimizeCode = async (
|
export const optimizeCode = async (
|
||||||
input: OptimizeCodeInput
|
input: OptimizeCodeInput
|
||||||
): Promise<OptimizeCodeOutput> => {
|
): Promise<OptimizeCodeOutput> => {
|
||||||
const model = openai("gpt-4o-mini");
|
const model = openai("gpt-4o-mini");
|
||||||
|
|
||||||
const prompt = `
|
// 获取题目详情(如果提供了problemId)
|
||||||
Analyze the following programming code for potential errors, inefficiencies or code style issues.
|
let problemDetails = "";
|
||||||
Provide an optimized version of the code with explanations. Focus on:
|
if (input.problemId) {
|
||||||
1. Fixing any syntax errors
|
try {
|
||||||
2. Improving performance
|
const problem = await prisma.problem.findUnique({
|
||||||
3. Enhancing code readability
|
where: { problemId: input.problemId },
|
||||||
4. Following best practices
|
});
|
||||||
|
if (problem) {
|
||||||
Original code:
|
problemDetails = `
|
||||||
\`\`\`
|
Problem Requirements:
|
||||||
${input.code}
|
-------------------
|
||||||
\`\`\`
|
Description: ${problem.description}
|
||||||
|
Input: ${problem.inputSpec}
|
||||||
Error message (if any): ${input.error || "No error message provided"}
|
Output: ${problem.outputSpec}
|
||||||
|
Test Cases: ${JSON.stringify(problem.testCases)}
|
||||||
Respond ONLY with the JSON object containing the optimized code and explanations.
|
`;
|
||||||
Format:
|
}
|
||||||
{
|
} catch (error) {
|
||||||
"optimizedCode": "optimized code here",
|
console.error("Failed to fetch problem details:", error);
|
||||||
"explanation": "explanation of changes made",
|
}
|
||||||
"issuesFixed": ["list of issues fixed"]
|
|
||||||
}
|
}
|
||||||
`;
|
|
||||||
|
|
||||||
|
// 构建AI提示词
|
||||||
|
const prompt = `
|
||||||
|
Analyze the following programming code for potential errors, inefficiencies or code style issues.
|
||||||
|
Provide an optimized version of the code with explanations. Focus on:
|
||||||
|
1. Fixing any syntax errors
|
||||||
|
2. Improving performance
|
||||||
|
3. Enhancing code readability
|
||||||
|
4. Following best practices
|
||||||
|
|
||||||
|
Original code:
|
||||||
|
\`\`\`
|
||||||
|
${input.code}
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
Error message (if any): ${input.error || "No error message provided"}
|
||||||
|
|
||||||
|
${problemDetails}
|
||||||
|
|
||||||
|
Respond ONLY with the JSON object containing the optimized code and explanations.
|
||||||
|
Format:
|
||||||
|
{
|
||||||
|
"optimizedCode": "optimized code here",
|
||||||
|
"explanation": "explanation of changes made",
|
||||||
|
"issuesFixed": ["list of issues fixed"]
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
// 发送请求给OpenAI
|
||||||
const messages: CoreMessage[] = [{ role: "user", content: prompt }];
|
const messages: CoreMessage[] = [{ role: "user", content: prompt }];
|
||||||
|
|
||||||
let text;
|
let text;
|
||||||
try {
|
try {
|
||||||
const response = await generateText({
|
const response = await generateText({
|
||||||
@ -49,6 +82,7 @@ export const optimizeCode = async (
|
|||||||
throw new Error("Failed to generate response from OpenAI");
|
throw new Error("Failed to generate response from OpenAI");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 解析LLM响应
|
||||||
let llmResponseJson;
|
let llmResponseJson;
|
||||||
try {
|
try {
|
||||||
const cleanedText = text.trim();
|
const cleanedText = text.trim();
|
||||||
@ -59,9 +93,8 @@ export const optimizeCode = async (
|
|||||||
throw new Error("Invalid JSON response from LLM");
|
throw new Error("Invalid JSON response from LLM");
|
||||||
}
|
}
|
||||||
|
|
||||||
const validationResult =
|
// 验证响应格式
|
||||||
OptimizeCodeOutputSchema.safeParse(llmResponseJson);
|
const validationResult = OptimizeCodeOutputSchema.safeParse(llmResponseJson);
|
||||||
|
|
||||||
if (!validationResult.success) {
|
if (!validationResult.success) {
|
||||||
console.error("Zod validation failed:", validationResult.error.format());
|
console.error("Zod validation failed:", validationResult.error.format());
|
||||||
throw new Error("Response validation failed");
|
throw new Error("Response validation failed");
|
||||||
|
@ -1,17 +1,19 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
|
// 优化代码的输入类型
|
||||||
export const OptimizeCodeInputSchema = z.object({
|
export const OptimizeCodeInputSchema = z.object({
|
||||||
code: z.string(),
|
code: z.string(), // 用户输入的代码
|
||||||
error: z.string().optional(),
|
error: z.string().optional(), // 可选的错误信息
|
||||||
|
problemId: z.string().optional(), // 可选的题目ID
|
||||||
});
|
});
|
||||||
|
|
||||||
export type OptimizeCodeInput = z.infer<typeof OptimizeCodeInputSchema>;
|
export type OptimizeCodeInput = z.infer<typeof OptimizeCodeInputSchema>;
|
||||||
|
|
||||||
|
// 优化代码的输出类型
|
||||||
export const OptimizeCodeOutputSchema = z.object({
|
export const OptimizeCodeOutputSchema = z.object({
|
||||||
optimizedCode: z.string(),
|
optimizedCode: z.string(), // 优化后的代码
|
||||||
explanation: z.string(),
|
explanation: z.string(), // 优化说明
|
||||||
issuesFixed: z.array(z.string()).optional(),
|
issuesFixed: z.array(z.string()).optional(), // 修复的问题列表
|
||||||
});
|
});
|
||||||
|
|
||||||
export type OptimizeCodeOutput = z.infer<typeof OptimizeCodeOutputSchema>;
|
export type OptimizeCodeOutput = z.infer<typeof OptimizeCodeOutputSchema>;
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user