|
| 1 | +import { sql } from "@acme/db"; |
| 2 | +import { |
| 3 | + EmbeddingTokenUsage, |
| 4 | + JournalEmbedding, |
| 5 | + LLMTokenUsage, |
| 6 | + ModelPrices, |
| 7 | +} from "@acme/db/schema"; |
| 8 | +import { openai } from "@ai-sdk/openai"; |
| 9 | +import type { TRPCRouterRecord } from "@trpc/server"; |
| 10 | +import { TRPCError } from "@trpc/server"; |
| 11 | +import { embed } from "ai"; |
| 12 | +import { z } from "zod/v4"; |
| 13 | +import { protectedProcedure, publicProcedure } from "../trpc.js"; |
| 14 | + |
| 15 | +export const aiRouter = { |
| 16 | + createJournalEmbedding: publicProcedure |
| 17 | + .input( |
| 18 | + z.object({ |
| 19 | + content: z.string(), |
| 20 | + date: z.string(), |
| 21 | + journalEntryId: z.string().uuid(), |
| 22 | + model: z.string(), |
| 23 | + provider: z.string(), |
| 24 | + userId: z.string().uuid(), |
| 25 | + }), |
| 26 | + ) |
| 27 | + .mutation(async ({ ctx, input }) => { |
| 28 | + try { |
| 29 | + const { embedding, usage } = await embed({ |
| 30 | + maxRetries: 5, |
| 31 | + model: openai.embedding("text-embedding-3-small"), |
| 32 | + value: input.content, |
| 33 | + }); |
| 34 | + |
| 35 | + return await ctx.db.transaction(async (tx) => { |
| 36 | + // Store token usage with automatic pricing calculation |
| 37 | + await tx.insert(EmbeddingTokenUsage).values({ |
| 38 | + metadata: { |
| 39 | + content_id: input.journalEntryId, |
| 40 | + content_type: "journal_entry", |
| 41 | + }, |
| 42 | + model_price_id: sql`( |
| 43 | + SELECT id FROM ${ModelPrices} |
| 44 | + WHERE provider = ${input.provider} |
| 45 | + AND model = ${input.model} |
| 46 | + AND model_type = 'embedding' |
| 47 | + AND is_active = 'true' |
| 48 | + LIMIT 1 |
| 49 | + )`, |
| 50 | + token_count: usage.tokens, |
| 51 | + total_cost: sql`( |
| 52 | + SELECT (${usage.tokens} * embedding_price_per_1m_tokens / 1000000.0)::decimal(10,6) |
| 53 | + FROM ${ModelPrices} |
| 54 | + WHERE provider = ${input.provider} |
| 55 | + AND model = ${input.model} |
| 56 | + AND model_type = 'embedding' |
| 57 | + AND is_active = 'true' |
| 58 | + LIMIT 1 |
| 59 | + )`, |
| 60 | + user_id: input.userId, |
| 61 | + }); |
| 62 | + |
| 63 | + // Store the embedding |
| 64 | + const [journalEmbedding] = await tx |
| 65 | + .insert(JournalEmbedding) |
| 66 | + .values({ |
| 67 | + chunk_text: input.content, |
| 68 | + date: input.date, |
| 69 | + embedding, |
| 70 | + journal_entry_id: input.journalEntryId, |
| 71 | + user_id: input.userId, |
| 72 | + }) |
| 73 | + .onConflictDoUpdate({ |
| 74 | + set: { |
| 75 | + chunk_text: input.content, |
| 76 | + embedding, |
| 77 | + }, |
| 78 | + target: [JournalEmbedding.journal_entry_id], |
| 79 | + }) |
| 80 | + .returning(); |
| 81 | + |
| 82 | + return journalEmbedding; |
| 83 | + }); |
| 84 | + } catch (error) { |
| 85 | + console.error("Error creating journal embedding:", error); |
| 86 | + throw new TRPCError({ |
| 87 | + code: "INTERNAL_SERVER_ERROR", |
| 88 | + message: "Failed to create journal embedding", |
| 89 | + }); |
| 90 | + } |
| 91 | + }), |
| 92 | + // Procedure for tracking LLM token usage |
| 93 | + trackLLMUsage: protectedProcedure |
| 94 | + .input( |
| 95 | + z.object({ |
| 96 | + inputTokens: z.number(), |
| 97 | + metadata: z.record(z.string(), z.unknown()).optional(), |
| 98 | + model: z.string(), |
| 99 | + outputTokens: z.number(), |
| 100 | + provider: z.string(), |
| 101 | + }), |
| 102 | + ) |
| 103 | + .mutation(async ({ ctx, input }) => { |
| 104 | + try { |
| 105 | + return await ctx.db.transaction(async (tx) => { |
| 106 | + const totalTokens = input.inputTokens + input.outputTokens; |
| 107 | + |
| 108 | + return await tx |
| 109 | + .insert(LLMTokenUsage) |
| 110 | + .values({ |
| 111 | + input_tokens: input.inputTokens, |
| 112 | + metadata: input.metadata, |
| 113 | + model_price_id: sql`( |
| 114 | + SELECT id FROM ${ModelPrices} |
| 115 | + WHERE provider = ${input.provider} |
| 116 | + AND model = ${input.model} |
| 117 | + AND model_type = 'llm' |
| 118 | + AND is_active = 'true' |
| 119 | + LIMIT 1 |
| 120 | + )`, |
| 121 | + output_tokens: input.outputTokens, |
| 122 | + total_cost: sql`( |
| 123 | + SELECT ( |
| 124 | + (${input.inputTokens} * input_price_per_1m_tokens / 1000000.0) + |
| 125 | + (${input.outputTokens} * output_price_per_1m_tokens / 1000000.0) |
| 126 | + )::decimal(10,6) |
| 127 | + FROM ${ModelPrices} |
| 128 | + WHERE provider = ${input.provider} |
| 129 | + AND model = ${input.model} |
| 130 | + AND model_type = 'llm' |
| 131 | + AND is_active = 'true' |
| 132 | + LIMIT 1 |
| 133 | + )`, |
| 134 | + total_tokens: totalTokens, |
| 135 | + user_id: ctx.session.user.id, |
| 136 | + }) |
| 137 | + .returning(); |
| 138 | + }); |
| 139 | + } catch (error) { |
| 140 | + console.error("Error tracking LLM usage:", error); |
| 141 | + throw new TRPCError({ |
| 142 | + code: "INTERNAL_SERVER_ERROR", |
| 143 | + message: "Failed to track LLM usage", |
| 144 | + }); |
| 145 | + } |
| 146 | + }), |
| 147 | +} satisfies TRPCRouterRecord; |
0 commit comments