76 lines
2.4 KiB
TypeScript
76 lines
2.4 KiB
TypeScript
import { generateText } from "ai";
|
||
import { getLanguageModelById } from "@/lib/ai/dynamic-provider";
|
||
|
||
export async function buildDirectAgentImageAnalysisAnswer(params: {
|
||
question: string;
|
||
summary: string;
|
||
modelId?: string;
|
||
}) {
|
||
const normalizedQuestion = String(params.question || "").trim();
|
||
const normalizedSummary = String(params.summary || "").trim();
|
||
|
||
if (!normalizedSummary) {
|
||
return "";
|
||
}
|
||
|
||
const buildFallbackAnswer = () => {
|
||
const intro = normalizedQuestion
|
||
? "我先根据当前锁定图片给你一个直接结论:"
|
||
: "我先根据当前锁定图片做一个直接分析:";
|
||
return [
|
||
intro,
|
||
normalizedSummary,
|
||
normalizedQuestion
|
||
? "如果你要,我可以继续往主体构图、风格、问题点或优化建议里再拆细。"
|
||
: "",
|
||
]
|
||
.filter(Boolean)
|
||
.join("\n\n");
|
||
};
|
||
|
||
const candidateModelIds = Array.from(
|
||
new Set(
|
||
[params.modelId]
|
||
.map((value) => String(value || "").trim())
|
||
.filter(Boolean),
|
||
),
|
||
);
|
||
|
||
for (const candidateModelId of candidateModelIds) {
|
||
try {
|
||
const model = await getLanguageModelById(candidateModelId);
|
||
if (!model) continue;
|
||
|
||
const { text } = await generateText({
|
||
model,
|
||
system: [
|
||
"你是无限画布里的图片分析助手。",
|
||
"只能根据给定的图像观察摘要回答,不要编造图片中不可见的事实。",
|
||
"如果用户问题超出已知信息,要明确说信息不足,不要硬猜。",
|
||
"优先给出直接结论,再补充2到4条简洁依据或建议。",
|
||
].join("\n"),
|
||
prompt: [
|
||
normalizedQuestion ? `用户问题:${normalizedQuestion}` : "用户要求:请分析当前图片。",
|
||
`图像观察摘要:\n${normalizedSummary}`,
|
||
"请用中文直接回答,不要复述“根据摘要/根据图片”,也不要输出多余寒暄。",
|
||
].join("\n\n"),
|
||
temperature: 0.2,
|
||
maxTokens: 320,
|
||
abortSignal: AbortSignal.timeout(20_000),
|
||
} as any);
|
||
|
||
const normalizedText = String(text || "").trim();
|
||
if (normalizedText) {
|
||
return normalizedText;
|
||
}
|
||
} catch (error) {
|
||
console.warn("[Direct Agent Analysis Answer] generation failed:", {
|
||
modelId: candidateModelId,
|
||
error,
|
||
});
|
||
}
|
||
}
|
||
|
||
return buildFallbackAnswer();
|
||
}
|