@telemetry-dev/sdk 0.1.10 → 0.1.12
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/README.md +68 -0
- package/dist/index.d.mts +156 -2
- package/dist/index.mjs +329 -3
- package/package.json +1 -1
- package/src/config.ts +1 -1
- package/src/index.ts +19 -0
- package/src/prompts.ts +740 -0
- package/src/span.ts +3 -0
package/README.md
CHANGED
|
@@ -111,6 +111,72 @@ The default is parent-based always-on. Session roots keep the configured root po
|
|
|
111
111
|
Nested spans and explicitly parented spans keep the real parent's policy.
|
|
112
112
|
The SDK installs the [session sampling wrapper](https://github.com/telemetry-dev/telemetry/blob/main/packages/otel/README.md#correlation-attributes) on its provider. This includes the global provider that Eve uses.
|
|
113
113
|
|
|
114
|
+
## Prompts
|
|
115
|
+
|
|
116
|
+
`getPrompt` fetches a prompt that you manage in telemetry.dev. Fetch it by its label, so that you
|
|
117
|
+
deploy a version when you move the label, without a change to the code:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import OpenAI from "openai";
|
|
121
|
+
import { getPrompt, init, withPrompt } from "@telemetry-dev/sdk";
|
|
122
|
+
import { wrapOpenAI } from "@telemetry-dev/openai";
|
|
123
|
+
|
|
124
|
+
init();
|
|
125
|
+
const openai = wrapOpenAI(new OpenAI());
|
|
126
|
+
|
|
127
|
+
const prompt = await getPrompt("support/reply", { label: "production" });
|
|
128
|
+
const messages = prompt.compile({ customer_message, tone });
|
|
129
|
+
|
|
130
|
+
const response = await withPrompt(prompt, () =>
|
|
131
|
+
openai.chat.completions.create({ model: prompt.model?.name ?? "gpt-4o", messages }),
|
|
132
|
+
);
|
|
133
|
+
|
|
134
|
+
// Pin one version, as in a test:
|
|
135
|
+
const pinned = await getPrompt("support/reply", { version: 13 });
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
- Without `label` and `version`, getPrompt fetches the `production` label. A text prompt needs
|
|
139
|
+
`type: "text"`; getPrompt rejects a prompt of the other type.
|
|
140
|
+
- `compile(variables)` puts the values in place of `{{name}}`. A missing value becomes an empty
|
|
141
|
+
text, and a value that is not a string becomes JSON. In a chat prompt, a placeholder message
|
|
142
|
+
becomes the list of messages in its variable. A text prompt compiles to a string.
|
|
143
|
+
- The prompt also has `model`, `parameters`, `tools`, and `responseFormat` of its version.
|
|
144
|
+
- getPrompt keeps each prompt. When the copy is older than `cacheTtlSeconds` (default 60), a call
|
|
145
|
+
returns it at once and fetches a new copy in the background. Only a call with no copy waits for a
|
|
146
|
+
fetch, for 10 seconds at most. Calls for the same prompt share one fetch.
|
|
147
|
+
- If a fetch fails, getPrompt returns the last copy that it fetched and reports the error through
|
|
148
|
+
`onError`. With no copy, it returns the `fallback` option (`version` is `null` and `isFallback`
|
|
149
|
+
is `true`). With no fallback, it rejects with a `PromptError` whose `code` tells why, for
|
|
150
|
+
example `prompt_not_found`, `label_not_found`, `insufficient_scope`, `missing_api_key`, or
|
|
151
|
+
`timeout`. A response with a different status and no API error gives `http_<status>`, for
|
|
152
|
+
example `http_302` for a redirect. getPrompt does not send the request to the location of a
|
|
153
|
+
redirect, thus your key does not go to a different host. With no copy, the calls of the next 10
|
|
154
|
+
seconds (or the TTL, if it is shorter) get the same result without a fetch. After a 429 or 503
|
|
155
|
+
response with a `Retry-After` header, getPrompt does not fetch that prompt again before that time
|
|
156
|
+
(one hour at most). This is the one SDK function that can reject: your app cannot run without
|
|
157
|
+
its prompt.
|
|
158
|
+
- getPrompt uses the API key and base URL of an enabled `init()`, or `TELEMETRY_DEV_API_KEY` and
|
|
159
|
+
`TELEMETRY_DEV_BASE_URL`, or its own `apiKey`, `baseUrl`, and `fetch` options. It reads the same
|
|
160
|
+
host that telemetry goes to, `https://ingest.telemetry.dev` by default. The key needs the read
|
|
161
|
+
scope for prompts.
|
|
162
|
+
- When a label sends part of the traffic to a second version, each session keeps one version: the
|
|
163
|
+
choice uses the session id of `propagateAttributes` (or of `sessionMode: "process"`). Without a
|
|
164
|
+
session id, each call chooses at random.
|
|
165
|
+
|
|
166
|
+
`withPrompt(prompt, fn)` records the prompt on each model call that starts inside `fn`:
|
|
167
|
+
`td.prompt.name`, `td.prompt.version`, and `td.prompt.label` (only for a prompt fetched by label).
|
|
168
|
+
When input capture is on, `td.prompt.variables` holds the JSON of the variables of the last
|
|
169
|
+
`compile()` of that prompt object before `withPrompt` starts, or of the last `compile()` inside
|
|
170
|
+
`fn`, after `mask` and truncation. If tasks that run at the same time share one prompt object, call
|
|
171
|
+
`compile()` in `withPrompt`, or call getPrompt in each task. getPrompt returns a new object from
|
|
172
|
+
the cache. If you do not, a task can record the variables of a different task. Tasks that run at the
|
|
173
|
+
same time inside one `withPrompt` share its variables, so call `withPrompt` in each task that
|
|
174
|
+
compiles its own. Model calls are the spans of type `generation` (operations `chat`,
|
|
175
|
+
`text_completion`, and `generate_content`), including the spans of the provider integrations that
|
|
176
|
+
use this SDK: OpenAI, Anthropic, Amazon Bedrock, Google GenAI, and OpenRouter. Spans from the AI SDK
|
|
177
|
+
and TanStack AI integrations, and from other OpenTelemetry tracers, do not get the attributes.
|
|
178
|
+
Messages from `compile()` that you pass to a model call outside `withPrompt` are not recorded.
|
|
179
|
+
|
|
114
180
|
## API
|
|
115
181
|
|
|
116
182
|
- `init(options?)` — create the client (isolated OTel TracerProvider by default).
|
|
@@ -130,6 +196,8 @@ The SDK installs the [session sampling wrapper](https://github.com/telemetry-dev
|
|
|
130
196
|
- `updateActiveSpan(fields)` — update the innermost active span.
|
|
131
197
|
- `propagateAttributes({ userId, sessionId, metadata }, fn)` — stamps `user.id`,
|
|
132
198
|
`gen_ai.conversation.id`, and `td.metadata.*` on every span and log record in scope.
|
|
199
|
+
- `getPrompt(name, options?)` — fetch a prompt by label or version; see [Prompts](#prompts).
|
|
200
|
+
- `withPrompt(prompt, fn)` — record the prompt on each model call in `fn`.
|
|
133
201
|
- `log(message, { level, eventName, attributes }?)` — log record correlated to the active trace.
|
|
134
202
|
- `getTraceparent()` — W3C traceparent of the active span (pass to other services; accept it via
|
|
135
203
|
`startSpan(name, { parent })`).
|
package/dist/index.d.mts
CHANGED
|
@@ -16,7 +16,7 @@ type MaskFn<T = unknown> = (value: T, ctx: {
|
|
|
16
16
|
interface TelemetryOptions {
|
|
17
17
|
/** telemetry.dev ingest key (`td_live_…`). Falls back to `TELEMETRY_DEV_API_KEY`. When absent the SDK is a no-op. */
|
|
18
18
|
apiKey?: string;
|
|
19
|
-
/**
|
|
19
|
+
/** Base URL for telemetry export and getPrompt. Falls back to `TELEMETRY_DEV_BASE_URL`, then `https://ingest.telemetry.dev`. */
|
|
20
20
|
baseUrl?: string;
|
|
21
21
|
/** Deployment environment label. Falls back to `TELEMETRY_DEV_ENVIRONMENT`, then `production`. */
|
|
22
22
|
environment?: string;
|
|
@@ -257,4 +257,158 @@ interface ObserveOptions extends StartSpanOptions {
|
|
|
257
257
|
*/
|
|
258
258
|
declare function observe<TThis, TArgs extends unknown[], TReturn>(fn: (this: TThis, ...args: TArgs) => TReturn, options?: ObserveOptions): (...args: TArgs) => TReturn;
|
|
259
259
|
//#endregion
|
|
260
|
-
|
|
260
|
+
//#region src/prompts.d.ts
|
|
261
|
+
/** A message of a chat prompt. A placeholder stands for a list of messages that the app passes. */
|
|
262
|
+
type PromptMessage = {
|
|
263
|
+
readonly role: "system" | "user" | "assistant";
|
|
264
|
+
readonly content: string;
|
|
265
|
+
} | {
|
|
266
|
+
readonly role: "placeholder";
|
|
267
|
+
readonly name: string;
|
|
268
|
+
};
|
|
269
|
+
/** A message that `compile()` makes from a prompt message. */
|
|
270
|
+
interface ChatMessage {
|
|
271
|
+
role: "system" | "user" | "assistant";
|
|
272
|
+
content: string;
|
|
273
|
+
}
|
|
274
|
+
interface PromptModel {
|
|
275
|
+
readonly provider: string;
|
|
276
|
+
readonly name: string;
|
|
277
|
+
}
|
|
278
|
+
/** The parameters that are set in the version. A parameter that is not set is absent. */
|
|
279
|
+
interface PromptParameters {
|
|
280
|
+
readonly temperature?: number;
|
|
281
|
+
readonly topP?: number;
|
|
282
|
+
readonly maxTokens?: number;
|
|
283
|
+
readonly frequencyPenalty?: number;
|
|
284
|
+
readonly presencePenalty?: number;
|
|
285
|
+
readonly stop?: readonly string[];
|
|
286
|
+
readonly seed?: number;
|
|
287
|
+
readonly toolChoice?: "auto" | "none" | "required" | {
|
|
288
|
+
readonly tool: string;
|
|
289
|
+
};
|
|
290
|
+
readonly parallelToolCalls?: boolean;
|
|
291
|
+
}
|
|
292
|
+
interface PromptTool {
|
|
293
|
+
readonly name: string;
|
|
294
|
+
readonly description: string;
|
|
295
|
+
/** JSON schema of the tool arguments. */
|
|
296
|
+
readonly parameters: Readonly<Record<string, unknown>>;
|
|
297
|
+
readonly strict: boolean;
|
|
298
|
+
}
|
|
299
|
+
type PromptResponseFormat = {
|
|
300
|
+
readonly type: "text";
|
|
301
|
+
} | {
|
|
302
|
+
readonly type: "json_object";
|
|
303
|
+
} | {
|
|
304
|
+
readonly type: "json_schema";
|
|
305
|
+
readonly name: string;
|
|
306
|
+
readonly schema: Readonly<Record<string, unknown>>;
|
|
307
|
+
readonly strict: boolean;
|
|
308
|
+
};
|
|
309
|
+
/**
|
|
310
|
+
* Values for `{{name}}` variables. A missing value, null, or undefined becomes an empty text, and a
|
|
311
|
+
* value that is not a string becomes JSON. A placeholder message takes a list of messages.
|
|
312
|
+
*/
|
|
313
|
+
type PromptVariables<M = ChatMessage> = Readonly<Record<string, string | number | boolean | null | undefined | readonly M[]>>;
|
|
314
|
+
interface PromptBase {
|
|
315
|
+
readonly name: string;
|
|
316
|
+
/** The version that the app got; null for the fallback. */
|
|
317
|
+
readonly version: number | null;
|
|
318
|
+
/** The label that the prompt was fetched by; null when it was fetched by version. */
|
|
319
|
+
readonly label: string | null;
|
|
320
|
+
/** Null for the fallback. */
|
|
321
|
+
readonly model: PromptModel | null;
|
|
322
|
+
readonly parameters: PromptParameters;
|
|
323
|
+
readonly tools: readonly PromptTool[];
|
|
324
|
+
readonly responseFormat: PromptResponseFormat;
|
|
325
|
+
/** True when getPrompt could not fetch the prompt and returned the `fallback` option. */
|
|
326
|
+
readonly isFallback: boolean;
|
|
327
|
+
}
|
|
328
|
+
interface ChatPrompt extends PromptBase {
|
|
329
|
+
readonly type: "chat";
|
|
330
|
+
readonly messages: readonly PromptMessage[];
|
|
331
|
+
readonly text: null;
|
|
332
|
+
/**
|
|
333
|
+
* Fills in the variables and replaces each placeholder message with the messages in its
|
|
334
|
+
* variable. `withPrompt` records the variables of the last call before it starts or inside it.
|
|
335
|
+
*/
|
|
336
|
+
compile<M = ChatMessage>(variables?: PromptVariables<M>): (ChatMessage | M)[];
|
|
337
|
+
}
|
|
338
|
+
interface TextPrompt extends PromptBase {
|
|
339
|
+
readonly type: "text";
|
|
340
|
+
readonly messages: readonly [];
|
|
341
|
+
readonly text: string;
|
|
342
|
+
/**
|
|
343
|
+
* Fills in the variables. `withPrompt` records the variables of the last call before it starts
|
|
344
|
+
* or inside it.
|
|
345
|
+
*/
|
|
346
|
+
compile(variables?: PromptVariables): string;
|
|
347
|
+
}
|
|
348
|
+
type Prompt = ChatPrompt | TextPrompt;
|
|
349
|
+
interface GetPromptOptionsBase {
|
|
350
|
+
/** Fetch the version that this label points to. Default "production" when `version` is not set. */
|
|
351
|
+
label?: string;
|
|
352
|
+
/** Fetch this version number. Do not set it together with `label`. */
|
|
353
|
+
version?: number;
|
|
354
|
+
/** Seconds before a call fetches a kept prompt again, in the background. Default 60. */
|
|
355
|
+
cacheTtlSeconds?: number;
|
|
356
|
+
/** API key with the prompts:read scope. Falls back to the initialized client, then `TELEMETRY_DEV_API_KEY`. */
|
|
357
|
+
apiKey?: string;
|
|
358
|
+
/** Falls back to the initialized client, then `TELEMETRY_DEV_BASE_URL`, then `https://ingest.telemetry.dev`. */
|
|
359
|
+
baseUrl?: string;
|
|
360
|
+
/** Falls back to the initialized client's `fetch`, then `globalThis.fetch`. */
|
|
361
|
+
fetch?: typeof fetch;
|
|
362
|
+
}
|
|
363
|
+
interface GetChatPromptOptions extends GetPromptOptionsBase {
|
|
364
|
+
/** Default "chat". getPrompt rejects a prompt of the other type. */
|
|
365
|
+
type?: "chat";
|
|
366
|
+
/** Messages to use when the prompt cannot be fetched and no copy of it is kept. */
|
|
367
|
+
fallback?: readonly PromptMessage[];
|
|
368
|
+
}
|
|
369
|
+
interface GetTextPromptOptions extends GetPromptOptionsBase {
|
|
370
|
+
type: "text";
|
|
371
|
+
/** Text to use when the prompt cannot be fetched and no copy of it is kept. */
|
|
372
|
+
fallback?: string;
|
|
373
|
+
}
|
|
374
|
+
type GetPromptOptions = GetChatPromptOptions | GetTextPromptOptions;
|
|
375
|
+
/**
|
|
376
|
+
* Why getPrompt failed. `code` is the code of the API error (`prompt_not_found`,
|
|
377
|
+
* `label_not_found`, `insufficient_scope`, `invalid_api_key`, …), or `missing_api_key`,
|
|
378
|
+
* `timeout`, `network_error`, `invalid_response`, or `type_mismatch`. A response with a different
|
|
379
|
+
* status and no API error gives `http_<status>`, for example `http_302` for a redirect: getPrompt
|
|
380
|
+
* does not go to the location of a redirect.
|
|
381
|
+
*/
|
|
382
|
+
declare class PromptError extends Error {
|
|
383
|
+
readonly code: string;
|
|
384
|
+
readonly status?: number | undefined;
|
|
385
|
+
readonly name = "PromptError";
|
|
386
|
+
constructor(code: string, message: string, status?: number | undefined, options?: {
|
|
387
|
+
cause?: unknown;
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Fetches a prompt version from telemetry.dev and keeps it. When the copy is older than
|
|
392
|
+
* `cacheTtlSeconds`, a call returns it at once and fetches a new one in the background. Only a call
|
|
393
|
+
* with no copy waits for a fetch, at most 10 seconds. Calls for the same prompt share one fetch.
|
|
394
|
+
* When a fetch fails, getPrompt returns the last copy that it kept; with no copy it returns
|
|
395
|
+
* `fallback`. With neither it rejects with a `PromptError`: unlike the telemetry functions,
|
|
396
|
+
* getPrompt cannot fail open, because the app cannot run without the prompt. With no copy, the
|
|
397
|
+
* calls of the next 10 seconds (or the TTL, if it is shorter) fail the same way without a fetch.
|
|
398
|
+
*
|
|
399
|
+
* A label with a gradual rollout gives each session one version: the choice uses the session id
|
|
400
|
+
* of `propagateAttributes`, or a random choice per call without one.
|
|
401
|
+
*/
|
|
402
|
+
declare function getPrompt(name: string, options: GetTextPromptOptions): Promise<TextPrompt>;
|
|
403
|
+
declare function getPrompt(name: string, options?: GetChatPromptOptions): Promise<ChatPrompt>;
|
|
404
|
+
/**
|
|
405
|
+
* Runs `fn` with `prompt` as the prompt of each model call (generation span) that starts inside
|
|
406
|
+
* it: the spans get `td.prompt.name`, `td.prompt.version`, `td.prompt.label`, and, when input
|
|
407
|
+
* capture is on, `td.prompt.variables`. The variables are those of the last `compile()` of this
|
|
408
|
+
* prompt object before withPrompt starts, or of the last `compile()` inside `fn`, so a compile in
|
|
409
|
+
* another task does not change them once withPrompt runs. Concurrent tasks in `fn` share the
|
|
410
|
+
* variables, so call withPrompt in each task that compiles its own.
|
|
411
|
+
*/
|
|
412
|
+
declare function withPrompt<T>(prompt: Prompt, fn: () => T): T;
|
|
413
|
+
//#endregion
|
|
414
|
+
export { type AgentFields, type BatchOptions, type BoundedCaptureDetails, type BoundedCaptureOptions, type BoundedCaptureResult, type ChatMessage, type ChatPrompt, type ClientOverrides, type ExportMode, type GenerationFields, type GetChatPromptOptions, type GetPromptOptions, type GetTextPromptOptions, type LogLevel, type LogOptions, type MaskFn, type ObserveOptions, type ParentRef, type Prompt, PromptError, type PromptMessage, type PromptModel, type PromptParameters, type PromptResponseFormat, type PromptTool, type PromptVariables, type PropagatedAttributes, SCOPE_NAME, type SdkLogLevel, type SpanCapturePolicy, type SpanFields, type SpanHandle, type SpanType, type StartSpanOptions, type TelemetryClient, type TelemetryOptions, TelemetrySpanProcessor, type TelemetrySpanProcessorOptions, type TextPrompt, type TokenUsage, type ToolFields, activeContext, boundedCapture, boundedCaptureDetails, captureEnabled, captureMasked, extractW3cContext, flush, getPrompt, getTraceparent, init, injectW3cContext, log, observe, propagateAttributes, shutdown, startActiveSpan, startSpan, updateActiveSpan, withContext, withPrompt };
|
package/dist/index.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { INVALID_SPAN_CONTEXT, ROOT_CONTEXT, SpanKind, SpanStatusCode, context, defaultTextMapGetter, defaultTextMapSetter, propagation, trace } from "@opentelemetry/api";
|
|
1
|
+
import { INVALID_SPAN_CONTEXT, ROOT_CONTEXT, SpanKind, SpanStatusCode, context, createContextKey, defaultTextMapGetter, defaultTextMapSetter, propagation, trace } from "@opentelemetry/api";
|
|
2
2
|
import { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator, parseTraceParent } from "@opentelemetry/core";
|
|
3
3
|
import { resourceFromAttributes } from "@opentelemetry/resources";
|
|
4
4
|
import { BatchLogRecordProcessor, LoggerProvider, SimpleLogRecordProcessor } from "@opentelemetry/sdk-logs";
|
|
5
5
|
import { BasicTracerProvider } from "@opentelemetry/sdk-trace-base";
|
|
6
|
-
import { AlsContextManager, BATCHED_METRIC_INTERVAL_MS, DEFAULT_BASE_URL, DEFAULT_BATCH, DORMANT_INTERVAL_MS, DURATION_BUCKETS, OUTPUT_CHUNK_HISTOGRAM, PROPAGATED_KEY, SCOPE_NAME, SCOPE_NAME as SCOPE_NAME$1, SCOPE_VERSION, StampingSpanProcessor, TelemetrySpanProcessor, activeContext, activeContext as activeContext$1, als, createExportFailures, createLogExporter, createMetricExporter, createMetricsPipeline, createTraceExporter, diag, jsonAttr, omitUndefined, otlpHeaders, propagateAttributes, propagatedFromContext, reportError, resolveEnv, sessionIdOf, sessionRootTracerProvider, sessionSampler, setLogLevel, withContext, withContext as withContext$1, withSessionParent } from "@telemetry-dev/otel";
|
|
6
|
+
import { AlsContextManager, BATCHED_METRIC_INTERVAL_MS, DEFAULT_BASE_URL, DEFAULT_BATCH, DORMANT_INTERVAL_MS, DURATION_BUCKETS, OUTPUT_CHUNK_HISTOGRAM, PROPAGATED_KEY, SCOPE_NAME, SCOPE_NAME as SCOPE_NAME$1, SCOPE_VERSION, StampingSpanProcessor, TelemetrySpanProcessor, activeContext, activeContext as activeContext$1, als, createExportFailures, createLogExporter, createMetricExporter, createMetricsPipeline, createTraceExporter, diag, jsonAttr, omitUndefined, otlpHeaders, propagateAttributes, propagatedFromContext, reportError, resolveEnv, sessionIdOf, sessionRootTracerProvider, sessionSampler, setLogLevel, sha256, withContext, withContext as withContext$1, withSessionParent } from "@telemetry-dev/otel";
|
|
7
7
|
import { SeverityNumber } from "@opentelemetry/api-logs";
|
|
8
8
|
//#region src/config.ts
|
|
9
9
|
const DEFAULT_MAX_ATTRIBUTE_LENGTH = 65536;
|
|
@@ -546,6 +546,330 @@ const NOOP_SPAN_HANDLE = {
|
|
|
546
546
|
end: () => {}
|
|
547
547
|
};
|
|
548
548
|
//#endregion
|
|
549
|
+
//#region src/prompts.ts
|
|
550
|
+
/**
|
|
551
|
+
* Why getPrompt failed. `code` is the code of the API error (`prompt_not_found`,
|
|
552
|
+
* `label_not_found`, `insufficient_scope`, `invalid_api_key`, …), or `missing_api_key`,
|
|
553
|
+
* `timeout`, `network_error`, `invalid_response`, or `type_mismatch`. A response with a different
|
|
554
|
+
* status and no API error gives `http_<status>`, for example `http_302` for a redirect: getPrompt
|
|
555
|
+
* does not go to the location of a redirect.
|
|
556
|
+
*/
|
|
557
|
+
var PromptError = class extends Error {
|
|
558
|
+
name = "PromptError";
|
|
559
|
+
constructor(code, message, status, options) {
|
|
560
|
+
super(message, options);
|
|
561
|
+
this.code = code;
|
|
562
|
+
this.status = status;
|
|
563
|
+
}
|
|
564
|
+
};
|
|
565
|
+
const FETCH_TIMEOUT_MS = 1e4;
|
|
566
|
+
/** The longest Retry-After that getPrompt honors, so that a bad header cannot stop fetches. */
|
|
567
|
+
const MAX_RETRY_AFTER_MS = 36e5;
|
|
568
|
+
/** How long a failed fetch with no copy answers calls, so that they do not each fetch again. */
|
|
569
|
+
const ERROR_TTL_MS = 1e4;
|
|
570
|
+
const MAX_CACHE_ENTRIES = 1e3;
|
|
571
|
+
/** IMF-fixdate, the HTTP date that servers send: `Sun, 06 Nov 1994 08:49:37 GMT`. */
|
|
572
|
+
const HTTP_DATE = /^[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT$/;
|
|
573
|
+
const VARIABLE = /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;
|
|
574
|
+
const MODEL_CALL_OPERATIONS = new Set([
|
|
575
|
+
"chat",
|
|
576
|
+
"text_completion",
|
|
577
|
+
"generate_content"
|
|
578
|
+
]);
|
|
579
|
+
const PROMPT_KEY = createContextKey("telemetry.dev prompt");
|
|
580
|
+
const cache = /* @__PURE__ */ new Map();
|
|
581
|
+
const compiledVariables = /* @__PURE__ */ new WeakMap();
|
|
582
|
+
/** The Retry-After of the response that failed with this error, in milliseconds. */
|
|
583
|
+
const retryAfter = /* @__PURE__ */ new WeakMap();
|
|
584
|
+
async function getPrompt(name, options = {}) {
|
|
585
|
+
const type = options.type ?? "chat";
|
|
586
|
+
checkOptions(name, options, type);
|
|
587
|
+
const core = currentClient().core;
|
|
588
|
+
const env = resolveEnv();
|
|
589
|
+
const apiKey = options.apiKey ?? core?.config.apiKey ?? env.TELEMETRY_DEV_API_KEY;
|
|
590
|
+
const baseUrl = (options.baseUrl || core?.config.baseUrl || env.TELEMETRY_DEV_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
591
|
+
const label = options.version === void 0 ? options.label ?? "production" : null;
|
|
592
|
+
const onError = core?.config.onError;
|
|
593
|
+
let response;
|
|
594
|
+
try {
|
|
595
|
+
if (!apiKey) throw new PromptError("missing_api_key", "No API key: pass apiKey or set TELEMETRY_DEV_API_KEY");
|
|
596
|
+
const url = new URL(`${baseUrl}/v1/prompts`);
|
|
597
|
+
url.searchParams.set("name", name);
|
|
598
|
+
if (label === null) url.searchParams.set("version", String(options.version));
|
|
599
|
+
else url.searchParams.set("label", label);
|
|
600
|
+
response = await load([
|
|
601
|
+
baseUrl,
|
|
602
|
+
keyFingerprint(apiKey),
|
|
603
|
+
name,
|
|
604
|
+
label === null ? `version:${options.version}` : `label:${label}`
|
|
605
|
+
].join("\0"), (options.cacheTtlSeconds ?? 60) * 1e3, () => fetchPrompt(url, {
|
|
606
|
+
authorization: `Bearer ${apiKey}`,
|
|
607
|
+
"x-telemetry-dev-sdk": core?.config.sdkName ?? "@telemetry-dev/sdk"
|
|
608
|
+
}, options.fetch ?? core?.config.fetchImpl ?? globalThis.fetch), onError);
|
|
609
|
+
} catch (error) {
|
|
610
|
+
if (options.fallback === void 0) throw error;
|
|
611
|
+
reportError(onError, error);
|
|
612
|
+
return createPrompt({
|
|
613
|
+
name,
|
|
614
|
+
type,
|
|
615
|
+
label,
|
|
616
|
+
version: null,
|
|
617
|
+
isFallback: true,
|
|
618
|
+
content: {
|
|
619
|
+
messages: type === "chat" ? options.fallback : [],
|
|
620
|
+
text: type === "text" ? options.fallback : null,
|
|
621
|
+
model: null,
|
|
622
|
+
parameters: {},
|
|
623
|
+
tools: [],
|
|
624
|
+
responseFormat: { type: "text" }
|
|
625
|
+
}
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
if (response.type !== type) throw new PromptError("type_mismatch", `${name} is a ${response.type} prompt; pass type: "${response.type}"`);
|
|
629
|
+
const chosen = response.rollout && inRollout(response) ? response.rollout : response;
|
|
630
|
+
return createPrompt({
|
|
631
|
+
name: response.name,
|
|
632
|
+
type,
|
|
633
|
+
label: response.label,
|
|
634
|
+
version: chosen.version,
|
|
635
|
+
isFallback: false,
|
|
636
|
+
content: chosen
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* Runs `fn` with `prompt` as the prompt of each model call (generation span) that starts inside
|
|
641
|
+
* it: the spans get `td.prompt.name`, `td.prompt.version`, `td.prompt.label`, and, when input
|
|
642
|
+
* capture is on, `td.prompt.variables`. The variables are those of the last `compile()` of this
|
|
643
|
+
* prompt object before withPrompt starts, or of the last `compile()` inside `fn`, so a compile in
|
|
644
|
+
* another task does not change them once withPrompt runs. Concurrent tasks in `fn` share the
|
|
645
|
+
* variables, so call withPrompt in each task that compiles its own.
|
|
646
|
+
*/
|
|
647
|
+
function withPrompt(prompt, fn) {
|
|
648
|
+
const scope = {
|
|
649
|
+
prompt,
|
|
650
|
+
variables: compiledVariables.get(prompt)
|
|
651
|
+
};
|
|
652
|
+
return withContext$1(activeContext$1().setValue(PROMPT_KEY, scope), fn);
|
|
653
|
+
}
|
|
654
|
+
/** The td.prompt.* attributes for a span with this operation that starts in `ctx`. */
|
|
655
|
+
function promptAttributes(ctx, operation, capture) {
|
|
656
|
+
if (!MODEL_CALL_OPERATIONS.has(operation)) return void 0;
|
|
657
|
+
const scope = ctx.getValue(PROMPT_KEY) ?? activeContext$1().getValue(PROMPT_KEY);
|
|
658
|
+
if (!scope) return void 0;
|
|
659
|
+
const { prompt, variables } = scope;
|
|
660
|
+
return omitUndefined({
|
|
661
|
+
"td.prompt.name": prompt.name,
|
|
662
|
+
"td.prompt.version": prompt.version ?? void 0,
|
|
663
|
+
"td.prompt.label": prompt.label ?? void 0,
|
|
664
|
+
"td.prompt.variables": variables !== void 0 && capture.captureInput ? prepareCaptureValue("td.prompt.variables", variables, capture) : void 0
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
function checkOptions(name, options, type) {
|
|
668
|
+
if (typeof name !== "string" || name.length === 0) throw new TypeError("name must be a non-empty string");
|
|
669
|
+
if (type !== "chat" && type !== "text") throw new TypeError("type must be \"chat\" or \"text\"");
|
|
670
|
+
if (options.label !== void 0 && options.version !== void 0) throw new TypeError("Pass label or version, not both");
|
|
671
|
+
if (options.version !== void 0 && (!Number.isSafeInteger(options.version) || options.version < 1)) throw new RangeError("version must be a positive integer");
|
|
672
|
+
const ttl = options.cacheTtlSeconds;
|
|
673
|
+
if (ttl !== void 0 && !(Number.isFinite(ttl) && ttl >= 0)) throw new RangeError("cacheTtlSeconds must be a non-negative number");
|
|
674
|
+
if (options.fallback !== void 0 && (type === "chat" ? !Array.isArray(options.fallback) : typeof options.fallback !== "string")) throw new TypeError(type === "chat" ? "fallback must be a list of messages" : "fallback must be a string");
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* Returns the kept copy of a prompt, and fetches a new copy in the background when it is older
|
|
678
|
+
* than the TTL. Only a call with no copy waits for a fetch. A failed fetch with no copy fails the
|
|
679
|
+
* calls of the next ERROR_TTL_MS (or the TTL, if it is shorter) without a fetch.
|
|
680
|
+
*/
|
|
681
|
+
async function load(key, ttlMs, fetchResponse, onError) {
|
|
682
|
+
let entry = cache.get(key);
|
|
683
|
+
if (!entry) {
|
|
684
|
+
if (cache.size >= MAX_CACHE_ENTRIES) cache.delete(cache.keys().next().value);
|
|
685
|
+
entry = {
|
|
686
|
+
checkedAt: 0,
|
|
687
|
+
retryAt: 0
|
|
688
|
+
};
|
|
689
|
+
cache.set(key, entry);
|
|
690
|
+
}
|
|
691
|
+
const fresh = Date.now() < Math.max(entry.checkedAt + (entry.response ? ttlMs : Math.min(ttlMs, ERROR_TTL_MS)), entry.retryAt);
|
|
692
|
+
if (entry.response) {
|
|
693
|
+
if (!fresh) entry.pending ??= refresh(entry, fetchResponse, onError);
|
|
694
|
+
return entry.response;
|
|
695
|
+
}
|
|
696
|
+
if (fresh) throw entry.error;
|
|
697
|
+
return entry.pending ??= refresh(entry, fetchResponse, onError);
|
|
698
|
+
}
|
|
699
|
+
function refresh(entry, fetchResponse, onError) {
|
|
700
|
+
return fetchResponse().then((response) => {
|
|
701
|
+
entry.response = response;
|
|
702
|
+
entry.retryAt = 0;
|
|
703
|
+
return response;
|
|
704
|
+
}, (error) => {
|
|
705
|
+
const delay = error instanceof PromptError ? retryAfter.get(error) : void 0;
|
|
706
|
+
entry.retryAt = delay === void 0 ? 0 : Date.now() + delay;
|
|
707
|
+
if (!entry.response) {
|
|
708
|
+
entry.error = error;
|
|
709
|
+
throw error;
|
|
710
|
+
}
|
|
711
|
+
reportError(onError, error);
|
|
712
|
+
return entry.response;
|
|
713
|
+
}).finally(() => {
|
|
714
|
+
entry.checkedAt = Date.now();
|
|
715
|
+
entry.pending = void 0;
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
async function fetchPrompt(url, headers, fetchImpl) {
|
|
719
|
+
const controller = new AbortController();
|
|
720
|
+
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
721
|
+
try {
|
|
722
|
+
const res = await fetchImpl(url, {
|
|
723
|
+
method: "GET",
|
|
724
|
+
headers,
|
|
725
|
+
signal: controller.signal,
|
|
726
|
+
redirect: "manual"
|
|
727
|
+
});
|
|
728
|
+
const body = await res.json().catch(() => void 0);
|
|
729
|
+
if (!res.ok) {
|
|
730
|
+
const error = isRecord(body) && isRecord(body.error) ? body.error : {};
|
|
731
|
+
const failure = new PromptError(typeof error.code === "string" ? error.code : `http_${res.status}`, typeof error.message === "string" ? error.message : `telemetry.dev returned ${res.status}`, res.status);
|
|
732
|
+
const delay = retryAfterMs(res);
|
|
733
|
+
if (delay !== void 0) retryAfter.set(failure, delay);
|
|
734
|
+
throw failure;
|
|
735
|
+
}
|
|
736
|
+
const response = parseResponse(body);
|
|
737
|
+
if (!response) throw new PromptError("invalid_response", "telemetry.dev returned a prompt it cannot read");
|
|
738
|
+
return response;
|
|
739
|
+
} catch (error) {
|
|
740
|
+
if (controller.signal.aborted) throw new PromptError("timeout", `Fetching the prompt took more than ${FETCH_TIMEOUT_MS} ms`);
|
|
741
|
+
if (error instanceof PromptError) throw error;
|
|
742
|
+
throw new PromptError("network_error", "Could not reach telemetry.dev", void 0, { cause: error });
|
|
743
|
+
} finally {
|
|
744
|
+
clearTimeout(timer);
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
function createPrompt(input) {
|
|
748
|
+
const { content, type } = input;
|
|
749
|
+
const prompt = Object.freeze({
|
|
750
|
+
name: input.name,
|
|
751
|
+
type,
|
|
752
|
+
version: input.version,
|
|
753
|
+
label: input.label,
|
|
754
|
+
messages: content.messages,
|
|
755
|
+
text: content.text,
|
|
756
|
+
model: content.model,
|
|
757
|
+
parameters: content.parameters,
|
|
758
|
+
tools: content.tools,
|
|
759
|
+
responseFormat: content.responseFormat,
|
|
760
|
+
isFallback: input.isFallback,
|
|
761
|
+
compile(variables = {}) {
|
|
762
|
+
compiledVariables.set(prompt, variables);
|
|
763
|
+
const scope = activeContext$1().getValue(PROMPT_KEY);
|
|
764
|
+
if (scope?.prompt === prompt) scope.variables = variables;
|
|
765
|
+
return type === "chat" ? compileMessages(content.messages, variables) : fill(content.text ?? "", variables);
|
|
766
|
+
}
|
|
767
|
+
});
|
|
768
|
+
return prompt;
|
|
769
|
+
}
|
|
770
|
+
function compileMessages(messages, variables) {
|
|
771
|
+
return messages.flatMap((message) => {
|
|
772
|
+
if (message.role !== "placeholder") return [{
|
|
773
|
+
role: message.role,
|
|
774
|
+
content: fill(message.content, variables)
|
|
775
|
+
}];
|
|
776
|
+
const value = Object.hasOwn(variables, message.name) ? variables[message.name] : void 0;
|
|
777
|
+
if (value == null) return [];
|
|
778
|
+
if (!Array.isArray(value)) throw new TypeError(`The ${message.name} variable must be a list of messages`);
|
|
779
|
+
return value;
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
function fill(text, variables) {
|
|
783
|
+
return text.replace(VARIABLE, (_tag, name) => {
|
|
784
|
+
const value = Object.hasOwn(variables, name) ? variables[name] : void 0;
|
|
785
|
+
if (value == null) return "";
|
|
786
|
+
return typeof value === "string" ? value : jsonAttr(value) ?? "";
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
function inRollout(response) {
|
|
790
|
+
const sessionId = sessionIdOf(activeContext$1()) ?? currentClient().core?.config.processSessionId;
|
|
791
|
+
return (sessionId === void 0 ? Math.floor(Math.random() * 100) : fnv1a(`${response.name}:${response.label}:${sessionId}`) % 100) < response.rollout.percent;
|
|
792
|
+
}
|
|
793
|
+
function fnv1a(text) {
|
|
794
|
+
let hash = 2166136261;
|
|
795
|
+
for (const byte of new TextEncoder().encode(text)) hash = Math.imul(hash ^ byte, 16777619) >>> 0;
|
|
796
|
+
return hash;
|
|
797
|
+
}
|
|
798
|
+
function keyFingerprint(apiKey) {
|
|
799
|
+
const digest = sha256(new TextEncoder().encode(apiKey)).subarray(0, 16);
|
|
800
|
+
return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
801
|
+
}
|
|
802
|
+
/** The Retry-After of a 429 or 503 response, as seconds or an IMF-fixdate HTTP date, capped. */
|
|
803
|
+
function retryAfterMs(res) {
|
|
804
|
+
if (res.status !== 429 && res.status !== 503) return void 0;
|
|
805
|
+
const value = res.headers.get("retry-after")?.trim();
|
|
806
|
+
if (!value) return void 0;
|
|
807
|
+
let ms;
|
|
808
|
+
if (/^\d+$/.test(value)) ms = Number(value) * 1e3;
|
|
809
|
+
else if (HTTP_DATE.test(value)) ms = Date.parse(value) - Date.now();
|
|
810
|
+
else return void 0;
|
|
811
|
+
return ms > 0 ? Math.min(ms, MAX_RETRY_AFTER_MS) : void 0;
|
|
812
|
+
}
|
|
813
|
+
function parseResponse(body) {
|
|
814
|
+
if (!isRecord(body)) return void 0;
|
|
815
|
+
const { name, type, label, version, rollout } = body;
|
|
816
|
+
if (typeof name !== "string" || type !== "chat" && type !== "text" || label !== null && typeof label !== "string" || !isVersion(version)) return;
|
|
817
|
+
const content = parseContent(body, type);
|
|
818
|
+
if (!content) return void 0;
|
|
819
|
+
if (rollout == null) return deepFreeze({
|
|
820
|
+
name,
|
|
821
|
+
type,
|
|
822
|
+
label,
|
|
823
|
+
version,
|
|
824
|
+
...content,
|
|
825
|
+
rollout: null
|
|
826
|
+
});
|
|
827
|
+
if (!isRecord(rollout) || !isVersion(rollout.version) || !Number.isInteger(rollout.percent) || rollout.percent < 0 || rollout.percent > 100) return;
|
|
828
|
+
const rolloutContent = parseContent(rollout, type);
|
|
829
|
+
if (!rolloutContent) return void 0;
|
|
830
|
+
return deepFreeze({
|
|
831
|
+
name,
|
|
832
|
+
type,
|
|
833
|
+
label,
|
|
834
|
+
version,
|
|
835
|
+
...content,
|
|
836
|
+
rollout: {
|
|
837
|
+
percent: rollout.percent,
|
|
838
|
+
version: rollout.version,
|
|
839
|
+
...rolloutContent
|
|
840
|
+
}
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
function parseContent(value, type) {
|
|
844
|
+
const { messages, text, model, parameters, tools, responseFormat } = value;
|
|
845
|
+
if (!(type === "chat" ? Array.isArray(messages) && messages.every(isPromptMessage) : typeof text === "string") || !isRecord(model) || typeof model.provider !== "string" || typeof model.name !== "string" || !isRecord(parameters) || !Array.isArray(tools) || !tools.every((tool) => isRecord(tool) && typeof tool.name === "string") || !isRecord(responseFormat) || typeof responseFormat.type !== "string") return;
|
|
846
|
+
return {
|
|
847
|
+
messages: type === "chat" ? messages : [],
|
|
848
|
+
text: type === "text" ? text : null,
|
|
849
|
+
model,
|
|
850
|
+
parameters,
|
|
851
|
+
tools,
|
|
852
|
+
responseFormat
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
function isPromptMessage(value) {
|
|
856
|
+
if (!isRecord(value)) return false;
|
|
857
|
+
return value.role === "placeholder" ? typeof value.name === "string" : (value.role === "system" || value.role === "user" || value.role === "assistant") && typeof value.content === "string";
|
|
858
|
+
}
|
|
859
|
+
function isVersion(value) {
|
|
860
|
+
return Number.isSafeInteger(value) && value >= 1;
|
|
861
|
+
}
|
|
862
|
+
function isRecord(value) {
|
|
863
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
864
|
+
}
|
|
865
|
+
function deepFreeze(value) {
|
|
866
|
+
if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
|
|
867
|
+
Object.freeze(value);
|
|
868
|
+
for (const item of Object.values(value)) deepFreeze(item);
|
|
869
|
+
}
|
|
870
|
+
return value;
|
|
871
|
+
}
|
|
872
|
+
//#endregion
|
|
549
873
|
//#region src/span.ts
|
|
550
874
|
const SPAN_META = /* @__PURE__ */ new WeakMap();
|
|
551
875
|
const SEVERITY_ERROR = 17;
|
|
@@ -621,6 +945,7 @@ function createSpanHandle(core, name, options = {}) {
|
|
|
621
945
|
"gen_ai.conversation.id": sessionId
|
|
622
946
|
}), sessionId, core.config.apiKey);
|
|
623
947
|
const attrs = fieldsToAttributes(options, meta.type, meta.capture);
|
|
948
|
+
const operation = attrs["gen_ai.operation.name"] ?? SPAN_TYPE_OPERATIONS[meta.type];
|
|
624
949
|
const span = core.tracer.startSpan(name, {
|
|
625
950
|
kind: options.kind ?? SpanKind.INTERNAL,
|
|
626
951
|
startTime: options.startTime,
|
|
@@ -628,6 +953,7 @@ function createSpanHandle(core, name, options = {}) {
|
|
|
628
953
|
attributes: {
|
|
629
954
|
"gen_ai.operation.name": SPAN_TYPE_OPERATIONS[meta.type],
|
|
630
955
|
...propagatedFromContext(parentCtx),
|
|
956
|
+
...promptAttributes(parentCtx, operation, meta.capture),
|
|
631
957
|
...attrs
|
|
632
958
|
}
|
|
633
959
|
}, parentCtx);
|
|
@@ -815,4 +1141,4 @@ function observe(fn, options) {
|
|
|
815
1141
|
return wrapped;
|
|
816
1142
|
}
|
|
817
1143
|
//#endregion
|
|
818
|
-
export { SCOPE_NAME, TelemetrySpanProcessor, activeContext, boundedCapture, boundedCaptureDetails, captureEnabled, captureMasked, extractW3cContext, flush, getTraceparent, init, injectW3cContext, log, observe, propagateAttributes, shutdown, startActiveSpan, startSpan, updateActiveSpan, withContext };
|
|
1144
|
+
export { PromptError, SCOPE_NAME, TelemetrySpanProcessor, activeContext, boundedCapture, boundedCaptureDetails, captureEnabled, captureMasked, extractW3cContext, flush, getPrompt, getTraceparent, init, injectW3cContext, log, observe, propagateAttributes, shutdown, startActiveSpan, startSpan, updateActiveSpan, withContext, withPrompt };
|
package/package.json
CHANGED
package/src/config.ts
CHANGED
|
@@ -22,7 +22,7 @@ export type MaskFn<T = unknown> = (value: T, ctx: { key: string }) => T;
|
|
|
22
22
|
export interface TelemetryOptions {
|
|
23
23
|
/** telemetry.dev ingest key (`td_live_…`). Falls back to `TELEMETRY_DEV_API_KEY`. When absent the SDK is a no-op. */
|
|
24
24
|
apiKey?: string;
|
|
25
|
-
/**
|
|
25
|
+
/** Base URL for telemetry export and getPrompt. Falls back to `TELEMETRY_DEV_BASE_URL`, then `https://ingest.telemetry.dev`. */
|
|
26
26
|
baseUrl?: string;
|
|
27
27
|
/** Deployment environment label. Falls back to `TELEMETRY_DEV_ENVIRONMENT`, then `production`. */
|
|
28
28
|
environment?: string;
|
package/src/index.ts
CHANGED
|
@@ -46,6 +46,25 @@ export { log, type LogOptions } from "./logs.ts";
|
|
|
46
46
|
|
|
47
47
|
export { observe, type ObserveOptions } from "./observe.ts";
|
|
48
48
|
|
|
49
|
+
export {
|
|
50
|
+
type ChatMessage,
|
|
51
|
+
type ChatPrompt,
|
|
52
|
+
type GetChatPromptOptions,
|
|
53
|
+
getPrompt,
|
|
54
|
+
type GetPromptOptions,
|
|
55
|
+
type GetTextPromptOptions,
|
|
56
|
+
type Prompt,
|
|
57
|
+
PromptError,
|
|
58
|
+
type PromptMessage,
|
|
59
|
+
type PromptModel,
|
|
60
|
+
type PromptParameters,
|
|
61
|
+
type PromptResponseFormat,
|
|
62
|
+
type PromptTool,
|
|
63
|
+
type PromptVariables,
|
|
64
|
+
type TextPrompt,
|
|
65
|
+
withPrompt,
|
|
66
|
+
} from "./prompts.ts";
|
|
67
|
+
|
|
49
68
|
export {
|
|
50
69
|
activeContext,
|
|
51
70
|
extractW3cContext,
|