toad-eye 1.1.0 → 2.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.
Files changed (90) hide show
  1. package/README.md +132 -87
  2. package/dist/agent.d.ts +41 -0
  3. package/dist/agent.js +91 -0
  4. package/dist/alerts/channels.d.ts +2 -0
  5. package/dist/alerts/channels.js +81 -0
  6. package/dist/alerts/conditions.d.ts +29 -0
  7. package/dist/alerts/conditions.js +147 -0
  8. package/dist/alerts/grafana.d.ts +5 -0
  9. package/dist/alerts/grafana.js +19 -0
  10. package/dist/alerts/index.d.ts +5 -0
  11. package/dist/alerts/index.js +12 -0
  12. package/dist/alerts/manager.d.ts +13 -0
  13. package/dist/alerts/manager.js +87 -0
  14. package/dist/alerts/types.d.ts +46 -0
  15. package/dist/alerts/types.js +1 -0
  16. package/dist/budget/error.d.ts +10 -0
  17. package/dist/budget/error.js +22 -0
  18. package/dist/budget/index.d.ts +3 -0
  19. package/dist/budget/index.js +2 -0
  20. package/dist/budget/tracker.d.ts +35 -0
  21. package/dist/budget/tracker.js +121 -0
  22. package/dist/budget/types.d.ts +34 -0
  23. package/dist/budget/types.js +1 -0
  24. package/dist/cli.js +127 -18
  25. package/dist/core/metrics.d.ts +14 -0
  26. package/dist/core/metrics.js +119 -0
  27. package/dist/core/pricing.d.ts +24 -0
  28. package/dist/core/pricing.js +52 -0
  29. package/dist/{spans.d.ts → core/spans.d.ts} +3 -1
  30. package/dist/core/spans.js +143 -0
  31. package/dist/core/tracer.d.ts +9 -0
  32. package/dist/core/tracer.js +93 -0
  33. package/dist/drift/baseline.d.ts +16 -0
  34. package/dist/drift/baseline.js +16 -0
  35. package/dist/drift/cosine.d.ts +13 -0
  36. package/dist/drift/cosine.js +39 -0
  37. package/dist/drift/embedding-provider.d.ts +21 -0
  38. package/dist/drift/embedding-provider.js +8 -0
  39. package/dist/drift/index.d.ts +9 -0
  40. package/dist/drift/index.js +8 -0
  41. package/dist/drift/monitor.d.ts +29 -0
  42. package/dist/drift/monitor.js +47 -0
  43. package/dist/drift/openai-embeddings.d.ts +6 -0
  44. package/dist/drift/openai-embeddings.js +26 -0
  45. package/dist/export.d.ts +46 -0
  46. package/dist/export.js +108 -0
  47. package/dist/guard.d.ts +26 -0
  48. package/dist/guard.js +45 -0
  49. package/dist/index.d.ts +17 -5
  50. package/dist/index.js +10 -3
  51. package/dist/instrumentations/anthropic.d.ts +1 -0
  52. package/dist/instrumentations/anthropic.js +73 -0
  53. package/dist/instrumentations/create.d.ts +11 -0
  54. package/dist/instrumentations/create.js +165 -0
  55. package/dist/instrumentations/gemini.d.ts +1 -0
  56. package/dist/instrumentations/gemini.js +48 -0
  57. package/dist/instrumentations/openai.d.ts +1 -0
  58. package/dist/instrumentations/openai.js +94 -0
  59. package/dist/instrumentations/registry.d.ts +5 -0
  60. package/dist/instrumentations/registry.js +31 -0
  61. package/dist/instrumentations/types.d.ts +37 -0
  62. package/dist/instrumentations/types.js +1 -0
  63. package/dist/types/attributes.d.ts +48 -0
  64. package/dist/types/attributes.js +53 -0
  65. package/dist/types/config.d.ts +34 -0
  66. package/dist/types/config.js +1 -0
  67. package/dist/types/index.d.ts +17 -0
  68. package/dist/types/index.js +13 -0
  69. package/dist/types/metrics.d.ts +33 -0
  70. package/dist/types/metrics.js +35 -0
  71. package/dist/types/providers.d.ts +5 -0
  72. package/dist/types/providers.js +1 -0
  73. package/dist/types/spans.d.ts +40 -0
  74. package/dist/types/spans.js +1 -0
  75. package/package.json +38 -4
  76. package/templates/alerts.example.yml +54 -0
  77. package/templates/docker-compose.yml +1 -2
  78. package/templates/grafana/dashboards/cost-breakdown.json +208 -0
  79. package/templates/grafana/dashboards/error-drilldown.json +188 -0
  80. package/templates/grafana/dashboards/finops-attribution.json +278 -0
  81. package/templates/grafana/dashboards/latency-analysis.json +134 -0
  82. package/templates/grafana/dashboards/llm-overview.json +161 -30
  83. package/templates/grafana/dashboards/model-comparison.json +143 -0
  84. package/dist/metrics.d.ts +0 -6
  85. package/dist/metrics.js +0 -46
  86. package/dist/spans.js +0 -61
  87. package/dist/tracer.d.ts +0 -4
  88. package/dist/tracer.js +0 -46
  89. package/dist/types.d.ts +0 -69
  90. package/dist/types.js +0 -32
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Drift monitor — runtime semantic drift detection with sampling.
3
+ *
4
+ * Not every response is checked (embedding API calls cost money).
5
+ * By default, every 10th response is sampled. The drift value is
6
+ * recorded as a Prometheus histogram metric with provider/model labels.
7
+ */
8
+ import { createOpenAIEmbeddingProvider } from "./openai-embeddings.js";
9
+ import { cosineDrift } from "./cosine.js";
10
+ import { loadBaseline } from "./baseline.js";
11
+ import { recordSemanticDrift } from "../core/metrics.js";
12
+ function createProvider(config) {
13
+ switch (config.provider) {
14
+ case "openai":
15
+ return createOpenAIEmbeddingProvider(config.apiKey, config.model);
16
+ case "custom":
17
+ return { name: "custom", embed: config.embed };
18
+ }
19
+ }
20
+ export function createDriftMonitor(config) {
21
+ const provider = createProvider(config.embedding);
22
+ const sampleRate = config.sampleRate ?? 10;
23
+ const baseline = loadBaseline(config.baselinePath);
24
+ let counter = 0;
25
+ if (baseline === undefined) {
26
+ console.warn(`[toad-eye] No baseline found at ${config.baselinePath}. Drift monitoring disabled until baseline is saved.`);
27
+ }
28
+ async function performCheck(response, providerName, model) {
29
+ if (baseline === undefined)
30
+ return undefined;
31
+ counter++;
32
+ if (counter % sampleRate !== 0)
33
+ return undefined;
34
+ const embedding = await provider.embed(response);
35
+ const drift = cosineDrift(embedding, baseline.embeddings);
36
+ recordSemanticDrift(drift, providerName, model);
37
+ return drift;
38
+ }
39
+ return {
40
+ check: performCheck,
41
+ checkInBackground(response, providerName, model) {
42
+ void performCheck(response, providerName, model).catch((err) => {
43
+ console.warn(`[toad-eye] Drift check failed (non-blocking): ${err instanceof Error ? err.message : String(err)}`);
44
+ });
45
+ },
46
+ };
47
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * OpenAI embedding provider using text-embedding-3-small.
3
+ * Calls the OpenAI API directly via fetch — no SDK dependency.
4
+ */
5
+ import type { EmbeddingProvider } from "./embedding-provider.js";
6
+ export declare function createOpenAIEmbeddingProvider(apiKey: string, model?: string): EmbeddingProvider;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * OpenAI embedding provider using text-embedding-3-small.
3
+ * Calls the OpenAI API directly via fetch — no SDK dependency.
4
+ */
5
+ const DEFAULT_MODEL = "text-embedding-3-small";
6
+ const OPENAI_API_URL = "https://api.openai.com/v1/embeddings";
7
+ export function createOpenAIEmbeddingProvider(apiKey, model = DEFAULT_MODEL) {
8
+ return {
9
+ name: `openai/${model}`,
10
+ async embed(text) {
11
+ const response = await fetch(OPENAI_API_URL, {
12
+ method: "POST",
13
+ headers: {
14
+ Authorization: `Bearer ${apiKey}`,
15
+ "Content-Type": "application/json",
16
+ },
17
+ body: JSON.stringify({ input: text, model }),
18
+ });
19
+ if (!response.ok) {
20
+ throw new Error(`OpenAI Embeddings API error: ${response.status} ${response.statusText}`);
21
+ }
22
+ const body = (await response.json());
23
+ return body.data[0].embedding;
24
+ },
25
+ };
26
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Trace-to-Dataset Export — converts production Jaeger traces into toad-eval test cases.
3
+ *
4
+ * Fetches a trace by ID from the Jaeger Query API, extracts LLM call data
5
+ * (prompt, model, provider, response), and generates a YAML file in toad-eval format
6
+ * with auto-generated assertions (max_length, not_contains, is_json).
7
+ */
8
+ interface JaegerTag {
9
+ readonly key: string;
10
+ readonly type: string;
11
+ readonly value: string | number | boolean;
12
+ }
13
+ interface JaegerSpan {
14
+ readonly traceID: string;
15
+ readonly spanID: string;
16
+ readonly operationName: string;
17
+ readonly tags: readonly JaegerTag[];
18
+ readonly startTime: number;
19
+ readonly duration: number;
20
+ }
21
+ interface JaegerTrace {
22
+ readonly traceID: string;
23
+ readonly spans: readonly JaegerSpan[];
24
+ }
25
+ export interface ExportTraceOptions {
26
+ readonly jaegerUrl?: string | undefined;
27
+ readonly output?: string | undefined;
28
+ }
29
+ /**
30
+ * Fetch a trace from Jaeger by trace ID.
31
+ * Requires Jaeger to be running with the Query API available.
32
+ */
33
+ export declare function fetchTrace(traceId: string, jaegerUrl?: string): Promise<JaegerTrace>;
34
+ /**
35
+ * Convert a Jaeger trace to a toad-eval YAML string.
36
+ * Extracts LLM spans with prompt data, generates assertions from completions.
37
+ *
38
+ * Returns undefined if no exportable spans found (e.g. recordContent was false).
39
+ */
40
+ export declare function traceToEvalYaml(trace: JaegerTrace): string | undefined;
41
+ /**
42
+ * Full export pipeline: fetch trace from Jaeger → convert to toad-eval YAML.
43
+ * Returns the YAML string. Caller is responsible for writing to file.
44
+ */
45
+ export declare function exportTrace(traceId: string, options?: ExportTraceOptions): Promise<string>;
46
+ export {};
package/dist/export.js ADDED
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Trace-to-Dataset Export — converts production Jaeger traces into toad-eval test cases.
3
+ *
4
+ * Fetches a trace by ID from the Jaeger Query API, extracts LLM call data
5
+ * (prompt, model, provider, response), and generates a YAML file in toad-eval format
6
+ * with auto-generated assertions (max_length, not_contains, is_json).
7
+ */
8
+ import { stringify } from "yaml";
9
+ import { GEN_AI_ATTRS } from "./types/index.js";
10
+ const DEFAULT_JAEGER_URL = "http://localhost:16686";
11
+ const LENGTH_BUFFER_MULTIPLIER = 1.5;
12
+ const REFUSAL_MARKER = "i cannot";
13
+ function getTagValue(tags, key) {
14
+ const tag = tags.find((t) => t.key === key);
15
+ return tag !== undefined ? String(tag.value) : undefined;
16
+ }
17
+ function isJson(text) {
18
+ try {
19
+ JSON.parse(text);
20
+ return true;
21
+ }
22
+ catch {
23
+ return false;
24
+ }
25
+ }
26
+ function buildAssertions(completion) {
27
+ const assertions = [];
28
+ if (completion !== undefined) {
29
+ assertions.push({
30
+ type: "max_length",
31
+ value: Math.ceil(completion.length * LENGTH_BUFFER_MULTIPLIER),
32
+ });
33
+ if (!completion.toLowerCase().includes(REFUSAL_MARKER)) {
34
+ assertions.push({ type: "not_contains", value: "I cannot" });
35
+ }
36
+ if (isJson(completion)) {
37
+ assertions.push({ type: "is_json", value: true });
38
+ }
39
+ }
40
+ return assertions;
41
+ }
42
+ function spanToEvalCase(span, index) {
43
+ const prompt = getTagValue(span.tags, GEN_AI_ATTRS.PROMPT);
44
+ if (prompt === undefined)
45
+ return undefined;
46
+ const completion = getTagValue(span.tags, GEN_AI_ATTRS.COMPLETION);
47
+ return {
48
+ id: `production-case-${index + 1}`,
49
+ variables: { input: prompt },
50
+ assertions: buildAssertions(completion),
51
+ };
52
+ }
53
+ /**
54
+ * Fetch a trace from Jaeger by trace ID.
55
+ * Requires Jaeger to be running with the Query API available.
56
+ */
57
+ export async function fetchTrace(traceId, jaegerUrl = DEFAULT_JAEGER_URL) {
58
+ const url = `${jaegerUrl}/api/traces/${traceId}`;
59
+ const response = await fetch(url);
60
+ if (!response.ok) {
61
+ throw new Error(`Failed to fetch trace ${traceId}: ${response.status} ${response.statusText}`);
62
+ }
63
+ const body = (await response.json());
64
+ if (body.data.length === 0) {
65
+ throw new Error(`Trace ${traceId} not found`);
66
+ }
67
+ return body.data[0];
68
+ }
69
+ /**
70
+ * Convert a Jaeger trace to a toad-eval YAML string.
71
+ * Extracts LLM spans with prompt data, generates assertions from completions.
72
+ *
73
+ * Returns undefined if no exportable spans found (e.g. recordContent was false).
74
+ */
75
+ export function traceToEvalYaml(trace) {
76
+ const cases = trace.spans
77
+ .map((span, i) => spanToEvalCase(span, i))
78
+ .filter((c) => c !== undefined);
79
+ if (cases.length === 0)
80
+ return undefined;
81
+ // Pick model/provider from first span that has them
82
+ const firstSpanWithMeta = trace.spans.find((s) => getTagValue(s.tags, GEN_AI_ATTRS.REQUEST_MODEL) !== undefined);
83
+ const dataset = {
84
+ name: `exported-trace-${trace.traceID.slice(0, 8)}`,
85
+ source: "toad-eye-export",
86
+ metadata: {
87
+ trace_id: trace.traceID,
88
+ exported_at: new Date().toISOString(),
89
+ model: getTagValue(firstSpanWithMeta?.tags ?? [], GEN_AI_ATTRS.REQUEST_MODEL) ?? "unknown",
90
+ provider: getTagValue(firstSpanWithMeta?.tags ?? [], GEN_AI_ATTRS.PROVIDER) ??
91
+ "unknown",
92
+ },
93
+ cases,
94
+ };
95
+ return stringify(dataset);
96
+ }
97
+ /**
98
+ * Full export pipeline: fetch trace from Jaeger → convert to toad-eval YAML.
99
+ * Returns the YAML string. Caller is responsible for writing to file.
100
+ */
101
+ export async function exportTrace(traceId, options = {}) {
102
+ const trace = await fetchTrace(traceId, options.jaegerUrl);
103
+ const yaml = traceToEvalYaml(trace);
104
+ if (yaml === undefined) {
105
+ throw new Error(`No exportable spans in trace ${traceId}. Was recordContent enabled?`);
106
+ }
107
+ return yaml;
108
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Shadow Guardrails integration — records toad-guard validation results
3
+ * as span attributes and metrics without blocking LLM responses.
4
+ *
5
+ * toad-guard validates each LLM response and passes the result here.
6
+ * In shadow mode, validation runs but never throws — results are recorded
7
+ * for observability only, letting you tune guardrail thresholds on
8
+ * production traffic before switching to enforce mode.
9
+ *
10
+ * Usage from toad-guard:
11
+ * ```ts
12
+ * import { recordGuardResult } from "toad-eye";
13
+ *
14
+ * const result = guard.validate(response);
15
+ * recordGuardResult(result); // records as span attrs + metrics
16
+ * ```
17
+ */
18
+ import type { GuardResult } from "./types/index.js";
19
+ /**
20
+ * Record a guard validation result as span attributes and metrics.
21
+ *
22
+ * Attaches guard attributes to a child span and increments counters.
23
+ * If the guard failed, also increments the `would_block` counter —
24
+ * useful for measuring how often shadow guardrails would have blocked.
25
+ */
26
+ export declare function recordGuardResult(result: GuardResult): void;
package/dist/guard.js ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Shadow Guardrails integration — records toad-guard validation results
3
+ * as span attributes and metrics without blocking LLM responses.
4
+ *
5
+ * toad-guard validates each LLM response and passes the result here.
6
+ * In shadow mode, validation runs but never throws — results are recorded
7
+ * for observability only, letting you tune guardrail thresholds on
8
+ * production traffic before switching to enforce mode.
9
+ *
10
+ * Usage from toad-guard:
11
+ * ```ts
12
+ * import { recordGuardResult } from "toad-eye";
13
+ *
14
+ * const result = guard.validate(response);
15
+ * recordGuardResult(result); // records as span attrs + metrics
16
+ * ```
17
+ */
18
+ import { trace } from "@opentelemetry/api";
19
+ import { GEN_AI_ATTRS, INSTRUMENTATION_NAME } from "./types/index.js";
20
+ import { recordGuardEvaluation, recordGuardWouldBlock, } from "./core/metrics.js";
21
+ const tracer = trace.getTracer(INSTRUMENTATION_NAME);
22
+ /**
23
+ * Record a guard validation result as span attributes and metrics.
24
+ *
25
+ * Attaches guard attributes to a child span and increments counters.
26
+ * If the guard failed, also increments the `would_block` counter —
27
+ * useful for measuring how often shadow guardrails would have blocked.
28
+ */
29
+ export function recordGuardResult(result) {
30
+ const span = tracer.startSpan(`guard.evaluate.${result.ruleName}`);
31
+ span.setAttributes({
32
+ [GEN_AI_ATTRS.GUARD_MODE]: result.mode,
33
+ [GEN_AI_ATTRS.GUARD_PASSED]: result.passed,
34
+ [GEN_AI_ATTRS.GUARD_RULE_NAME]: result.ruleName,
35
+ ...(!result.passed &&
36
+ result.failureReason !== undefined && {
37
+ [GEN_AI_ATTRS.GUARD_FAILURE_REASON]: result.failureReason,
38
+ }),
39
+ });
40
+ span.end();
41
+ recordGuardEvaluation(result.ruleName);
42
+ if (!result.passed) {
43
+ recordGuardWouldBlock(result.ruleName);
44
+ }
45
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,17 @@
1
- export { initObservability, shutdown, getConfig } from "./tracer.js";
2
- export { traceLLMCall } from "./spans.js";
3
- export type { LLMCallInput, LLMCallOutput } from "./spans.js";
4
- export type { ToadEyeConfig, LLMSpanAttributes, LLMProvider, SpanStatus, MetricName, } from "./types.js";
5
- export { LLM_METRICS, LLM_ATTRS } from "./types.js";
1
+ export { initObservability, shutdown, getConfig, getBudgetTracker, } from "./core/tracer.js";
2
+ export { BudgetTracker, ToadBudgetExceededError } from "./budget/index.js";
3
+ export type { BudgetConfig, BudgetExceededMode, BudgetExceededInfo, DowngradeCallback, } from "./budget/index.js";
4
+ export { AlertManager, startAlertsFromFile, parseCondition, } from "./alerts/index.js";
5
+ export type { AlertsConfig, AlertRule, AlertChannelConfig, FiredAlert, } from "./alerts/index.js";
6
+ export { traceLLMCall } from "./core/spans.js";
7
+ export { traceAgentStep, traceAgentQuery } from "./agent.js";
8
+ export { recordGuardResult } from "./guard.js";
9
+ export { createDriftMonitor, createOpenAIEmbeddingProvider, cosineSimilarity, cosineDrift, saveBaseline, loadBaseline, } from "./drift/index.js";
10
+ export type { DriftMonitor, DriftMonitorConfig, EmbeddingProvider, EmbeddingConfig, DriftBaseline, } from "./drift/index.js";
11
+ export { exportTrace, fetchTrace, traceToEvalYaml } from "./export.js";
12
+ export type { ExportTraceOptions } from "./export.js";
13
+ export { calculateCost, setCustomPricing, getModelPricing, } from "./core/pricing.js";
14
+ export type { ModelPricing } from "./core/pricing.js";
15
+ export type { LLMCallInput, LLMCallOutput } from "./core/spans.js";
16
+ export type { ToadEyeConfig, LLMSpanAttributes, LLMProvider, SpanStatus, MetricName, AgentStepType, AgentStepInput, GuardMode, GuardResult, } from "./types/index.js";
17
+ export { GEN_AI_METRICS, GEN_AI_ATTRS, LLM_METRICS, LLM_ATTRS, } from "./types/index.js";
package/dist/index.js CHANGED
@@ -1,3 +1,10 @@
1
- export { initObservability, shutdown, getConfig } from "./tracer.js";
2
- export { traceLLMCall } from "./spans.js";
3
- export { LLM_METRICS, LLM_ATTRS } from "./types.js";
1
+ export { initObservability, shutdown, getConfig, getBudgetTracker, } from "./core/tracer.js";
2
+ export { BudgetTracker, ToadBudgetExceededError } from "./budget/index.js";
3
+ export { AlertManager, startAlertsFromFile, parseCondition, } from "./alerts/index.js";
4
+ export { traceLLMCall } from "./core/spans.js";
5
+ export { traceAgentStep, traceAgentQuery } from "./agent.js";
6
+ export { recordGuardResult } from "./guard.js";
7
+ export { createDriftMonitor, createOpenAIEmbeddingProvider, cosineSimilarity, cosineDrift, saveBaseline, loadBaseline, } from "./drift/index.js";
8
+ export { exportTrace, fetchTrace, traceToEvalYaml } from "./export.js";
9
+ export { calculateCost, setCustomPricing, getModelPricing, } from "./core/pricing.js";
10
+ export { GEN_AI_METRICS, GEN_AI_ATTRS, LLM_METRICS, LLM_ATTRS, } from "./types/index.js";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,73 @@
1
+ import { register } from "./registry.js";
2
+ import { createInstrumentation } from "./create.js";
3
+ function extractMessages(messages) {
4
+ if (!Array.isArray(messages))
5
+ return "";
6
+ return messages
7
+ .map((m) => {
8
+ if (typeof m.content === "string")
9
+ return m.content;
10
+ if (Array.isArray(m.content)) {
11
+ return m.content
12
+ .filter((b) => b.type === "text")
13
+ .map((b) => b.text)
14
+ .join("");
15
+ }
16
+ return "";
17
+ })
18
+ .filter(Boolean)
19
+ .join("\n");
20
+ }
21
+ function extractCompletion(content) {
22
+ if (!Array.isArray(content))
23
+ return "";
24
+ return content
25
+ .filter((b) => b.type === "text")
26
+ .map((b) => b.text ?? "")
27
+ .join("");
28
+ }
29
+ const messagesCreate = {
30
+ getPrototype: (sdk) => sdk?.Messages?.prototype,
31
+ method: "create",
32
+ extractRequest: (body) => {
33
+ const b = body;
34
+ return {
35
+ prompt: extractMessages(b?.messages),
36
+ model: b?.model ?? "unknown",
37
+ temperature: b?.temperature ?? 1.0,
38
+ };
39
+ },
40
+ extractResponse: (response) => {
41
+ const r = response;
42
+ return {
43
+ completion: extractCompletion(r?.content),
44
+ inputTokens: r?.usage?.input_tokens ?? 0,
45
+ outputTokens: r?.usage?.output_tokens ?? 0,
46
+ };
47
+ },
48
+ isStreaming: (body) => !!body?.stream,
49
+ extractStreamResponse: (chunks) => {
50
+ // Anthropic stream events: message_start, content_block_delta, message_delta, message_stop
51
+ let completion = "";
52
+ let inputTokens = 0;
53
+ let outputTokens = 0;
54
+ for (const chunk of chunks) {
55
+ const event = chunk;
56
+ if (event.type === "content_block_delta" && event.delta?.text) {
57
+ completion += event.delta.text;
58
+ }
59
+ if (event.type === "message_start" && event.message?.usage) {
60
+ inputTokens = event.message.usage.input_tokens ?? 0;
61
+ }
62
+ if (event.type === "message_delta" && event.usage) {
63
+ outputTokens = event.usage.output_tokens ?? 0;
64
+ }
65
+ }
66
+ return { completion, inputTokens, outputTokens };
67
+ },
68
+ };
69
+ register(createInstrumentation({
70
+ name: "anthropic",
71
+ moduleName: "@anthropic-ai/sdk",
72
+ patches: [messagesCreate],
73
+ }));
@@ -0,0 +1,11 @@
1
+ import type { LLMProvider } from "../types/index.js";
2
+ import type { Instrumentation, PatchTarget } from "./types.js";
3
+ /**
4
+ * Factory for creating SDK instrumentations.
5
+ * Eliminates boilerplate: SDK resolution, prototype patching, error handling, cleanup.
6
+ */
7
+ export declare function createInstrumentation(config: {
8
+ name: LLMProvider;
9
+ moduleName: string;
10
+ patches: PatchTarget[];
11
+ }): Instrumentation;
@@ -0,0 +1,165 @@
1
+ import { createRequire } from "node:module";
2
+ import { trace, diag, SpanStatusCode } from "@opentelemetry/api";
3
+ import { traceLLMCall } from "../core/spans.js";
4
+ import { calculateCost } from "../core/pricing.js";
5
+ import { recordRequestDuration, recordRequestCost, recordTokens, recordRequest, recordError, } from "../core/metrics.js";
6
+ import { GEN_AI_ATTRS, INSTRUMENTATION_NAME } from "../types/index.js";
7
+ const require = createRequire(import.meta.url);
8
+ function isModuleInstalled(moduleName) {
9
+ try {
10
+ require.resolve(moduleName);
11
+ return true;
12
+ }
13
+ catch {
14
+ return false;
15
+ }
16
+ }
17
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
+ function loadModule(moduleName) {
19
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
20
+ const sdk = require(moduleName);
21
+ return sdk.default ?? sdk;
22
+ }
23
+ /**
24
+ * Wrap an async iterable stream to intercept chunks.
25
+ * Yields every chunk transparently to the caller while collecting them.
26
+ * On stream end, calls onComplete with all accumulated chunks.
27
+ */
28
+ async function* wrapAsyncIterable(stream, onChunk, onComplete, onError) {
29
+ const chunks = [];
30
+ try {
31
+ for await (const chunk of stream) {
32
+ chunks.push(chunk);
33
+ onChunk(chunk);
34
+ yield chunk;
35
+ }
36
+ onComplete(chunks);
37
+ }
38
+ catch (err) {
39
+ onError(err);
40
+ throw err;
41
+ }
42
+ }
43
+ function createStreamingHandler(
44
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
45
+ original, patch, providerName) {
46
+ const tracer = trace.getTracer(INSTRUMENTATION_NAME);
47
+ return async function handleStreaming(thisArg, body, rest) {
48
+ const req = patch.extractRequest(body);
49
+ const start = performance.now();
50
+ const response = await original.call(thisArg, body, ...rest);
51
+ // The response should be an async iterable (Stream, MessageStream, etc.)
52
+ // We wrap it to intercept chunks
53
+ const span = tracer.startSpan(`gen_ai.${providerName}.${req.model}`);
54
+ span.setAttributes({
55
+ [GEN_AI_ATTRS.PROVIDER]: providerName,
56
+ [GEN_AI_ATTRS.REQUEST_MODEL]: req.model,
57
+ [GEN_AI_ATTRS.TEMPERATURE]: req.temperature ?? 1.0,
58
+ [GEN_AI_ATTRS.OPERATION]: "chat",
59
+ });
60
+ const wrapped = wrapAsyncIterable(response, () => { }, (chunks) => {
61
+ const duration = performance.now() - start;
62
+ const res = patch.extractStreamResponse(chunks);
63
+ const cost = calculateCost(req.model, res.inputTokens, res.outputTokens);
64
+ span.setAttributes({
65
+ [GEN_AI_ATTRS.RESPONSE_MODEL]: req.model,
66
+ [GEN_AI_ATTRS.INPUT_TOKENS]: res.inputTokens,
67
+ [GEN_AI_ATTRS.OUTPUT_TOKENS]: res.outputTokens,
68
+ [GEN_AI_ATTRS.COST]: cost,
69
+ [GEN_AI_ATTRS.STATUS]: "success",
70
+ });
71
+ span.setStatus({ code: SpanStatusCode.OK });
72
+ span.end();
73
+ recordRequest(providerName, req.model);
74
+ recordRequestDuration(duration, providerName, req.model);
75
+ recordRequestCost(cost, providerName, req.model);
76
+ recordTokens(res.inputTokens + res.outputTokens, providerName, req.model);
77
+ }, (err) => {
78
+ const duration = performance.now() - start;
79
+ const message = err instanceof Error ? err.message : String(err);
80
+ span.setAttributes({
81
+ [GEN_AI_ATTRS.STATUS]: "error",
82
+ [GEN_AI_ATTRS.ERROR]: message,
83
+ });
84
+ span.setStatus({ code: SpanStatusCode.ERROR, message });
85
+ span.end();
86
+ recordRequest(providerName, req.model);
87
+ recordRequestDuration(duration, providerName, req.model);
88
+ recordError(providerName, req.model);
89
+ });
90
+ // Return an object that looks like the original stream but with our wrapper
91
+ // Preserve the original object shape — SDKs may have extra methods/properties
92
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
93
+ const proxy = Object.create(response);
94
+ proxy[Symbol.asyncIterator] = () => wrapped[Symbol.asyncIterator]();
95
+ return proxy;
96
+ };
97
+ }
98
+ function createPatchedMethod(
99
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
100
+ original, patch, providerName) {
101
+ const streamHandler = patch.isStreaming && patch.extractStreamResponse
102
+ ? createStreamingHandler(original, patch, providerName)
103
+ : null;
104
+ return function patchedMethod(body, ...rest) {
105
+ if (patch.shouldSkip?.(body)) {
106
+ return original.call(this, body, ...rest);
107
+ }
108
+ // Handle streaming calls
109
+ if (streamHandler && patch.isStreaming?.(body)) {
110
+ return streamHandler(this, body, rest);
111
+ }
112
+ const req = patch.extractRequest(body);
113
+ return traceLLMCall({
114
+ provider: providerName,
115
+ model: req.model,
116
+ prompt: req.prompt,
117
+ temperature: req.temperature,
118
+ }, async () => {
119
+ const response = await original.call(this, body, ...rest);
120
+ const res = patch.extractResponse(response, req.model);
121
+ return {
122
+ completion: res.completion,
123
+ inputTokens: res.inputTokens,
124
+ outputTokens: res.outputTokens,
125
+ cost: calculateCost(req.model, res.inputTokens, res.outputTokens),
126
+ };
127
+ });
128
+ };
129
+ }
130
+ /**
131
+ * Factory for creating SDK instrumentations.
132
+ * Eliminates boilerplate: SDK resolution, prototype patching, error handling, cleanup.
133
+ */
134
+ export function createInstrumentation(config) {
135
+ const activePatches = [];
136
+ return {
137
+ name: config.name,
138
+ enable() {
139
+ if (!isModuleInstalled(config.moduleName))
140
+ return false;
141
+ try {
142
+ const mod = loadModule(config.moduleName);
143
+ for (const patch of config.patches) {
144
+ const proto = patch.getPrototype(mod);
145
+ if (!proto?.[patch.method])
146
+ continue;
147
+ const original = proto[patch.method];
148
+ proto[patch.method] = createPatchedMethod(original, patch, config.name);
149
+ activePatches.push({ proto, method: patch.method, original });
150
+ }
151
+ return activePatches.length > 0;
152
+ }
153
+ catch (err) {
154
+ diag.warn(`toad-eye: failed to patch ${config.name}: ${err}`);
155
+ return false;
156
+ }
157
+ },
158
+ disable() {
159
+ for (const { proto, method, original } of activePatches) {
160
+ proto[method] = original;
161
+ }
162
+ activePatches.length = 0;
163
+ },
164
+ };
165
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,48 @@
1
+ import { register } from "./registry.js";
2
+ import { createInstrumentation } from "./create.js";
3
+ function extractPrompt(request) {
4
+ if (typeof request === "string")
5
+ return request;
6
+ if (typeof request === "object" && request !== null) {
7
+ const req = request;
8
+ if (Array.isArray(req.contents)) {
9
+ return req.contents
10
+ .flatMap((c) => c.parts ?? [])
11
+ .map((p) => p.text ?? "")
12
+ .filter(Boolean)
13
+ .join("\n");
14
+ }
15
+ }
16
+ return "";
17
+ }
18
+ const generateContent = {
19
+ getPrototype: (sdk) => sdk?.GenerativeModel?.prototype,
20
+ method: "generateContent",
21
+ extractRequest(body) {
22
+ return {
23
+ prompt: extractPrompt(body),
24
+ // model comes from `this.model` — injected by create.ts via the patched function's `this`
25
+ model: "unknown",
26
+ };
27
+ },
28
+ extractResponse: (response) => {
29
+ const r = response;
30
+ let completion = "";
31
+ try {
32
+ completion = r?.response?.text?.() ?? "";
33
+ }
34
+ catch {
35
+ // text() may throw if response is blocked
36
+ }
37
+ return {
38
+ completion,
39
+ inputTokens: r?.response?.usageMetadata?.promptTokenCount ?? 0,
40
+ outputTokens: r?.response?.usageMetadata?.candidatesTokenCount ?? 0,
41
+ };
42
+ },
43
+ };
44
+ register(createInstrumentation({
45
+ name: "gemini",
46
+ moduleName: "@google/generative-ai",
47
+ patches: [generateContent],
48
+ }));
@@ -0,0 +1 @@
1
+ export {};