You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

169 lines
5.4 KiB
TypeScript

import {
router,
publicProcedure,
createCallerFactory,
} from "../../trpc/server.js";
import { db, type Fact } from "../../database/lowdb.js";
import type { DraftMessage } from "../../types.js";
import { openrouter, MODEL_NAME } from "./provider.js";
import { generateObject, generateText, jsonSchema } from "ai";
const factTriggersSystemPrompt = ({
previousRunningSummary,
messagesSincePreviousRunningSummary,
mainResponseContent,
}: {
previousRunningSummary: string;
messagesSincePreviousRunningSummary: Array<DraftMessage>;
mainResponseContent: string;
}) => `You are an expert at idenitfying situations when facts are useful.
You will be given a summary of a conversation, and the messages exchanged since that summary was produced.
Then you will be given a fact that was extracted from that conversation, and you will need to identify a natural language phrase that describes a situation in which it would be useful to invoke the fact.
The facts will be used to enrich context of conversations with AI assistants: upon each turn, a semantic database will be searched to see whether the current situation in the conversation matches any situations that are deemed to render the fact useful, and the fact will be injected into the context of the conversation.
Your task is to produce a list of triggers for the fact.
* You should not extract any facts that are already in the summary.
* The user should be referred to as "the user" in the fact text.
* The user's pronouns should be either he or she, NOT "they" or "them", because these triggers will be read by an AI assistant to give it context; and excessive use of "they" or "them" will make what they refer to unclear or ambiguous.
* The assistant should be referred to as "I" or "me", because these triggers will be read by an AI assistant to give it context.
<running_summary>
${previousRunningSummary}
</running_summary>
${messagesSincePreviousRunningSummary.map(
(message) =>
`<${message.role}_message>${message.parts
.filter((p) => p.type === "text")
.map((p) => p.text)
.join("\n")}</${message.role}_message>`
)}
<assistant_response>
${mainResponseContent}
</assistant_response>
`;
const factTriggersUserPrompt = ({
factContent,
}: {
factContent: string;
}) => `<fact_content>
${factContent}
</fact_content>
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 } }) => {
return db.data.factTriggers.filter(
(factTrigger) => factTrigger.sourceFactId === factId
);
}),
deleteOne: publicProcedure
.input(
(x) =>
x as {
factTriggerId: string;
}
)
.mutation(async ({ input: { factTriggerId } }) => {
const deletedFactTriggerIndex = db.data.factTriggers.findIndex(
(factTrigger) => factTrigger.id === factTriggerId
);
if (deletedFactTriggerIndex === -1)
throw new Error("Fact trigger not found");
db.data.factTriggers.splice(deletedFactTriggerIndex, 1);
await db.write();
return { ok: true };
}),
update: publicProcedure
.input(
(x) =>
x as {
factTriggerId: string;
content: string;
}
)
.mutation(async ({ input: { factTriggerId, content } }) => {
const factTriggerIndex = db.data.factTriggers.findIndex(
(factTrigger) => factTrigger.id === factTriggerId
);
if (factTriggerIndex === -1) throw new Error("Fact trigger not found");
db.data.factTriggers[factTriggerIndex].content = content;
await db.write();
return { ok: true };
}),
generateFromFact: publicProcedure
.input(
(x) =>
x as {
previousRunningSummary: string;
messagesSincePreviousRunningSummary: Array<DraftMessage>;
mainResponseContent: string;
fact: Fact;
}
)
.mutation(
async ({
input: {
previousRunningSummary,
messagesSincePreviousRunningSummary,
mainResponseContent,
fact,
},
}) => {
const factTriggers = await generateObject({
model: openrouter(MODEL_NAME),
messages: [
{
role: "system" as const,
content: factTriggersSystemPrompt({
previousRunningSummary,
messagesSincePreviousRunningSummary,
mainResponseContent,
}),
},
{
role: "user" as const,
content: factTriggersUserPrompt({
factContent: fact.content,
}),
},
],
schema: jsonSchema<{
factTriggers: Array<string>;
}>({
type: "object",
properties: {
factTriggers: {
type: "array",
items: {
type: "string",
},
},
},
required: ["factTriggers"],
}),
maxRetries: 0,
// tools: undefined,
}).catch((err) => {
console.error(err);
return {
object: {
factTriggers: [] as Array<string>,
},
};
});
return factTriggers;
}
),
});
export const createCaller = createCallerFactory(factTriggers);