@gammatech/aijsx 0.4.0-beta.5 → 0.4.0-beta.6

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.
@@ -306,4 +306,4 @@ declare function AIFragment({ children }: {
306
306
  children: AINode;
307
307
  }): Renderable;
308
308
 
309
- export { type AIComponent as A, BoundLogger as B, type ContextValues as C, NoopLogImplementation as D, type EvaluatorFn as E, type FunctionChain as F, ConsoleLogger as G, CombinedLogger as H, type Literal as I, type RenderableStream as J, type RenderResult as K, LogImplementation as L, attachedContextSymbol as M, type NotAsyncGenerator as N, type AIElement as O, type PromptParsed as P, type Renderable as Q, type RenderContext as R, type StreamChain as S, type PropsOfAIComponent as T, UserMessage as U, type EvaluatorResult as V, type OutputParser as W, type PromptRenderResult as X, type Prompt as a, type Context as b, type AINode as c, createAIElement as d, AIFragment as e, LoggerContext as f, createContext as g, type RenderTraceInfo as h, type ChatCompletionRole as i, SystemMessage as j, AssistantMessage as k, type RenderedConversationMessage as l, computeUsage as m, ChatCompletionError as n, type LogChainStart as o, type LogChainComplete as p, type LogChainError as q, type LogPromptStart as r, type LogPromptComplete as s, type LogPromptError as t, type ChatCompletionRequestPayloads as u, type LogChatCompletionRequest as v, type LogChatCompletionResponse as w, type LogLevel as x, type LogContext as y, type Logger as z };
309
+ export { type AIComponent as A, type Logger as B, type ContextValues as C, BoundLogger as D, type EvaluatorFn as E, type FunctionChain as F, NoopLogImplementation as G, ConsoleLogger as H, CombinedLogger as I, type Literal as J, type RenderableStream as K, LogImplementation as L, type RenderResult as M, type NotAsyncGenerator as N, attachedContextSymbol as O, type PromptParsed as P, type AIElement as Q, type RenderContext as R, type StreamChain as S, type Renderable as T, UserMessage as U, type PropsOfAIComponent as V, type OutputParser as W, type PromptRenderResult as X, type Prompt as a, type EvaluatorResult as b, type Context as c, type AINode as d, createAIElement as e, AIFragment as f, LoggerContext as g, createContext as h, type RenderTraceInfo as i, type ChatCompletionRole as j, SystemMessage as k, AssistantMessage as l, type RenderedConversationMessage as m, computeUsage as n, ChatCompletionError as o, type LogChainStart as p, type LogChainComplete as q, type LogChainError as r, type LogPromptStart as s, type LogPromptComplete as t, type LogPromptError as u, type ChatCompletionRequestPayloads as v, type LogChatCompletionRequest as w, type LogChatCompletionResponse as x, type LogLevel as y, type LogContext as z };
@@ -306,4 +306,4 @@ declare function AIFragment({ children }: {
306
306
  children: AINode;
307
307
  }): Renderable;
308
308
 
