@gammatech/aijsx 0.11.4-dev.2024-07-08 → 0.12.0-dev.2024-07-08

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/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { L as LogChatCompletionRequest, A as AINode, C as ChatMessage, R as RenderContext, a as LogImplementation, S as SpanProcessor, b as ContextValues, c as Context, T as Tracer, d as ReadableSpan, e as SpanExporter, f as AIComponent, g as SpanAttributes, P as Prompt, h as ChatCompletionRequestPayloads, D as DebugMessage, E as EvaluatorResult, i as EvaluatorFn, j as PromptParsed, J as JSX } from './jsx-dev-runtime-vXV-PExh.mjs';
2
- export { y as AIElement, l as AIFragment, B as BoundLogger, n as ChatRole, u as CombinedLogger, s as ConsoleLogger, I as ImagePart, o as ImagePartProps, v as Literal, p as LogChatCompletionResponse, q as LogLevel, r as Logger, N as NoopLogImplementation, V as OutputParser, F as PropsOfAIComponent, w as RenderResult, z as Renderable, K as Span, G as SpanContext, M as SpanEvent, H as SpanStatus, Q as TracingContext, O as TracingContextKey, U as TracingContextManager, x as attachedContextSymbol, k as createAIElement, m as createContext, t as toDebugMessage } from './jsx-dev-runtime-vXV-PExh.mjs';
1
+ import { L as LogChatCompletionRequest, A as AINode, C as ChatMessage, R as RenderContext, a as LogImplementation, S as SpanProcessor, b as ContextValues, c as Context, T as Tracer, d as ReadableSpan, e as SpanAttributes, f as SpanExporter, g as AIComponent, P as Prompt, h as ChatCompletionRequestPayloads, D as DebugMessage, E as EvaluatorResult, i as EvaluatorFn, j as PromptParsed, J as JSX } from './jsx-dev-runtime-S--1HQKU.mjs';
2
+ export { y as AIElement, l as AIFragment, B as BoundLogger, n as ChatRole, u as CombinedLogger, s as ConsoleLogger, I as ImagePart, o as ImagePartProps, v as Literal, p as LogChatCompletionResponse, q as LogLevel, r as Logger, N as NoopLogImplementation, V as OutputParser, F as PropsOfAIComponent, w as RenderResult, z as Renderable, K as Span, G as SpanContext, M as SpanEvent, H as SpanStatus, Q as TracingContext, O as TracingContextKey, U as TracingContextManager, x as attachedContextSymbol, k as createAIElement, m as createContext, t as toDebugMessage } from './jsx-dev-runtime-S--1HQKU.mjs';
3
3
  import { ZodObject, ZodRawShape, ZodTypeAny, ZodString, z } from 'zod';
4
4
  import { OpenAI } from 'openai';
5
5
  export { OpenAI as OpenAIClient } from 'openai';
@@ -100,19 +100,27 @@ declare class AITraceAPI {
100
100
  }
101
101
  declare const tracing: AITraceAPI;
102
102
 
103
+ type SpanProcessingStatus = 'running' | 'processing' | 'done';
103
104
  declare class SpanTree {
104
105
  roots: SpanTreeNode[];
105
- addSpan(span: ReadableSpan): boolean;
106
+ addSpan(span: ReadableSpan, status: SpanProcessingStatus): boolean;
106
107
  findNode(id: string): SpanTreeNode | null;
107
108
  }
108
109
  declare class SpanTreeNode {
109
- readonly id: string;
110
- readonly name: string;
110
+ span: ReadableSpan;
111
+ status: SpanProcessingStatus;
111
112
  readonly parent: SpanTreeNode | null;
112
113
  readonly children: SpanTreeNode[];
113
- readonly attrs: Record<string, any>;
114
- constructor(id: string, name: string, parent: SpanTreeNode | null, children: SpanTreeNode[], attrs: Record<string, any>);
114
+ childrenDonePromise: Promise<void>;
115
+ resolveChildrenDonePromise: () => void;
116
+ constructor(span: ReadableSpan, status: SpanProcessingStatus, parent?: SpanTreeNode | null, children?: SpanTreeNode[]);
117
+ get name(): string;
118
+ get id(): string;
119
+ get attrs(): SpanAttributes;
115
120
  addChild(child: SpanTreeNode): void;
121
+ descendents(fn: (node: SpanTreeNode) => void): void;
122
+ everyDescendent(fn: (node: SpanTreeNode) => boolean): boolean;
123
+ getRootByName(name: string): SpanTreeNode | null;
116
124
  getNearestAttribute<K>(key: string): K | null;
117
125
  getRootAttribute<K>(key: string): K | null;
118
126
  }
