drop db interface, use kysely instead for more more flexibility (at the cost of more coupling)

This commit is contained in:
Avraham Sakal
2025-09-21 17:14:27 -04:00
parent 21931a20cb
commit 360bfc6df3
8 changed files with 139 additions and 362 deletions
+65 -36
View File
@@ -69,7 +69,7 @@ export const chat = router({
input: { conversationId, messages, systemPrompt, parameters },
ctx,
}) {
const { db, openrouter, jwt } = ctx;
const { dbClient, openrouter, jwt } = ctx;
const factsCaller = createCallerFacts(ctx);
const messagesCaller = createCallerMessages(ctx);
const factTriggerCaller = createCallerFactTriggers(ctx);
@@ -98,14 +98,24 @@ export const chat = router({
} as const;
/** Save the incoming message to the database. */
const insertedUserMessage = await db.messages.create({
const userMessageRowToInsert = {
conversationId,
// content: messages[messages.length - 1].content,
// role: "user" as const,
...messages[messages.length - 1],
index: messages.length - 1,
createdAt: new Date().toISOString(),
});
};
const insertedUserMessageRows = await dbClient
.insertInto("messages")
.values({
...userMessageRowToInsert,
parts: JSON.stringify(userMessageRowToInsert.parts),
})
.returningAll()
.execute();
const insertedUserMessage =
insertedUserMessageRows[0] as CommittedMessage;
// Emit status update
yield {
@@ -167,13 +177,17 @@ export const chat = router({
messagesSincePreviousRunningSummary: [],
newMessages: messagesSincePreviousRunningSummary,
});
const insertedFactsFromUserMessage = await db.facts.createMany(
factsFromUserMessageResponse.object.facts.map((fact) => ({
userId: jwt?.id as string,
sourceMessageId: insertedUserMessage.id,
content: fact,
}))
);
const insertedFactsFromUserMessage = await dbClient
.insertInto("facts")
.values(
factsFromUserMessageResponse.object.facts.map((fact) => ({
userId: jwt?.id as string,
sourceMessageId: insertedUserMessage.id,
content: fact,
}))
)
.returningAll()
.execute();
// Emit status update
yield {
@@ -191,15 +205,21 @@ export const chat = router({
mainResponseContent: mainResponse.text,
previousRunningSummary,
});
const insertedAssistantMessage = await db.messages.create({
conversationId,
// content: mainResponse.text,
parts: [{ type: "text", text: mainResponse.text }],
runningSummary: runningSummaryResponse.text,
role: "assistant" as const,
index: messages.length,
createdAt: new Date().toISOString(),
});
const insertedAssistantMessage = (
await dbClient
.insertInto("messages")
.values({
conversationId,
// content: mainResponse.text,
parts: JSON.stringify([{ type: "text", text: mainResponse.text }]),
runningSummary: runningSummaryResponse.text,
role: "assistant" as const,
index: messages.length,
createdAt: new Date().toISOString(),
})
.returningAll()
.execute()
)[0];
// Emit status update
yield {
@@ -222,14 +242,18 @@ export const chat = router({
],
});
const insertedFactsFromAssistantMessage = await db.facts.createMany(
factsFromAssistantMessageResponse.object.facts.map((factContent) => ({
userId: jwt?.id as string,
sourceMessageId: insertedAssistantMessage.id,
content: factContent,
createdAt: new Date().toISOString(),
}))
);
const insertedFactsFromAssistantMessage = await dbClient
.insertInto("facts")
.values(
factsFromAssistantMessageResponse.object.facts.map((factContent) => ({
userId: jwt?.id as string,
sourceMessageId: insertedAssistantMessage.id,
content: factContent,
createdAt: new Date().toISOString(),
}))
)
.returningAll()
.execute();
const insertedFacts = [
...insertedFactsFromUserMessage,
@@ -255,15 +279,20 @@ export const chat = router({
fact,
});
const insertedFactTriggers: Array<Omit<FactTrigger, "id">> =
factTriggers.object.factTriggers.map((factTrigger) => ({
sourceFactId: fact.id,
content: factTrigger,
priorityMultiplier: 1,
priorityMultiplierReason: "",
scopeConversationId: conversationId,
createdAt: new Date().toISOString(),
}));
await db.factTriggers.createMany(insertedFactTriggers);
await dbClient
.insertInto("fact_triggers")
.values(
factTriggers.object.factTriggers.map((factTrigger) => ({
sourceFactId: fact.id,
content: factTrigger,
priorityMultiplier: 1,
priorityMultiplierReason: "",
scopeConversationId: conversationId,
createdAt: new Date().toISOString(),
}))
)
.returningAll()
.execute();
}
// Emit final result
+32 -10
View File
@@ -56,13 +56,26 @@ Generate a list of situations in which the fact is useful.`;
export const factTriggers = router({
fetchByFactId: publicProcedure
.input((x) => x as { factId: string })
.query(async ({ input: { factId }, ctx: { db } }) => {
return db.factTriggers.findByFactId(factId);
.query(async ({ input: { factId }, ctx: { dbClient } }) => {
const rows = await dbClient
.selectFrom("fact_triggers")
.innerJoin("facts", "facts.id", "fact_triggers.sourceFactId")
.selectAll("fact_triggers")
.where("sourceFactId", "=", factId)
.execute();
return rows;
}),
fetchByConversationId: publicProcedure
.input((x) => x as { conversationId: string })
.query(async ({ input: { conversationId }, ctx: { db } }) => {
return await db.factTriggers.findByConversationId(conversationId);
.query(async ({ input: { conversationId }, ctx: { dbClient } }) => {
const rows = await dbClient
.selectFrom("fact_triggers")
.innerJoin("facts", "facts.id", "fact_triggers.sourceFactId")
.innerJoin("messages", "messages.id", "facts.sourceMessageId")
.selectAll("fact_triggers")
.where("messages.conversationId", "=", conversationId)
.execute();
return rows;
}),
deleteOne: publicProcedure
.input(
@@ -71,8 +84,11 @@ export const factTriggers = router({
factTriggerId: string;
}
)
.mutation(async ({ input: { factTriggerId }, ctx: { db } }) => {
await db.factTriggers.delete(factTriggerId);
.mutation(async ({ input: { factTriggerId }, ctx: { dbClient } }) => {
await dbClient
.deleteFrom("fact_triggers")
.where("id", "=", factTriggerId)
.execute();
return { ok: true };
}),
update: publicProcedure
@@ -83,10 +99,16 @@ export const factTriggers = router({
content: string;
}
)
.mutation(async ({ input: { factTriggerId, content }, ctx: { db } }) => {
db.factTriggers.update(factTriggerId, { content });
return { ok: true };
}),
.mutation(
async ({ input: { factTriggerId, content }, ctx: { dbClient } }) => {
await dbClient
.updateTable("fact_triggers")
.set({ content })
.where("id", "=", factTriggerId)
.execute();
return { ok: true };
}
),
generateFromFact: publicProcedure
.input(
(x) =>
+1 -2
View File
@@ -1,7 +1,7 @@
import type { TSchema } from "@sinclair/typebox";
import { TypeCompiler } from "@sinclair/typebox/compiler";
import { initTRPC, TRPCError } from "@trpc/server";
import type { getDb, getDbClient } from "../../database/postgres";
import type { getDbClient } from "../../database/postgres";
import type { getOpenrouter } from "@server/provider.js";
import type { JWT } from "@auth/core/jwt";
@@ -12,7 +12,6 @@ import type { JWT } from "@auth/core/jwt";
const t = initTRPC
.context<
object & {
db: ReturnType<typeof getDb>;
dbClient: ReturnType<typeof getDbClient>;
openrouter: ReturnType<typeof getOpenrouter>;
jwt?: JWT | null;