mirror of
https://github.com/moeru-ai/airi.git
synced 2026-12-02 18:08:22 +00:00
feat(api-server): report GenAI metrics with the OTel semantic convention names (#3450)
Some checks failed
CI / Type Check (push) Blocked by required conditions
CI / Detect changes (push) Waiting to run
CI / Lint (push) Blocked by required conditions
CI / Build Test (stage-web) (push) Blocked by required conditions
CI / Build Test (stage-tamagotchi) (push) Blocked by required conditions
CI / Build Test (ui-playgrounds) (push) Blocked by required conditions
CI / Build Test (stage-tamagotchi-godot) (push) Blocked by required conditions
CI / Unit Test (others) (push) Blocked by required conditions
CI / Unit Test (api-server-1) (push) Blocked by required conditions
CI / Unit Test (api-server-2) (push) Blocked by required conditions
CI / Unit Test (stage-tamagotchi) (push) Blocked by required conditions
CI / Unit Test (stage-ui-1) (push) Blocked by required conditions
CI / Unit Test (stage-ui-2) (push) Blocked by required conditions
CI / Unit Test (push) Blocked by required conditions
CI / Type Check (others) (push) Blocked by required conditions
CI / Type Check (desktop) (push) Blocked by required conditions
CI / Type Check (web) (push) Blocked by required conditions
CI / Check Provenance (push) Blocked by required conditions
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Build - docs (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
Release Tamagotchi / Plan Updates (push) Waiting to run
Release Tamagotchi / Build (push) Blocked by required conditions
Release Tamagotchi / Build-1 (push) Blocked by required conditions
Release Tamagotchi / Build-2 (push) Blocked by required conditions
Release Tamagotchi / Build-3 (push) Blocked by required conditions
Release Tamagotchi / Build-4 (push) Blocked by required conditions
Release Tamagotchi / Publish Bundle (push) Blocked by required conditions
Release Tamagotchi / Promote Canary to Stable (push) Blocked by required conditions
Release Tamagotchi / Publish GitCode Release Mirror (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-1 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-2 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-3 (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
Update Nix pnpmDeps Hash / update (push) Waiting to run
Crowdin upload changed translations / upload-translations-to-crowdin (push) Has been cancelled
Some checks failed
CI / Type Check (push) Blocked by required conditions
CI / Detect changes (push) Waiting to run
CI / Lint (push) Blocked by required conditions
CI / Build Test (stage-web) (push) Blocked by required conditions
CI / Build Test (stage-tamagotchi) (push) Blocked by required conditions
CI / Build Test (ui-playgrounds) (push) Blocked by required conditions
CI / Build Test (stage-tamagotchi-godot) (push) Blocked by required conditions
CI / Unit Test (others) (push) Blocked by required conditions
CI / Unit Test (api-server-1) (push) Blocked by required conditions
CI / Unit Test (api-server-2) (push) Blocked by required conditions
CI / Unit Test (stage-tamagotchi) (push) Blocked by required conditions
CI / Unit Test (stage-ui-1) (push) Blocked by required conditions
CI / Unit Test (stage-ui-2) (push) Blocked by required conditions
CI / Unit Test (push) Blocked by required conditions
CI / Type Check (others) (push) Blocked by required conditions
CI / Type Check (desktop) (push) Blocked by required conditions
CI / Type Check (web) (push) Blocked by required conditions
CI / Check Provenance (push) Blocked by required conditions
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Build - docs (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
Release Tamagotchi / Plan Updates (push) Waiting to run
Release Tamagotchi / Build (push) Blocked by required conditions
Release Tamagotchi / Build-1 (push) Blocked by required conditions
Release Tamagotchi / Build-2 (push) Blocked by required conditions
Release Tamagotchi / Build-3 (push) Blocked by required conditions
Release Tamagotchi / Build-4 (push) Blocked by required conditions
Release Tamagotchi / Publish Bundle (push) Blocked by required conditions
Release Tamagotchi / Promote Canary to Stable (push) Blocked by required conditions
Release Tamagotchi / Publish GitCode Release Mirror (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-1 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-2 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-3 (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
Update Nix pnpmDeps Hash / update (push) Waiting to run
Crowdin upload changed translations / upload-translations-to-crowdin (push) Has been cancelled
## Summary
The API gateway reported GenAI metrics with names that are not in the
OpenTelemetry GenAI semantic conventions. It also did not report cache
tokens, reasoning tokens, or cost. Postgres already had this data, but
Prometheus did not. This PR uses the convention names from
[`open-telemetry/semantic-conventions-genai`](https://github.com/open-telemetry/semantic-conventions-genai)
and adds the missing values. Then an OpenRouter-style usage dashboard
can use only Prometheus. Top users stay in Postgres, because `user_id`
is a high-cardinality label.
The GenAI constants now live only in `@proj-airi/trace-kit`. trace-kit
already had 17 hand-copied GenAI attribute names. The GenAI conventions
moved to a new repository that has no release and no npm package. The
GenAI exports of `@opentelemetry/semantic-conventions` are deprecated
and use the old names. So a script in trace-kit generates
`src/conventions/semconv.ts` from a pinned commit (`e6658f1`,
2026-11-06) of the registry YAML. The 17 old copies have the same
values. An upgrade changes the commit and runs `pnpm -F
@proj-airi/trace-kit generate:semconv`. The diff of the generated file
then shows each renamed name. The API imports the names from the new
`@proj-airi/trace-kit/semconv` entry. That entry has only constants, so
the server does not load the trace runtime.
The dashboards change in a paired PR. Apply it to Grafana after this PR
deploys:
- [airi-deploy#5](https://github.com/proj-airi/airi-deploy/pull/5)
feat(grafana): read the GenAI semantic convention metrics and add spend
panels · 2026-11-08 · @luoling8192
## Change map
| Metric or attribute | Before | After | Description |
| --- | --- | --- | --- |
| Chat and Responses duration | `gen_ai.client.operation.duration` |
`gen_ai.client.inference.duration` | The conventions say that inference
must not use `operation.duration` |
| Request count | `gen_ai.client.operation.count` | Removed | Use the
`_count` series of the duration histograms |
| Input and output tokens | `gen_ai.client.token.usage.input/output` |
`gen_ai.client.inference.usage.input_tokens/output_tokens` | Convention
names, with `gen_ai.token.modality=unknown` |
| Cache and reasoning tokens | Not reported |
`gen_ai.client.inference.usage.cache_read.input_tokens`,
`cache_write.input_tokens`, `reasoning.output_tokens` | Values from
`extractUsageFromBody` |
| First chunk latency | `gen_ai.client.first_token.duration` |
`gen_ai.client.inference.time_to_first_chunk` | Chat, Responses, and the
TTS WebSocket |
| Cost | Not reported | `airi.gen_ai.client.cost` (USD) | The
conventions have no cost metric. The value is the upstream cost that the
provider reports, not the Flux charge |
| Provider label | `provider` | `gen_ai.provider.name` | Gateway
`airi.gen_ai.gateway.*` counters keep `provider` |
| Other labels | None | `gen_ai.response.model`, and `error.type` when
the status is 400 or more | `http.response.status_code` stays |
| TTS duration | `gen_ai.client.operation.duration` | Same | TTS is not
an inference operation |
| GenAI constants | Strings in `utils/observability.ts`, and 17 hand
copies in trace-kit | Generated once in trace-kit, imported from
`@proj-airi/trace-kit/semconv` | `error.type` comes from
`@opentelemetry/semantic-conventions`. The trace-kit test that compared
copies with the deprecated npm exports is removed |
| Span attributes | Input and output tokens | Also
`gen_ai.usage.cache_read.input_tokens`, `cache_write.input_tokens`,
`reasoning.output_tokens` | |
Token and cost counters record only positive values, as the conventions
require. A missing or zero value records nothing.
## Boundaries and risks
| Invariant or boundary | Failure mode | Protection | Evidence or gap |
| --- | --- | --- | --- |
| Dashboards in `proj-airi/airi-deploy` read the old names | Panels go
empty after deploy |
[airi-deploy#5](https://github.com/proj-airi/airi-deploy/pull/5) moves
them | Apply that PR to Grafana right after this deploy |
| Grafana alert rules read the old names | Alerts stop firing | None. No
repository has the rules | Unverified. Check the rules in Grafana |
| Generated constants match the pinned registry | A hand edit or a stale
file gives wrong names | The file is generated, and the generator throws
on duplicate names | `render.test.ts`. Regenerating in rc gave no diff |
| trace-kit consumers | Removing `SEMCONV_VERSION` or changing the root
exports breaks a consumer | Nothing read `SEMCONV_VERSION`. The 17 names
keep their values | Typecheck of trace-kit dependents in rc, see
Verification |
| Docker build of the API | The image misses trace-kit | Both API
Dockerfiles copy and build `packages/stream-kit` and
`packages/trace-kit` | No Docker build ran. Checked by reading the
Dockerfiles |
| Cost matches the provider receipt | Cost is recorded as the Flux
charge, or is lost when the wallet cannot pay | `costUsd` comes from
`price.costReceipt.usage.costUsd`, before settlement | `route.test.ts`:
a drained wallet still records `0.038` USD |
| Label cardinality | High-cardinality labels | Only model, provider,
operation, status, and error type. No user ID | Code review |
| The conventions are at `development` stability | Names can change
again | None | Accepted risk |
## Verification
All checks ran in an rc Workspace, on a clean clone with this diff
applied.
- `pnpm -F @proj-airi/api-server typecheck`: passed.
- `pnpm -F @proj-airi/api-server exec vitest run`: 88 files passed and 2
skipped. 975 tests passed and 4 skipped.
- `pnpm exec eslint <changed files>`: 0 errors. The warnings that remain
were there before this change.
- `pnpm install --frozen-lockfile` (full workspace): passed. The
lockfile change is the API link to trace-kit and the trace-kit
devDependencies.
- `pnpm -F @proj-airi/trace-kit build`: passed, with `dist/semconv.mjs`.
- `turbo run test:run` for trace-kit, ui-trace, and testing-audio: 28
tasks passed. trace-kit 73 tests, ui-trace 17 tests.
- `turbo run typecheck --filter=...@proj-airi/trace-kit
--filter=@proj-airi/api-server --continue`: 10 of 13 passed.
`airi-plugin-game-chess`, `stage-tamagotchi`, and
`stage-tamagotchi-kirie` failed on errors in `electron-vueuse` and Vue
pages. The same three fail on the merge base `b51672dc8` in the same
Workspace.
- Full API suite on the final head: 974 passed, 1 failed. The failure is
a 5 s timeout in `mock-db.test.ts` under node load. The file passed
alone. Earlier runs had the same timeouts in PGlite tests.
- New tests in `telemetry.test.ts` cover each new counter, its
attributes, the skip of zero values, and `error.type`.
I did not check the exported names on a live Prometheus. With the OTLP
translation, I expect `airi_gen_ai_client_cost_total` and
`gen_ai_client_inference_usage_input_tokens_total`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8878ffcee6
commit
a0d1b2ce03
26 changed files with 1447 additions and 169 deletions
|
|
@ -15,13 +15,14 @@ The package depends only on `@proj-airi/stream-kit`, `es-toolkit`, and `valibot`
|
|||
## Do not use it for
|
||||
|
||||
- Product UI. Product UI reads domain projections of eventa events, not traces.
|
||||
- Remote telemetry. Upload to a telemetry service is out of scope.
|
||||
- Remote telemetry. Upload to a telemetry service is out of scope. A service that sends OpenTelemetry data can still import the names from `@proj-airi/trace-kit/semconv`.
|
||||
- Logs that a person reads in a terminal. Use `@guiiai/logg`.
|
||||
|
||||
## Entry points
|
||||
|
||||
| Import | Contents |
|
||||
| --- | --- |
|
||||
| `@proj-airi/trace-kit/semconv` | Only the OpenTelemetry GenAI names: attribute keys, enum values, and metric names. It imports no other module, so a server can use it without the trace runtime. |
|
||||
| `@proj-airi/trace-kit` | Record types, the Valibot schema, the `define*` functions, `ClockGraph`, `TraceSource`, `TraceSpan`, `SeriesWriter` for frequent series such as audio levels, and the conventions |
|
||||
| `@proj-airi/trace-kit/collector` | `TraceCollector`: buffer, pinned set, series rings, watermarks, source lifecycle, and the flight recorder |
|
||||
| `@proj-airi/trace-kit/projections` | `TraceReader`, the timeline, the event log, and attribute metrics |
|
||||
|
|
@ -65,9 +66,11 @@ import { ATTR_AIRI_TOPIC_ID, ATTR_GEN_AI_REQUEST_MODEL } from '@proj-airi/trace-
|
|||
span.update({ [ATTR_GEN_AI_REQUEST_MODEL]: model, [ATTR_AIRI_TOPIC_ID]: topicId })
|
||||
```
|
||||
|
||||
- The `ATTR_GEN_AI_*` constants are copies of the exports of `@opentelemetry/semantic-conventions/incubating`, with the same names and values. `SEMCONV_VERSION` is the package version that they follow.
|
||||
- Upstream tells libraries not to import the incubating entry at runtime. A test compares each copy with the installed package, so a change upstream fails the tests.
|
||||
- `ATTR_GEN_AI_MEMORY_QUERY_TEXT` is not in the npm package yet. It follows the GenAI conventions repository.
|
||||
- The `gen_ai.*` names come from `src/conventions/semconv.ts`. It is generated from a pinned commit of [`open-telemetry/semantic-conventions-genai`](https://github.com/open-telemetry/semantic-conventions-genai). `SEMCONV_GENAI_COMMIT` is that commit.
|
||||
- That repository has no release and no npm package. The GenAI exports of `@opentelemetry/semantic-conventions` are deprecated and use the old names.
|
||||
- Do not edit `src/conventions/semconv.ts` by hand. To upgrade, change `COMMIT` in `scripts/semconv/generate.ts` and run `pnpm -F @proj-airi/trace-kit generate:semconv`. The script needs network access.
|
||||
- Read the diff of the generated file. A removed or renamed name breaks the typecheck of each consumer. If a metric name changed, update the Grafana dashboards in `proj-airi/airi-deploy` in the same release.
|
||||
- When OpenTelemetry publishes an npm package for the GenAI conventions, import the names from it and delete the generator.
|
||||
- The other constants, for example `ATTR_CENSORED`, `ATTR_DECISION_LATENCY_MS`, and `ATTR_AIRI_TOPIC_ID`, are AIRI names.
|
||||
|
||||
## Collect and read
|
||||
|
|
|
|||
|
|
@ -20,6 +20,10 @@
|
|||
"types": "./dist/index.d.mts",
|
||||
"default": "./dist/index.mjs"
|
||||
},
|
||||
"./semconv": {
|
||||
"types": "./dist/semconv.d.mts",
|
||||
"default": "./dist/semconv.mjs"
|
||||
},
|
||||
"./collector": {
|
||||
"types": "./dist/collector/index.d.mts",
|
||||
"default": "./dist/collector/index.mjs"
|
||||
|
|
@ -55,7 +59,8 @@
|
|||
"scripts": {
|
||||
"test:run": "vitest run --config vitest.config.ts",
|
||||
"build": "tsdown",
|
||||
"typecheck": "tsc --noEmit"
|
||||
"generate:semconv": "tsx scripts/semconv/generate.ts",
|
||||
"typecheck": "tsc --noEmit && tsc --noEmit -p scripts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@proj-airi/stream-kit": "workspace:^",
|
||||
|
|
@ -63,6 +68,8 @@
|
|||
"valibot": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@opentelemetry/semantic-conventions": "catalog:"
|
||||
"@types/node": "catalog:",
|
||||
"tsx": "catalog:",
|
||||
"yaml": "catalog:"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
27
packages/trace-kit/scripts/semconv/generate.ts
Normal file
27
packages/trace-kit/scripts/semconv/generate.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
/** Downloads the pinned GenAI registry files and writes `src/conventions/semconv.ts`. */
|
||||
|
||||
import { writeFile } from 'node:fs/promises'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import { parse } from 'valibot'
|
||||
import { parse as parseYaml } from 'yaml'
|
||||
|
||||
import { registryFileSchema, renderModule } from './render'
|
||||
|
||||
// To upgrade, change this commit, run `generate`, and read the diff of `src/conventions/semconv.ts` for renamed names.
|
||||
const COMMIT = 'e6658f14c9d9ea0760825f029cb82e7673f48fab'
|
||||
const FILES = ['model/gen-ai/registry.yaml', 'model/gen-ai/metrics.yaml', 'model/gen-ai/token-metrics.yaml']
|
||||
|
||||
const output = resolve(dirname(fileURLToPath(import.meta.url)), '../../src/conventions/semconv.ts')
|
||||
|
||||
const files = await Promise.all(FILES.map(async (path) => {
|
||||
const url = `https://raw.githubusercontent.com/open-telemetry/semantic-conventions-genai/${COMMIT}/${path}`
|
||||
const response = await fetch(url)
|
||||
if (!response.ok)
|
||||
throw new Error(`Failed to download ${url}: HTTP ${response.status}`)
|
||||
return parse(registryFileSchema, parseYaml(await response.text()))
|
||||
}))
|
||||
|
||||
await writeFile(output, renderModule({ commit: COMMIT, files: FILES }, files))
|
||||
console.info(`Wrote ${output}`)
|
||||
45
packages/trace-kit/scripts/semconv/render.test.ts
Normal file
45
packages/trace-kit/scripts/semconv/render.test.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { constantName, renderModule } from './render'
|
||||
|
||||
const source = { commit: 'abc123', files: ['model/gen-ai/registry.yaml'] }
|
||||
|
||||
describe('renderModule', () => {
|
||||
it('renders attributes, enum members, and metrics as constants', () => {
|
||||
const output = renderModule(source, [
|
||||
{
|
||||
attributes: [{
|
||||
key: 'gen_ai.token.modality',
|
||||
brief: 'The modality of the tokens being counted.',
|
||||
stability: 'development',
|
||||
type: { members: [{ id: 'unknown', value: 'unknown', brief: 'The modality is not known.' }] },
|
||||
}],
|
||||
},
|
||||
{
|
||||
metrics: [{ name: 'gen_ai.client.inference.usage.cache_read.input_tokens', instrument: 'counter', unit: '{token}', brief: 'Input tokens served from a cache.' }],
|
||||
},
|
||||
])
|
||||
|
||||
expect(output).toContain(`export const SEMCONV_GENAI_COMMIT = 'abc123'`)
|
||||
expect(output).toContain(`export const ATTR_GEN_AI_TOKEN_MODALITY = 'gen_ai.token.modality'`)
|
||||
expect(output).toContain(`export const GEN_AI_TOKEN_MODALITY_VALUE_UNKNOWN = 'unknown'`)
|
||||
expect(output).toContain(`export const METRIC_GEN_AI_CLIENT_INFERENCE_USAGE_CACHE_READ_INPUT_TOKENS = 'gen_ai.client.inference.usage.cache_read.input_tokens'`)
|
||||
expect(output).toContain(' * Instrument: `counter`. Unit: `{token}`.')
|
||||
})
|
||||
|
||||
it('rejects two names that map to the same constant', () => {
|
||||
expect(() => renderModule(source, [{ attributes: [{ key: 'a.b', type: 'string' }, { key: 'a_b', type: 'string' }] }])).toThrow('Duplicate constant ATTR_A_B')
|
||||
})
|
||||
|
||||
it('escapes comment terminators in briefs', () => {
|
||||
const output = renderModule(source, [{ attributes: [{ key: 'x.y', brief: 'ends */ early', type: 'string' }] }])
|
||||
expect(output).toContain(' * ends *\\/ early')
|
||||
})
|
||||
})
|
||||
|
||||
describe('constantName', () => {
|
||||
it('maps dots and dashes to underscores', () => {
|
||||
expect(constantName('gen_ai.provider.name')).toBe('GEN_AI_PROVIDER_NAME')
|
||||
expect(constantName('azure.ai-inference')).toBe('AZURE_AI_INFERENCE')
|
||||
})
|
||||
})
|
||||
95
packages/trace-kit/scripts/semconv/render.ts
Normal file
95
packages/trace-kit/scripts/semconv/render.ts
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
import type { InferOutput } from 'valibot'
|
||||
|
||||
import { array, looseObject, object, optional, parse, string, union } from 'valibot'
|
||||
|
||||
const memberSchema = looseObject({
|
||||
id: string(),
|
||||
value: union([string(), looseObject({})]),
|
||||
brief: optional(string()),
|
||||
stability: optional(string()),
|
||||
})
|
||||
|
||||
const attributeSchema = looseObject({
|
||||
key: string(),
|
||||
brief: optional(string()),
|
||||
stability: optional(string()),
|
||||
type: union([string(), looseObject({ members: array(memberSchema) })]),
|
||||
})
|
||||
|
||||
const metricSchema = looseObject({
|
||||
name: string(),
|
||||
instrument: string(),
|
||||
unit: string(),
|
||||
brief: optional(string()),
|
||||
stability: optional(string()),
|
||||
})
|
||||
|
||||
/** The subset of a Weaver `definition/2` file that the generator reads. */
|
||||
export const registryFileSchema = looseObject({
|
||||
attributes: optional(array(attributeSchema)),
|
||||
metrics: optional(array(metricSchema)),
|
||||
})
|
||||
|
||||
export type RegistryFile = InferOutput<typeof registryFileSchema>
|
||||
|
||||
const sourceSchema = object({ commit: string(), files: array(string()) })
|
||||
|
||||
/** Converts a dotted semantic convention name to an upper snake case identifier. */
|
||||
export function constantName(name: string): string {
|
||||
return name.replace(/[^a-z0-9]+/gi, '_').toUpperCase()
|
||||
}
|
||||
|
||||
function docComment(lines: Array<string | undefined>): string {
|
||||
const text = lines
|
||||
.filter((line): line is string => Boolean(line))
|
||||
.map(line => line.replace(/\s+/g, ' ').replace(/\*\//g, '*\\/').trim())
|
||||
return ['/**', ...text.map(line => ` * ${line}`), ' */'].join('\n')
|
||||
}
|
||||
|
||||
function stabilityLine(stability: string | undefined): string | undefined {
|
||||
return stability ? `Stability: \`${stability}\`.` : undefined
|
||||
}
|
||||
|
||||
/** Renders the constants module for the parsed registry files. Throws on duplicate constant names. */
|
||||
export function renderModule(source: { commit: string, files: string[] }, files: RegistryFile[]): string {
|
||||
const { commit, files: paths } = parse(sourceSchema, source)
|
||||
const seen = new Set<string>()
|
||||
const blocks: string[] = []
|
||||
|
||||
function add(name: string, doc: string, value: string): void {
|
||||
if (seen.has(name))
|
||||
throw new Error(`Duplicate constant ${name}`)
|
||||
seen.add(name)
|
||||
blocks.push(`${doc}\nexport const ${name} = '${value}'`)
|
||||
}
|
||||
|
||||
const attributes = files.flatMap(file => file.attributes ?? []).sort((a, b) => a.key.localeCompare(b.key))
|
||||
for (const attribute of attributes) {
|
||||
add(`ATTR_${constantName(attribute.key)}`, docComment([attribute.brief, stabilityLine(attribute.stability)]), attribute.key)
|
||||
if (typeof attribute.type === 'string')
|
||||
continue
|
||||
for (const member of attribute.type.members) {
|
||||
if (typeof member.value !== 'string')
|
||||
continue
|
||||
add(`${constantName(attribute.key)}_VALUE_${constantName(member.id)}`, docComment([member.brief, stabilityLine(member.stability)]), member.value)
|
||||
}
|
||||
}
|
||||
|
||||
const metrics = files.flatMap(file => file.metrics ?? []).sort((a, b) => a.name.localeCompare(b.name))
|
||||
for (const metric of metrics)
|
||||
add(`METRIC_${constantName(metric.name)}`, docComment([metric.brief, `Instrument: \`${metric.instrument}\`. Unit: \`${metric.unit}\`.`, stabilityLine(metric.stability)]), metric.name)
|
||||
|
||||
return [
|
||||
'// This file is generated by `pnpm -F @proj-airi/trace-kit generate:semconv`. Do not edit it.',
|
||||
'// The comments are upstream briefs, so the comment wording rules do not apply.',
|
||||
'/* eslint-disable slop/no-jargon */',
|
||||
`// Source: https://github.com/open-telemetry/semantic-conventions-genai/tree/${commit}`,
|
||||
`// Files: ${paths.join(', ')}`,
|
||||
'',
|
||||
`/** The semantic-conventions-genai commit that these constants come from. */`,
|
||||
`export const SEMCONV_GENAI_COMMIT = '${commit}'`,
|
||||
'',
|
||||
blocks.join('\n\n'),
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
14
packages/trace-kit/scripts/tsconfig.json
Normal file
14
packages/trace-kit/scripts/tsconfig.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"extends": "../../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"lib": [
|
||||
"ESNext"
|
||||
],
|
||||
"types": [
|
||||
"node"
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"./**/*.ts"
|
||||
]
|
||||
}
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import * as incubating from '@opentelemetry/semantic-conventions/incubating'
|
||||
|
||||
import * as semconv from './semconv'
|
||||
|
||||
/** Copies that the npm package does not export yet. Each one has a `NOTICE` in `./semconv`. */
|
||||
const NOT_RELEASED = new Set(['ATTR_GEN_AI_MEMORY_QUERY_TEXT'])
|
||||
|
||||
const copies = Object.entries(semconv).filter(([name]) => name !== 'SEMCONV_VERSION' && !NOT_RELEASED.has(name))
|
||||
|
||||
describe('semconv copies', () => {
|
||||
it.each(copies)('%s equals the export of @opentelemetry/semantic-conventions/incubating', (name, value) => {
|
||||
expect(incubating).toHaveProperty(name, value)
|
||||
})
|
||||
|
||||
it.each([...NOT_RELEASED])('%s is not in the npm package yet', (name) => {
|
||||
// When this fails, the package has the attribute. Remove it from NOT_RELEASED and remove its NOTICE.
|
||||
expect(incubating).not.toHaveProperty(name)
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -3,6 +3,7 @@ import { defineConfig } from 'tsdown'
|
|||
export default defineConfig({
|
||||
entry: {
|
||||
'index': 'src/index.ts',
|
||||
'semconv': 'src/conventions/semconv.ts',
|
||||
'collector/index': 'src/collector/index.ts',
|
||||
'projections/index': 'src/projections/index.ts',
|
||||
'profiles/voice': 'src/profiles/voice.ts',
|
||||
|
|
|
|||
|
|
@ -5,6 +5,6 @@ export default defineConfig({
|
|||
environment: 'node',
|
||||
// The reader benchmark runs a full garbage collection before each heap read.
|
||||
execArgv: ['--expose-gc'],
|
||||
include: ['src/**/*.test.ts'],
|
||||
include: ['src/**/*.test.ts', 'scripts/**/*.test.ts'],
|
||||
},
|
||||
})
|
||||
|
|
|
|||
13
pnpm-lock.yaml
generated
13
pnpm-lock.yaml
generated
|
|
@ -5969,9 +5969,15 @@ importers:
|
|||
specifier: 'catalog:'
|
||||
version: 1.5.0(typescript@6.0.3)
|
||||
devDependencies:
|
||||
'@opentelemetry/semantic-conventions':
|
||||
'@types/node':
|
||||
specifier: 'catalog:'
|
||||
version: 1.43.0
|
||||
version: 26.2.0
|
||||
tsx:
|
||||
specifier: 'catalog:'
|
||||
version: 4.23.12
|
||||
yaml:
|
||||
specifier: 'catalog:'
|
||||
version: 2.9.1
|
||||
|
||||
packages/ui:
|
||||
dependencies:
|
||||
|
|
@ -6528,6 +6534,9 @@ importers:
|
|||
'@proj-airi/server-sdk-shared':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/server-sdk-shared
|
||||
'@proj-airi/trace-kit':
|
||||
specifier: workspace:^
|
||||
version: link:../../../packages/trace-kit
|
||||
'@xsai/shared-stream':
|
||||
specifier: 'catalog:'
|
||||
version: 0.5.1
|
||||
|
|
|
|||
|
|
@ -15,6 +15,8 @@ COPY server/apps/api/package.json server/apps/api/package.json
|
|||
COPY server/packages/auth-shared/package.json server/packages/auth-shared/package.json
|
||||
COPY server/packages/http-error-shared/package.json server/packages/http-error-shared/package.json
|
||||
COPY server/packages/server-sdk-shared/package.json server/packages/server-sdk-shared/package.json
|
||||
COPY packages/stream-kit/package.json packages/stream-kit/package.json
|
||||
COPY packages/trace-kit/package.json packages/trace-kit/package.json
|
||||
|
||||
RUN --mount=type=cache,id=pnpm-store,target=/root/.pnpm-store \
|
||||
pnpm install --frozen-lockfile --ignore-scripts
|
||||
|
|
@ -23,8 +25,11 @@ COPY server/apps/api server/apps/api
|
|||
COPY server/packages/auth-shared server/packages/auth-shared
|
||||
COPY server/packages/http-error-shared server/packages/http-error-shared
|
||||
COPY server/packages/server-sdk-shared server/packages/server-sdk-shared
|
||||
COPY packages/stream-kit packages/stream-kit
|
||||
COPY packages/trace-kit packages/trace-kit
|
||||
|
||||
RUN pnpm -F @proj-airi/server-sdk-shared run build
|
||||
RUN pnpm -F @proj-airi/stream-kit run build && pnpm -F @proj-airi/trace-kit run build
|
||||
RUN pnpm -F @proj-airi/api-server run build
|
||||
|
||||
EXPOSE 3000
|
||||
|
|
|
|||
|
|
@ -50,6 +50,7 @@
|
|||
"@proj-airi/auth-shared": "workspace:*",
|
||||
"@proj-airi/http-error-shared": "workspace:*",
|
||||
"@proj-airi/server-sdk-shared": "workspace:*",
|
||||
"@proj-airi/trace-kit": "workspace:^",
|
||||
"@xsai/shared-stream": "catalog:",
|
||||
"drizzle-orm": "catalog:",
|
||||
"drizzle-valibot": "catalog:",
|
||||
|
|
|
|||
|
|
@ -13,6 +13,8 @@ COPY server/apps/api/package.json server/apps/api/package.json
|
|||
COPY server/packages/auth-shared/package.json server/packages/auth-shared/package.json
|
||||
COPY server/packages/http-error-shared/package.json server/packages/http-error-shared/package.json
|
||||
COPY server/packages/server-sdk-shared/package.json server/packages/server-sdk-shared/package.json
|
||||
COPY packages/stream-kit/package.json packages/stream-kit/package.json
|
||||
COPY packages/trace-kit/package.json packages/trace-kit/package.json
|
||||
|
||||
RUN pnpm install --frozen-lockfile --ignore-scripts
|
||||
|
||||
|
|
@ -20,8 +22,11 @@ COPY server/apps/api server/apps/api
|
|||
COPY server/packages/auth-shared server/packages/auth-shared
|
||||
COPY server/packages/http-error-shared server/packages/http-error-shared
|
||||
COPY server/packages/server-sdk-shared server/packages/server-sdk-shared
|
||||
COPY packages/stream-kit packages/stream-kit
|
||||
COPY packages/trace-kit packages/trace-kit
|
||||
|
||||
RUN pnpm -F @proj-airi/server-sdk-shared run build
|
||||
RUN pnpm -F @proj-airi/stream-kit run build && pnpm -F @proj-airi/trace-kit run build
|
||||
RUN pnpm -F @proj-airi/api-server run build
|
||||
|
||||
EXPOSE 3000
|
||||
|
|
|
|||
|
|
@ -12,6 +12,16 @@ import type { Env } from '../libs/env'
|
|||
import { useLogger } from '@guiiai/logg'
|
||||
import { metrics, trace } from '@opentelemetry/api'
|
||||
import { logs, SeverityNumber } from '@opentelemetry/api-logs'
|
||||
import {
|
||||
METRIC_GEN_AI_CLIENT_INFERENCE_DURATION,
|
||||
METRIC_GEN_AI_CLIENT_INFERENCE_TIME_TO_FIRST_CHUNK,
|
||||
METRIC_GEN_AI_CLIENT_INFERENCE_USAGE_CACHE_READ_INPUT_TOKENS,
|
||||
METRIC_GEN_AI_CLIENT_INFERENCE_USAGE_CACHE_WRITE_INPUT_TOKENS,
|
||||
METRIC_GEN_AI_CLIENT_INFERENCE_USAGE_INPUT_TOKENS,
|
||||
METRIC_GEN_AI_CLIENT_INFERENCE_USAGE_OUTPUT_TOKENS,
|
||||
METRIC_GEN_AI_CLIENT_INFERENCE_USAGE_REASONING_OUTPUT_TOKENS,
|
||||
METRIC_GEN_AI_CLIENT_OPERATION_DURATION,
|
||||
} from '@proj-airi/trace-kit/semconv'
|
||||
|
||||
import {
|
||||
METRIC_AIRI_DB_POOL_CONNECTIONS,
|
||||
|
|
@ -20,6 +30,7 @@ import {
|
|||
METRIC_AIRI_EMAIL_SEND,
|
||||
METRIC_AIRI_FLUX_CREDITED,
|
||||
METRIC_AIRI_FLUX_UNBILLED,
|
||||
METRIC_AIRI_GEN_AI_CLIENT_COST,
|
||||
METRIC_AIRI_GEN_AI_GATEWAY_CONFIG_INVALID_HMAC,
|
||||
METRIC_AIRI_GEN_AI_GATEWAY_CONFIG_RELOAD,
|
||||
METRIC_AIRI_GEN_AI_GATEWAY_DECRYPT_FAILURES,
|
||||
|
|
@ -45,11 +56,6 @@ import {
|
|||
METRIC_CHAT_MESSAGES,
|
||||
METRIC_FLUX_CONSUMED,
|
||||
METRIC_FLUX_INSUFFICIENT_BALANCE,
|
||||
METRIC_GEN_AI_CLIENT_FIRST_TOKEN_DURATION,
|
||||
METRIC_GEN_AI_CLIENT_OPERATION_COUNT,
|
||||
METRIC_GEN_AI_CLIENT_OPERATION_DURATION,
|
||||
METRIC_GEN_AI_CLIENT_TOKEN_USAGE_INPUT,
|
||||
METRIC_GEN_AI_CLIENT_TOKEN_USAGE_OUTPUT,
|
||||
METRIC_STRIPE_CHECKOUT_COMPLETED,
|
||||
METRIC_STRIPE_CHECKOUT_CREATED,
|
||||
METRIC_STRIPE_EVENTS,
|
||||
|
|
@ -143,12 +149,17 @@ export interface RevenueMetrics {
|
|||
}
|
||||
|
||||
export interface GenAiMetrics {
|
||||
/** TTS duration. Chat and Responses use `inferenceDuration`. */
|
||||
operationDuration: Histogram
|
||||
operationCount: Counter
|
||||
tokenUsageInput: Counter
|
||||
tokenUsageOutput: Counter
|
||||
inferenceDuration: Histogram
|
||||
timeToFirstChunk: Histogram
|
||||
inputTokens: Counter
|
||||
outputTokens: Counter
|
||||
cacheReadInputTokens: Counter
|
||||
cacheWriteInputTokens: Counter
|
||||
reasoningOutputTokens: Counter
|
||||
costUsd: Counter
|
||||
fluxConsumed: Counter
|
||||
firstTokenDuration: Histogram
|
||||
streamInterrupted: Counter
|
||||
}
|
||||
|
||||
|
|
@ -377,25 +388,44 @@ export function initOtel(env: Env): OtelInstance | null {
|
|||
// GenAI metrics (semconv: gen_ai.client.*)
|
||||
const genAi: GenAiMetrics = {
|
||||
operationDuration: meter.createHistogram(METRIC_GEN_AI_CLIENT_OPERATION_DURATION, {
|
||||
description: 'GenAI client operation duration',
|
||||
description: 'GenAI client operation duration (TTS)',
|
||||
unit: 's',
|
||||
}),
|
||||
operationCount: meter.createCounter(METRIC_GEN_AI_CLIENT_OPERATION_COUNT, {
|
||||
description: 'Number of GenAI client operations',
|
||||
inferenceDuration: meter.createHistogram(METRIC_GEN_AI_CLIENT_INFERENCE_DURATION, {
|
||||
description: 'GenAI client inference duration (chat and responses)',
|
||||
unit: 's',
|
||||
}),
|
||||
tokenUsageInput: meter.createCounter(METRIC_GEN_AI_CLIENT_TOKEN_USAGE_INPUT, {
|
||||
description: 'Total input (prompt) tokens consumed',
|
||||
timeToFirstChunk: meter.createHistogram(METRIC_GEN_AI_CLIENT_INFERENCE_TIME_TO_FIRST_CHUNK, {
|
||||
description: 'Time from request start to the first chunk of a streaming response',
|
||||
unit: 's',
|
||||
}),
|
||||
tokenUsageOutput: meter.createCounter(METRIC_GEN_AI_CLIENT_TOKEN_USAGE_OUTPUT, {
|
||||
description: 'Total output (completion) tokens consumed',
|
||||
inputTokens: meter.createCounter(METRIC_GEN_AI_CLIENT_INFERENCE_USAGE_INPUT_TOKENS, {
|
||||
description: 'Input (prompt) tokens, including cached tokens',
|
||||
unit: '{token}',
|
||||
}),
|
||||
outputTokens: meter.createCounter(METRIC_GEN_AI_CLIENT_INFERENCE_USAGE_OUTPUT_TOKENS, {
|
||||
description: 'Output (completion) tokens, including reasoning tokens',
|
||||
unit: '{token}',
|
||||
}),
|
||||
cacheReadInputTokens: meter.createCounter(METRIC_GEN_AI_CLIENT_INFERENCE_USAGE_CACHE_READ_INPUT_TOKENS, {
|
||||
description: 'Input tokens served from a provider-managed cache',
|
||||
unit: '{token}',
|
||||
}),
|
||||
cacheWriteInputTokens: meter.createCounter(METRIC_GEN_AI_CLIENT_INFERENCE_USAGE_CACHE_WRITE_INPUT_TOKENS, {
|
||||
description: 'Input tokens written to a provider-managed cache',
|
||||
unit: '{token}',
|
||||
}),
|
||||
reasoningOutputTokens: meter.createCounter(METRIC_GEN_AI_CLIENT_INFERENCE_USAGE_REASONING_OUTPUT_TOKENS, {
|
||||
description: 'Output tokens used for reasoning',
|
||||
unit: '{token}',
|
||||
}),
|
||||
costUsd: meter.createCounter(METRIC_AIRI_GEN_AI_CLIENT_COST, {
|
||||
description: 'Upstream inference cost in USD that the provider reports',
|
||||
unit: '{USD}',
|
||||
}),
|
||||
fluxConsumed: meter.createCounter(METRIC_FLUX_CONSUMED, {
|
||||
description: 'Total flux consumed',
|
||||
}),
|
||||
firstTokenDuration: meter.createHistogram(METRIC_GEN_AI_CLIENT_FIRST_TOKEN_DURATION, {
|
||||
description: 'Time from request start to first streamed token (TTFB for streaming)',
|
||||
unit: 's',
|
||||
}),
|
||||
streamInterrupted: meter.createCounter(METRIC_AIRI_GEN_AI_STREAM_INTERRUPTED, {
|
||||
description: 'Streaming responses interrupted before completion',
|
||||
}),
|
||||
|
|
@ -500,9 +530,12 @@ export function initOtel(env: Env): OtelInstance | null {
|
|||
revenue.fluxUnbilled,
|
||||
revenue.ttsChars,
|
||||
revenue.ttsPreflightRejections,
|
||||
genAi.operationCount,
|
||||
genAi.tokenUsageInput,
|
||||
genAi.tokenUsageOutput,
|
||||
genAi.inputTokens,
|
||||
genAi.outputTokens,
|
||||
genAi.cacheReadInputTokens,
|
||||
genAi.cacheWriteInputTokens,
|
||||
genAi.reasoningOutputTokens,
|
||||
genAi.costUsd,
|
||||
genAi.fluxConsumed,
|
||||
genAi.streamInterrupted,
|
||||
gateway.fallbackCount,
|
||||
|
|
|
|||
|
|
@ -180,9 +180,8 @@ function makeFakeDeps(overrides: {
|
|||
})),
|
||||
}
|
||||
const genAi = {
|
||||
operationCount: { add: vi.fn() },
|
||||
operationDuration: { record: vi.fn() },
|
||||
firstTokenDuration: { record: vi.fn() },
|
||||
timeToFirstChunk: { record: vi.fn() },
|
||||
}
|
||||
const configKV = {
|
||||
getOptional: vi.fn(async (key: string) => {
|
||||
|
|
@ -286,9 +285,8 @@ describe('audio-speech-ws route', () => {
|
|||
})
|
||||
|
||||
// Duration and time to first audio are recorded once, with the start frame's model.
|
||||
expect(deps.genAi.operationCount.add).toHaveBeenCalledTimes(1)
|
||||
expect(deps.genAi.operationDuration.record).toHaveBeenCalledTimes(1)
|
||||
expect(deps.genAi.firstTokenDuration.record).toHaveBeenCalledTimes(1)
|
||||
expect(deps.genAi.timeToFirstChunk.record).toHaveBeenCalledTimes(1)
|
||||
expect(deps.genAi.operationDuration.record.mock.calls[0][1]).toMatchObject({
|
||||
'gen_ai.request.model': 'volcengine/seed-tts-2.0',
|
||||
'http.response.status_code': 200,
|
||||
|
|
|
|||
|
|
@ -10,6 +10,9 @@ import WebSocket from 'ws'
|
|||
import { useLogger } from '@guiiai/logg'
|
||||
import { context as otelContext, SpanStatusCode, trace } from '@opentelemetry/api'
|
||||
import { ApiError } from '@proj-airi/http-error-shared'
|
||||
import {
|
||||
ATTR_GEN_AI_REQUEST_MODEL,
|
||||
} from '@proj-airi/trace-kit/semconv'
|
||||
import { ofetch } from 'ofetch'
|
||||
|
||||
import { nanoid } from '../../utils/id'
|
||||
|
|
@ -19,7 +22,6 @@ import {
|
|||
AIRI_ATTR_GEN_AI_GATEWAY_UPSTREAM_URL,
|
||||
AIRI_ATTR_GEN_AI_OPERATION_KIND,
|
||||
AIRI_ATTR_GEN_AI_STREAM,
|
||||
GEN_AI_ATTR_REQUEST_MODEL,
|
||||
} from '../../utils/observability'
|
||||
import { bufferToString, readUsageChars, toBufferLike } from './protocol'
|
||||
|
||||
|
|
@ -440,7 +442,7 @@ export function createSessionState(
|
|||
if (billed)
|
||||
return
|
||||
billed = true
|
||||
span.setAttribute(GEN_AI_ATTR_REQUEST_MODEL, modelLabel)
|
||||
span.setAttribute(ATTR_GEN_AI_REQUEST_MODEL, modelLabel)
|
||||
|
||||
let fluxConsumed = 0
|
||||
try {
|
||||
|
|
@ -468,15 +470,14 @@ export function createSessionState(
|
|||
|
||||
function recordMetrics() {
|
||||
const attrs = {
|
||||
[GEN_AI_ATTR_REQUEST_MODEL]: modelLabel,
|
||||
[ATTR_GEN_AI_REQUEST_MODEL]: modelLabel,
|
||||
[AIRI_ATTR_GEN_AI_OPERATION_KIND]: 'tts',
|
||||
[AIRI_ATTR_GEN_AI_STREAM]: true,
|
||||
'http.response.status_code': 200,
|
||||
}
|
||||
opts.genAi?.operationCount.add(1, attrs)
|
||||
opts.genAi?.operationDuration.record((Date.now() - startedAt) / 1000, attrs)
|
||||
if (firstAudioAt != null)
|
||||
opts.genAi?.firstTokenDuration.record((firstAudioAt - startedAt) / 1000, attrs)
|
||||
opts.genAi?.timeToFirstChunk.record((firstAudioAt - startedAt) / 1000, attrs)
|
||||
}
|
||||
|
||||
function finalize() {
|
||||
|
|
|
|||
|
|
@ -8,12 +8,14 @@ import type { FluxService } from '../../../../services/domain/flux'
|
|||
import type { UsageInfo } from '../../../../services/domain/generation-usage'
|
||||
|
||||
import { createPaymentRequiredError, createServiceUnavailableError } from '@proj-airi/http-error-shared'
|
||||
import {
|
||||
ATTR_GEN_AI_REQUEST_MODEL,
|
||||
} from '@proj-airi/trace-kit/semconv'
|
||||
import { safeParse } from 'valibot'
|
||||
|
||||
import { resolveProviderCostAdapter } from '../../../../services/adapters/llm/cost'
|
||||
import { billingPolicySchema, priceLlmCost } from '../../../../services/domain/billing/billing'
|
||||
import { availableMicroFlux, MICRO_FLUX_PER_FLUX, microFluxToFlux } from '../../../../services/domain/billing/flux-posting'
|
||||
import { GEN_AI_ATTR_REQUEST_MODEL } from '../../../../utils/observability'
|
||||
|
||||
export interface ChatFluxDebitInput extends UsageInfo {
|
||||
llmBilling: LlmBillingService
|
||||
|
|
@ -104,7 +106,7 @@ export function createOpenAiRouteBilling(deps: {
|
|||
stage: 'streaming' | 'non_streaming'
|
||||
}): void {
|
||||
deps.revenue?.fluxUnbilled.add(input.amount, {
|
||||
[GEN_AI_ATTR_REQUEST_MODEL]: input.model,
|
||||
[ATTR_GEN_AI_REQUEST_MODEL]: input.model,
|
||||
reason: 'debit_failed',
|
||||
stage: input.stage,
|
||||
})
|
||||
|
|
@ -126,7 +128,7 @@ export async function debitChatFlux(input: ChatFluxDebitInput): Promise<number>
|
|||
|
||||
if (!result.replay && result.charged < result.requested) {
|
||||
input.revenue?.fluxUnbilled.add(result.requested - result.charged, {
|
||||
[GEN_AI_ATTR_REQUEST_MODEL]: input.model,
|
||||
[ATTR_GEN_AI_REQUEST_MODEL]: input.model,
|
||||
reason: 'partial_debit_drained',
|
||||
stage: input.stage,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,9 +1,15 @@
|
|||
import type { GenAiMetrics } from '../../../../otel'
|
||||
import type { RequestLogService } from '../../../../services/domain/request-log'
|
||||
|
||||
import { ATTR_ERROR_TYPE } from '@opentelemetry/semantic-conventions'
|
||||
import {
|
||||
ATTR_GEN_AI_OPERATION_NAME,
|
||||
ATTR_GEN_AI_PROVIDER_NAME,
|
||||
ATTR_GEN_AI_RESPONSE_MODEL,
|
||||
ATTR_GEN_AI_TOKEN_MODALITY,
|
||||
} from '@proj-airi/trace-kit/semconv'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { GEN_AI_ATTR_OPERATION_NAME } from '../../../../utils/observability'
|
||||
import { createRouteTelemetry, getLlmMetricAttributes, tracer } from './telemetry'
|
||||
|
||||
describe('openAI route telemetry', () => {
|
||||
|
|
@ -14,7 +20,7 @@ describe('openAI route telemetry', () => {
|
|||
span.end()
|
||||
const startSpan = vi.spyOn(tracer, 'startSpan').mockReturnValue(span)
|
||||
const record = vi.fn()
|
||||
const genAi = Object.assign({} as GenAiMetrics, { firstTokenDuration: { record } })
|
||||
const genAi = Object.assign({} as GenAiMetrics, { timeToFirstChunk: { record } })
|
||||
const requestLogService = Object.assign({} as RequestLogService, { logRequest: vi.fn() })
|
||||
const telemetry = createRouteTelemetry({
|
||||
genAi,
|
||||
|
|
@ -25,14 +31,77 @@ describe('openAI route telemetry', () => {
|
|||
telemetry.recordFirstToken({ model: 'gpt-5', provider: 'openai', startedAt: 1000, firstChunkAt: 1500, operation: 'responses' })
|
||||
|
||||
expect(startSpan).toHaveBeenCalledWith('llm.gateway.responses', expect.objectContaining({
|
||||
attributes: expect.objectContaining({ [GEN_AI_ATTR_OPERATION_NAME]: 'responses' }),
|
||||
attributes: expect.objectContaining({ [ATTR_GEN_AI_OPERATION_NAME]: 'responses' }),
|
||||
}))
|
||||
expect(record).toHaveBeenCalledWith(0.5, expect.objectContaining({ [GEN_AI_ATTR_OPERATION_NAME]: 'responses' }))
|
||||
expect(record).toHaveBeenCalledWith(0.5, expect.objectContaining({ [ATTR_GEN_AI_OPERATION_NAME]: 'responses', [ATTR_GEN_AI_PROVIDER_NAME]: 'openai' }))
|
||||
})
|
||||
|
||||
it('attributes Responses operation metrics to the standard operation name', () => {
|
||||
expect(getLlmMetricAttributes({ model: 'gpt-5', provider: 'openai', status: 200, type: 'responses' })).toMatchObject({
|
||||
[GEN_AI_ATTR_OPERATION_NAME]: 'responses',
|
||||
[ATTR_GEN_AI_OPERATION_NAME]: 'responses',
|
||||
})
|
||||
})
|
||||
|
||||
function createRecordingTelemetry() {
|
||||
const genAi = Object.assign({} as GenAiMetrics, {
|
||||
inferenceDuration: { record: vi.fn() },
|
||||
inputTokens: { add: vi.fn() },
|
||||
outputTokens: { add: vi.fn() },
|
||||
cacheReadInputTokens: { add: vi.fn() },
|
||||
cacheWriteInputTokens: { add: vi.fn() },
|
||||
reasoningOutputTokens: { add: vi.fn() },
|
||||
costUsd: { add: vi.fn() },
|
||||
fluxConsumed: { add: vi.fn() },
|
||||
})
|
||||
const requestLogService = Object.assign({} as RequestLogService, { logRequest: vi.fn() })
|
||||
const telemetry = createRouteTelemetry({ genAi, requestLogService })
|
||||
return { genAi, telemetry }
|
||||
}
|
||||
|
||||
it('records usage, cache, reasoning, and cost with the semantic convention attributes', () => {
|
||||
const { genAi, telemetry } = createRecordingTelemetry()
|
||||
|
||||
telemetry.recordMetrics({
|
||||
model: 'gpt-5',
|
||||
responseModel: 'openai/gpt-5-2025-08-07',
|
||||
status: 200,
|
||||
type: 'chat',
|
||||
provider: 'openrouter.ai',
|
||||
durationMs: 1500,
|
||||
fluxConsumed: 3,
|
||||
promptTokens: 120,
|
||||
completionTokens: 40,
|
||||
cachedTokens: 100,
|
||||
cacheWriteTokens: 20,
|
||||
reasoningTokens: 10,
|
||||
costUsd: 0.0042,
|
||||
})
|
||||
|
||||
const attrs = {
|
||||
'gen_ai.request.model': 'gpt-5',
|
||||
[ATTR_GEN_AI_RESPONSE_MODEL]: 'openai/gpt-5-2025-08-07',
|
||||
[ATTR_GEN_AI_OPERATION_NAME]: 'chat',
|
||||
[ATTR_GEN_AI_PROVIDER_NAME]: 'openrouter.ai',
|
||||
'http.response.status_code': 200,
|
||||
}
|
||||
const tokenAttrs = { ...attrs, [ATTR_GEN_AI_TOKEN_MODALITY]: 'unknown' }
|
||||
expect(genAi.inferenceDuration.record).toHaveBeenCalledWith(1.5, attrs)
|
||||
expect(genAi.inputTokens.add).toHaveBeenCalledWith(120, tokenAttrs)
|
||||
expect(genAi.outputTokens.add).toHaveBeenCalledWith(40, tokenAttrs)
|
||||
expect(genAi.cacheReadInputTokens.add).toHaveBeenCalledWith(100, tokenAttrs)
|
||||
expect(genAi.cacheWriteInputTokens.add).toHaveBeenCalledWith(20, tokenAttrs)
|
||||
expect(genAi.reasoningOutputTokens.add).toHaveBeenCalledWith(10, attrs)
|
||||
expect(genAi.costUsd.add).toHaveBeenCalledWith(0.0042, attrs)
|
||||
})
|
||||
|
||||
it('skips missing or zero usage and marks failed requests with error.type', () => {
|
||||
const { genAi, telemetry } = createRecordingTelemetry()
|
||||
|
||||
telemetry.recordMetrics({ model: 'gpt-5', status: 502, type: 'chat', provider: 'openrouter.ai', durationMs: 10, fluxConsumed: 0, promptTokens: 0, costUsd: 0 })
|
||||
|
||||
expect(genAi.inferenceDuration.record).toHaveBeenCalledWith(0.01, expect.objectContaining({ [ATTR_ERROR_TYPE]: '502' }))
|
||||
expect(genAi.inferenceDuration.record.mock.calls[0][1]).not.toHaveProperty(ATTR_GEN_AI_RESPONSE_MODEL)
|
||||
for (const counter of [genAi.inputTokens, genAi.outputTokens, genAi.cacheReadInputTokens, genAi.cacheWriteInputTokens, genAi.reasoningOutputTokens, genAi.costUsd])
|
||||
expect(counter.add).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import type { Attributes, Counter } from '@opentelemetry/api'
|
||||
|
||||
import type { GenAiMetrics } from '../../../../otel'
|
||||
import type { GenerationObservation } from '../../../../services/domain/generation-observation'
|
||||
import type { UsageInfo } from '../../../../services/domain/generation-usage'
|
||||
|
|
@ -6,16 +8,25 @@ import type { RequestLogService } from '../../../../services/domain/request-log'
|
|||
|
||||
import { useLogger } from '@guiiai/logg'
|
||||
import { context, SpanStatusCode, trace } from '@opentelemetry/api'
|
||||
import { ATTR_ERROR_TYPE } from '@opentelemetry/semantic-conventions'
|
||||
import {
|
||||
ATTR_GEN_AI_OPERATION_NAME,
|
||||
ATTR_GEN_AI_PROVIDER_NAME,
|
||||
ATTR_GEN_AI_REQUEST_MODEL,
|
||||
ATTR_GEN_AI_RESPONSE_MODEL,
|
||||
ATTR_GEN_AI_TOKEN_MODALITY,
|
||||
ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
|
||||
ATTR_GEN_AI_USAGE_CACHE_WRITE_INPUT_TOKENS,
|
||||
ATTR_GEN_AI_USAGE_INPUT_TOKENS,
|
||||
ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,
|
||||
ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,
|
||||
} from '@proj-airi/trace-kit/semconv'
|
||||
|
||||
import {
|
||||
AIRI_ATTR_BILLING_FLUX_CONSUMED,
|
||||
AIRI_ATTR_GEN_AI_OPERATION_KIND,
|
||||
AIRI_ATTR_GEN_AI_STREAM,
|
||||
AIRI_ATTR_GEN_AI_STREAM_INTERRUPTED,
|
||||
GEN_AI_ATTR_OPERATION_NAME,
|
||||
GEN_AI_ATTR_REQUEST_MODEL,
|
||||
GEN_AI_ATTR_USAGE_INPUT_TOKENS,
|
||||
GEN_AI_ATTR_USAGE_OUTPUT_TOKENS,
|
||||
} from '../../../../utils/observability'
|
||||
|
||||
export const tracer = trace.getTracer('v1-completions')
|
||||
|
|
@ -29,33 +40,38 @@ export interface OperationMetricsInput extends UsageInfo {
|
|||
provider: string
|
||||
durationMs: number
|
||||
fluxConsumed: number
|
||||
/** Upstream cost that the provider reports. It is not the Flux charge. */
|
||||
costUsd?: number
|
||||
}
|
||||
|
||||
export type RequestLogInput = GenerationObservation
|
||||
|
||||
type GenerationOperation = 'chat' | 'responses'
|
||||
|
||||
export function getLlmMetricAttributes(opts: { model: string, type: string, status: number, provider: string }): Record<string, string | number> {
|
||||
// `provider` is the upstream the router actually used (winning upstream on
|
||||
// success, last-tried on exhaustion), so per-provider rollups in Grafana
|
||||
// line up with each vendor's own console. Same label name as the gateway
|
||||
// error counters (`airi_gen_ai_gateway_upstream_errors{provider}`) so the
|
||||
// two can be compared/joined.
|
||||
if (opts.type === 'chat' || opts.type === 'responses') {
|
||||
return {
|
||||
[GEN_AI_ATTR_REQUEST_MODEL]: opts.model,
|
||||
[GEN_AI_ATTR_OPERATION_NAME]: opts.type,
|
||||
'http.response.status_code': opts.status,
|
||||
'provider': opts.provider,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
[GEN_AI_ATTR_REQUEST_MODEL]: opts.model,
|
||||
[AIRI_ATTR_GEN_AI_OPERATION_KIND]: opts.type,
|
||||
export function getLlmMetricAttributes(opts: { model: string, type: string, status: number, provider: string, responseModel?: string }): Attributes {
|
||||
// `gen_ai.provider.name` is the upstream that the router used: the winning
|
||||
// upstream on success, or the last tried upstream on exhaustion. Gateway
|
||||
// error counters still use the `provider` label with the same value.
|
||||
const attrs: Attributes = {
|
||||
[ATTR_GEN_AI_REQUEST_MODEL]: opts.model,
|
||||
[ATTR_GEN_AI_PROVIDER_NAME]: opts.provider,
|
||||
'http.response.status_code': opts.status,
|
||||
'provider': opts.provider,
|
||||
}
|
||||
if (opts.type === 'chat' || opts.type === 'responses')
|
||||
attrs[ATTR_GEN_AI_OPERATION_NAME] = opts.type
|
||||
else
|
||||
attrs[AIRI_ATTR_GEN_AI_OPERATION_KIND] = opts.type
|
||||
if (opts.responseModel)
|
||||
attrs[ATTR_GEN_AI_RESPONSE_MODEL] = opts.responseModel
|
||||
if (opts.status >= 400)
|
||||
attrs[ATTR_ERROR_TYPE] = String(opts.status)
|
||||
return attrs
|
||||
}
|
||||
|
||||
// The semantic conventions allow only known, strictly positive token and cost measurements.
|
||||
function addPositive(counter: Counter, value: number | undefined, attrs: Attributes): void {
|
||||
if (value != null && value > 0)
|
||||
counter.add(value, attrs)
|
||||
}
|
||||
|
||||
// Fresh per-request context handed to `llmRouter.route` / `routeTts` so the
|
||||
|
|
@ -76,13 +92,16 @@ export function createRouteTelemetry(deps: {
|
|||
if (!deps.genAi)
|
||||
return
|
||||
const attrs = getLlmMetricAttributes(opts)
|
||||
deps.genAi.operationCount.add(1, attrs)
|
||||
deps.genAi.operationDuration.record(opts.durationMs / 1000, attrs)
|
||||
// Upstream usage does not split tokens by modality, so every token counter uses `unknown`.
|
||||
const tokenAttrs = { ...attrs, [ATTR_GEN_AI_TOKEN_MODALITY]: 'unknown' }
|
||||
deps.genAi.inferenceDuration.record(opts.durationMs / 1000, attrs)
|
||||
deps.genAi.fluxConsumed.add(opts.fluxConsumed, attrs)
|
||||
if (opts.promptTokens != null)
|
||||
deps.genAi.tokenUsageInput.add(opts.promptTokens, attrs)
|
||||
if (opts.completionTokens != null)
|
||||
deps.genAi.tokenUsageOutput.add(opts.completionTokens, attrs)
|
||||
addPositive(deps.genAi.inputTokens, opts.promptTokens, tokenAttrs)
|
||||
addPositive(deps.genAi.outputTokens, opts.completionTokens, tokenAttrs)
|
||||
addPositive(deps.genAi.cacheReadInputTokens, opts.cachedTokens, tokenAttrs)
|
||||
addPositive(deps.genAi.cacheWriteInputTokens, opts.cacheWriteTokens, tokenAttrs)
|
||||
addPositive(deps.genAi.reasoningOutputTokens, opts.reasoningTokens, attrs)
|
||||
addPositive(deps.genAi.costUsd, opts.costUsd, attrs)
|
||||
}
|
||||
|
||||
function recordRequestLog(entry: RequestLogInput) {
|
||||
|
|
@ -92,8 +111,8 @@ export function createRouteTelemetry(deps: {
|
|||
function startGenerationSpan(input: { model: string, stream: boolean, operation: GenerationOperation }): GatewaySpan {
|
||||
return tracer.startSpan(`llm.gateway.${input.operation}`, {
|
||||
attributes: {
|
||||
[GEN_AI_ATTR_OPERATION_NAME]: input.operation,
|
||||
[GEN_AI_ATTR_REQUEST_MODEL]: input.model,
|
||||
[ATTR_GEN_AI_OPERATION_NAME]: input.operation,
|
||||
[ATTR_GEN_AI_REQUEST_MODEL]: input.model,
|
||||
[AIRI_ATTR_GEN_AI_STREAM]: input.stream,
|
||||
},
|
||||
})
|
||||
|
|
@ -102,7 +121,7 @@ export function createRouteTelemetry(deps: {
|
|||
function startTtsSpan(input: { model: string }): GatewaySpan {
|
||||
return tracer.startSpan('llm.gateway.tts', {
|
||||
attributes: {
|
||||
[GEN_AI_ATTR_REQUEST_MODEL]: input.model,
|
||||
[ATTR_GEN_AI_REQUEST_MODEL]: input.model,
|
||||
[AIRI_ATTR_GEN_AI_OPERATION_KIND]: 'text_to_speech',
|
||||
},
|
||||
})
|
||||
|
|
@ -127,8 +146,11 @@ export function createRouteTelemetry(deps: {
|
|||
|
||||
function recordUsageOnSpan(span: GatewaySpan, input: UsageInfo & { fluxConsumed: number }): void {
|
||||
span.setAttributes({
|
||||
[GEN_AI_ATTR_USAGE_INPUT_TOKENS]: input.promptTokens ?? 0,
|
||||
[GEN_AI_ATTR_USAGE_OUTPUT_TOKENS]: input.completionTokens ?? 0,
|
||||
[ATTR_GEN_AI_USAGE_INPUT_TOKENS]: input.promptTokens ?? 0,
|
||||
[ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: input.completionTokens ?? 0,
|
||||
[ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: input.cachedTokens,
|
||||
[ATTR_GEN_AI_USAGE_CACHE_WRITE_INPUT_TOKENS]: input.cacheWriteTokens,
|
||||
[ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: input.reasoningTokens,
|
||||
[AIRI_ATTR_BILLING_FLUX_CONSUMED]: input.fluxConsumed,
|
||||
})
|
||||
}
|
||||
|
|
@ -144,10 +166,10 @@ export function createRouteTelemetry(deps: {
|
|||
firstChunkAt: number
|
||||
operation: GenerationOperation
|
||||
}): void {
|
||||
deps.genAi?.firstTokenDuration.record((input.firstChunkAt - input.startedAt) / 1000, {
|
||||
[GEN_AI_ATTR_REQUEST_MODEL]: input.model,
|
||||
[GEN_AI_ATTR_OPERATION_NAME]: input.operation,
|
||||
provider: input.provider,
|
||||
deps.genAi?.timeToFirstChunk.record((input.firstChunkAt - input.startedAt) / 1000, {
|
||||
[ATTR_GEN_AI_REQUEST_MODEL]: input.model,
|
||||
[ATTR_GEN_AI_OPERATION_NAME]: input.operation,
|
||||
[ATTR_GEN_AI_PROVIDER_NAME]: input.provider,
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -161,7 +183,7 @@ export function createRouteTelemetry(deps: {
|
|||
// Counter so alerts/dashboards can fire on interrupted streams; the
|
||||
// span attribute alone only shows up in trace search, not metrics.
|
||||
deps.genAi?.streamInterrupted.add(1, {
|
||||
[GEN_AI_ATTR_REQUEST_MODEL]: input.model,
|
||||
[ATTR_GEN_AI_REQUEST_MODEL]: input.model,
|
||||
stage: input.stage,
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -370,7 +370,7 @@ function streamChatCompletion(input: {
|
|||
|
||||
input.telemetry.recordUsageOnSpan(input.span, { ...usage, fluxConsumed: feeFlux })
|
||||
input.telemetry.endSpan(input.span)
|
||||
input.telemetry.recordMetrics({ ...usage, model: input.requestModel, status: input.response.status, type: 'chat', provider: input.routeCtxProvider, durationMs: input.durationMs, fluxConsumed: feeFlux })
|
||||
input.telemetry.recordMetrics({ ...usage, costUsd: price.costReceipt.usage.costUsd, model: input.requestModel, status: input.response.status, type: 'chat', provider: input.routeCtxProvider, durationMs: input.durationMs, fluxConsumed: feeFlux })
|
||||
|
||||
input.telemetry.recordRequestLog({
|
||||
...observation,
|
||||
|
|
@ -467,13 +467,13 @@ async function completeNonStreamingChat(input: {
|
|||
observation.errorBody = captureErrorMessage(error)
|
||||
input.telemetry.recordRequestLog({ ...observation, ...usage, status, userId: input.userId, requestId: input.requestId, model: input.requestModel })
|
||||
input.telemetry.failSpan(input.span, 'Chat settlement failed')
|
||||
input.telemetry.recordMetrics({ ...usage, model: input.requestModel, status, type: 'chat', provider: input.routeCtxProvider, durationMs: observation.durationMs, fluxConsumed: feeFlux })
|
||||
input.telemetry.recordMetrics({ ...usage, costUsd: price.costReceipt.usage.costUsd, model: input.requestModel, status, type: 'chat', provider: input.routeCtxProvider, durationMs: observation.durationMs, fluxConsumed: feeFlux })
|
||||
throw error
|
||||
}
|
||||
input.telemetry.recordRequestLog({ ...observation, ...usage, userId: input.userId, requestId: input.requestId, model: input.requestModel })
|
||||
input.telemetry.recordUsageOnSpan(input.span, { ...usage, fluxConsumed: feeFlux })
|
||||
input.telemetry.endSpan(input.span)
|
||||
input.telemetry.recordMetrics({ ...usage, model: input.requestModel, status: input.response.status, type: 'chat', provider: input.routeCtxProvider, durationMs: input.durationMs, fluxConsumed: feeFlux })
|
||||
input.telemetry.recordMetrics({ ...usage, costUsd: price.costReceipt.usage.costUsd, model: input.requestModel, status: input.response.status, type: 'chat', provider: input.routeCtxProvider, durationMs: input.durationMs, fluxConsumed: feeFlux })
|
||||
|
||||
input.logger.withFields({
|
||||
requestId: input.requestId,
|
||||
|
|
|
|||
|
|
@ -208,7 +208,7 @@ export function responsesCreate(deps: V1RouteDeps): GatewayCallback<'responses.c
|
|||
}
|
||||
telemetry.recordUsageOnSpan(span, { ...usage, fluxConsumed: feeFlux })
|
||||
telemetry.endSpan(span)
|
||||
telemetry.recordMetrics({ ...usage, model, status: upstream.status, type: 'responses', provider: routeCtx.provider, durationMs, fluxConsumed: feeFlux })
|
||||
telemetry.recordMetrics({ ...usage, costUsd: price.costReceipt.usage.costUsd, model, status: upstream.status, type: 'responses', provider: routeCtx.provider, durationMs, fluxConsumed: feeFlux })
|
||||
telemetry.recordRequestLog({ ...observation, ...usage, timeToFirstTokenMs, userId: input.userId, requestId, model, status: upstream.status, durationMs })
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -72,11 +72,15 @@ function createMockBillingService(flux = 100): BillingService {
|
|||
function createMockGenAiMetrics(): GenAiMetrics {
|
||||
return {
|
||||
operationDuration: { record: vi.fn() },
|
||||
operationCount: { add: vi.fn() },
|
||||
tokenUsageInput: { add: vi.fn() },
|
||||
tokenUsageOutput: { add: vi.fn() },
|
||||
inferenceDuration: { record: vi.fn() },
|
||||
timeToFirstChunk: { record: vi.fn() },
|
||||
inputTokens: { add: vi.fn() },
|
||||
outputTokens: { add: vi.fn() },
|
||||
cacheReadInputTokens: { add: vi.fn() },
|
||||
cacheWriteInputTokens: { add: vi.fn() },
|
||||
reasoningOutputTokens: { add: vi.fn() },
|
||||
costUsd: { add: vi.fn() },
|
||||
fluxConsumed: { add: vi.fn() },
|
||||
firstTokenDuration: { record: vi.fn() },
|
||||
streamInterrupted: { add: vi.fn() },
|
||||
} as unknown as GenAiMetrics
|
||||
}
|
||||
|
|
@ -596,6 +600,10 @@ describe('v1CompletionsRoutes', () => {
|
|||
)
|
||||
// Telemetry reports the 38 Flux fee, not the 5 Flux that the drained wallet could pay.
|
||||
expect(genAi.fluxConsumed.add).toHaveBeenCalledWith(38, expect.anything())
|
||||
// Cost and tokens are the upstream usage, also when the wallet cannot pay all of it.
|
||||
expect(genAi.costUsd.add).toHaveBeenCalledWith(0.038, expect.objectContaining({ 'gen_ai.operation.name': 'chat' }))
|
||||
expect(genAi.inputTokens.add).toHaveBeenCalledWith(20000, expect.objectContaining({ 'gen_ai.token.modality': 'unknown' }))
|
||||
expect(genAi.outputTokens.add).toHaveBeenCalledWith(18000, expect.objectContaining({ 'gen_ai.token.modality': 'unknown' }))
|
||||
})
|
||||
|
||||
it('should proxy upstream response on success', async () => {
|
||||
|
|
@ -3043,7 +3051,7 @@ describe('issue #2479 hosted Responses', () => {
|
|||
}, { user: testUser })
|
||||
|
||||
expect(response.status).toBe(502)
|
||||
expect(metrics.operationCount.add).toHaveBeenCalledWith(1, expect.objectContaining({ provider: 'openai' }))
|
||||
expect(metrics.inferenceDuration.record).toHaveBeenCalledWith(expect.any(Number), expect.objectContaining({ 'gen_ai.provider.name': 'openai', 'error.type': '502' }))
|
||||
})
|
||||
|
||||
it('rejects invalid JSON and insufficient balance before routing', async () => {
|
||||
|
|
@ -3118,7 +3126,7 @@ describe('issue #2479 hosted Responses', () => {
|
|||
const response = await harness.send({ stream: true })
|
||||
const reader = response.body!.getReader()
|
||||
await reader.read()
|
||||
expect(metrics.firstTokenDuration.record).not.toHaveBeenCalled()
|
||||
expect(metrics.timeToFirstChunk.record).not.toHaveBeenCalled()
|
||||
|
||||
now = 1500
|
||||
upstream!.enqueue(encoder.encode('event: response.output_text.delta\ndata: {"type":"response.output_text.delta","delta":"hello"}\n\n'))
|
||||
|
|
@ -3128,7 +3136,7 @@ describe('issue #2479 hosted Responses', () => {
|
|||
while (!result.done)
|
||||
result = await reader.read()
|
||||
|
||||
expect(metrics.firstTokenDuration.record).toHaveBeenCalledWith(0.5, expect.objectContaining({ 'gen_ai.operation.name': 'responses' }))
|
||||
expect(metrics.timeToFirstChunk.record).toHaveBeenCalledWith(0.5, expect.objectContaining({ 'gen_ai.operation.name': 'responses' }))
|
||||
}
|
||||
finally {
|
||||
nowSpy.mockRestore()
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@
|
|||
* Grafana until an event happens — making panels look broken on fresh deploys
|
||||
* and absence-based alerts impossible to author.
|
||||
*
|
||||
* Histograms (gen_ai.client.first_token.duration, airi.email.duration, ...)
|
||||
* Histograms (gen_ai.client.inference.duration, airi.email.duration, ...)
|
||||
* are intentionally NOT in the output — they only register on first .record().
|
||||
*
|
||||
* NOTE: Run WITHOUT `--import ./instrumentation.ts`. The preload would start
|
||||
|
|
|
|||
|
|
@ -8,13 +8,16 @@ import type { VoicePackService } from '../voice-packs'
|
|||
import { useLogger } from '@guiiai/logg'
|
||||
import { context, SpanStatusCode, trace } from '@opentelemetry/api'
|
||||
import { ApiError, createBadRequestError, createPaymentRequiredError } from '@proj-airi/http-error-shared'
|
||||
import {
|
||||
ATTR_GEN_AI_PROVIDER_NAME,
|
||||
ATTR_GEN_AI_REQUEST_MODEL,
|
||||
} from '@proj-airi/trace-kit/semconv'
|
||||
import { check, pipe, safeParse, string, transform } from 'valibot'
|
||||
|
||||
import { nanoid } from '../../../utils/id'
|
||||
import {
|
||||
AIRI_ATTR_BILLING_FLUX_CONSUMED,
|
||||
AIRI_ATTR_GEN_AI_OPERATION_KIND,
|
||||
GEN_AI_ATTR_REQUEST_MODEL,
|
||||
} from '../../../utils/observability'
|
||||
|
||||
const tracer = trace.getTracer('v1-completions')
|
||||
|
|
@ -169,7 +172,7 @@ export function createOpenAiSpeechService(deps: OpenAiSpeechServiceDeps) {
|
|||
|
||||
const span = tracer.startSpan('llm.gateway.tts', {
|
||||
attributes: {
|
||||
[GEN_AI_ATTR_REQUEST_MODEL]: requestModel,
|
||||
[ATTR_GEN_AI_REQUEST_MODEL]: requestModel,
|
||||
[AIRI_ATTR_GEN_AI_OPERATION_KIND]: 'text_to_speech',
|
||||
},
|
||||
})
|
||||
|
|
@ -260,12 +263,11 @@ export function createOpenAiSpeechService(deps: OpenAiSpeechServiceDeps) {
|
|||
fluxConsumed: number
|
||||
}): void {
|
||||
const attrs = {
|
||||
[GEN_AI_ATTR_REQUEST_MODEL]: input.model,
|
||||
[ATTR_GEN_AI_REQUEST_MODEL]: input.model,
|
||||
[AIRI_ATTR_GEN_AI_OPERATION_KIND]: 'tts',
|
||||
[ATTR_GEN_AI_PROVIDER_NAME]: input.provider,
|
||||
'http.response.status_code': input.status,
|
||||
'provider': input.provider,
|
||||
}
|
||||
deps.genAi?.operationCount.add(1, attrs)
|
||||
deps.genAi?.operationDuration.record(input.durationMs / 1000, attrs)
|
||||
deps.genAi?.fluxConsumed.add(input.fluxConsumed, attrs)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,13 +2,7 @@
|
|||
// Span attribute constants (OTel semantic conventions + AIRI custom)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// GenAI semconv attributes — https://opentelemetry.io/docs/specs/semconv/gen-ai/
|
||||
export const GEN_AI_ATTR_OPERATION_NAME = 'gen_ai.operation.name'
|
||||
export const GEN_AI_ATTR_REQUEST_MODEL = 'gen_ai.request.model'
|
||||
export const GEN_AI_ATTR_RESPONSE_MODEL = 'gen_ai.response.model'
|
||||
export const GEN_AI_ATTR_SYSTEM = 'gen_ai.system'
|
||||
export const GEN_AI_ATTR_USAGE_INPUT_TOKENS = 'gen_ai.usage.input_tokens'
|
||||
export const GEN_AI_ATTR_USAGE_OUTPUT_TOKENS = 'gen_ai.usage.output_tokens'
|
||||
// GenAI semconv attributes come from `@proj-airi/trace-kit/semconv`.
|
||||
|
||||
// AIRI custom span attributes
|
||||
export const AIRI_ATTR_BILLING_FLUX_CONSUMED = 'airi.billing.flux_consumed'
|
||||
|
|
@ -64,11 +58,9 @@ export const METRIC_STRIPE_CHECKOUT_COMPLETED = 'stripe.checkout.completed'
|
|||
export const METRIC_STRIPE_EVENTS = 'stripe.events'
|
||||
export const METRIC_FLUX_INSUFFICIENT_BALANCE = 'flux.insufficient_balance'
|
||||
|
||||
// GenAI — https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-metrics/
|
||||
export const METRIC_GEN_AI_CLIENT_OPERATION_DURATION = 'gen_ai.client.operation.duration'
|
||||
export const METRIC_GEN_AI_CLIENT_OPERATION_COUNT = 'gen_ai.client.operation.count'
|
||||
export const METRIC_GEN_AI_CLIENT_TOKEN_USAGE_INPUT = 'gen_ai.client.token.usage.input'
|
||||
export const METRIC_GEN_AI_CLIENT_TOKEN_USAGE_OUTPUT = 'gen_ai.client.token.usage.output'
|
||||
// GenAI semconv metric names come from `@proj-airi/trace-kit/semconv`.
|
||||
// The conventions have no cost metric. This counter is the provider-reported upstream cost in USD.
|
||||
export const METRIC_AIRI_GEN_AI_CLIENT_COST = 'airi.gen_ai.client.cost'
|
||||
export const METRIC_FLUX_CONSUMED = 'airi.billing.flux.consumed'
|
||||
|
||||
// AIRI billing — credit/debit visibility beyond raw consumption
|
||||
|
|
@ -99,7 +91,6 @@ export const METRIC_AIRI_RATE_LIMIT_BLOCKED = 'airi.rate_limit.blocked'
|
|||
|
||||
// AIRI GenAI — stream quality
|
||||
export const METRIC_AIRI_GEN_AI_STREAM_INTERRUPTED = 'airi.gen_ai.stream.interrupted'
|
||||
export const METRIC_GEN_AI_CLIENT_FIRST_TOKEN_DURATION = 'gen_ai.client.first_token.duration'
|
||||
|
||||
// AIRI router gateway — in-process LLM/TTS routing fallback / health signals.
|
||||
//
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue