| 182 | } |
| 183 | |
| 184 | export function recordChatCompletionTrace(params: { |
| 185 | body: ChatCompletionRequestBody |
| 186 | userId: string |
| 187 | agentId: string |
| 188 | ancestorRunIds: string[] |
| 189 | logger: Logger |
| 190 | insertChatCompletionTraceBigquery?: InsertChatCompletionTraceBigqueryFn |
| 191 | scheduleTraceWrite?: ScheduleTraceWrite |
| 192 | }) { |
| 193 | const { |
| 194 | body, |
| 195 | userId, |
| 196 | agentId, |
| 197 | ancestorRunIds, |
| 198 | logger, |
| 199 | insertChatCompletionTraceBigquery, |
| 200 | scheduleTraceWrite = (task) => { |
| 201 | setTimeout(() => { |
| 202 | void task() |
| 203 | }, 0) |
| 204 | }, |
| 205 | } = params |
| 206 | if (typeof body.codebuff_metadata?.trace_session_id !== 'string') { |
| 207 | return null |
| 208 | } |
| 209 | if (!insertChatCompletionTraceBigquery) { |
| 210 | return null |
| 211 | } |
| 212 | |
| 213 | const traceRequestId = randomUUID() |
| 214 | body.codebuff_metadata = { |
| 215 | ...(body.codebuff_metadata ?? {}), |
| 216 | trace_request_id: traceRequestId, |
| 217 | } |
| 218 | |
| 219 | scheduleTraceWrite(() => { |
| 220 | let traceRecord: ReturnType<typeof buildChatCompletionTraceRecord> |
| 221 | try { |
| 222 | traceRecord = buildChatCompletionTraceRecord({ |
| 223 | body, |
| 224 | userId, |
| 225 | agentId, |
| 226 | ancestorRunIds, |
| 227 | traceRequestId, |
| 228 | createdAt: new Date(), |
| 229 | }) |
| 230 | } catch (error) { |
| 231 | logger.error( |
| 232 | { error, traceId: traceRequestId }, |
| 233 | 'Failed to build chat completion trace row', |
| 234 | ) |
| 235 | return Promise.resolve() |
| 236 | } |
| 237 | |
| 238 | return insertChatCompletionTraceToBigQuery({ |
| 239 | row: traceRecord.row, |
| 240 | logger, |
| 241 | insertChatCompletionTraceBigquery, |