309
- export { type AIComponent as A, BoundLogger as B, type ContextValues as C, NoopLogImplementation as D, type EvaluatorFn as E, type FunctionChain as F, ConsoleLogger as G, CombinedLogger as H, type Literal as I, type RenderableStream as J, type RenderResult as K, LogImplementation as L, attachedContextSymbol as M, type NotAsyncGenerator as N, type AIElement as O, type PromptParsed as P, type Renderable as Q, type RenderContext as R, type StreamChain as S, type PropsOfAIComponent as T, UserMessage as U, type EvaluatorResult as V, type OutputParser as W, type PromptRenderResult as X, type Prompt as a, type Context as b, type AINode as c, createAIElement as d, AIFragment as e, LoggerContext as f, createContext as g, type RenderTraceInfo as h, type ChatCompletionRole as i, SystemMessage as j, AssistantMessage as k, type RenderedConversationMessage as l, computeUsage as m, ChatCompletionError as n, type LogChainStart as o, type LogChainComplete as p, type LogChainError as q, type LogPromptStart as r, type LogPromptComplete as s, type LogPromptError as t, type ChatCompletionRequestPayloads as u, type LogChatCompletionRequest as v, type LogChatCompletionResponse as w, type LogLevel as x, type LogContext as y, type Logger as z };
309
+ export { type AIComponent as A, type Logger as B, type ContextValues as C, BoundLogger as D, type EvaluatorFn as E, type FunctionChain as F, NoopLogImplementation as G, ConsoleLogger as H, CombinedLogger as I, type Literal as J, type RenderableStream as K, LogImplementation as L, type RenderResult as M, type NotAsyncGenerator as N, attachedContextSymbol as O, type PromptParsed as P, type AIElement as Q, type RenderContext as R, type StreamChain as S, type Renderable as T, UserMessage as U, type PropsOfAIComponent as V, type OutputParser as W, type PromptRenderResult as X, type Prompt as a, type EvaluatorResult as b, type Context as c, type AINode as d, createAIElement as e, AIFragment as f, LoggerContext as g, createContext as h, type RenderTraceInfo as i, type ChatCompletionRole as j, SystemMessage as k, AssistantMessage as l, type RenderedConversationMessage as m, computeUsage as n, ChatCompletionError as o, type LogChainStart as p, type LogChainComplete as q, type LogChainError as r, type LogPromptStart as s, type LogPromptComplete as t, type LogPromptError as u, type ChatCompletionRequestPayloads as v, type LogChatCompletionRequest as w, type LogChatCompletionResponse as x, type LogLevel as y, type LogContext as z };
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { R as RenderContext, L as LogImplementation, C as ContextValues, A as AIComponent, E as EvaluatorFn, P as PromptParsed, a as Prompt, N as NotAsyncGenerator, F as FunctionChain, S as StreamChain, b as Context, c as AINode } from './createElement-gT2wWwEd.mjs';
2
- export { O as AIElement, e as AIFragment, k as AssistantMessage, B as BoundLogger, n as ChatCompletionError, u as ChatCompletionRequestPayloads, i as ChatCompletionRole, H as CombinedLogger, G as ConsoleLogger, V as EvaluatorResult, I as Literal, p as LogChainComplete, q as LogChainError, o as LogChainStart, v as LogChatCompletionRequest, w as LogChatCompletionResponse, y as LogContext, x as LogLevel, s as LogPromptComplete, t as LogPromptError, r as LogPromptStart, z as Logger, f as LoggerContext, D as NoopLogImplementation, W as OutputParser, X as PromptRenderResult, T as PropsOfAIComponent, K as RenderResult, h as RenderTraceInfo, Q as Renderable, J as RenderableStream, l as RenderedConversationMessage, j as SystemMessage, U as UserMessage, M as attachedContextSymbol, m as computeUsage, d as createAIElement, g as createContext } from './createElement-gT2wWwEd.mjs';
1
+ import { R as RenderContext, L as LogImplementation, C as ContextValues, A as AIComponent, E as EvaluatorFn, P as PromptParsed, a as Prompt, N as NotAsyncGenerator, F as FunctionChain, S as StreamChain, b as EvaluatorResult, c as Context, d as AINode } from './createElement-M3MXUt8O.mjs';
2
+ export { Q as AIElement, f as AIFragment, l as AssistantMessage, D as BoundLogger, o as ChatCompletionError, v as ChatCompletionRequestPayloads, j as ChatCompletionRole, I as CombinedLogger, H as ConsoleLogger, J as Literal, q as LogChainComplete, r as LogChainError, p as LogChainStart, w as LogChatCompletionRequest, x as LogChatCompletionResponse, z as LogContext, y as LogLevel, t as LogPromptComplete, u as LogPromptError, s as LogPromptStart, B as Logger, g as LoggerContext, G as NoopLogImplementation, W as OutputParser, X as PromptRenderResult, V as PropsOfAIComponent, M as RenderResult, i as RenderTraceInfo, T as Renderable, K as RenderableStream, m as RenderedConversationMessage, k as SystemMessage, U as UserMessage, O as attachedContextSymbol, n as computeUsage, e as createAIElement, h as createContext } from './createElement-M3MXUt8O.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';
@@ -60,6 +60,9 @@ declare class ParseVariablesError extends Error {
60
60
  declare class PromptInvalidOutputError extends Error {
61
61
  }
62
62
 
63
+ declare function evaluatePrompt<V extends Record<string, any>>(prompt: Prompt<V>, variables: V, result: string): Promise<EvaluatorResult[]>;
64
+ declare function evaluatePrompt<V extends Record<string, any>, O>(prompt: PromptParsed<V, O>, variables: V, result: O): Promise<EvaluatorResult[]>;
65
+
63
66
  type OpenAIChatCompletionRequest = OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming;
64
67
  type OpenAIChatMessage = ChatCompletionSystemMessageParam | ChatCompletionUserMessageParam | ChatCompletionAssistantMessageParam;
65
68
  declare module '@gammatech/aijsx' {
@@ -140,4 +143,4 @@ type AnthropicChatCompletionProps = {
140
143
  */
141
144
  declare function AnthropicChatCompletion(props: AnthropicChatCompletionProps, { render, logger, getContext }: RenderContext): AsyncGenerator<string, void, unknown>;
142
145
 
143
- export { AIComponent, AINode, AnthropicChatCompletion, type AnthropicChatCompletionRequest, AnthropicClientContext, ChainParseVariablesError, ContentTypeImage, Context, EvaluatorFn, FunctionChain, LogImplementation, NotAsyncGenerator, OpenAIChatCompletion, type OpenAIChatCompletionRequest, type OpenAIChatMessage, OpenAIClientContext, OpenAIVisionChatCompletion, ParseVariablesError, Prompt, PromptInvalidOutputError, PromptParseVariablesError, PromptParsed, RenderContext, StreamChain, type ValidAnthropicChatModel, type ValidOpenAIChatModel, type ValidOpenAIVisionModel, createFunctionChain, createPrompt, createRenderContext, createStreamChain, defaultMaxTokens, tokenCountForOpenAIMessage, tokenCountForOpenAIVisionMessage, tokenLimitForChatModel, tokenizer };
146
+ export { AIComponent, AINode, AnthropicChatCompletion, type AnthropicChatCompletionRequest, AnthropicClientContext, ChainParseVariablesError, ContentTypeImage, Context, EvaluatorFn, EvaluatorResult, FunctionChain, LogImplementation, NotAsyncGenerator, OpenAIChatCompletion, type OpenAIChatCompletionRequest, type OpenAIChatMessage, OpenAIClientContext, OpenAIVisionChatCompletion, ParseVariablesError, Prompt, PromptInvalidOutputError, PromptParseVariablesError, PromptParsed, RenderContext, StreamChain, type ValidAnthropicChatModel, type ValidOpenAIChatModel, type ValidOpenAIVisionModel, createFunctionChain, createPrompt, createRenderContext, createStreamChain, defaultMaxTokens, evaluatePrompt, tokenCountForOpenAIMessage, tokenCountForOpenAIVisionMessage, tokenLimitForChatModel, tokenizer };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { R as RenderContext, L as LogImplementation, C as ContextValues, A as AIComponent, E as EvaluatorFn, P as PromptParsed, a as Prompt, N as NotAsyncGenerator, F as FunctionChain, S as StreamChain, b as Context, c as AINode } from './createElement-gT2wWwEd.js';
2
- export { O as AIElement, e as AIFragment, k as AssistantMessage, B as BoundLogger, n as ChatCompletionError, u as ChatCompletionRequestPayloads, i as ChatCompletionRole, H as CombinedLogger, G as ConsoleLogger, V as EvaluatorResult, I as Literal, p as LogChainComplete, q as LogChainError, o as LogChainStart, v as LogChatCompletionRequest, w as LogChatCompletionResponse, y as LogContext, x as LogLevel, s as LogPromptComplete, t as LogPromptError, r as LogPromptStart, z as Logger, f as LoggerContext, D as NoopLogImplementation, W as OutputParser, X as PromptRenderResult, T as PropsOfAIComponent, K as RenderResult, h as RenderTraceInfo, Q as Renderable, J as RenderableStream, l as RenderedConversationMessage, j as SystemMessage, U as UserMessage, M as attachedContextSymbol, m as computeUsage, d as createAIElement, g as createContext } from './createElement-gT2wWwEd.js';
1
+ import { R as RenderContext, L as LogImplementation, C as ContextValues, A as AIComponent, E as EvaluatorFn, P as PromptParsed, a as Prompt, N as NotAsyncGenerator, F as FunctionChain, S as StreamChain, b as EvaluatorResult, c as Context, d as AINode } from './createElement-M3MXUt8O.js';
2
+ export { Q as AIElement, f as AIFragment, l as AssistantMessage, D as BoundLogger, o as ChatCompletionError, v as ChatCompletionRequestPayloads, j as ChatCompletionRole, I as CombinedLogger, H as ConsoleLogger, J as Literal, q as LogChainComplete, r as LogChainError, p as LogChainStart, w as LogChatCompletionRequest, x as LogChatCompletionResponse, z as LogContext, y as LogLevel, t as LogPromptComplete, u as LogPromptError, s as LogPromptStart, B as Logger, g as LoggerContext, G as NoopLogImplementation, W as OutputParser, X as PromptRenderResult, V as PropsOfAIComponent, M as RenderResult, i as RenderTraceInfo, T as Renderable, K as RenderableStream, m as RenderedConversationMessage, k as SystemMessage, U as UserMessage, O as attachedContextSymbol, n as computeUsage, e as createAIElement, h as createContext } from './createElement-M3MXUt8O.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';
@@ -60,6 +60,9 @@ declare class ParseVariablesError extends Error {
60
60
  declare class PromptInvalidOutputError extends Error {
61
61
  }
62
62
 
63
+ declare function evaluatePrompt<V extends Record<string, any>>(prompt: Prompt<V>, variables: V, result: string): Promise<EvaluatorResult[]>;
64
+ declare function evaluatePrompt<V extends Record<string, any>, O>(prompt: PromptParsed<V, O>, variables: V, result: O): Promise<EvaluatorResult[]>;
65
+
63
66
  type OpenAIChatCompletionRequest = OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming;
64
67
  type OpenAIChatMessage = ChatCompletionSystemMessageParam | ChatCompletionUserMessageParam | ChatCompletionAssistantMessageParam;
65
68
  declare module '@gammatech/aijsx' {
@@ -140,4 +143,4 @@ type AnthropicChatCompletionProps = {
140
143
  */
141
144
  declare function AnthropicChatCompletion(props: AnthropicChatCompletionProps, { render, logger, getContext }: RenderContext): AsyncGenerator<string, void, unknown>;
142
145
 
143
- export { AIComponent, AINode, AnthropicChatCompletion, type AnthropicChatCompletionRequest, AnthropicClientContext, ChainParseVariablesError, ContentTypeImage, Context, EvaluatorFn, FunctionChain, LogImplementation, NotAsyncGenerator, OpenAIChatCompletion, type OpenAIChatCompletionRequest, type OpenAIChatMessage, OpenAIClientContext, OpenAIVisionChatCompletion, ParseVariablesError, Prompt, PromptInvalidOutputError, PromptParseVariablesError, PromptParsed, RenderContext, StreamChain, type ValidAnthropicChatModel, type ValidOpenAIChatModel, type ValidOpenAIVisionModel, createFunctionChain, createPrompt, createRenderContext, createStreamChain, defaultMaxTokens, tokenCountForOpenAIMessage, tokenCountForOpenAIVisionMessage, tokenLimitForChatModel, tokenizer };
146
+ export { AIComponent, AINode, AnthropicChatCompletion, type AnthropicChatCompletionRequest, AnthropicClientContext, ChainParseVariablesError, ContentTypeImage, Context, EvaluatorFn, EvaluatorResult, FunctionChain, LogImplementation, NotAsyncGenerator, OpenAIChatCompletion, type OpenAIChatCompletionRequest, type OpenAIChatMessage, OpenAIClientContext, OpenAIVisionChatCompletion, ParseVariablesError, Prompt, PromptInvalidOutputError, PromptParseVariablesError, PromptParsed, RenderContext, StreamChain, type ValidAnthropicChatModel, type ValidOpenAIChatModel, type ValidOpenAIVisionModel, createFunctionChain, createPrompt, createRenderContext, createStreamChain, defaultMaxTokens, evaluatePrompt, tokenCountForOpenAIMessage, tokenCountForOpenAIVisionMessage, tokenLimitForChatModel, tokenizer };
package/dist/index.js CHANGED
@@ -62,6 +62,7 @@ __export(src_exports, {
62
62
  createRenderContext: () => createRenderContext,
63
63
  createStreamChain: () => createStreamChain,
64
64
  defaultMaxTokens: () => defaultMaxTokens,
65
+ evaluatePrompt: () => evaluatePrompt,
65
66
  tokenCountForOpenAIMessage: () => tokenCountForOpenAIMessage,
66
67
  tokenCountForOpenAIVisionMessage: () => tokenCountForOpenAIVisionMessage,
67
68
  tokenLimitForChatModel: () => tokenLimitForChatModel,
@@ -440,6 +441,17 @@ var ParseVariablesError = class extends Error {
440
441
  var PromptInvalidOutputError = class extends Error {
441
442
  };
442
443
 
444
+ // src/prompt/parseVariables.ts
445
+ function parseVariables(schema, variables) {
446
+ try {
447
+ return { success: true, result: schema.parse(variables) };
448
+ } catch (e) {
449
+ const err = e;
450
+ const errors = JSON.stringify(err.flatten());
451
+ return { success: false, errors };
452
+ }
453
+ }
454
+
443
455
  // src/utils.ts
444
456
  var import_nanoid = require("nanoid");
445
457
  var uuid = {
@@ -490,8 +502,8 @@ function createRenderContext({
490
502
  //
491
503
  // We can think of the Root span as a "symlink" to the current
492
504
  // application trace span
493
- spanId: parentSpanId || uuid.spanId(),
494
- parentSpanId: null,
505
+ spanId: uuid.spanId(),
506
+ parentSpanId,
495
507
  key: "Root",
496
508
  renderType: "root",
497
509
  parent: null
@@ -697,7 +709,11 @@ var StreamRenderContext = class _StreamRenderContext {
697
709
  }
698
710
  if (isAIElement(element)) {
699
711
  const ctxValues = attachedContextValues(element) || {};
700
- const newCtx = self.enterElement(element, ctxValues);
712
+ const newCtx = self.enterElement(
713
+ element,
714
+ ctxValues,
715
+ !!opts.skipElementSpan
716
+ );
701
717
  const logger = newCtx.logger;
702
718
  const isFragment = element.tag.name === "AIFragment";
703
719
  try {
@@ -787,15 +803,6 @@ var StreamRenderContext = class _StreamRenderContext {
787
803
  }
788
804
  }
789
805
  }
790
- parseVariables(schema, variables) {
791
- try {
792
- return { success: true, result: schema.parse(variables) };
793
- } catch (e) {
794
- const err = e;
795
- const errors = JSON.stringify(err.flatten());
796
- return { success: false, errors };
797
- }
798
- }
799
806
  renderPrompt(prompt, variables) {
800
807
  const startTime = (/* @__PURE__ */ new Date()).toISOString();
801
808
  const startTimestamp = performance.now();
@@ -805,7 +812,7 @@ var StreamRenderContext = class _StreamRenderContext {
805
812
  variables
806
813
  });
807
814
  const { schema, component: Component } = prompt;
808
- const parsedVariables = this.parseVariables(schema, variables);
815
+ const parsedVariables = parseVariables(schema, variables);
809
816
  if (!parsedVariables.success) {
810
817
  const error = new ParseVariablesError(parsedVariables.errors);
811
818
  this.logger.promptError({
@@ -841,7 +848,9 @@ var StreamRenderContext = class _StreamRenderContext {
841
848
  });
842
849
  throw error;
843
850
  };
844
- const generator = this.renderElement(/* @__PURE__ */ jsx(Component, { ...varsToUse }), {});
851
+ const generator = this.renderElement(/* @__PURE__ */ jsx(Component, { ...varsToUse }), {
852
+ skipElementSpan: true
853
+ });
845
854
  const result = new AccumulatedRenderResult(generator, {
846
855
  onDone: logComplete,
847
856
  onError: logError
@@ -858,7 +867,7 @@ var StreamRenderContext = class _StreamRenderContext {
858
867
  variables
859
868
  });
860
869
  const { schema, component: Component } = prompt;
861
- const parsedVariables = this.parseVariables(schema, variables);
870
+ const parsedVariables = parseVariables(schema, variables);
862
871
  if (!parsedVariables.success) {
863
872
  const error = new ParseVariablesError(parsedVariables.errors);
864
873
  this.logger.promptError({
@@ -872,9 +881,13 @@ var StreamRenderContext = class _StreamRenderContext {
872
881
  throw error;
873
882
  }
874
883
  try {
875
- const output = await this.render(
876
- /* @__PURE__ */ jsx(Component, { ...parsedVariables.result })
884
+ const stream = this.renderElement(
885
+ /* @__PURE__ */ jsx(Component, { ...parsedVariables.result }),
886
+ {
887
+ skipElementSpan: true
888
+ }
877
889
  );
890
+ const output = await accumResults(stream);
878
891
  const parsedOutput = prompt.parse(output);
879
892
  if (validateOutput) {
880
893
  try {
@@ -916,7 +929,7 @@ var StreamRenderContext = class _StreamRenderContext {
916
929
  variables
917
930
  });
918
931
  const { schema } = chain;
919
- const parsedVariables = this.parseVariables(schema, variables);
932
+ const parsedVariables = parseVariables(schema, variables);
920
933
  if (!parsedVariables.success) {
921
934
  const error = new ParseVariablesError(parsedVariables.errors);
922
935
  this.logger.chainError({
@@ -990,34 +1003,42 @@ var StreamRenderContext = class _StreamRenderContext {
990
1003
  return this.contextValues[context.key] ?? context.defaultValue;
991
1004
  };
992
1005
  enterChain(chain) {
1006
+ const info = this.traceInfo.renderType === "root" ? {} : {
1007
+ parentSpanId: this.traceInfo.spanId,
1008
+ parent: this.traceInfo,
1009
+ spanId: uuid.spanId()
1010
+ };
993
1011
  const newTraceInfo = {
994
1012
  ...this.traceInfo,
995
- parentSpanId: this.traceInfo.spanId,
996
- spanId: uuid.spanId(),
1013
+ ...info,
997
1014
  renderType: "chain",
998
- key: chain.key,
999
- parent: this.traceInfo
1015
+ key: chain.key
1000
1016
  };
1001
1017
  return new _StreamRenderContext(newTraceInfo, this.contextValues);
1002
1018
  }
1003
1019
  enterPrompt(prompt) {
1020
+ const info = this.traceInfo.renderType === "root" ? {} : {
1021
+ parentSpanId: this.traceInfo.spanId,
1022
+ parent: this.traceInfo,
1023
+ spanId: uuid.spanId()
1024
+ };
1004
1025
  const newTraceInfo = {
1005
1026
  ...this.traceInfo,
1006
- parentSpanId: this.traceInfo.spanId,
1007
- spanId: uuid.spanId(),
1027
+ ...info,
1008
1028
  renderType: "prompt",
1009
- key: prompt.key,
1010
- parent: this.traceInfo
1029
+ key: prompt.key
1011
1030
  };
1012
1031
  return new _StreamRenderContext(newTraceInfo, this.contextValues);
1013
1032
  }
1014
1033
  // @internal
1015
- enterElement(element, newCtx) {
1034
+ enterElement(element, newCtx, skipSpan = false) {
1035
+ const info = skipSpan ? {} : {
1036
+ renderType: "element",
1037
+ key: element.tag.name
1038
+ };
1016
1039
  const newTraceInfo = {
1017
1040
  ...this.traceInfo,
1018
- renderType: "element",
1019
- key: element.tag.name,
1020
- parent: this.traceInfo
1041
+ ...info
1021
1042
  };
1022
1043
  return new _StreamRenderContext(newTraceInfo, {
1023
1044
  ...this.contextValues,
@@ -1150,6 +1171,19 @@ function createStreamChain(chain) {
1150
1171
  };
1151
1172
  }
1152
1173
 
1174
+ // src/prompt/evaluatePrompt.ts
1175
+ async function evaluatePrompt(prompt, variables, result) {
1176
+ const parsed = parseVariables(prompt.schema, variables);
1177
+ if (!parsed.success) {
1178
+ throw new ParseVariablesError(parsed.errors);
1179
+ }
1180
+ return (await Promise.all(
1181
+ prompt.evaluators.map(
1182
+ (evaluator) => evaluator(parsed.result, result)
1183
+ )
1184
+ )).flat();
1185
+ }
1186
+
1153
1187
  // src/lib/openai/OpenAI.tsx
1154
1188
  var import_openai = require("openai");
1155
1189
 
@@ -1745,6 +1779,7 @@ var import_tokenizer4 = require("@anthropic-ai/tokenizer");
1745
1779
  createRenderContext,
1746
1780
  createStreamChain,
1747
1781
  defaultMaxTokens,
1782
+ evaluatePrompt,
1748
1783
  tokenCountForOpenAIMessage,
1749
1784
  tokenCountForOpenAIVisionMessage,
1750
1785
  tokenLimitForChatModel,
package/dist/index.mjs CHANGED
@@ -351,6 +351,17 @@ var ParseVariablesError = class extends Error {
351
351
  var PromptInvalidOutputError = class extends Error {
352
352
  };
353
353
 
354
+ // src/prompt/parseVariables.ts
355
+ function parseVariables(schema, variables) {
356
+ try {
357
+ return { success: true, result: schema.parse(variables) };
358
+ } catch (e) {
359
+ const err = e;
360
+ const errors = JSON.stringify(err.flatten());
361
+ return { success: false, errors };
362
+ }
363
+ }
364
+
354
365
  // src/utils.ts
355
366
  import { nanoid } from "nanoid";
356
367
  var uuid = {
@@ -401,8 +412,8 @@ function createRenderContext({
401
412
  //
402
413
  // We can think of the Root span as a "symlink" to the current
403
414
  // application trace span
404
- spanId: parentSpanId || uuid.spanId(),
405
- parentSpanId: null,
415
+ spanId: uuid.spanId(),
416
+ parentSpanId,
406
417
  key: "Root",
407
418
  renderType: "root",
408
419
  parent: null
@@ -601,7 +612,11 @@ var StreamRenderContext = class _StreamRenderContext {
601
612
  }
602
613
  if (isAIElement(element)) {
603
614
  const ctxValues = attachedContextValues(element) || {};
604
- const newCtx = self.enterElement(element, ctxValues);
615
+ const newCtx = self.enterElement(
616
+ element,
617
+ ctxValues,
618
+ !!opts.skipElementSpan
619
+ );
605
620
  const logger = newCtx.logger;
606
621
  const isFragment = element.tag.name === "AIFragment";
607
622
  try {
@@ -691,15 +706,6 @@ var StreamRenderContext = class _StreamRenderContext {
691
706
  }
692
707
  }
693
708
  }
694
- parseVariables(schema, variables) {
695
- try {
696
- return { success: true, result: schema.parse(variables) };
697
- } catch (e) {
698
- const err = e;
699
- const errors = JSON.stringify(err.flatten());
700
- return { success: false, errors };
701
- }
702
- }
703
709
  renderPrompt(prompt, variables) {
704
710
  const startTime = (/* @__PURE__ */ new Date()).toISOString();
705
711
  const startTimestamp = performance.now();
@@ -709,7 +715,7 @@ var StreamRenderContext = class _StreamRenderContext {
709
715
  variables
710
716
  });
711
717
  const { schema, component: Component } = prompt;
712
- const parsedVariables = this.parseVariables(schema, variables);
718
+ const parsedVariables = parseVariables(schema, variables);
713
719
  if (!parsedVariables.success) {
714
720
  const error = new ParseVariablesError(parsedVariables.errors);
715
721
  this.logger.promptError({
@@ -745,7 +751,9 @@ var StreamRenderContext = class _StreamRenderContext {
745
751
  });
746
752
  throw error;
747
753
  };
748
- const generator = this.renderElement(/* @__PURE__ */ jsx(Component, { ...varsToUse }), {});
754
+ const generator = this.renderElement(/* @__PURE__ */ jsx(Component, { ...varsToUse }), {
755
+ skipElementSpan: true
756
+ });
749
757
  const result = new AccumulatedRenderResult(generator, {
750
758
  onDone: logComplete,
751
759
  onError: logError
@@ -762,7 +770,7 @@ var StreamRenderContext = class _StreamRenderContext {
762
770
  variables
763
771
  });
764
772
  const { schema, component: Component } = prompt;
765
- const parsedVariables = this.parseVariables(schema, variables);
773
+ const parsedVariables = parseVariables(schema, variables);
766
774
  if (!parsedVariables.success) {
767
775
  const error = new ParseVariablesError(parsedVariables.errors);
768
776
  this.logger.promptError({
@@ -776,9 +784,13 @@ var StreamRenderContext = class _StreamRenderContext {
776
784
  throw error;
777
785
  }
778
786
  try {
779
- const output = await this.render(
780
- /* @__PURE__ */ jsx(Component, { ...parsedVariables.result })
787
+ const stream = this.renderElement(
788
+ /* @__PURE__ */ jsx(Component, { ...parsedVariables.result }),
789
+ {
790
+ skipElementSpan: true
791
+ }
781
792
  );
793
+ const output = await accumResults(stream);
782
794
  const parsedOutput = prompt.parse(output);
783
795
  if (validateOutput) {
784
796
  try {
@@ -820,7 +832,7 @@ var StreamRenderContext = class _StreamRenderContext {
820
832
  variables
821
833
  });
822
834
  const { schema } = chain;
823
- const parsedVariables = this.parseVariables(schema, variables);
835
+ const parsedVariables = parseVariables(schema, variables);
824
836
  if (!parsedVariables.success) {
825
837
  const error = new ParseVariablesError(parsedVariables.errors);
826
838
  this.logger.chainError({
@@ -894,34 +906,42 @@ var StreamRenderContext = class _StreamRenderContext {
894
906
  return this.contextValues[context.key] ?? context.defaultValue;
895
907
  };
896
908
  enterChain(chain) {
909
+ const info = this.traceInfo.renderType === "root" ? {} : {
910
+ parentSpanId: this.traceInfo.spanId,
911
+ parent: this.traceInfo,
912
+ spanId: uuid.spanId()
913
+ };
897
914
  const newTraceInfo = {
898
915
  ...this.traceInfo,
899
- parentSpanId: this.traceInfo.spanId,
900
- spanId: uuid.spanId(),
916
+ ...info,
901
917
  renderType: "chain",
902
- key: chain.key,
903
- parent: this.traceInfo
918
+ key: chain.key
904
919
  };
905
920
  return new _StreamRenderContext(newTraceInfo, this.contextValues);
906
921
  }
907
922
  enterPrompt(prompt) {
923
+ const info = this.traceInfo.renderType === "root" ? {} : {
924
+ parentSpanId: this.traceInfo.spanId,
925
+ parent: this.traceInfo,
926
+ spanId: uuid.spanId()
927
+ };
908
928
  const newTraceInfo = {
909
929
  ...this.traceInfo,
910
- parentSpanId: this.traceInfo.spanId,
911
- spanId: uuid.spanId(),
930
+ ...info,
912
931
  renderType: "prompt",
913
- key: prompt.key,
914
- parent: this.traceInfo
932
+ key: prompt.key
915
933
  };
916
934
  return new _StreamRenderContext(newTraceInfo, this.contextValues);
917
935
  }
918
936
  // @internal
919
- enterElement(element, newCtx) {
937
+ enterElement(element, newCtx, skipSpan = false) {
938
+ const info = skipSpan ? {} : {
939
+ renderType: "element",
940
+ key: element.tag.name
941
+ };
920
942
  const newTraceInfo = {
921
943
  ...this.traceInfo,
922
- renderType: "element",
923
- key: element.tag.name,
924
- parent: this.traceInfo
944
+ ...info
925
945
  };
926
946
  return new _StreamRenderContext(newTraceInfo, {
927
947
  ...this.contextValues,
@@ -1054,6 +1074,19 @@ function createStreamChain(chain) {
1054
1074
  };
1055
1075
  }
1056
1076
 
1077
+ // src/prompt/evaluatePrompt.ts
1078
+ async function evaluatePrompt(prompt, variables, result) {
1079
+ const parsed = parseVariables(prompt.schema, variables);
1080
+ if (!parsed.success) {
1081
+ throw new ParseVariablesError(parsed.errors);
1082
+ }
1083
+ return (await Promise.all(
1084
+ prompt.evaluators.map(
1085
+ (evaluator) => evaluator(parsed.result, result)
1086
+ )
1087
+ )).flat();
1088
+ }
1089
+
1057
1090
  // src/lib/openai/OpenAI.tsx
1058
1091
  import { OpenAI as OpenAIClient } from "openai";
1059
1092
 
@@ -1648,6 +1681,7 @@ export {
1648
1681
  createRenderContext,
1649
1682
  createStreamChain,
1650
1683
  defaultMaxTokens,
1684
+ evaluatePrompt,
1651
1685
  tokenCountForOpenAIMessage,
1652
1686
  tokenCountForOpenAIVisionMessage,
1653
1687
  tokenLimitForChatModel,
@@ -1,3 +1,3 @@
1
1
  export { Fragment, JSX, jsx, jsxDEV, jsxs } from './jsx-runtime.mjs';
2
- import './createElement-gT2wWwEd.mjs';
2
+ import './createElement-M3MXUt8O.mjs';
3
3
  import 'zod';
@@ -1,3 +1,3 @@
1
1
  export { Fragment, JSX, jsx, jsxDEV, jsxs } from './jsx-runtime.js';
2
- import './createElement-gT2wWwEd.js';
2
+ import './createElement-M3MXUt8O.js';
3
3
  import 'zod';
@@ -1,4 +1,4 @@
1
- import { A as AIComponent, O as AIElement, e as AIFragment } from './createElement-gT2wWwEd.mjs';
1
+ import { A as AIComponent, Q as AIElement, f as AIFragment } from './createElement-M3MXUt8O.mjs';
2
2
  import 'zod';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { A as AIComponent, O as AIElement, e as AIFragment } from './createElement-gT2wWwEd.js';
1
+ import { A as AIComponent, Q as AIElement, f as AIFragment } from './createElement-M3MXUt8O.js';
2
2
  import 'zod';
3
3
 
4
4
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gammatech/aijsx",
3
- "version": "0.4.0-beta.5",
3
+ "version": "0.4.0-beta.6",
4
4
  "description": "Rewrite of aijsx",
5
5
  "author": "Jordan Garcia",
6
6
  "license": "MIT",