Some checks failed
Build and publish Docker image / docker (push) Failing after 2m33s
79 lines
1.7 KiB
TypeScript
79 lines
1.7 KiB
TypeScript
import { prisma } from "@/lib/db";
|
|
import { runLlmChat } from "@/lib/litellm";
|
|
import type { SupportedLanguage } from "@/lib/types";
|
|
|
|
export async function answerQuestion(question: string, language: SupportedLanguage) {
|
|
const entries = await prisma.knowledgeEntry.findMany({
|
|
where: {
|
|
language,
|
|
status: "PUBLISHED",
|
|
},
|
|
include: {
|
|
sources: {
|
|
include: {
|
|
source: true,
|
|
},
|
|
},
|
|
},
|
|
orderBy: {
|
|
updatedAt: "desc",
|
|
},
|
|
take: 6,
|
|
});
|
|
|
|
const context = entries.map((entry) => ({
|
|
title: entry.title,
|
|
summary: entry.summary,
|
|
sources: entry.sources.map((link) => ({
|
|
title: link.source.title,
|
|
url: link.source.url,
|
|
})),
|
|
}));
|
|
|
|
const llmResult = await runLlmChat([
|
|
{
|
|
role: "system",
|
|
content:
|
|
"Beantworte Fragen nur mit dem gegebenen Kontext. Wenn Kontext fehlt, sage das klar. Fuege Quellen-URLs in Klammern an.",
|
|
},
|
|
{
|
|
role: "user",
|
|
content: JSON.stringify({ question, language, context }),
|
|
},
|
|
]);
|
|
|
|
const answer = await prisma.questionAnswer.create({
|
|
data: {
|
|
question,
|
|
language,
|
|
answer: llmResult.content,
|
|
model: llmResult.model,
|
|
tokenCount: llmResult.tokenCount,
|
|
sources: {
|
|
create: uniqueSources(entries).map((sourceId) => ({
|
|
sourceId,
|
|
})),
|
|
},
|
|
},
|
|
include: {
|
|
sources: {
|
|
include: {
|
|
source: true,
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
return answer;
|
|
}
|
|
|
|
function uniqueSources(entries: Array<{ sources: Array<{ sourceId: string }> }>) {
|
|
const ids = new Set<string>();
|
|
for (const entry of entries) {
|
|
for (const link of entry.sources) {
|
|
ids.add(link.sourceId);
|
|
}
|
|
}
|
|
return [...ids].slice(0, 8);
|
|
}
|