@@ -133,34 +141,16 @@ type CostFn = (tokensUsed: {
133
141
  * 3. sum totalCost on the root span
134
142
  * 4. sum totalUsage on the root span
135
143
  */
136
- declare abstract class EnrichingSpanProcessor implements SpanProcessor {
144
+ declare class AISpanProcessor implements SpanProcessor {
137
145
  private readonly exporter;
138
- protected finalSpans: {
139
- status: 'running' | 'processing' | 'done';
140
- span: ReadableSpan;
141
- }[];
142
- protected onAllDonePromise: Promise<void> | null;
143
- protected onAllDonePromiseResolve: (() => void) | null;
144
146
  protected spanTree: SpanTree;
145
147
  constructor(exporter: SpanExporter);
146
148
  onStart(span: ReadableSpan): Promise<void>;
147
149
  onEnd(span: ReadableSpan): Promise<void>;
148
- abstract onTraceComplete(rootSpan: ReadableSpan): Promise<void>;
149
- abstract enrichSpan(span: ReadableSpan): Promise<ReadableSpan>;
150
150
  shutdown(): Promise<void> | undefined;
151
- }
152
- declare class AISpanProcessor extends EnrichingSpanProcessor {
153
- protected totalCost: number;
154
- protected totalUsage: {
155
- prompt: number;
156
- completion: number;
157
- total: number;
158
- };
159
- onTraceComplete(rootSpan: ReadableSpan): Promise<void>;
151
+ onRootPromptDone(rootSpan: ReadableSpan): Promise<void>;
160
152
  enrichSpan(span: ReadableSpan): Promise<ReadableSpan>;
161
153
  protected addPromptKeys(span: ReadableSpan): Promise<ReadableSpan>;
162
- protected updateCost(span: ReadableSpan): Promise<ReadableSpan>;
163
- protected updateUsage(span: ReadableSpan): Promise<ReadableSpan>;
164
154
  protected evaluatePrompt(span: ReadableSpan): Promise<ReadableSpan>;
165
155
  }
166
156
 
@@ -321,4 +311,4 @@ type GoogleChatCompletionProps = {
321
311
  };
322
312
  declare function GoogleChatCompletion(props: GoogleChatCompletionProps, ctx: RenderContext): JSX.Element;
323
313
 
324
- export { AIComponent, AINode, AISpanAttributes, AISpanProcessor, AnthropicChatCompletion, type AnthropicChatCompletionRequest, AnthropicClientContext, AssistantMessage, type ChatCompletionClientAndProvider, ChatCompletionError, type ChatCompletionRequestPayloads, ChatMessage, Context, type CostFn, DebugMessage, DefaultMaxRetriesContext, EnrichingSpanProcessor, EvaluatorFn, EvaluatorResult, Fallback, type GetChatCompletionClientAndProvider, GoogleChatCompletion, type GoogleChatCompletionRequest, GoogleClientContext, LogChatCompletionRequest, LogImplementation, OpenAIChatCompletion, type OpenAIChatCompletionRequest, type OpenAIChatMessage, OpenAIClientContext, ParseVariablesError, ProcessedAISpanAttributes, type Prompt, PromptInvalidOutputError, PromptParsed, ReadableSpan, RenderContext, Retry, RetryCountContext, RetryLastErrorContext, SpanAttributes, SpanExporter, SpanProcessor, SystemMessage, type TokenizerFn, Trace, Tracer, UserMessage, type ValidAnthropicChatModel, type ValidGoogleChatModel, type ValidOpenAIChatModel, type ValidOpenAIVisionModel, anthropicTokenizer, computeUsage, createPrompt, createRenderContext, evaluatePrompt, isPromptParsed, openaiTokenizer, tracing };
314
+ export { AIComponent, AINode, AISpanAttributes, AISpanProcessor, AnthropicChatCompletion, type AnthropicChatCompletionRequest, AnthropicClientContext, AssistantMessage, type ChatCompletionClientAndProvider, ChatCompletionError, type ChatCompletionRequestPayloads, ChatMessage, Context, type CostFn, DebugMessage, DefaultMaxRetriesContext, EvaluatorFn, EvaluatorResult, Fallback, type GetChatCompletionClientAndProvider, GoogleChatCompletion, type GoogleChatCompletionRequest, GoogleClientContext, LogChatCompletionRequest, LogImplementation, OpenAIChatCompletion, type OpenAIChatCompletionRequest, type OpenAIChatMessage, OpenAIClientContext, ParseVariablesError, ProcessedAISpanAttributes, type Prompt, PromptInvalidOutputError, PromptParsed, ReadableSpan, RenderContext, Retry, RetryCountContext, RetryLastErrorContext, SpanAttributes, SpanExporter, SpanProcessor, SystemMessage, type TokenizerFn, Trace, Tracer, UserMessage, type ValidAnthropicChatModel, type ValidGoogleChatModel, type ValidOpenAIChatModel, type ValidOpenAIVisionModel, anthropicTokenizer, computeUsage, createPrompt, createRenderContext, evaluatePrompt, isPromptParsed, openaiTokenizer, tracing };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { L as LogChatCompletionRequest, A as AINode, C as ChatMessage, R as RenderContext, a as LogImplementation, S as SpanProcessor, b as ContextValues, c as Context, T as Tracer, d as ReadableSpan, e as SpanExporter, f as AIComponent, g as SpanAttributes, P as Prompt, h as ChatCompletionRequestPayloads, D as DebugMessage, E as EvaluatorResult, i as EvaluatorFn, j as PromptParsed, J as JSX } from './jsx-dev-runtime-vXV-PExh.js';
2
- export { y as AIElement, l as AIFragment, B as BoundLogger, n as ChatRole, u as CombinedLogger, s as ConsoleLogger, I as ImagePart, o as ImagePartProps, v as Literal, p as LogChatCompletionResponse, q as LogLevel, r as Logger, N as NoopLogImplementation, V as OutputParser, F as PropsOfAIComponent, w as RenderResult, z as Renderable, K as Span, G as SpanContext, M as SpanEvent, H as SpanStatus, Q as TracingContext, O as TracingContextKey, U as TracingContextManager, x as attachedContextSymbol, k as createAIElement, m as createContext, t as toDebugMessage } from './jsx-dev-runtime-vXV-PExh.js';
1
+ import { L as LogChatCompletionRequest, A as AINode, C as ChatMessage, R as RenderContext, a as LogImplementation, S as SpanProcessor, b as ContextValues, c as Context, T as Tracer, d as ReadableSpan, e as SpanAttributes, f as SpanExporter, g as AIComponent, P as Prompt, h as ChatCompletionRequestPayloads, D as DebugMessage, E as EvaluatorResult, i as EvaluatorFn, j as PromptParsed, J as JSX } from './jsx-dev-runtime-S--1HQKU.js';
2
+ export { y as AIElement, l as AIFragment, B as BoundLogger, n as ChatRole, u as CombinedLogger, s as ConsoleLogger, I as ImagePart, o as ImagePartProps, v as Literal, p as LogChatCompletionResponse, q as LogLevel, r as Logger, N as NoopLogImplementation, V as OutputParser, F as PropsOfAIComponent, w as RenderResult, z as Renderable, K as Span, G as SpanContext, M as SpanEvent, H as SpanStatus, Q as TracingContext, O as TracingContextKey, U as TracingContextManager, x as attachedContextSymbol, k as createAIElement, m as createContext, t as toDebugMessage } from './jsx-dev-runtime-S--1HQKU.js';
3
3
  import { ZodObject, ZodRawShape, ZodTypeAny, ZodString, z } from 'zod';
4
4
  import { OpenAI } from 'openai';
5
5
  export { OpenAI as OpenAIClient } from 'openai';
@@ -100,19 +100,27 @@ declare class AITraceAPI {
100
100
  }
101
101
  declare const tracing: AITraceAPI;
102
102
 
103
+ type SpanProcessingStatus = 'running' | 'processing' | 'done';
103
104
  declare class SpanTree {
104
105
  roots: SpanTreeNode[];
105
- addSpan(span: ReadableSpan): boolean;
106
+ addSpan(span: ReadableSpan, status: SpanProcessingStatus): boolean;
106
107
  findNode(id: string): SpanTreeNode | null;
107
108
  }
108
109
  declare class SpanTreeNode {
109
- readonly id: string;
110
- readonly name: string;
110
+ span: ReadableSpan;
111
+ status: SpanProcessingStatus;
111
112
  readonly parent: SpanTreeNode | null;
112
113
  readonly children: SpanTreeNode[];
113
- readonly attrs: Record<string, any>;
114
- constructor(id: string, name: string, parent: SpanTreeNode | null, children: SpanTreeNode[], attrs: Record<string, any>);
114
+ childrenDonePromise: Promise<void>;
115
+ resolveChildrenDonePromise: () => void;
116
+ constructor(span: ReadableSpan, status: SpanProcessingStatus, parent?: SpanTreeNode | null, children?: SpanTreeNode[]);
117
+ get name(): string;
118
+ get id(): string;
119
+ get attrs(): SpanAttributes;
115
120
  addChild(child: SpanTreeNode): void;
121
+ descendents(fn: (node: SpanTreeNode) => void): void;
122
+ everyDescendent(fn: (node: SpanTreeNode) => boolean): boolean;
123
+ getRootByName(name: string): SpanTreeNode | null;
116
124
  getNearestAttribute<K>(key: string): K | null;
117
125
  getRootAttribute<K>(key: string): K | null;
118
126
  }
@@ -133,34 +141,16 @@ type CostFn = (tokensUsed: {
133
141
  * 3. sum totalCost on the root span
134
142
  * 4. sum totalUsage on the root span
135
143
  */
136
- declare abstract class EnrichingSpanProcessor implements SpanProcessor {
144
+ declare class AISpanProcessor implements SpanProcessor {
137
145
  private readonly exporter;
138
- protected finalSpans: {
139
- status: 'running' | 'processing' | 'done';
140
- span: ReadableSpan;
141
- }[];
142
- protected onAllDonePromise: Promise<void> | null;
143
- protected onAllDonePromiseResolve: (() => void) | null;
144
146
  protected spanTree: SpanTree;
145
147
  constructor(exporter: SpanExporter);
146
148
  onStart(span: ReadableSpan): Promise<void>;
147
149
  onEnd(span: ReadableSpan): Promise<void>;
148
- abstract onTraceComplete(rootSpan: ReadableSpan): Promise<void>;
149
- abstract enrichSpan(span: ReadableSpan): Promise<ReadableSpan>;
150
150
  shutdown(): Promise<void> | undefined;
151
- }
152
- declare class AISpanProcessor extends EnrichingSpanProcessor {
153
- protected totalCost: number;
154
- protected totalUsage: {
155
- prompt: number;
156
- completion: number;
157
- total: number;
158
- };
159
- onTraceComplete(rootSpan: ReadableSpan): Promise<void>;
151
+ onRootPromptDone(rootSpan: ReadableSpan): Promise<void>;
160
152
  enrichSpan(span: ReadableSpan): Promise<ReadableSpan>;
161
153
  protected addPromptKeys(span: ReadableSpan): Promise<ReadableSpan>;
162
- protected updateCost(span: ReadableSpan): Promise<ReadableSpan>;
163
- protected updateUsage(span: ReadableSpan): Promise<ReadableSpan>;
164
154
  protected evaluatePrompt(span: ReadableSpan): Promise<ReadableSpan>;
165
155
  }
166
156
 
@@ -321,4 +311,4 @@ type GoogleChatCompletionProps = {
321
311
  };
322
312
  declare function GoogleChatCompletion(props: GoogleChatCompletionProps, ctx: RenderContext): JSX.Element;
323
313
 
324
- export { AIComponent, AINode, AISpanAttributes, AISpanProcessor, AnthropicChatCompletion, type AnthropicChatCompletionRequest, AnthropicClientContext, AssistantMessage, type ChatCompletionClientAndProvider, ChatCompletionError, type ChatCompletionRequestPayloads, ChatMessage, Context, type CostFn, DebugMessage, DefaultMaxRetriesContext, EnrichingSpanProcessor, EvaluatorFn, EvaluatorResult, Fallback, type GetChatCompletionClientAndProvider, GoogleChatCompletion, type GoogleChatCompletionRequest, GoogleClientContext, LogChatCompletionRequest, LogImplementation, OpenAIChatCompletion, type OpenAIChatCompletionRequest, type OpenAIChatMessage, OpenAIClientContext, ParseVariablesError, ProcessedAISpanAttributes, type Prompt, PromptInvalidOutputError, PromptParsed, ReadableSpan, RenderContext, Retry, RetryCountContext, RetryLastErrorContext, SpanAttributes, SpanExporter, SpanProcessor, SystemMessage, type TokenizerFn, Trace, Tracer, UserMessage, type ValidAnthropicChatModel, type ValidGoogleChatModel, type ValidOpenAIChatModel, type ValidOpenAIVisionModel, anthropicTokenizer, computeUsage, createPrompt, createRenderContext, evaluatePrompt, isPromptParsed, openaiTokenizer, tracing };
314
+ export { AIComponent, AINode, AISpanAttributes, AISpanProcessor, AnthropicChatCompletion, type AnthropicChatCompletionRequest, AnthropicClientContext, AssistantMessage, type ChatCompletionClientAndProvider, ChatCompletionError, type ChatCompletionRequestPayloads, ChatMessage, Context, type CostFn, DebugMessage, DefaultMaxRetriesContext, EvaluatorFn, EvaluatorResult, Fallback, type GetChatCompletionClientAndProvider, GoogleChatCompletion, type GoogleChatCompletionRequest, GoogleClientContext, LogChatCompletionRequest, LogImplementation, OpenAIChatCompletion, type OpenAIChatCompletionRequest, type OpenAIChatMessage, OpenAIClientContext, ParseVariablesError, ProcessedAISpanAttributes, type Prompt, PromptInvalidOutputError, PromptParsed, ReadableSpan, RenderContext, Retry, RetryCountContext, RetryLastErrorContext, SpanAttributes, SpanExporter, SpanProcessor, SystemMessage, type TokenizerFn, Trace, Tracer, UserMessage, type ValidAnthropicChatModel, type ValidGoogleChatModel, type ValidOpenAIChatModel, type ValidOpenAIVisionModel, anthropicTokenizer, computeUsage, createPrompt, createRenderContext, evaluatePrompt, isPromptParsed, openaiTokenizer, tracing };
package/dist/index.js CHANGED
@@ -40,7 +40,6 @@ __export(src_exports, {
40
40
  CombinedLogger: () => CombinedLogger,
41
41
  ConsoleLogger: () => ConsoleLogger,
42
42
  DefaultMaxRetriesContext: () => DefaultMaxRetriesContext,
43
- EnrichingSpanProcessor: () => EnrichingSpanProcessor,
44
43
  Fallback: () => Fallback,
45
44
  GoogleChatCompletion: () => GoogleChatCompletion,
46
45
  GoogleClientContext: () => GoogleClientContext,
@@ -1631,33 +1630,17 @@ async function* Fallback({ shouldFallback = () => true, fallback, children }, ct
1631
1630
  // src/tracing/SpanTree.ts
1632
1631
  var SpanTree = class {
1633
1632
  roots = [];
1634
- addSpan(span) {
1633
+ addSpan(span, status) {
1635
1634
  const parentId = span.parentSpanId;
1636
1635
  if (!parentId) {
1637
- this.roots.push(
1638
- new SpanTreeNode(
1639
- span.spanContext.spanId,
1640
- span.name,
1641
- null,
1642
- [],
1643
- span.attributes
1644
- )
1645
- );
1636
+ this.roots.push(new SpanTreeNode(span, status));
1646
1637
  return true;
1647
1638
  }
1648
1639
  const parent = this.findNode(parentId);
1649
1640
  if (!parent) {
1650
1641
  return false;
1651
1642
  }
1652
- parent.addChild(
1653
- new SpanTreeNode(
1654
- span.spanContext.spanId,
1655
- span.name,
1656
- parent,
1657
- [],
1658
- span.attributes
1659
- )
1660
- );
1643
+ parent.addChild(new SpanTreeNode(span, status, parent));
1661
1644
  return true;
1662
1645
  }
1663
1646
  findNode(id) {
@@ -1683,16 +1666,59 @@ function findSpanNode(root, id) {
1683
1666
  return null;
1684
1667
  }
1685
1668
  var SpanTreeNode = class {
1686
- constructor(id, name, parent, children, attrs) {
1687
- this.id = id;
1688
- this.name = name;
1669
+ constructor(span, status, parent = null, children = []) {
1670
+ this.span = span;
1671
+ this.status = status;
1689
1672
  this.parent = parent;
1690
1673
  this.children = children;
1691
- this.attrs = attrs;
1674
+ this.childrenDonePromise = new Promise((resolve) => {
1675
+ this.resolveChildrenDonePromise = resolve;
1676
+ });
1677
+ }
1678
+ childrenDonePromise;
1679
+ resolveChildrenDonePromise = () => {
1680
+ };
1681
+ get name() {
1682
+ return this.span.name;
1683
+ }
1684
+ get id() {
1685
+ return this.span.spanContext.spanId;
1686
+ }
1687
+ get attrs() {
1688
+ return this.span.attributes;
1692
1689
  }
1693
1690
  addChild(child) {
1694
1691
  this.children.push(child);
1695
1692
  }
1693
+ descendents(fn) {
1694
+ for (const child of this.children) {
1695
+ fn(child);
1696
+ child.descendents(fn);
1697
+ }
1698
+ }
1699
+ everyDescendent(fn) {
1700
+ let result = true;
1701
+ this.descendents((node) => {
1702
+ if (!result) {
1703
+ return;
1704
+ }
1705
+ if (!fn(node)) {
1706
+ result = false;
1707
+ }
1708
+ });
1709
+ return result;
1710
+ }
1711
+ getRootByName(name) {
1712
+ let node = this;
1713
+ let found = null;
1714
+ while (node) {
1715
+ if (node.name === name) {
1716
+ found = node;
1717
+ }
1718
+ node = node.parent;
1719
+ }
1720
+ return found;
1721
+ }
1696
1722
  getNearestAttribute(key) {
1697
1723
  return getNearestAttribute(this.parent, key);
1698
1724
  }
@@ -1734,65 +1760,69 @@ async function evaluatePrompt(prompt, variables, result) {
1734
1760
  }
1735
1761
 
1736
1762
  // src/tracing/AISpanProcessor.ts
1737
- var EnrichingSpanProcessor = class {
1763
+ var AISpanProcessor = class {
1738
1764
  constructor(exporter) {
1739
1765
  this.exporter = exporter;
1740
- this.onAllDonePromise = new Promise((resolve) => {
1741
- this.onAllDonePromiseResolve = resolve;
1742
- });
1743
1766
  }
1744
- finalSpans = [];
1745
- onAllDonePromise = null;
1746
- onAllDonePromiseResolve = null;
1747
1767
  spanTree = new SpanTree();
1748
1768
  async onStart(span) {
1749
- this.spanTree.addSpan(span);
1750
- this.finalSpans.push({
1751
- status: "running",
1752
- span
1753
- });
1769
+ this.spanTree.addSpan(span, "running");
1754
1770
  }
1755
1771
  async onEnd(span) {
1756
- const entry = this.finalSpans.find(
1757
- (a) => a.span.spanContext.spanId === span.spanContext.spanId
1758
- );
1772
+ const entry = this.spanTree.findNode(span.spanContext.spanId);
1759
1773
  if (!entry) {
1760
1774
  throw new Error("onEnd called without onStart");
1761
1775
  }
1762
- const enrichedSpan = await this.enrichSpan(span);
1763
1776
  entry.status = "processing";
1764
- entry.span = enrichedSpan;
1777
+ entry.span = await this.enrichSpan(span);
1765
1778
  entry.status = "done";
1766
- if (this.finalSpans.every((a) => a.status === "done")) {
1767
- this.onAllDonePromiseResolve?.();
1779
+ const rootPrompt = entry.getRootByName("ai.prompt");
1780
+ if (!rootPrompt) {
1781
+ this.exporter.export([entry.span]);
1782
+ return;
1768
1783
  }
1769
- if (span.parentSpanId == null) {
1770
- await this.onAllDonePromise;
1771
- await this.onTraceComplete(enrichedSpan);
1784
+ if (rootPrompt.everyDescendent(({ status }) => status === "done")) {
1785
+ rootPrompt.resolveChildrenDonePromise();
1772
1786
  }
1773
- this.exporter.export([enrichedSpan]);
1787
+ if (span.spanContext.spanId === rootPrompt.id) {
1788
+ await rootPrompt.childrenDonePromise;
1789
+ await this.onRootPromptDone(entry.span);
1790
+ }
1791
+ this.exporter.export([entry.span]);
1774
1792
  }
1775
1793
  shutdown() {
1776
1794
  return this.exporter.shutdown?.();
1777
1795
  }
1778
- };
1779
- var AISpanProcessor = class extends EnrichingSpanProcessor {
1780
- totalCost = 0;
1781
- totalUsage = {
1782
- prompt: 0,
1783
- completion: 0,
1784
- total: 0
1785
- };
1786
- async onTraceComplete(rootSpan) {
1787
- rootSpan.attributes.totalCost = this.totalCost;
1788
- rootSpan.attributes.totalUsage = this.totalUsage;
1796
+ async onRootPromptDone(rootSpan) {
1797
+ let totalCost = 0;
1798
+ const totalUsage = {
1799
+ prompt: 0,
1800
+ completion: 0,
1801
+ total: 0
1802
+ };
1803
+ const root = this.spanTree.findNode(rootSpan.spanContext.spanId);
1804
+ root?.descendents(({ span }) => {
1805
+ if (!isChatCompletionSpan(span)) {
1806
+ return;
1807
+ }
1808
+ const { cost, tokensUsed } = span.attributes;
1809
+ if (typeof cost === "number") {
1810
+ totalCost += cost;
1811
+ }
1812
+ if (!tokensUsed || tokensUsed.total == null || tokensUsed.completion == null || tokensUsed.prompt == null) {
1813
+ return;
1814
+ }
1815
+ totalUsage.prompt += tokensUsed.prompt;
1816
+ totalUsage.completion += tokensUsed.completion;
1817
+ totalUsage.total += tokensUsed.total;
1818
+ });
1819
+ rootSpan.attributes.totalCost = totalCost;
1820
+ rootSpan.attributes.totalUsage = totalUsage;
1789
1821
  }
1790
1822
  async enrichSpan(span) {
1791
1823
  const result1 = await this.evaluatePrompt(span);
1792
- const result2 = await this.updateCost(result1);
1793
- const result3 = await this.updateUsage(result2);
1794
- const result4 = await this.addPromptKeys(result3);
1795
- return result4;
1824
+ const result2 = await this.addPromptKeys(result1);
1825
+ return result2;
1796
1826
  }
1797
1827
  async addPromptKeys(span) {
1798
1828
  if (!isChatCompletionSpan(span) && !isPromptSpan(span)) {
@@ -1815,29 +1845,6 @@ var AISpanProcessor = class extends EnrichingSpanProcessor {
1815
1845
  };
1816
1846
  return final;
1817
1847
  }
1818
- async updateCost(span) {
1819
- if (!isChatCompletionSpan(span)) {
1820
- return span;
1821
- }
1822
- const { cost } = span.attributes;
1823
- if (typeof cost === "number") {
1824
- this.totalCost += cost;
1825
- }
1826
- return span;
1827
- }
1828
- async updateUsage(span) {
1829
- if (!isChatCompletionSpan(span)) {
1830
- return span;
1831
- }
1832
- const tokensUsed = span.attributes.tokensUsed;
1833
- if (!tokensUsed || tokensUsed.total == null || tokensUsed.completion == null || tokensUsed.prompt == null) {
1834
- return span;
1835
- }
1836
- this.totalUsage.prompt += tokensUsed.prompt;
1837
- this.totalUsage.completion += tokensUsed.completion;
1838
- this.totalUsage.total += tokensUsed.total;
1839
- return span;
1840
- }
1841
1848
  async evaluatePrompt(span) {
1842
1849
  if (!isPrompt2(span.attributes.prompt)) {
1843
1850
  return span;
@@ -2942,7 +2949,6 @@ var import_vertexai2 = require("@google-cloud/vertexai");
2942
2949
  CombinedLogger,
2943
2950
  ConsoleLogger,
2944
2951
  DefaultMaxRetriesContext,
2945
- EnrichingSpanProcessor,
2946
2952
  Fallback,
2947
2953
  GoogleChatCompletion,
2948
2954
  GoogleClientContext,
package/dist/index.mjs CHANGED
@@ -1528,33 +1528,17 @@ async function* Fallback({ shouldFallback = () => true, fallback, children }, ct
1528
1528
  // src/tracing/SpanTree.ts
1529
1529
  var SpanTree = class {
1530
1530
  roots = [];
1531
- addSpan(span) {
1531
+ addSpan(span, status) {
1532
1532
  const parentId = span.parentSpanId;
1533
1533
  if (!parentId) {
1534
- this.roots.push(
1535
- new SpanTreeNode(
1536
- span.spanContext.spanId,
1537
- span.name,
1538
- null,
1539
- [],
1540
- span.attributes
1541
- )
1542
- );
1534
+ this.roots.push(new SpanTreeNode(span, status));
1543
1535
  return true;
1544
1536
  }
1545
1537
  const parent = this.findNode(parentId);
1546
1538
  if (!parent) {
1547
1539
  return false;
1548
1540
  }
1549
- parent.addChild(
1550
- new SpanTreeNode(
1551
- span.spanContext.spanId,
1552
- span.name,
1553
- parent,
1554
- [],
1555
- span.attributes
1556
- )
1557
- );
1541
+ parent.addChild(new SpanTreeNode(span, status, parent));
1558
1542
  return true;
1559
1543
  }
1560
1544
  findNode(id) {
@@ -1580,16 +1564,59 @@ function findSpanNode(root, id) {
1580
1564
  return null;
1581
1565
  }
1582
1566
  var SpanTreeNode = class {
1583
- constructor(id, name, parent, children, attrs) {
1584
- this.id = id;
1585
- this.name = name;
1567
+ constructor(span, status, parent = null, children = []) {
1568
+ this.span = span;
1569
+ this.status = status;
1586
1570
  this.parent = parent;
1587
1571
  this.children = children;
1588
- this.attrs = attrs;
1572
+ this.childrenDonePromise = new Promise((resolve) => {
1573
+ this.resolveChildrenDonePromise = resolve;
1574
+ });
1575
+ }
1576
+ childrenDonePromise;
1577
+ resolveChildrenDonePromise = () => {
1578
+ };
1579
+ get name() {
1580
+ return this.span.name;
1581
+ }
1582
+ get id() {
1583
+ return this.span.spanContext.spanId;
1584
+ }
1585
+ get attrs() {
1586
+ return this.span.attributes;
1589
1587
  }
1590
1588
  addChild(child) {
1591
1589
  this.children.push(child);
1592
1590
  }
1591
+ descendents(fn) {
1592
+ for (const child of this.children) {
1593
+ fn(child);
1594
+ child.descendents(fn);
1595
+ }
1596
+ }
1597
+ everyDescendent(fn) {
1598
+ let result = true;
1599
+ this.descendents((node) => {
1600
+ if (!result) {
1601
+ return;
1602
+ }
1603
+ if (!fn(node)) {
1604
+ result = false;
1605
+ }
1606
+ });
1607
+ return result;
1608
+ }
1609
+ getRootByName(name) {
1610
+ let node = this;
1611
+ let found = null;
1612
+ while (node) {
1613
+ if (node.name === name) {
1614
+ found = node;
1615
+ }
1616
+ node = node.parent;
1617
+ }
1618
+ return found;
1619
+ }
1593
1620
  getNearestAttribute(key) {
1594
1621
  return getNearestAttribute(this.parent, key);
1595
1622
  }
@@ -1631,65 +1658,69 @@ async function evaluatePrompt(prompt, variables, result) {
1631
1658
  }
1632
1659
 
1633
1660
  // src/tracing/AISpanProcessor.ts
1634
- var EnrichingSpanProcessor = class {
1661
+ var AISpanProcessor = class {
1635
1662
  constructor(exporter) {
1636
1663
  this.exporter = exporter;
1637
- this.onAllDonePromise = new Promise((resolve) => {
1638
- this.onAllDonePromiseResolve = resolve;
1639
- });
1640
1664
  }
1641
- finalSpans = [];
1642
- onAllDonePromise = null;
1643
- onAllDonePromiseResolve = null;
1644
1665
  spanTree = new SpanTree();
1645
1666
  async onStart(span) {
1646
- this.spanTree.addSpan(span);
1647
- this.finalSpans.push({
1648
- status: "running",
1649
- span
1650
- });
1667
+ this.spanTree.addSpan(span, "running");
1651
1668
  }
1652
1669
  async onEnd(span) {
1653
- const entry = this.finalSpans.find(
1654
- (a) => a.span.spanContext.spanId === span.spanContext.spanId
1655
- );
1670
+ const entry = this.spanTree.findNode(span.spanContext.spanId);
1656
1671
  if (!entry) {
1657
1672
  throw new Error("onEnd called without onStart");
1658
1673
  }
1659
- const enrichedSpan = await this.enrichSpan(span);
1660
1674
  entry.status = "processing";
1661
- entry.span = enrichedSpan;
1675
+ entry.span = await this.enrichSpan(span);
1662
1676
  entry.status = "done";
1663
- if (this.finalSpans.every((a) => a.status === "done")) {
1664
- this.onAllDonePromiseResolve?.();
1677
+ const rootPrompt = entry.getRootByName("ai.prompt");
1678
+ if (!rootPrompt) {
1679
+ this.exporter.export([entry.span]);
1680
+ return;
1665
1681
  }
1666
- if (span.parentSpanId == null) {
1667
- await this.onAllDonePromise;
1668
- await this.onTraceComplete(enrichedSpan);
1682
+ if (rootPrompt.everyDescendent(({ status }) => status === "done")) {
1683
+ rootPrompt.resolveChildrenDonePromise();
1669
1684
  }
1670
- this.exporter.export([enrichedSpan]);
1685
+ if (span.spanContext.spanId === rootPrompt.id) {
1686
+ await rootPrompt.childrenDonePromise;
1687
+ await this.onRootPromptDone(entry.span);
1688
+ }
1689
+ this.exporter.export([entry.span]);
1671
1690
  }
1672
1691
  shutdown() {
1673
1692
  return this.exporter.shutdown?.();
1674
1693
  }
1675
- };
1676
- var AISpanProcessor = class extends EnrichingSpanProcessor {
1677
- totalCost = 0;
1678
- totalUsage = {
1679
- prompt: 0,
1680
- completion: 0,
1681
- total: 0
1682
- };
1683
- async onTraceComplete(rootSpan) {
1684
- rootSpan.attributes.totalCost = this.totalCost;
1685
- rootSpan.attributes.totalUsage = this.totalUsage;
1694
+ async onRootPromptDone(rootSpan) {
1695
+ let totalCost = 0;
1696
+ const totalUsage = {
1697
+ prompt: 0,
1698
+ completion: 0,
1699
+ total: 0
1700
+ };
1701
+ const root = this.spanTree.findNode(rootSpan.spanContext.spanId);
1702
+ root?.descendents(({ span }) => {
1703
+ if (!isChatCompletionSpan(span)) {
1704
+ return;
1705
+ }
1706
+ const { cost, tokensUsed } = span.attributes;
1707
+ if (typeof cost === "number") {
1708
+ totalCost += cost;
1709
+ }
1710
+ if (!tokensUsed || tokensUsed.total == null || tokensUsed.completion == null || tokensUsed.prompt == null) {
1711
+ return;
1712
+ }
1713
+ totalUsage.prompt += tokensUsed.prompt;
1714
+ totalUsage.completion += tokensUsed.completion;
1715
+ totalUsage.total += tokensUsed.total;
1716
+ });
1717
+ rootSpan.attributes.totalCost = totalCost;
1718
+ rootSpan.attributes.totalUsage = totalUsage;
1686
1719
  }
1687
1720
  async enrichSpan(span) {
1688
1721
  const result1 = await this.evaluatePrompt(span);
1689
- const result2 = await this.updateCost(result1);
1690
- const result3 = await this.updateUsage(result2);
1691
- const result4 = await this.addPromptKeys(result3);
1692
- return result4;
1722
+ const result2 = await this.addPromptKeys(result1);
1723
+ return result2;
1693
1724
  }
1694
1725
  async addPromptKeys(span) {
1695
1726
  if (!isChatCompletionSpan(span) && !isPromptSpan(span)) {
@@ -1712,29 +1743,6 @@ var AISpanProcessor = class extends EnrichingSpanProcessor {
1712
1743
  };
1713
1744
  return final;
1714
1745
  }
1715
- async updateCost(span) {
1716
- if (!isChatCompletionSpan(span)) {
1717
- return span;
1718
- }
1719
- const { cost } = span.attributes;
1720
- if (typeof cost === "number") {
1721
- this.totalCost += cost;
1722
- }
1723
- return span;
1724
- }
1725
- async updateUsage(span) {
1726
- if (!isChatCompletionSpan(span)) {
1727
- return span;
1728
- }
1729
- const tokensUsed = span.attributes.tokensUsed;
1730
- if (!tokensUsed || tokensUsed.total == null || tokensUsed.completion == null || tokensUsed.prompt == null) {
1731
- return span;
1732
- }
1733
- this.totalUsage.prompt += tokensUsed.prompt;
1734
- this.totalUsage.completion += tokensUsed.completion;
1735
- this.totalUsage.total += tokensUsed.total;
1736
- return span;
1737
- }
1738
1746
  async evaluatePrompt(span) {
1739
1747
  if (!isPrompt2(span.attributes.prompt)) {
1740
1748
  return span;
@@ -2846,7 +2854,6 @@ export {
2846
2854
  CombinedLogger,
2847
2855
  ConsoleLogger,
2848
2856
  DefaultMaxRetriesContext,
2849
- EnrichingSpanProcessor,
2850
2857
  Fallback,
2851
2858
  GoogleChatCompletion,
2852
2859
  GoogleClientContext,
@@ -354,4 +354,4 @@ declare const jsxs: typeof jsx;
354
354
  /** @hidden */
355
355
  declare const Fragment: typeof AIFragment;
356
356
 
357
- export { type AINode as A, BoundLogger as B, type ChatMessage as C, type DebugMessage as D, type EvaluatorResult as E, type PropsOfAIComponent as F, type SpanContext as G, type SpanStatus as H, ImagePart as I, JSX as J, type Span as K, type LogChatCompletionRequest as L, type SpanEvent as M, NoopLogImplementation as N, type TracingContextKey as O, type Prompt as P, type TracingContext as Q, type RenderContext as R, type SpanProcessor as S, type Tracer as T, type TracingContextManager as U, type OutputParser as V, jsx as W, jsxDEV as X, jsxs as Y, Fragment as Z, LogImplementation as a, type ContextValues as b, type Context as c, type ReadableSpan as d, type SpanExporter as e, type AIComponent as f, type SpanAttributes as g, type ChatCompletionRequestPayloads as h, type EvaluatorFn as i, type PromptParsed as j, createAIElement as k, AIFragment as l, createContext as m, type ChatRole as n, type ImagePartProps as o, type LogChatCompletionResponse as p, type LogLevel as q, type Logger as r, ConsoleLogger as s, toDebugMessage as t, CombinedLogger as u, type Literal as v, type RenderResult as w, attachedContextSymbol as x, type AIElement as y, type Renderable as z };
357
+ export { type AINode as A, BoundLogger as B, type ChatMessage as C, type DebugMessage as D, type EvaluatorResult as E, type PropsOfAIComponent as F, type SpanContext as G, type SpanStatus as H, ImagePart as I, JSX as J, type Span as K, type LogChatCompletionRequest as L, type SpanEvent as M, NoopLogImplementation as N, type TracingContextKey as O, type Prompt as P, type TracingContext as Q, type RenderContext as R, type SpanProcessor as S, type Tracer as T, type TracingContextManager as U, type OutputParser as V, jsx as W, jsxDEV as X, jsxs as Y, Fragment as Z, LogImplementation as a, type ContextValues as b, type Context as c, type ReadableSpan as d, type SpanAttributes as e, type SpanExporter as f, type AIComponent as g, type ChatCompletionRequestPayloads as h, type EvaluatorFn as i, type PromptParsed as j, createAIElement as k, AIFragment as l, createContext as m, type ChatRole as n, type ImagePartProps as o, type LogChatCompletionResponse as p, type LogLevel as q, type Logger as r, ConsoleLogger as s, toDebugMessage as t, CombinedLogger as u, type Literal as v, type RenderResult as w, attachedContextSymbol as x, type AIElement as y, type Renderable as z };
@@ -354,4 +354,4 @@ declare const jsxs: typeof jsx;
354
354
  /** @hidden */
355
355
  declare const Fragment: typeof AIFragment;
356
356
 
357
- export { type AINode as A, BoundLogger as B, type ChatMessage as C, type DebugMessage as D, type EvaluatorResult as E, type PropsOfAIComponent as F, type SpanContext as G, type SpanStatus as H, ImagePart as I, JSX as J, type Span as K, type LogChatCompletionRequest as L, type SpanEvent as M, NoopLogImplementation as N, type TracingContextKey as O, type Prompt as P, type TracingContext as Q, type RenderContext as R, type SpanProcessor as S, type Tracer as T, type TracingContextManager as U, type OutputParser as V, jsx as W, jsxDEV as X, jsxs as Y, Fragment as Z, LogImplementation as a, type ContextValues as b, type Context as c, type ReadableSpan as d, type SpanExporter as e, type AIComponent as f, type SpanAttributes as g, type ChatCompletionRequestPayloads as h, type EvaluatorFn as i, type PromptParsed as j, createAIElement as k, AIFragment as l, createContext as m, type ChatRole as n, type ImagePartProps as o, type LogChatCompletionResponse as p, type LogLevel as q, type Logger as r, ConsoleLogger as s, toDebugMessage as t, CombinedLogger as u, type Literal as v, type RenderResult as w, attachedContextSymbol as x, type AIElement as y, type Renderable as z };
357
+ export { type AINode as A, BoundLogger as B, type ChatMessage as C, type DebugMessage as D, type EvaluatorResult as E, type PropsOfAIComponent as F, type SpanContext as G, type SpanStatus as H, ImagePart as I, JSX as J, type Span as K, type LogChatCompletionRequest as L, type SpanEvent as M, NoopLogImplementation as N, type TracingContextKey as O, type Prompt as P, type TracingContext as Q, type RenderContext as R, type SpanProcessor as S, type Tracer as T, type TracingContextManager as U, type OutputParser as V, jsx as W, jsxDEV as X, jsxs as Y, Fragment as Z, LogImplementation as a, type ContextValues as b, type Context as c, type ReadableSpan as d, type SpanAttributes as e, type SpanExporter as f, type AIComponent as g, type ChatCompletionRequestPayloads as h, type EvaluatorFn as i, type PromptParsed as j, createAIElement as k, AIFragment as l, createContext as m, type ChatRole as n, type ImagePartProps as o, type LogChatCompletionResponse as p, type LogLevel as q, type Logger as r, ConsoleLogger as s, toDebugMessage as t, CombinedLogger as u, type Literal as v, type RenderResult as w, attachedContextSymbol as x, type AIElement as y, type Renderable as z };
@@ -1,2 +1,2 @@
1
- export { Z as Fragment, J as JSX, W as jsx, X as jsxDEV, Y as jsxs } from './jsx-dev-runtime-vXV-PExh.mjs';
1
+ export { Z as Fragment, J as JSX, W as jsx, X as jsxDEV, Y as jsxs } from './jsx-dev-runtime-S--1HQKU.mjs';
2
2
  import 'zod';
@@ -1,2 +1,2 @@
1
- export { Z as Fragment, J as JSX, W as jsx, X as jsxDEV, Y as jsxs } from './jsx-dev-runtime-vXV-PExh.js';
1
+ export { Z as Fragment, J as JSX, W as jsx, X as jsxDEV, Y as jsxs } from './jsx-dev-runtime-S--1HQKU.js';
2
2
  import 'zod';
@@ -1,2 +1,2 @@
1
- export { Z as Fragment, J as JSX, W as jsx, X as jsxDEV, Y as jsxs } from './jsx-dev-runtime-vXV-PExh.mjs';
1
+ export { Z as Fragment, J as JSX, W as jsx, X as jsxDEV, Y as jsxs } from './jsx-dev-runtime-S--1HQKU.mjs';
2
2
  import 'zod';
@@ -1,2 +1,2 @@
1
- export { Z as Fragment, J as JSX, W as jsx, X as jsxDEV, Y as jsxs } from './jsx-dev-runtime-vXV-PExh.js';
1
+ export { Z as Fragment, J as JSX, W as jsx, X as jsxDEV, Y as jsxs } from './jsx-dev-runtime-S--1HQKU.js';
2
2
  import 'zod';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gammatech/aijsx",
3
- "version": "0.11.4-dev.2024-07-08",
3
+ "version": "0.12.0-dev.2024-07-08",
4
4
  "description": "Rewrite of aijsx",
5
5
  "author": "Jordan Garcia",
6
6
  "license": "MIT",