Skip to content
Logixlysia
Esc
↑↓navigate↵open⌘Jpreview
On this page

AI SDK metrics

Record LLM usage on request logs with one line of AI SDK middleware

Wrap the model with aiMiddleware(log) and every call records its usage, streams included. The logixlysia/ai subpath adds no dependency.

import { gateway, streamText, wrapLanguageModel } from 'ai'
import { aiMiddleware } from 'logixlysia/ai'

const model = gateway('anthropic/claude-sonnet-4.5')

app.post('/chat', ({ log }) =>
  streamText({
    model: wrapLanguageModel({ model, middleware: aiMiddleware(log) }),
    prompt: 'Hello'
  }).toTextStreamResponse()
)

Recorded fields

The fields land in the line’s context.ai.

Field Meaning
calls Model calls in this request
errors Calls that failed: rejected, stream failed or ended without a finish, or finish reason error
model, provider The last call’s model and provider
finishReason The last call’s finish reason, such as stop
inputTokens, outputTokens, reasoningTokens Tokens the provider reported
cacheReadTokens, cacheWriteTokens The part of inputTokens read from, and written to, the provider’s prompt cache. Each appears when at least one call reported a number above zero
totalTokens Input plus output tokens
msToFinish Time from the call to its last chunk
msToFirstChunk Streams only: the last call’s time to its first text
tokensPerSecond Streams only: the last call’s output tokens over the time from first text to finish

Several calls in one request are summed: calls, errors, the token counts and msToFinish add up, while the other fields keep the last call’s values. A field the provider did not report is left out. An SDK retry is its own call, so a request that retried and succeeded still carries errors.

Which line carries them

Route Lines
generateText Access line with ai
Generator stream (for await ... yield) Access line with ai
Custom log first Custom line, then the access line with ai
toTextStreamResponse() Access line, then ai call finished with ai

A returned Response writes its access line before the stream ends. The usage arrives too late for that line, so the middleware writes its own at INFO. Each late call writes one, carrying the request’s totals so far.

A failed call that lands after the line writes ai call failed at WARNING instead.

Limits

  • A stream the client cancels before its finish chunk records nothing, because the call never finishes on the server. A stream cancelled after the client read its finish chunk is recorded with its usage and finish reason.
  • In a handler, useLogger() needs useAsyncLocalStorage: true. Without it useLogger() returns a no-op logger and nothing is recorded.
  • Tested against ai 7.

Other SDKs

For an SDK with no middleware, pass the numbers yourself. This form writes no line of its own, so the fields reach a sink only on a line written after the merge.

import { mergeAIMetrics } from 'logixlysia/ai'

app.post('/chat', ({ log }) => {
  // After your SDK call:
  mergeAIMetrics(log, {
    model: 'claude-sonnet',
    provider: 'anthropic',
    inputTokens: 1200,
    outputTokens: 400,
    totalTokens: 1600,
    msToFinish: 2300
  })

  return { ok: true }
})

mergeAIMetrics(store.logger, request, metrics) works the same way when you have no log. Both forms, and aiMiddleware, add to one total per request, so you can mix them. An app with more than one logixlysia() instance keeps one total per instance.

Was this page helpful?