@@ -10,7 +10,7 @@ import removeMarkdown from "remove-markdown";
1010import type { z } from "zod/v4" ;
1111import { model } from "~/ai/providers/openai/embedding" ;
1212import { schema } from "~/components/editor/block-schema" ;
13- import { embedder } from "~/trpc/server" ;
13+ import { api , embedder } from "~/trpc/server" ;
1414import { handler } from "../_lib/webhook-handler" ;
1515
1616const CHUNK_PARAMS : ChunkParams = {
@@ -102,14 +102,33 @@ export const POST = handler(zDocumentEmbeddingTask, async (payload) => {
102102 const mDocument =
103103 await MDocument . fromMarkdown ( markdown ) . chunk ( CHUNK_PARAMS ) ;
104104
105- // ! TODO: Here's where we get the usage tokens, we must process these in a different transaction
106- // ! To guarantee that the usage is tracked regardless of the success of the embedding.
107- const { embeddings, usage : _usage } = await embedMany ( {
105+ const { embeddings, usage } = await embedMany ( {
108106 maxRetries : 5 ,
109107 model,
110108 values : mDocument . map ( ( chunk ) => chunk . text ) ,
111109 } ) ;
112110
111+ if ( usage ) {
112+ try {
113+ await api . usage . trackAiModelUsage ( {
114+ metadata : {
115+ document_id : document . id ,
116+ model_version : model . specificationVersion ,
117+ } ,
118+ metrics : [ { quantity : usage . tokens , unit : "tokens" } ] ,
119+ model_id : model . modelId ,
120+ model_provider : model . provider ,
121+ user_id : document . user_id ,
122+ } ) ;
123+ } catch ( error ) {
124+ console . error (
125+ "Failed to track AI usage for document embedding:" ,
126+ error ,
127+ ) ;
128+ // Continue with embedding even if usage tracking fails
129+ }
130+ }
131+
113132 const insertions : z . infer < typeof zInsertDocumentEmbedding > [ ] = [ ] ;
114133
115134 for ( const [ index , embedding ] of embeddings . entries ( ) ) {
0 commit comments