feat(AI服务):lpt-ai 独立服务初始版本

- Fastify + TypeScript,OpenAI 兼容接口对接 SiliconFlow
- POST /ai/aggregate-report:残片聚合为学习报告(支持预期对比)
- POST /ai/generate-mind-map:生成思维导图缩进大纲(与后端解析格式一致)
- Key 从环境变量读取且日志脱敏,未配置时返回 503 由调用方降级
- prompt 模板集中管理,vitest 单元测试
This commit is contained in:
2026-07-03 23:48:51 +08:00
commit 44c07d28bd
11 changed files with 4187 additions and 0 deletions
+80
View File
@@ -0,0 +1,80 @@
/**
* AI 能力路由
*/
import type { FastifyInstance } from "fastify";
import { chat, isAvailable, loadConfig, LlmError } from "../llm/client.js";
import { aggregateReportPrompt, generateMindMapPrompt, type FragmentInput } from "../llm/prompts.js";
interface AggregateReportBody {
taskName: string;
fragments: FragmentInput[];
expectation?: string;
}
interface GenerateMindMapBody {
taskName: string;
taskDescription?: string;
reports: string[];
fragments: string[];
}
export async function aiRoutes(app: FastifyInstance): Promise<void> {
const config = loadConfig();
app.get("/health", async () => ({
status: "ok",
llmAvailable: isAvailable(config),
model: config.model,
}));
/**
* 残片聚合为学习报告
*/
app.post<{ Body: AggregateReportBody }>("/ai/aggregate-report", async (request, reply) => {
const { taskName, fragments, expectation } = request.body ?? ({} as AggregateReportBody);
if (!taskName || !Array.isArray(fragments) || fragments.length === 0) {
return reply.status(400).send({ error: "taskName 与 fragments 不可为空" });
}
try {
const messages = aggregateReportPrompt(taskName, fragments, expectation);
const report = await chat(config, messages);
return { report: report.trim(), model: config.model };
} catch (err) {
if (err instanceof LlmError) {
return reply.status(err.statusCode).send({ error: err.message });
}
throw err;
}
});
/**
* 从学习数据生成思维导图大纲(缩进文本,与后端 MindMapTreeTool 格式一致)
*/
app.post<{ Body: GenerateMindMapBody }>("/ai/generate-mind-map", async (request, reply) => {
const { taskName, taskDescription, reports, fragments } =
request.body ?? ({} as GenerateMindMapBody);
if (!taskName || ((reports?.length ?? 0) === 0 && (fragments?.length ?? 0) === 0)) {
return reply.status(400).send({ error: "taskName 不可为空且 reports/fragments 至少一项非空" });
}
try {
const messages = generateMindMapPrompt(
taskName,
taskDescription ?? "",
reports ?? [],
fragments ?? [],
);
const outline = await chat(config, messages, { maxTokens: 4096 });
return { outline: outline.trim(), model: config.model };
} catch (err) {
if (err instanceof LlmError) {
return reply.status(err.statusCode).send({ error: err.message });
}
throw err;
}
});
}