@telemetry-dev/tanstack-ai 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +95 -0
- package/dist/index.d.mts +40 -0
- package/dist/index.mjs +681 -0
- package/package.json +62 -0
- package/src/config.ts +48 -0
- package/src/index.ts +2 -0
- package/src/middleware.ts +659 -0
- package/src/otel.ts +247 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 telemetry.dev
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# @telemetry-dev/tanstack-ai
|
|
2
|
+
|
|
3
|
+
TanStack AI telemetry integration for [telemetry.dev](https://telemetry.dev). A `chat()` middleware
|
|
4
|
+
that streams every run to the telemetry.dev ingest API. Each `chat()` call is its own OTel trace: a
|
|
5
|
+
root span (operation `chat`, or `invoke_agent` once tools are used), a `chat` span per agent-loop
|
|
6
|
+
iteration, and an `execute_tool` span per tool call — spans are typed by `gen_ai.operation.name`.
|
|
7
|
+
Conversations are carried by `gen_ai.conversation.id` (lifted from `metadata.sessionId`, falling
|
|
8
|
+
back to the chat's `threadId`), not by sharing one trace.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @telemetry-dev/tanstack-ai @tanstack/ai
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Requires `@tanstack/ai >= 0.28.0 < 1`.
|
|
17
|
+
|
|
18
|
+
## Environment
|
|
19
|
+
|
|
20
|
+
| Variable | Required | Default | Notes |
|
|
21
|
+
| --------------------------- | -------- | ------------------------------ | ---------------------------------------------------------------------- |
|
|
22
|
+
| `TELEMETRY_DEV_API_KEY` | yes | — | Ingest key (`td_live_…`). No key ⇒ the middleware is a complete no-op. |
|
|
23
|
+
| `TELEMETRY_DEV_BASE_URL` | no | `https://ingest.telemetry.dev` | Trailing slashes are stripped. |
|
|
24
|
+
| `TELEMETRY_DEV_ENVIRONMENT` | no | `production` | Environment label on every trace. |
|
|
25
|
+
| `OTEL_SERVICE_NAME` | no | `unknown_service` | Service name on every trace. |
|
|
26
|
+
|
|
27
|
+
All four are also settable via `telemetryDev({ apiKey, baseUrl, environment, serviceName })`, which
|
|
28
|
+
takes precedence over the environment.
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { chat } from "@tanstack/ai";
|
|
34
|
+
import { openaiText } from "@tanstack/ai-openai";
|
|
35
|
+
import { telemetryDev } from "@telemetry-dev/tanstack-ai";
|
|
36
|
+
|
|
37
|
+
const stream = chat({
|
|
38
|
+
adapter: openaiText("gpt-4o"),
|
|
39
|
+
messages,
|
|
40
|
+
metadata: { userId: "u_123", sessionId: "s_456", tenant: "acme" },
|
|
41
|
+
middleware: [telemetryDev()],
|
|
42
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`metadata.userId` is recorded as the `user.id` span attribute and `metadata.sessionId` as
|
|
46
|
+
`gen_ai.conversation.id` (when absent, the chat's `threadId` is used); any remaining metadata keys
|
|
47
|
+
ride along as `td.metadata.<key>` attributes. Each call is its own trace — `sessionId` only
|
|
48
|
+
correlates calls through `gen_ai.conversation.id`, it never merges them into a single trace.
|
|
49
|
+
|
|
50
|
+
A single `telemetryDev()` instance is **concurrency-safe**: per-run state is keyed by the chat's
|
|
51
|
+
middleware context, so you can create one at module scope and share it across overlapping `chat()`
|
|
52
|
+
calls:
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
const telemetry = telemetryDev();
|
|
56
|
+
|
|
57
|
+
// reuse in every handler
|
|
58
|
+
chat({ adapter, messages, middleware: [telemetry] });
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Serverless (Cloudflare Workers etc.)
|
|
62
|
+
|
|
63
|
+
By default the terminal hook awaits the ingest POST so the runtime doesn't tear down before it
|
|
64
|
+
flushes. Supply `waitUntil` to hand the POST off to the platform instead:
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
telemetryDev({ waitUntil: (p) => ctx.waitUntil(p) });
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## What gets captured
|
|
71
|
+
|
|
72
|
+
- **Tokens:** input/output per iteration, plus cache-read, cache-write, and reasoning token
|
|
73
|
+
breakdowns and provider-reported cost when the adapter supplies them
|
|
74
|
+
(`gen_ai.usage.cache_read.input_tokens`, `gen_ai.usage.cache_creation.input_tokens`,
|
|
75
|
+
`gen_ai.usage.reasoning.output_tokens`, `gen_ai.usage.cost`). Absent fields are omitted, never
|
|
76
|
+
zeroed; when no provider cost is reported, cost is computed server-side from pricing tables.
|
|
77
|
+
- **Content:** the per-iteration request messages (`gen_ai.input.messages`, exactly what the
|
|
78
|
+
adapter sends) and the assistant text (`gen_ai.output.messages`); tool calls carry
|
|
79
|
+
`gen_ai.tool.call.arguments` / `gen_ai.tool.call.result`.
|
|
80
|
+
- **Sampling:** `gen_ai.request.temperature` / `top_p` / `max_tokens`, read across provider-native
|
|
81
|
+
spellings (including Ollama's nested `options`).
|
|
82
|
+
- **Errors:** a run that errors or aborts is still flushed — open spans are closed with
|
|
83
|
+
`status: "error"` and an `error.type` attribute (`"cancelled"` for aborts); failed tool calls get
|
|
84
|
+
an `exception` event.
|
|
85
|
+
- **Structured output:** when `chat({ outputSchema })` finalizes through a separate
|
|
86
|
+
structured-output model call, that call gets its own span (`gen_ai.output.type: "json"`, output
|
|
87
|
+
set to the raw JSON) and its usage is counted alongside — never instead of — the agent loop's.
|
|
88
|
+
- **Metrics:** `gen_ai.client.operation.duration` per iteration and tool call, and
|
|
89
|
+
`gen_ai.client.token.usage` per iteration, both following the OTel GenAI semantic conventions.
|
|
90
|
+
|
|
91
|
+
## Limitations
|
|
92
|
+
|
|
93
|
+
- **TTFT:** time-to-first-chunk is not currently reported.
|
|
94
|
+
- Middleware hook exceptions are wrapped in `try/catch` and routed to the optional `onError`
|
|
95
|
+
callback so instrumentation can never break your chat.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { Attributes } from "@opentelemetry/api";
|
|
2
|
+
import { ReadableSpan } from "@opentelemetry/sdk-trace-base";
|
|
3
|
+
import { ChatMiddleware } from "@tanstack/ai";
|
|
4
|
+
|
|
5
|
+
//#region src/config.d.ts
|
|
6
|
+
interface TelemetryDevOptions {
|
|
7
|
+
/** telemetry.dev ingest key (`td_live_…`). Falls back to `TELEMETRY_DEV_API_KEY`. When absent the integration is a no-op. */
|
|
8
|
+
apiKey?: string;
|
|
9
|
+
/** Ingest base URL. Falls back to `TELEMETRY_DEV_BASE_URL`, then `https://ingest.telemetry.dev`. */
|
|
10
|
+
baseUrl?: string;
|
|
11
|
+
/** Deployment environment label. Falls back to `TELEMETRY_DEV_ENVIRONMENT`, then `production`. */
|
|
12
|
+
environment?: string;
|
|
13
|
+
/** Service name attached to every trace. Falls back to `OTEL_SERVICE_NAME`, then `unknown_service`. */
|
|
14
|
+
serviceName?: string;
|
|
15
|
+
/** Injected fetch implementation. Defaults to `globalThis.fetch`. */
|
|
16
|
+
fetch?: typeof fetch;
|
|
17
|
+
/** Serverless extender (e.g. Cloudflare `ctx.waitUntil`). When provided, `onFinish` does not await the POST. */
|
|
18
|
+
waitUntil?: (p: Promise<unknown>) => void;
|
|
19
|
+
/** Receives any error raised while emitting telemetry; the integration never throws into the SDK. */
|
|
20
|
+
onError?: (error: unknown) => void;
|
|
21
|
+
}
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region src/otel.d.ts
|
|
24
|
+
interface EmitterOverrides {
|
|
25
|
+
sendSpans?: (spans: ReadableSpan[]) => Promise<void>;
|
|
26
|
+
recordDuration?: (seconds: number, attributes: Attributes) => void;
|
|
27
|
+
recordTokens?: (tokenType: "input" | "output", count: number, attributes: Attributes) => void;
|
|
28
|
+
}
|
|
29
|
+
//#endregion
|
|
30
|
+
//#region src/middleware.d.ts
|
|
31
|
+
/**
|
|
32
|
+
* Build a TanStack AI chat middleware that streams `chat()` runs to telemetry.dev as
|
|
33
|
+
* OpenTelemetry GenAI (`gen_ai.*`) spans + metrics: one root span per `chat()` call, one CLIENT
|
|
34
|
+
* span per agent-loop iteration, and one span per tool execution. Per-run state is keyed by the
|
|
35
|
+
* middleware context in a WeakMap, so a single `telemetryDev()` instance is safe to share across
|
|
36
|
+
* concurrent and overlapping `chat()` calls (e.g. registered once at module scope).
|
|
37
|
+
*/
|
|
38
|
+
declare function telemetryDev(options?: TelemetryDevOptions, overrides?: EmitterOverrides): ChatMiddleware;
|
|
39
|
+
//#endregion
|
|
40
|
+
export { type TelemetryDevOptions, telemetryDev };
|