@superbased/sdk 0.0.1-placeholder.0 → 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/NOTICE +4 -0
- package/README.md +434 -5
- package/dist/cjs/admit.d.ts +139 -0
- package/dist/cjs/admit.js +442 -0
- package/dist/cjs/admit.js.map +1 -0
- package/dist/cjs/attrs.d.ts +113 -0
- package/dist/cjs/attrs.js +183 -0
- package/dist/cjs/attrs.js.map +1 -0
- package/dist/cjs/config.d.ts +202 -0
- package/dist/cjs/config.js +386 -0
- package/dist/cjs/config.js.map +1 -0
- package/dist/cjs/context.d.ts +102 -0
- package/dist/cjs/context.js +234 -0
- package/dist/cjs/context.js.map +1 -0
- package/dist/cjs/control.d.ts +99 -0
- package/dist/cjs/control.js +243 -0
- package/dist/cjs/control.js.map +1 -0
- package/dist/cjs/cost.d.ts +108 -0
- package/dist/cjs/cost.js +211 -0
- package/dist/cjs/cost.js.map +1 -0
- package/dist/cjs/destination.d.ts +125 -0
- package/dist/cjs/destination.js +357 -0
- package/dist/cjs/destination.js.map +1 -0
- package/dist/cjs/experiments.d.ts +237 -0
- package/dist/cjs/experiments.js +678 -0
- package/dist/cjs/experiments.js.map +1 -0
- package/dist/cjs/export.d.ts +84 -0
- package/dist/cjs/export.js +328 -0
- package/dist/cjs/export.js.map +1 -0
- package/dist/cjs/index.d.ts +168 -0
- package/dist/cjs/index.js +581 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/instrument.d.ts +88 -0
- package/dist/cjs/instrument.js +397 -0
- package/dist/cjs/instrument.js.map +1 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/policy.d.ts +77 -0
- package/dist/cjs/policy.js +252 -0
- package/dist/cjs/policy.js.map +1 -0
- package/dist/cjs/prompts.d.ts +175 -0
- package/dist/cjs/prompts.js +476 -0
- package/dist/cjs/prompts.js.map +1 -0
- package/dist/cjs/propagation.d.ts +34 -0
- package/dist/cjs/propagation.js +151 -0
- package/dist/cjs/propagation.js.map +1 -0
- package/dist/cjs/req.d.ts +10 -0
- package/dist/cjs/req.js +3 -0
- package/dist/cjs/req.js.map +1 -0
- package/dist/cjs/runtime.d.ts +44 -0
- package/dist/cjs/runtime.js +67 -0
- package/dist/cjs/runtime.js.map +1 -0
- package/dist/cjs/scores.d.ts +102 -0
- package/dist/cjs/scores.js +226 -0
- package/dist/cjs/scores.js.map +1 -0
- package/dist/cjs/spans.d.ts +193 -0
- package/dist/cjs/spans.js +398 -0
- package/dist/cjs/spans.js.map +1 -0
- package/dist/cjs/vendor.d.ts +33 -0
- package/dist/cjs/vendor.js +67 -0
- package/dist/cjs/vendor.js.map +1 -0
- package/dist/esm/admit.d.ts +139 -0
- package/dist/esm/admit.js +432 -0
- package/dist/esm/admit.js.map +1 -0
- package/dist/esm/attrs.d.ts +113 -0
- package/dist/esm/attrs.js +179 -0
- package/dist/esm/attrs.js.map +1 -0
- package/dist/esm/config.d.ts +202 -0
- package/dist/esm/config.js +364 -0
- package/dist/esm/config.js.map +1 -0
- package/dist/esm/context.d.ts +102 -0
- package/dist/esm/context.js +221 -0
- package/dist/esm/context.js.map +1 -0
- package/dist/esm/control.d.ts +99 -0
- package/dist/esm/control.js +230 -0
- package/dist/esm/control.js.map +1 -0
- package/dist/esm/cost.d.ts +108 -0
- package/dist/esm/cost.js +202 -0
- package/dist/esm/cost.js.map +1 -0
- package/dist/esm/destination.d.ts +125 -0
- package/dist/esm/destination.js +346 -0
- package/dist/esm/destination.js.map +1 -0
- package/dist/esm/experiments.d.ts +237 -0
- package/dist/esm/experiments.js +666 -0
- package/dist/esm/experiments.js.map +1 -0
- package/dist/esm/export.d.ts +84 -0
- package/dist/esm/export.js +314 -0
- package/dist/esm/export.js.map +1 -0
- package/dist/esm/index.d.ts +168 -0
- package/dist/esm/index.js +500 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/instrument.d.ts +88 -0
- package/dist/esm/instrument.js +391 -0
- package/dist/esm/instrument.js.map +1 -0
- package/dist/esm/policy.d.ts +77 -0
- package/dist/esm/policy.js +240 -0
- package/dist/esm/policy.js.map +1 -0
- package/dist/esm/prompts.d.ts +175 -0
- package/dist/esm/prompts.js +460 -0
- package/dist/esm/prompts.js.map +1 -0
- package/dist/esm/propagation.d.ts +34 -0
- package/dist/esm/propagation.js +145 -0
- package/dist/esm/propagation.js.map +1 -0
- package/dist/esm/req.d.ts +10 -0
- package/dist/esm/req.js +2 -0
- package/dist/esm/req.js.map +1 -0
- package/dist/esm/runtime.d.ts +44 -0
- package/dist/esm/runtime.js +59 -0
- package/dist/esm/runtime.js.map +1 -0
- package/dist/esm/scores.d.ts +102 -0
- package/dist/esm/scores.js +219 -0
- package/dist/esm/scores.js.map +1 -0
- package/dist/esm/spans.d.ts +193 -0
- package/dist/esm/spans.js +378 -0
- package/dist/esm/spans.js.map +1 -0
- package/dist/esm/vendor.d.ts +33 -0
- package/dist/esm/vendor.js +61 -0
- package/dist/esm/vendor.js.map +1 -0
- package/package.json +121 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scores.js","sourceRoot":"","sources":["../../src/scores.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;;;AAqGH,gCAyCC;AA+ED,sBAEC;AAcD,4BAGC;AA9OD,6CAA4H;AAC5H,yCAA+C;AAC/C,6CAAgD;AAEnC,QAAA,YAAY,GAAU,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,iBAAiB,EAAE,CAAC;AAItE,QAAA,WAAW,GAAyB,CAAC,SAAS,EAAE,SAAS,EAAE,aAAa,CAAC,CAAC;AAC1E,QAAA,qBAAqB,GAAG,eAAe,CAAC;AAErD,MAAM,IAAI,GAAG,qBAAqB,CAAC;AACnC,MAAM,EAAE,GAAG,0BAA0B,CAAC;AACtC,MAAM,KAAK,GAAG,gBAAgB,CAAC;AAC/B,MAAM,IAAI,GAAG,gBAAgB,CAAC;AAC9B,MAAM,eAAe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AI,EAAE,CAAC,EAAE,GAAG,EAAE,IAAI,IAAI,EAAE,CAAC;YACpC,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC;YAC1B,IAAI,GAAG,CAAC,EAAE;gBAAE,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,EAAE,IAAI,GAAG,CAAC,EAAE,CAAC;;gBACjC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC;QAC7C,CAAC;QACD,GAAG,CAAC,EAAE,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACxD,IAAI,CAAC,GAAG,CAAC,EAAE;YAAE,UAAU,CAAC,GAAG,CAAC,CAAC;QAC7B,OAAO,GAAG,CAAC;IACb,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,KAAK,CAAC,IAAY,EAAE,KAAgC,EAAE,OAAqB,EAAE;IAC3F,OAAO,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;AACxD,CAAC;AAOD;;;;;;GAMG;AACH,SAAgB,QAAQ,CAAC,KAAgC,EAAE,OAAwB,EAAE;IACnF,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;IAC/B,OAAO,KAAK,CAAC,IAAI,IAAI,6BAAqB,EAAE,KAAK,EAAE,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,CAAC;AACtF,CAAC","sourcesContent":["/**\n * Scores and feedback (W3-1; contract `contracts/scores.md`, lane B7; the\n * API is sdk-api-surface.md section 7.1, the same as Python's).\n *\n * A score is one judgement about one trace or one span: a name, a value, who\n * produced it, an optional comment. Feedback is a score an end user of the\n * app gave. Both are written through the SDK control API to every target of\n * the destination in force: online `POST <org>/v1/sdk/scores` (scope\n * `sdk:write`), local `POST <machine>/api/obs/scores`, `both` to each with\n * the same `id`, so the stored score id is the same on both sides. They land\n * on the existing owners (org annotations, machine `obs_eval_scores`); the\n * SDK adds no store of its own.\n *\n * The id makes a write idempotent: the SDK mints `sdk_<32 hex>` when you\n * give none and reuses it on its one retry, so a retried write never doubles\n * a score.\n *\n * Nothing throws: a score the scorecore rules refuse (a bad name, a kind\n * that disagrees with the value, no trace) resolves with `ok: false` and an\n * error naming the contract's code, before any call; network and server\n * failures resolve the same way. flush() waits for pending writes.\n */\n\nimport { apiTimeout, call, noTargetReason, retryable, targets, track, type ControlOptions, type Route } from \"./control.js\";\nimport { getCurrentTraceId } from \"./spans.js\";\nimport { destinationKnown } from \"./runtime.js\";\n\nexport const SCORES_ROUTE: Route = { online: \"/scores\", local: \"/api/obs/scores\" };\n\n/** numeric, boolean or categorical; inferred from the value's type when not given. */\nexport type ScoreKind = \"numeric\" | \"boolean\" | \"categorical\";\nexport const SCORE_KINDS: readonly ScoreKind[] = [\"numeric\", \"boolean\", \"categorical\"];\nexport const DEFAULT_FEEDBACK_NAME = \"user_feedback\";\n\nconst NAME = /^[a-z0-9_.-]{1,64}$/;\nconst ID = /^[A-Za-z0-9_.:-]{1,128}$/;\nconst TRACE = /^[0-9a-f]{32}$/;\nconst SPAN = /^[0-9a-f]{16}$/;\nconst MAX_VALUE_BYTES = 120;\nconst MAX_COMMENT_BYTES = 2000;\nconst MAX_SCORER_NAME = 64;\nconst MAX_SCORER_VERSION = 32;\n\nexport interface ScoreOptions extends ControlOptions {\n /** Defaults to the active trace. */\n traceId?: string;\n /** Score one span of the trace; unset, the score is trace-level (also inside a span, as in Python). */\n spanId?: string;\n comment?: string;\n /** The value kind; must agree with the value's type (`kind_mismatch` otherwise). */\n kind?: ScoreKind;\n /** The automated scorer that produced the value (1-64 chars). */\n scorer?: string;\n /** Its version (1-32 chars; default \"1\" when `scorer` is set), so two versions' results coexist. */\n scorerVersion?: string;\n /** An experiment run id: ties the score to that run. */\n runId?: string;\n /** The idempotency id (default `sdk_<32 hex>`, fresh per call). */\n scoreId?: string;\n /** When the judgement was made (default: the server's receive time). */\n timestamp?: Date | string;\n}\n\n/** One destination's outcome. */\nexport interface ScoreDestinationResult {\n ok: boolean;\n status: number;\n /** The stored score id (`sc_...`) this destination returned (\"\" when it did not accept). */\n id: string;\n error: string;\n}\n\nexport interface ScoreResult {\n /** True when EVERY destination accepted the score (as in Python). */\n ok: boolean;\n /** The stored score id (`sc_...`) the first accepting destination returned. */\n id: string;\n /** The idempotency id that was sent. */\n clientId: string;\n /** Each destination's outcome, by name (`local`, `online`). */\n destinations: Record<string, ScoreDestinationResult>;\n /** Every problem: validation (`<code>: <message>`) or per destination (`<name>: <error>`). */\n errors: string[];\n}\n\n/** A score the rules refuse (contract scores.md section 1; the code is the contract's). */\nexport class ScoreError extends Error {\n constructor(\n readonly code: string,\n message: string,\n ) {\n super(`${code}: ${message}`);\n this.name = \"ScoreError\";\n }\n}\n\nfunction kindOf(value: unknown): ScoreKind {\n if (typeof value === \"boolean\") return \"boolean\";\n if (typeof value === \"number\") return \"numeric\";\n if (typeof value === \"string\") return \"categorical\";\n throw new ScoreError(\"invalid_value\", `value must be a number, a boolean or a string, got ${value === null ? \"null\" : typeof value}`);\n}\n\nconst bytes = (s: string) => new TextEncoder().encode(s).length;\n\nfunction randomHex32(): string {\n const c = (globalThis as { crypto?: { getRandomValues?: (a: Uint8Array) => Uint8Array } }).crypto;\n const a = new Uint8Array(16);\n if (c?.getRandomValues) c.getRandomValues(a);\n else for (let i = 0; i < a.length; i++) a[i] = Math.floor(Math.random() * 256);\n return [...a].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\ninterface BuildOptions extends ScoreOptions {\n source?: \"sdk\" | \"feedback\";\n}\n\n/**\n * The wire score object (scores.md section 1), validated with the scorecore\n * rules. Throws ScoreError naming the contract's code (`score()` turns that\n * into a result; this is exported for tests and advanced callers).\n */\nexport function buildScore(name: string, value: unknown, o: BuildOptions = {}): Record<string, unknown> {\n const n = String(name ?? \"\")\n .trim()\n .toLowerCase();\n if (!NAME.test(n)) throw new ScoreError(\"invalid_name\", `name ${JSON.stringify(name)} must be 1-64 chars of a-z 0-9 _ . -`);\n const inferred = kindOf(value);\n if (o.kind !== undefined && o.kind !== inferred) {\n if (!SCORE_KINDS.includes(o.kind)) throw new ScoreError(\"kind_mismatch\", `kind ${JSON.stringify(o.kind)} is not numeric, boolean or categorical`);\n throw new ScoreError(\"kind_mismatch\", `kind ${o.kind} does not match a ${typeof value} value`);\n }\n let v = value as number | string | boolean;\n if (inferred === \"numeric\" && !Number.isFinite(v)) throw new ScoreError(\"invalid_value\", `value ${String(v)} is not a finite number`);\n if (inferred === \"categorical\") {\n const t = String(v).trim();\n if (!t || bytes(t) > MAX_VALUE_BYTES || /[\\r\\n]/.test(t)) {\n throw new ScoreError(\"invalid_value\", `a categorical value must be 1-${MAX_VALUE_BYTES} bytes on one line`);\n }\n v = t;\n }\n const tid = (o.traceId || getCurrentTraceId()).trim().toLowerCase();\n if (!tid) throw new ScoreError(\"invalid_trace_id\", \"no traceId given and no current span\");\n if (!TRACE.test(tid) || /^0+$/.test(tid)) throw new ScoreError(\"invalid_trace_id\", `traceId ${JSON.stringify(o.traceId)} must be 32 hex characters, not all zero`);\n const sid = (o.spanId ?? \"\").trim().toLowerCase();\n if (sid && (!SPAN.test(sid) || /^0+$/.test(sid))) throw new ScoreError(\"invalid_span_id\", `spanId ${JSON.stringify(o.spanId)} must be 16 hex characters`);\n if (o.comment != null && bytes(String(o.comment)) > MAX_COMMENT_BYTES) throw new ScoreError(\"comment_too_long\", `comment is over ${MAX_COMMENT_BYTES} bytes`);\n const cid = o.scoreId || `sdk_${randomHex32()}`;\n if (!ID.test(cid)) throw new ScoreError(\"invalid_id\", `scoreId ${JSON.stringify(o.scoreId)} must be 1-128 chars of A-Z a-z 0-9 _ . : -`);\n const source = o.source ?? \"sdk\";\n if (source !== \"sdk\" && source !== \"feedback\") throw new ScoreError(\"invalid_source\", `source ${JSON.stringify(source)} must be sdk or feedback`);\n const out: Record<string, unknown> = { id: cid, trace_id: tid, name: n, value: v, kind: inferred, source };\n if (sid) out.span_id = sid;\n if (o.comment) out.comment = String(o.comment);\n if (o.scorer) {\n if (o.scorer.length > MAX_SCORER_NAME || (o.scorerVersion && o.scorerVersion.length > MAX_SCORER_VERSION)) {\n throw new ScoreError(\"bad_request\", \"scorer name is 1-64 chars and version 1-32\");\n }\n out.scorer = { name: o.scorer, version: o.scorerVersion || \"1\" };\n }\n if (o.runId) out.run_id = String(o.runId);\n if (o.timestamp) out.timestamp = o.timestamp instanceof Date ? o.timestamp.toISOString() : o.timestamp;\n return out;\n}\n\nfunction readAnswer(body: unknown): { accepted: Map<number, string>; rejected: Map<number, string> } {\n const b = (body && typeof body === \"object\" ? body : {}) as Record<string, unknown>;\n const arr = (v: unknown) => (Array.isArray(v) ? v.filter((x) => x && typeof x === \"object\") : []) as Record<string, unknown>[];\n const accepted = new Map<number, string>();\n const rejected = new Map<number, string>();\n for (const a of arr(b.accepted)) accepted.set(typeof a.index === \"number\" ? a.index : 0, typeof a.id === \"string\" ? a.id : \"\");\n for (const r of arr(b.rejected)) {\n const msg = `${String(r.error ?? \"rejected\")}: ${String(r.message ?? \"\")}`.replace(/: $/, \"\");\n rejected.set(typeof r.index === \"number\" ? r.index : 0, msg);\n }\n return { accepted, rejected };\n}\n\nlet lastLog = 0;\nfunction logFailure(res: ScoreResult): void {\n const now = Date.now();\n if (now - lastLog < 60_000) return;\n lastLog = now;\n try {\n console.warn(`@superbased/sdk: a score was not stored: ${res.errors.join(\"; \") || \"unknown\"}`);\n } catch {\n // ignore\n }\n}\n\nfunction write(name: string, value: unknown, o: BuildOptions): Promise<ScoreResult> {\n let body: Record<string, unknown>;\n try {\n body = buildScore(name, value, o);\n } catch (err) {\n const res: ScoreResult = { ok: false, id: \"\", clientId: \"\", destinations: {}, errors: [err instanceof Error ? err.message : String(err)] };\n logFailure(res);\n return Promise.resolve(res);\n }\n const res: ScoreResult = { ok: false, id: \"\", clientId: body.id as string, destinations: {}, errors: [] };\n // The body (and the trace it scores) is fixed now; the target waits for the\n // destination (review E-33).\n const work = destinationKnown().then(() => send(body, res, o));\n return track(work);\n}\n\nfunction send(body: Record<string, unknown>, res: ScoreResult, o: BuildOptions): Promise<ScoreResult> {\n const ts = targets(\"write\", o);\n if (!ts.length) {\n res.errors.push(noTargetReason());\n logFailure(res);\n return Promise.resolve(res);\n }\n const timeoutMs = apiTimeout(o);\n return Promise.all(\n ts.map(async (t) => {\n let r = await call(t, \"POST\", SCORES_ROUTE, { body, timeoutMs });\n if (retryable(r)) r = await call(t, \"POST\", SCORES_ROUTE, { body, timeoutMs });\n const ans = readAnswer(r.body);\n const ok = r.ok && ans.accepted.has(0) && !ans.rejected.has(0);\n const error = ok ? \"\" : ans.rejected.get(0) || `${r.status ? `HTTP ${r.status} ` : \"\"}${r.error}${r.message ? `: ${r.message}` : \"\"}`;\n return { name: t.name, out: { ok, status: r.status, id: ok ? (ans.accepted.get(0) ?? \"\") : \"\", error } };\n }),\n ).then((rows) => {\n for (const { name: n, out } of rows) {\n res.destinations[n] = out;\n if (out.ok) res.id = res.id || out.id;\n else res.errors.push(`${n}: ${out.error}`);\n }\n res.ok = rows.length > 0 && rows.every((r) => r.out.ok);\n if (!res.ok) logFailure(res);\n return res;\n });\n}\n\n/**\n * Attach a score to a trace (or one span of it). Never throws.\n *\n * ```ts\n * await score(\"faithfulness\", 0.92, { traceId, scorer: \"judge\", scorerVersion: \"3\" });\n * ```\n */\nexport function score(name: string, value: number | string | boolean, opts: ScoreOptions = {}): Promise<ScoreResult> {\n return write(name, value, { ...opts, source: \"sdk\" });\n}\n\nexport interface FeedbackOptions extends Omit<ScoreOptions, \"kind\" | \"scorer\" | \"scorerVersion\" | \"runId\"> {\n /** The score name (default `user_feedback`). */\n name?: string;\n}\n\n/**\n * Record an end user's feedback on a trace: a score with source `feedback`.\n * 👍/👎 as true/false, a rating as a number, or a label. Call it from the\n * request that receives the reaction (for example the backend route the\n * `@superbased/feedback-widget` posts to), with the trace id your app got\n * from `getCurrentTraceId()` when it answered. Never throws.\n */\nexport function feedback(value: number | string | boolean, opts: FeedbackOptions = {}): Promise<ScoreResult> {\n const { name, ...rest } = opts;\n return write(name || DEFAULT_FEEDBACK_NAME, value, { ...rest, source: \"feedback\" });\n}\n"]}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Span helpers: `withSpan` / `observe` and the typed helpers for LLM, tool,
|
|
3
|
+
* retriever, agent and embedding spans. Every key they write is in attrs.ts.
|
|
4
|
+
*/
|
|
5
|
+
import { type Span } from "@opentelemetry/api";
|
|
6
|
+
import { REQUEST_PARAMS } from "./attrs.js";
|
|
7
|
+
/** Canonical OpenInference span kinds (Observer normalizes either case). */
|
|
8
|
+
export declare const Kind: {
|
|
9
|
+
readonly LLM: "LLM";
|
|
10
|
+
readonly TOOL: "TOOL";
|
|
11
|
+
readonly RETRIEVER: "RETRIEVER";
|
|
12
|
+
readonly EMBEDDING: "EMBEDDING";
|
|
13
|
+
readonly CHAIN: "CHAIN";
|
|
14
|
+
readonly AGENT: "AGENT";
|
|
15
|
+
readonly GUARDRAIL: "GUARDRAIL";
|
|
16
|
+
readonly EVALUATOR: "EVALUATOR";
|
|
17
|
+
};
|
|
18
|
+
export type SpanKind = (typeof Kind)[keyof typeof Kind];
|
|
19
|
+
export interface SpanOptions {
|
|
20
|
+
kind?: SpanKind;
|
|
21
|
+
attributes?: Record<string, unknown>;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Run `fn` inside a span. A sync callback's value is returned synchronously;
|
|
25
|
+
* a promise is returned for an async one. Records an exception once, sets
|
|
26
|
+
* ERROR and `error.type` on failure; sets OK on success unless `fn` already
|
|
27
|
+
* set a status (an ERROR you set is kept).
|
|
28
|
+
*
|
|
29
|
+
* ```ts
|
|
30
|
+
* withSpan("plan", (span) => plan());
|
|
31
|
+
* withSpan("search", { kind: Kind.TOOL, attributes: { "tool.name": "search" } }, () => search(q));
|
|
32
|
+
* ```
|
|
33
|
+
*
|
|
34
|
+
* The A7 form `withSpan(name, kind, fn, attributes)` still works.
|
|
35
|
+
*/
|
|
36
|
+
export declare function withSpan<T>(name: string, fn: (span: Span) => T): T;
|
|
37
|
+
export declare function withSpan<T>(name: string, opts: SpanOptions, fn: (span: Span) => T): T;
|
|
38
|
+
export declare function withSpan<T>(name: string, kind: SpanKind, fn: (span: Span) => T, attributes?: Record<string, unknown>): T;
|
|
39
|
+
export interface ObserveOptions {
|
|
40
|
+
/** Span name (default: the function's name, else "observe"). */
|
|
41
|
+
name?: string;
|
|
42
|
+
kind?: SpanKind;
|
|
43
|
+
attributes?: Record<string, unknown>;
|
|
44
|
+
/** Record the call's arguments as `input.value` and its result as `output.value` (subject to captureContent). Default false. */
|
|
45
|
+
captureIo?: boolean;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Wrap a function so each call runs in a span. Works for sync and async
|
|
49
|
+
* functions (the span covers the awaited result); `this` and arguments pass
|
|
50
|
+
* through unchanged.
|
|
51
|
+
*
|
|
52
|
+
* ```ts
|
|
53
|
+
* const answer = observe(async (q: string) => llm(q), { name: "answer", kind: Kind.AGENT });
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
export declare function observe<A extends unknown[], R>(fn: (...args: A) => R, opts?: ObserveOptions): (...args: A) => R;
|
|
57
|
+
/** Set a span's serialized input (`input.value`), subject to captureContent. */
|
|
58
|
+
export declare function setInput(span: Span, input: unknown): void;
|
|
59
|
+
/** Set a span's serialized output (`output.value`; on a RETRIEVER span, `gen_ai.retrieval.documents`). */
|
|
60
|
+
export declare function setOutput(span: Span, output: unknown): void;
|
|
61
|
+
/** Anything that can stamp a prompt's identity on a span (a fetched {@link Prompt}). */
|
|
62
|
+
export interface PromptRef {
|
|
63
|
+
stamp(span?: Span): void;
|
|
64
|
+
}
|
|
65
|
+
export interface LlmInfo {
|
|
66
|
+
model?: string;
|
|
67
|
+
provider?: string;
|
|
68
|
+
/** `gen_ai.operation.name` (default "chat"). */
|
|
69
|
+
operation?: string;
|
|
70
|
+
/**
|
|
71
|
+
* The request: a string (`input.value`) or a message list
|
|
72
|
+
* (`gen_ai.input.messages`); content. A `Prompt` from `getPrompt()` stamps
|
|
73
|
+
* `sbo.prompt.*` on the span and records no content (the contract's
|
|
74
|
+
* `llm_span(prompt=<Prompt>)`; review E-49).
|
|
75
|
+
*/
|
|
76
|
+
prompt?: string | unknown[] | PromptRef;
|
|
77
|
+
/** System instructions (`gen_ai.system_instructions`); content. */
|
|
78
|
+
system?: unknown;
|
|
79
|
+
/** @deprecated Pass the fetched prompt as `prompt`; still read (review E-49). */
|
|
80
|
+
promptRef?: PromptRef;
|
|
81
|
+
attributes?: Record<string, unknown>;
|
|
82
|
+
}
|
|
83
|
+
/** withSpan for an LLM call: pre-tags `gen_ai.operation.name`, model and
|
|
84
|
+
* `gen_ai.provider.name` (plus the legacy `gen_ai.system`) and the
|
|
85
|
+
* OpenInference `llm.*` keys. Pass the response via setUsage({ response }). */
|
|
86
|
+
export declare function withLlmSpan<T>(name: string, info: LlmInfo, fn: (span: Span) => T): T;
|
|
87
|
+
export interface Usage {
|
|
88
|
+
/**
|
|
89
|
+
* Input tokens, GROSS: including cache-read and cache-write tokens (the
|
|
90
|
+
* GenAI semconv bucket). For a provider that reports net input (Anthropic),
|
|
91
|
+
* pass input + cache read + cache write.
|
|
92
|
+
*/
|
|
93
|
+
inputTokens?: number;
|
|
94
|
+
/** Output tokens, including reasoning tokens. */
|
|
95
|
+
outputTokens?: number;
|
|
96
|
+
/** Optional; Observer derives input + output when it is absent. */
|
|
97
|
+
totalTokens?: number;
|
|
98
|
+
/** Input tokens served from the prompt cache (a subset of inputTokens). */
|
|
99
|
+
cacheReadTokens?: number;
|
|
100
|
+
/** Input tokens written to the prompt cache (a subset of inputTokens). */
|
|
101
|
+
cacheWriteTokens?: number;
|
|
102
|
+
/** Reasoning / thinking tokens (a subset of outputTokens). */
|
|
103
|
+
reasoningTokens?: number;
|
|
104
|
+
responseId?: string;
|
|
105
|
+
requestId?: string;
|
|
106
|
+
responseModel?: string;
|
|
107
|
+
/** Why the model stopped (`gen_ai.response.finish_reasons`). */
|
|
108
|
+
finishReasons?: string[];
|
|
109
|
+
/** A reported cost. Observer prefers its own computed cost when it prices the model. */
|
|
110
|
+
costUsd?: number;
|
|
111
|
+
/** Request body; content. */
|
|
112
|
+
prompt?: string | unknown[];
|
|
113
|
+
/** Response body; content. */
|
|
114
|
+
response?: string | unknown[];
|
|
115
|
+
}
|
|
116
|
+
/** Reset the once-per-process net-input warning (tests only). */
|
|
117
|
+
export declare function _resetNetInputWarningForTests(): void;
|
|
118
|
+
/** Record token usage / ids on an LLM span with the keys Observer reconciles
|
|
119
|
+
* against proxy turns. `responseId` (the provider message id) doubles as the
|
|
120
|
+
* dedup key when no `requestId` is set. A negative count is a RangeError; a
|
|
121
|
+
* fraction is truncated. `inputTokens` is the GROSS input (cache reads and
|
|
122
|
+
* writes included); one below `cacheReadTokens + cacheWriteTokens` is read as
|
|
123
|
+
* a net count (Anthropic's `usage.input_tokens`), recorded as input + cache,
|
|
124
|
+
* counted in `diagnostics().usageNetInputCorrected` and warned about once. */
|
|
125
|
+
export declare function setUsage(span: Span, u: Usage): void;
|
|
126
|
+
export interface Content {
|
|
127
|
+
/** LLM request: a string or a message list (or, on a TOOL span, the tool args). */
|
|
128
|
+
prompt?: unknown;
|
|
129
|
+
/** LLM response: a string or a message list (or, on a TOOL span, the tool result). */
|
|
130
|
+
response?: unknown;
|
|
131
|
+
/** Tool call arguments. */
|
|
132
|
+
toolArgs?: unknown;
|
|
133
|
+
/** Tool call result. */
|
|
134
|
+
toolResult?: unknown;
|
|
135
|
+
}
|
|
136
|
+
/** Attach request/response bodies (LLM span: `input.value` / `output.value`,
|
|
137
|
+
* or `gen_ai.input.messages` / `gen_ai.output.messages` for a message list;
|
|
138
|
+
* TOOL span: `gen_ai.tool.call.arguments` / `.result`). No-op when capture is
|
|
139
|
+
* off; each body is clipped to maxContentChars. */
|
|
140
|
+
export declare function setContent(span: Span, c: Content): void;
|
|
141
|
+
export type RequestParams = {
|
|
142
|
+
[P in keyof typeof REQUEST_PARAMS]?: P extends "stopSequences" ? string[] : P extends "stream" ? boolean : P extends "reasoningLevel" ? string : number;
|
|
143
|
+
};
|
|
144
|
+
/** Record the request's sampling parameters (`gen_ai.request.*`). */
|
|
145
|
+
export declare function setRequestParams(span: Span, p: RequestParams): void;
|
|
146
|
+
export interface ToolInfo {
|
|
147
|
+
/** The tool's name (default: the span name). */
|
|
148
|
+
toolName?: string;
|
|
149
|
+
/** The model's tool-call id, when the call came from a model. */
|
|
150
|
+
callId?: string;
|
|
151
|
+
/** The call's arguments (any JSON value); content. */
|
|
152
|
+
arguments?: unknown;
|
|
153
|
+
attributes?: Record<string, unknown>;
|
|
154
|
+
}
|
|
155
|
+
/** withSpan for a tool call (`execute_tool`). Record the result with setToolResult. */
|
|
156
|
+
export declare function withToolSpan<T>(name: string, info: ToolInfo, fn: (span: Span) => T): T;
|
|
157
|
+
/** Record a tool call's result (`gen_ai.tool.call.result`); content. */
|
|
158
|
+
export declare function setToolResult(span: Span, result: unknown): void;
|
|
159
|
+
export interface RetrieverInfo {
|
|
160
|
+
/** The query text; content. */
|
|
161
|
+
query?: string;
|
|
162
|
+
attributes?: Record<string, unknown>;
|
|
163
|
+
}
|
|
164
|
+
/** One retrieved document. */
|
|
165
|
+
export interface Document {
|
|
166
|
+
id?: string;
|
|
167
|
+
content?: string;
|
|
168
|
+
score?: number;
|
|
169
|
+
metadata?: Record<string, unknown>;
|
|
170
|
+
}
|
|
171
|
+
/** withSpan for a retrieval (`retrieval`). Record what came back with setDocuments. */
|
|
172
|
+
export declare function withRetrieverSpan<T>(name: string, info: RetrieverInfo, fn: (span: Span) => T): T;
|
|
173
|
+
/** Record retrieved documents (`gen_ai.retrieval.documents`, a JSON array); content. */
|
|
174
|
+
export declare function setDocuments(span: Span, docs: Array<string | Document>): void;
|
|
175
|
+
export interface AgentInfo {
|
|
176
|
+
/** The agent's name (default: the span name). */
|
|
177
|
+
agentName?: string;
|
|
178
|
+
agentId?: string;
|
|
179
|
+
attributes?: Record<string, unknown>;
|
|
180
|
+
}
|
|
181
|
+
/** withSpan for an agent run (`invoke_agent`). Record input and answer with setInput / setOutput. */
|
|
182
|
+
export declare function withAgentSpan<T>(name: string, info: AgentInfo, fn: (span: Span) => T): T;
|
|
183
|
+
export interface EmbeddingInfo {
|
|
184
|
+
model?: string;
|
|
185
|
+
provider?: string;
|
|
186
|
+
attributes?: Record<string, unknown>;
|
|
187
|
+
}
|
|
188
|
+
/** withSpan for an embedding call (`embeddings`). Record tokens with setUsage({ inputTokens }). */
|
|
189
|
+
export declare function withEmbeddingSpan<T>(name: string, info: EmbeddingInfo, fn: (span: Span) => T): T;
|
|
190
|
+
/** The active trace id (32 hex), or "" outside a span. Use it to attach a score later. */
|
|
191
|
+
export declare function getCurrentTraceId(): string;
|
|
192
|
+
/** The active span id (16 hex), or "" outside a span. */
|
|
193
|
+
export declare function getCurrentSpanId(): string;
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Span helpers: `withSpan` / `observe` and the typed helpers for LLM, tool,
|
|
4
|
+
* retriever, agent and embedding spans. Every key they write is in attrs.ts.
|
|
5
|
+
*/
|
|
6
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
+
exports.Kind = void 0;
|
|
8
|
+
exports.withSpan = withSpan;
|
|
9
|
+
exports.observe = observe;
|
|
10
|
+
exports.setInput = setInput;
|
|
11
|
+
exports.setOutput = setOutput;
|
|
12
|
+
exports.withLlmSpan = withLlmSpan;
|
|
13
|
+
exports._resetNetInputWarningForTests = _resetNetInputWarningForTests;
|
|
14
|
+
exports.setUsage = setUsage;
|
|
15
|
+
exports.setContent = setContent;
|
|
16
|
+
exports.setRequestParams = setRequestParams;
|
|
17
|
+
exports.withToolSpan = withToolSpan;
|
|
18
|
+
exports.setToolResult = setToolResult;
|
|
19
|
+
exports.withRetrieverSpan = withRetrieverSpan;
|
|
20
|
+
exports.setDocuments = setDocuments;
|
|
21
|
+
exports.withAgentSpan = withAgentSpan;
|
|
22
|
+
exports.withEmbeddingSpan = withEmbeddingSpan;
|
|
23
|
+
exports.getCurrentTraceId = getCurrentTraceId;
|
|
24
|
+
exports.getCurrentSpanId = getCurrentSpanId;
|
|
25
|
+
const api_1 = require("@opentelemetry/api");
|
|
26
|
+
const attrs_js_1 = require("./attrs.js");
|
|
27
|
+
const policy_js_1 = require("./policy.js");
|
|
28
|
+
const runtime_js_1 = require("./runtime.js");
|
|
29
|
+
/** Canonical OpenInference span kinds (Observer normalizes either case). */
|
|
30
|
+
exports.Kind = {
|
|
31
|
+
LLM: "LLM",
|
|
32
|
+
TOOL: "TOOL",
|
|
33
|
+
RETRIEVER: "RETRIEVER",
|
|
34
|
+
EMBEDDING: "EMBEDDING",
|
|
35
|
+
CHAIN: "CHAIN",
|
|
36
|
+
AGENT: "AGENT",
|
|
37
|
+
GUARDRAIL: "GUARDRAIL",
|
|
38
|
+
EVALUATOR: "EVALUATOR",
|
|
39
|
+
};
|
|
40
|
+
function statusUnset(span) {
|
|
41
|
+
const st = span.status;
|
|
42
|
+
return !st || st.code === undefined || st.code === api_1.SpanStatusCode.UNSET;
|
|
43
|
+
}
|
|
44
|
+
function markOk(span) {
|
|
45
|
+
try {
|
|
46
|
+
if (statusUnset(span))
|
|
47
|
+
span.setStatus({ code: api_1.SpanStatusCode.OK });
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
// ignore
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function markError(span, err) {
|
|
54
|
+
try {
|
|
55
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
56
|
+
span.recordException(e);
|
|
57
|
+
span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: `${e.name}: ${e.message}` });
|
|
58
|
+
const attrs = span.attributes ?? {};
|
|
59
|
+
if (!(attrs_js_1.K.errorType in attrs))
|
|
60
|
+
span.setAttribute(attrs_js_1.K.errorType, e.name || "Error");
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
// ignore
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function isThenable(v) {
|
|
67
|
+
return v != null && (typeof v === "object" || typeof v === "function") && typeof v.then === "function";
|
|
68
|
+
}
|
|
69
|
+
function clean(attrs) {
|
|
70
|
+
const out = {};
|
|
71
|
+
for (const [k, v] of Object.entries(attrs)) {
|
|
72
|
+
if (v === undefined || v === null || v === "")
|
|
73
|
+
continue;
|
|
74
|
+
out[k] = v;
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
function runSpan(name, kind, fn, attributes = {}) {
|
|
79
|
+
return (0, runtime_js_1.tracer)().startActiveSpan(name, { attributes: clean({ [attrs_js_1.K.spanKind]: kind, ...attributes }) }, (span) => {
|
|
80
|
+
let out;
|
|
81
|
+
try {
|
|
82
|
+
out = fn(span);
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
markError(span, err);
|
|
86
|
+
span.end();
|
|
87
|
+
throw err;
|
|
88
|
+
}
|
|
89
|
+
if (isThenable(out)) {
|
|
90
|
+
return Promise.resolve(out).then((v) => {
|
|
91
|
+
markOk(span);
|
|
92
|
+
span.end();
|
|
93
|
+
return v;
|
|
94
|
+
}, (err) => {
|
|
95
|
+
markError(span, err);
|
|
96
|
+
span.end();
|
|
97
|
+
throw err;
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
markOk(span);
|
|
101
|
+
span.end();
|
|
102
|
+
return out;
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
function withSpan(name, a, b, attributes) {
|
|
106
|
+
if (typeof a === "function")
|
|
107
|
+
return runSpan(name, exports.Kind.CHAIN, a);
|
|
108
|
+
if (typeof a === "string")
|
|
109
|
+
return runSpan(name, a, b, attributes);
|
|
110
|
+
return runSpan(name, a?.kind ?? exports.Kind.CHAIN, b, a?.attributes);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Wrap a function so each call runs in a span. Works for sync and async
|
|
114
|
+
* functions (the span covers the awaited result); `this` and arguments pass
|
|
115
|
+
* through unchanged.
|
|
116
|
+
*
|
|
117
|
+
* ```ts
|
|
118
|
+
* const answer = observe(async (q: string) => llm(q), { name: "answer", kind: Kind.AGENT });
|
|
119
|
+
* ```
|
|
120
|
+
*/
|
|
121
|
+
function observe(fn, opts = {}) {
|
|
122
|
+
const name = opts.name || fn.name || "observe";
|
|
123
|
+
const kind = opts.kind ?? exports.Kind.CHAIN;
|
|
124
|
+
const wrapped = function (...args) {
|
|
125
|
+
return runSpan(name, kind, (span) => {
|
|
126
|
+
if (opts.captureIo)
|
|
127
|
+
setInput(span, args.length === 1 ? args[0] : args);
|
|
128
|
+
const out = fn.apply(this, args);
|
|
129
|
+
if (!opts.captureIo)
|
|
130
|
+
return out;
|
|
131
|
+
if (isThenable(out)) {
|
|
132
|
+
return Promise.resolve(out).then((v) => {
|
|
133
|
+
setOutput(span, v);
|
|
134
|
+
return v;
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
setOutput(span, out);
|
|
138
|
+
return out;
|
|
139
|
+
}, opts.attributes);
|
|
140
|
+
};
|
|
141
|
+
Object.defineProperty(wrapped, "name", { value: fn.name, configurable: true });
|
|
142
|
+
return wrapped;
|
|
143
|
+
}
|
|
144
|
+
function recording(span) {
|
|
145
|
+
try {
|
|
146
|
+
if (!span)
|
|
147
|
+
return false;
|
|
148
|
+
return typeof span.isRecording === "function" ? span.isRecording() : true;
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
function spanKindOf(span) {
|
|
155
|
+
const a = span.attributes ?? {};
|
|
156
|
+
return String(a[attrs_js_1.K.spanKind] ?? "").toUpperCase();
|
|
157
|
+
}
|
|
158
|
+
function contentAttr(span, key, v) {
|
|
159
|
+
if (!runtime_js_1.runtime.captureContent || v === undefined || v === null || !recording(span))
|
|
160
|
+
return;
|
|
161
|
+
try {
|
|
162
|
+
span.setAttribute(key, (0, runtime_js_1.truncateContent)((0, runtime_js_1.contentText)(v)));
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
// never raise
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/** Set a span's serialized input (`input.value`), subject to captureContent. */
|
|
169
|
+
function setInput(span, input) {
|
|
170
|
+
contentAttr(span, attrs_js_1.K.inputValue, input);
|
|
171
|
+
}
|
|
172
|
+
/** Set a span's serialized output (`output.value`; on a RETRIEVER span, `gen_ai.retrieval.documents`). */
|
|
173
|
+
function setOutput(span, output) {
|
|
174
|
+
contentAttr(span, recording(span) && spanKindOf(span) === exports.Kind.RETRIEVER ? attrs_js_1.K.retrievalDocuments : attrs_js_1.K.outputValue, output);
|
|
175
|
+
}
|
|
176
|
+
/** A registry prompt (anything with `stamp(span)`), not request content. */
|
|
177
|
+
function isPromptRef(v) {
|
|
178
|
+
return v !== null && typeof v === "object" && !Array.isArray(v) && typeof v.stamp === "function";
|
|
179
|
+
}
|
|
180
|
+
/** withSpan for an LLM call: pre-tags `gen_ai.operation.name`, model and
|
|
181
|
+
* `gen_ai.provider.name` (plus the legacy `gen_ai.system`) and the
|
|
182
|
+
* OpenInference `llm.*` keys. Pass the response via setUsage({ response }). */
|
|
183
|
+
function withLlmSpan(name, info, fn) {
|
|
184
|
+
const attrs = { [attrs_js_1.K.operation]: info.operation ?? "chat" };
|
|
185
|
+
if (info.model) {
|
|
186
|
+
attrs[attrs_js_1.K.requestModel] = info.model;
|
|
187
|
+
attrs[attrs_js_1.K.oiModel] = info.model;
|
|
188
|
+
}
|
|
189
|
+
if (info.provider) {
|
|
190
|
+
attrs[attrs_js_1.K.provider] = info.provider;
|
|
191
|
+
attrs[attrs_js_1.K.systemLegacy] = info.provider;
|
|
192
|
+
attrs[attrs_js_1.K.oiProvider] = info.provider;
|
|
193
|
+
}
|
|
194
|
+
const registry = isPromptRef(info.prompt) ? info.prompt : info.promptRef;
|
|
195
|
+
const content = isPromptRef(info.prompt) ? undefined : info.prompt;
|
|
196
|
+
if (runtime_js_1.runtime.captureContent) {
|
|
197
|
+
if (Array.isArray(content))
|
|
198
|
+
attrs[attrs_js_1.K.inputMessages] = (0, runtime_js_1.truncateContent)((0, runtime_js_1.contentText)(content));
|
|
199
|
+
else if (content != null)
|
|
200
|
+
attrs[attrs_js_1.K.inputValue] = (0, runtime_js_1.truncateContent)(String(content));
|
|
201
|
+
if (info.system != null)
|
|
202
|
+
attrs[attrs_js_1.K.systemInstructions] = (0, runtime_js_1.truncateContent)((0, runtime_js_1.contentText)(info.system));
|
|
203
|
+
}
|
|
204
|
+
Object.assign(attrs, info.attributes ?? {});
|
|
205
|
+
return runSpan(name, exports.Kind.LLM, (span) => {
|
|
206
|
+
if (registry)
|
|
207
|
+
registry.stamp(span);
|
|
208
|
+
return fn(span);
|
|
209
|
+
}, attrs);
|
|
210
|
+
}
|
|
211
|
+
const TOKEN_FIELDS = [
|
|
212
|
+
["inputTokens", attrs_js_1.K.inputTokens],
|
|
213
|
+
["outputTokens", attrs_js_1.K.outputTokens],
|
|
214
|
+
["totalTokens", attrs_js_1.K.totalTokens],
|
|
215
|
+
["cacheReadTokens", attrs_js_1.K.cacheReadTokens],
|
|
216
|
+
["cacheWriteTokens", attrs_js_1.K.cacheWriteTokens],
|
|
217
|
+
["reasoningTokens", attrs_js_1.K.reasoningTokens],
|
|
218
|
+
];
|
|
219
|
+
let netInputWarned = false;
|
|
220
|
+
/** Reset the once-per-process net-input warning (tests only). */
|
|
221
|
+
function _resetNetInputWarningForTests() {
|
|
222
|
+
netInputWarned = false;
|
|
223
|
+
}
|
|
224
|
+
const count = (v) => v != null && Number.isFinite(v) ? Math.trunc(v) : undefined;
|
|
225
|
+
/** The usage with a GROSS input count: `inputTokens` as given, unless it is
|
|
226
|
+
* below its own cache parts. Then it cannot be gross (it is a NET count, as
|
|
227
|
+
* Anthropic's `usage.input_tokens` is), so the cache parts are added (and to a
|
|
228
|
+
* `totalTokens` equal to that net input + output), the correction is counted
|
|
229
|
+
* (`diagnostics().usageNetInputCorrected`) and a warning is logged once. */
|
|
230
|
+
function grossUsage(u) {
|
|
231
|
+
const input = count(u.inputTokens);
|
|
232
|
+
const cache = (count(u.cacheReadTokens) ?? 0) + (count(u.cacheWriteTokens) ?? 0);
|
|
233
|
+
if (input === undefined || input >= cache)
|
|
234
|
+
return u;
|
|
235
|
+
policy_js_1.policyStats.usageNetInputCorrected += 1;
|
|
236
|
+
if (!netInputWarned) {
|
|
237
|
+
netInputWarned = true;
|
|
238
|
+
console.warn(`@superbased/sdk: setUsage inputTokens ${input} is below cacheReadTokens + cacheWriteTokens (${cache}); ` +
|
|
239
|
+
`recorded as a net count (input + cache = ${input + cache}). Pass the gross input: for Anthropic, ` +
|
|
240
|
+
"usage.input_tokens + cache_creation_input_tokens + cache_read_input_tokens.");
|
|
241
|
+
}
|
|
242
|
+
const out = { ...u, inputTokens: input + cache };
|
|
243
|
+
const total = count(u.totalTokens);
|
|
244
|
+
if (total !== undefined && total === input + (count(u.outputTokens) ?? 0))
|
|
245
|
+
out.totalTokens = total + cache;
|
|
246
|
+
return out;
|
|
247
|
+
}
|
|
248
|
+
/** Record token usage / ids on an LLM span with the keys Observer reconciles
|
|
249
|
+
* against proxy turns. `responseId` (the provider message id) doubles as the
|
|
250
|
+
* dedup key when no `requestId` is set. A negative count is a RangeError; a
|
|
251
|
+
* fraction is truncated. `inputTokens` is the GROSS input (cache reads and
|
|
252
|
+
* writes included); one below `cacheReadTokens + cacheWriteTokens` is read as
|
|
253
|
+
* a net count (Anthropic's `usage.input_tokens`), recorded as input + cache,
|
|
254
|
+
* counted in `diagnostics().usageNetInputCorrected` and warned about once. */
|
|
255
|
+
function setUsage(span, u) {
|
|
256
|
+
for (const [field, key] of TOKEN_FIELDS) {
|
|
257
|
+
const v = u[field];
|
|
258
|
+
if (v != null && Number.isFinite(v) && v < 0)
|
|
259
|
+
throw new RangeError(`@superbased/sdk: ${field} must not be negative`);
|
|
260
|
+
}
|
|
261
|
+
if (!recording(span))
|
|
262
|
+
return;
|
|
263
|
+
u = grossUsage(u);
|
|
264
|
+
try {
|
|
265
|
+
for (const [field, key] of TOKEN_FIELDS) {
|
|
266
|
+
const v = u[field];
|
|
267
|
+
if (v != null && Number.isFinite(v))
|
|
268
|
+
span.setAttribute(key, Math.trunc(v));
|
|
269
|
+
}
|
|
270
|
+
if (u.responseId)
|
|
271
|
+
span.setAttribute(attrs_js_1.K.responseId, u.responseId);
|
|
272
|
+
if (u.requestId)
|
|
273
|
+
span.setAttribute(attrs_js_1.K.requestId, u.requestId);
|
|
274
|
+
if (u.responseModel)
|
|
275
|
+
span.setAttribute(attrs_js_1.K.responseModel, u.responseModel);
|
|
276
|
+
if (u.finishReasons?.length)
|
|
277
|
+
span.setAttribute(attrs_js_1.K.finishReasons, u.finishReasons.map(String));
|
|
278
|
+
if (u.costUsd != null && Number.isFinite(u.costUsd))
|
|
279
|
+
span.setAttribute(attrs_js_1.K.cost, u.costUsd);
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
// never raise
|
|
283
|
+
}
|
|
284
|
+
if (u.prompt != null || u.response != null)
|
|
285
|
+
setContent(span, { prompt: u.prompt, response: u.response });
|
|
286
|
+
}
|
|
287
|
+
/** Attach request/response bodies (LLM span: `input.value` / `output.value`,
|
|
288
|
+
* or `gen_ai.input.messages` / `gen_ai.output.messages` for a message list;
|
|
289
|
+
* TOOL span: `gen_ai.tool.call.arguments` / `.result`). No-op when capture is
|
|
290
|
+
* off; each body is clipped to maxContentChars. */
|
|
291
|
+
function setContent(span, c) {
|
|
292
|
+
if (!runtime_js_1.runtime.captureContent || !recording(span))
|
|
293
|
+
return;
|
|
294
|
+
const tool = spanKindOf(span) === exports.Kind.TOOL;
|
|
295
|
+
const req = c.prompt ?? c.toolArgs;
|
|
296
|
+
const res = c.response ?? c.toolResult;
|
|
297
|
+
// Only a list whose every element is an object is a message list.
|
|
298
|
+
const isMessages = (v) => Array.isArray(v) && v.every((m) => m !== null && typeof m === "object" && !Array.isArray(m));
|
|
299
|
+
if (req != null)
|
|
300
|
+
contentAttr(span, tool ? attrs_js_1.K.toolArguments : isMessages(req) ? attrs_js_1.K.inputMessages : attrs_js_1.K.inputValue, req);
|
|
301
|
+
if (res != null)
|
|
302
|
+
contentAttr(span, tool ? attrs_js_1.K.toolResult : isMessages(res) ? attrs_js_1.K.outputMessages : attrs_js_1.K.outputValue, res);
|
|
303
|
+
}
|
|
304
|
+
/** Record the request's sampling parameters (`gen_ai.request.*`). */
|
|
305
|
+
function setRequestParams(span, p) {
|
|
306
|
+
if (!recording(span))
|
|
307
|
+
return;
|
|
308
|
+
try {
|
|
309
|
+
for (const [name, key] of Object.entries(attrs_js_1.REQUEST_PARAMS)) {
|
|
310
|
+
const v = p[name];
|
|
311
|
+
if (v === undefined || v === null)
|
|
312
|
+
continue;
|
|
313
|
+
if (Array.isArray(v))
|
|
314
|
+
span.setAttribute(key, v.map(String));
|
|
315
|
+
else if (typeof v === "number" || typeof v === "boolean" || typeof v === "string")
|
|
316
|
+
span.setAttribute(key, v);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
catch {
|
|
320
|
+
// never raise
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
/** withSpan for a tool call (`execute_tool`). Record the result with setToolResult. */
|
|
324
|
+
function withToolSpan(name, info, fn) {
|
|
325
|
+
const tool = info.toolName || name;
|
|
326
|
+
const attrs = {
|
|
327
|
+
[attrs_js_1.K.operation]: "execute_tool",
|
|
328
|
+
[attrs_js_1.K.toolName]: tool,
|
|
329
|
+
[attrs_js_1.K.oiToolName]: tool,
|
|
330
|
+
[attrs_js_1.K.toolCallId]: info.callId,
|
|
331
|
+
};
|
|
332
|
+
if (info.arguments !== undefined && runtime_js_1.runtime.captureContent)
|
|
333
|
+
attrs[attrs_js_1.K.toolArguments] = (0, runtime_js_1.truncateContent)((0, runtime_js_1.contentText)(info.arguments));
|
|
334
|
+
Object.assign(attrs, info.attributes ?? {});
|
|
335
|
+
return runSpan(name, exports.Kind.TOOL, fn, attrs);
|
|
336
|
+
}
|
|
337
|
+
/** Record a tool call's result (`gen_ai.tool.call.result`); content. */
|
|
338
|
+
function setToolResult(span, result) {
|
|
339
|
+
contentAttr(span, attrs_js_1.K.toolResult, result);
|
|
340
|
+
}
|
|
341
|
+
/** withSpan for a retrieval (`retrieval`). Record what came back with setDocuments. */
|
|
342
|
+
function withRetrieverSpan(name, info, fn) {
|
|
343
|
+
const attrs = { [attrs_js_1.K.operation]: "retrieval" };
|
|
344
|
+
if (info.query != null && runtime_js_1.runtime.captureContent)
|
|
345
|
+
attrs[attrs_js_1.K.retrievalQuery] = (0, runtime_js_1.truncateContent)(String(info.query));
|
|
346
|
+
Object.assign(attrs, info.attributes ?? {});
|
|
347
|
+
return runSpan(name, exports.Kind.RETRIEVER, fn, attrs);
|
|
348
|
+
}
|
|
349
|
+
/** Record retrieved documents (`gen_ai.retrieval.documents`, a JSON array); content. */
|
|
350
|
+
function setDocuments(span, docs) {
|
|
351
|
+
contentAttr(span, attrs_js_1.K.retrievalDocuments, docs.map((d) => (typeof d === "string" ? { content: d } : d)));
|
|
352
|
+
}
|
|
353
|
+
/** withSpan for an agent run (`invoke_agent`). Record input and answer with setInput / setOutput. */
|
|
354
|
+
function withAgentSpan(name, info, fn) {
|
|
355
|
+
const agent = info.agentName || name;
|
|
356
|
+
const attrs = {
|
|
357
|
+
[attrs_js_1.K.operation]: "invoke_agent",
|
|
358
|
+
[attrs_js_1.K.agentName]: agent,
|
|
359
|
+
[attrs_js_1.K.oiAgentName]: agent,
|
|
360
|
+
[attrs_js_1.K.agentId]: info.agentId,
|
|
361
|
+
...(info.attributes ?? {}),
|
|
362
|
+
};
|
|
363
|
+
return runSpan(name, exports.Kind.AGENT, fn, attrs);
|
|
364
|
+
}
|
|
365
|
+
/** withSpan for an embedding call (`embeddings`). Record tokens with setUsage({ inputTokens }). */
|
|
366
|
+
function withEmbeddingSpan(name, info, fn) {
|
|
367
|
+
const attrs = {
|
|
368
|
+
[attrs_js_1.K.operation]: "embeddings",
|
|
369
|
+
[attrs_js_1.K.requestModel]: info.model,
|
|
370
|
+
[attrs_js_1.K.provider]: info.provider,
|
|
371
|
+
[attrs_js_1.K.systemLegacy]: info.provider,
|
|
372
|
+
...(info.attributes ?? {}),
|
|
373
|
+
};
|
|
374
|
+
return runSpan(name, exports.Kind.EMBEDDING, fn, attrs);
|
|
375
|
+
}
|
|
376
|
+
// --- ids ---------------------------------------------------------------------------
|
|
377
|
+
function validId(id, len) {
|
|
378
|
+
return id && id.length === len && /^[0-9a-f]+$/.test(id) && !/^0+$/.test(id) ? id : "";
|
|
379
|
+
}
|
|
380
|
+
/** The active trace id (32 hex), or "" outside a span. Use it to attach a score later. */
|
|
381
|
+
function getCurrentTraceId() {
|
|
382
|
+
try {
|
|
383
|
+
return validId(api_1.trace.getActiveSpan()?.spanContext().traceId, 32);
|
|
384
|
+
}
|
|
385
|
+
catch {
|
|
386
|
+
return "";
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
/** The active span id (16 hex), or "" outside a span. */
|
|
390
|
+
function getCurrentSpanId() {
|
|
391
|
+
try {
|
|
392
|
+
return validId(api_1.trace.getActiveSpan()?.spanContext().spanId, 16);
|
|
393
|
+
}
|
|
394
|
+
catch {
|
|
395
|
+
return "";
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
//# sourceMappingURL=spans.js.map
|