@latitude-data/telemetry 2.0.1 → 2.0.4
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.cjs +33 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +33 -4
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../../../../src/sdk/redact.ts","../../../../src/env/env.ts","../../../../src/utils/utils.ts","../../../../../../constants/src/ai.ts","../../../../../../constants/src/config.ts","../../../../../../constants/src/evaluations/shared.ts","../../../../../../constants/src/evaluations/composite.ts","../../../../../../constants/src/evaluations/human.ts","../../../../../../constants/src/evaluations/llm.ts","../../../../../../constants/src/evaluations/rule.ts","../../../../../../constants/src/evaluations/index.ts","../../../../../../constants/src/events/events.ts","../../../../../../constants/src/experiments.ts","../../../../../../constants/src/grants.ts","../../../../../../constants/src/history.ts","../../../../../../constants/src/integrations.ts","../../../../../../constants/src/models.ts","../../../../../../constants/src/runs.ts","../../../../../../constants/src/tracing/span.ts","../../../../../../constants/src/tracing/trace.ts","../../../../../../constants/src/tracing/attributes.ts","../../../../../../constants/src/tracing/index.ts","../../../../../../constants/src/simulation.ts","../../../../../../constants/src/optimizations.ts","../../../../../../constants/src/index.ts","../../../../src/instrumentations/manual.ts","../../../../src/instrumentations/latitude.ts","../../../../../../constants/src/errors/constants.ts","../../../../../../constants/src/errors/latitudeError.ts","../../../../src/sdk/sdk.ts"],"sourcesContent":["import * as otel from '@opentelemetry/api'\nimport { ReadableSpan, SpanProcessor } from '@opentelemetry/sdk-trace-node'\n\nexport interface RedactSpanProcessorOptions {\n attributes: (string | RegExp)[]\n mask?: (attribute: string, value: any) => string\n}\n\nexport class RedactSpanProcessor implements SpanProcessor {\n private options: RedactSpanProcessorOptions\n\n constructor(options: RedactSpanProcessorOptions) {\n this.options = options\n\n if (!options.mask) {\n this.options.mask = (_attribute: string, _value: any) => '******'\n }\n }\n\n onStart(_span: ReadableSpan, _context: otel.Context): void {\n // Noop\n }\n\n onEnd(span: ReadableSpan): void {\n Object.assign(span.attributes, this.redactAttributes(span.attributes))\n for (const event of span.events) {\n if (!event.attributes) continue\n Object.assign(event.attributes, this.redactAttributes(event.attributes))\n }\n for (const link of span.links) {\n if (!link.attributes) continue\n Object.assign(link.attributes, this.redactAttributes(link.attributes))\n }\n }\n\n forceFlush(): Promise<void> {\n return Promise.resolve()\n }\n\n shutdown(): Promise<void> {\n return Promise.resolve()\n }\n\n private shouldRedact(attribute: string) {\n return this.options.attributes.some((pattern) => {\n if (typeof pattern === 'string') {\n return attribute === pattern\n } else if (pattern instanceof RegExp) {\n return pattern.test(attribute)\n }\n return false\n })\n }\n\n private redactAttributes(attributes: otel.Attributes) {\n const redacted: otel.Attributes = {}\n\n for (const [key, value] of Object.entries(attributes)) {\n if (this.shouldRedact(key)) {\n redacted[key] = this.options.mask!(key, value)\n }\n }\n\n return redacted\n }\n}\n\nexport const DEFAULT_REDACT_SPAN_PROCESSOR = () =>\n new RedactSpanProcessor({\n attributes: [\n /^.*auth.*$/i,\n /^.*authorization.*$/i,\n /^(?!gen_ai\\.).*usage.*$/i,\n /^(?!gen_ai\\.).*token.*$/i,\n /^.*secret.*$/i,\n /^.*key.*$/i,\n /^.*password.*$/i,\n /^.*cookie.*$/i,\n /^.*session.*$/i,\n /^.*credential.*$/i,\n /^.*signature.*$/i,\n /^.*oauth.*$/i,\n /^.*saml.*$/i,\n /^.*openid.*$/i,\n /^.*refresh.*$/i,\n /^.*jwt.*$/i,\n /^.*otp.*$/i,\n /^.*mfa.*$/i,\n /^.*csrf.*$/i,\n /^.*xsrf.*$/i,\n /^.*refresh.*$/i,\n /^.*x[-_]forwarded[-_]for.*$/i,\n /^.*x[-_]real[-_]ip.*$/i,\n ],\n })\n","const DEFAULT_GATEWAY_BASE_URL =\n {\n production: 'https://gateway.latitude.so',\n development: 'http://localhost:8787',\n test: 'http://localhost:8787',\n }[process.env.NODE_ENV ?? 'development'] ?? 'http://localhost:8787'\n\nfunction GET_GATEWAY_BASE_URL() {\n if (process.env.GATEWAY_BASE_URL) {\n return process.env.GATEWAY_BASE_URL\n }\n\n if (!process.env.GATEWAY_HOSTNAME) {\n return DEFAULT_GATEWAY_BASE_URL\n }\n\n const protocol = process.env.GATEWAY_SSL ? 'https' : 'http'\n const port = process.env.GATEWAY_PORT ?? (process.env.GATEWAY_SSL ? 443 : 80)\n const hostname = process.env.GATEWAY_HOSTNAME\n\n return `${protocol}://${hostname}:${port}`\n}\n\nexport const env = { GATEWAY_BASE_URL: GET_GATEWAY_BASE_URL() } as const\n","export function capitalize(str: string) {\n if (str.length === 0) return str\n return str.charAt(0).toUpperCase() + str.toLowerCase().slice(1)\n}\n\nexport function toCamelCase(str: string) {\n return str\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/[^A-Za-z0-9]+/g, ' ')\n .trim()\n .split(' ')\n .map((w, i) => (i ? capitalize(w) : w.toLowerCase()))\n .join('')\n}\n\nexport function toSnakeCase(str: string) {\n return str\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[^A-Za-z0-9]+/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_+|_+$/g, '')\n .toLowerCase()\n}\n\nexport function toKebabCase(input: string) {\n return input\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/[^A-Za-z0-9]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-+|-+$/g, '')\n .toLowerCase()\n}\n\nexport function omit<T extends object, K extends keyof T>(\n obj: T,\n keys: K[],\n): Omit<T, K> {\n const result = { ...obj }\n for (const key of keys) {\n delete result[key]\n }\n return result as Omit<T, K>\n}\n","import { Message, ToolCall } from '@latitude-data/constants/messages'\nimport { FinishReason, TextStreamPart, Tool } from 'ai'\nimport { JSONSchema7 } from 'json-schema'\nimport { z } from 'zod'\nimport {\n LegacyVercelSDKVersion4Usage as LanguageModelUsage,\n LegacyResponseMessage,\n type ReplaceTextDelta,\n} from './ai/vercelSdkV5ToV4'\nimport { ParameterType } from './config'\nimport { LatitudeEventData } from './events'\nimport { AzureConfig, LatitudePromptConfig } from './latitudePromptSchema'\nimport { Providers } from '.'\n\nexport type PromptSource = {\n commitUuid?: string\n documentUuid?: string\n evaluationUuid?: string\n}\n\nexport type AgentToolsMap = Record<string, string> // { [toolName]: agentPath }\n\nexport type ToolDefinition = JSONSchema7 & {\n description: string\n parameters: {\n type: 'object'\n properties: Record<string, JSONSchema7>\n required?: string[]\n additionalProperties: boolean\n }\n}\n\nexport type VercelProviderTool = {\n type: 'provider-defined'\n id: `${string}.${string}`\n name: string\n args: Record<string, unknown>\n inputSchema: Tool['inputSchema']\n}\n\nexport type VercelTools = Record<string, ToolDefinition | VercelProviderTool>\n\nexport type ToolDefinitionsMap = Record<string, ToolDefinition>\nexport type ToolsItem =\n | ToolDefinitionsMap // - tool_name: <tool_definition>\n | string // - latitude/* (no spaces)\n\n// Config supported by Vercel\nexport type VercelConfig = {\n provider: string\n model: string\n url?: string\n cacheControl?: boolean\n schema?: JSONSchema7\n parameters?: Record<string, { type: ParameterType }>\n tools?: VercelTools\n azure?: AzureConfig\n /**\n * DEPRECATED: Legacy before SDK v5. Use `maxOutputTokens` instead.\n */\n maxTokens?: number\n maxOutputTokens?: number\n\n /**\n * Max steps the run can take.\n */\n maxSteps?: number\n}\n\nexport type PartialPromptConfig = Omit<LatitudePromptConfig, 'provider'>\n\nexport type VercelChunk = TextStreamPart<any> // Original Vercel SDK v5 type\n\nexport type ProviderData = ReplaceTextDelta<VercelChunk>\n\nexport type ChainEventDto = ProviderData | LatitudeEventData\n\nexport type AssertedStreamType = 'text' | Record<string | symbol, unknown>\nexport type ChainCallResponseDto<S extends AssertedStreamType = 'text'> =\n S extends 'text'\n ? ChainStepTextResponse\n : S extends Record<string | symbol, unknown>\n ? ChainStepObjectResponse<S>\n : never\n\nexport type ChainEventDtoResponse =\n | Omit<ChainStepResponse<'object'>, 'providerLog'>\n | Omit<ChainStepResponse<'text'>, 'providerLog'>\n\nexport type StreamType = 'object' | 'text'\n\ntype BaseResponse = {\n text: string\n usage: LanguageModelUsage\n documentLogUuid?: string\n model: string\n provider: Providers\n cost: number\n input: Message[]\n output: LegacyResponseMessage[]\n}\n\nexport type ChainStepTextResponse = BaseResponse & {\n streamType: 'text'\n reasoning?: string | undefined\n toolCalls: ToolCall[] | null\n}\n\nexport type ChainStepObjectResponse<S extends Record<string, unknown> = any> =\n BaseResponse & {\n streamType: 'object'\n object: S\n }\n\nexport type ChainStepResponse<T extends StreamType> = T extends 'text'\n ? ChainStepTextResponse\n : T extends 'object'\n ? ChainStepObjectResponse\n : never\n\nexport enum StreamEventTypes {\n Latitude = 'latitude-event',\n Provider = 'provider-event',\n}\n\nexport type RunSyncAPIResponse<S extends AssertedStreamType = 'text'> = {\n uuid: string\n conversation: Message[]\n response: ChainCallResponseDto<S>\n source?: PromptSource\n}\n\nexport type ChatSyncAPIResponse<S extends AssertedStreamType = 'text'> =\n RunSyncAPIResponse<S>\n\nexport const toolCallResponseSchema = z.object({\n id: z.string(),\n name: z.string(),\n result: z.unknown(),\n isError: z.boolean().optional(),\n text: z.string().optional(),\n})\n\nexport type ToolCallResponse = z.infer<typeof toolCallResponseSchema>\n\nexport const FINISH_REASON_DETAILS = {\n stop: {\n name: 'Stop',\n description:\n 'Generation ended naturally, either the model thought it was done, or it emitted a user-supplied stop-sequence, before hitting any limits.',\n },\n length: {\n name: 'Length',\n description:\n 'The model hit a hard token boundary in the overall context window, so output was truncated.',\n },\n 'content-filter': {\n name: 'Content Filter',\n description:\n \"The provider's safety filters flagged part of the prospective text (hate, sexual, self-harm, violence, etc.), so generation was withheld, returning early.\",\n },\n 'tool-calls': {\n name: 'Tool Calls',\n description:\n 'Instead of generating text, the assistant asked for one or more declared tools to run; your code should handle them before asking the model to continue.',\n },\n error: {\n name: 'Error',\n description:\n 'The generation terminated because the provider encountered an error. This could be due to a variety of reasons, including timeouts, server issues, or problems with the input data.',\n },\n other: {\n name: 'Other',\n description:\n 'The generation ended without a specific reason. This could be due to a variety of reasons, including timeouts, server issues, or problems with the input data.',\n },\n unknown: {\n name: 'Unknown',\n description: `The provider returned a finish-reason not yet standardized. Check out the provider's documentation for more information.`,\n },\n} as const satisfies {\n [R in FinishReason]: {\n name: string\n description: string\n }\n}\n\nexport type ToolResultPayload = {\n value: unknown\n isError: boolean\n}\n\nexport * from './ai/vercelSdkV5ToV4'\n\nexport const EMPTY_USAGE = () => ({\n inputTokens: 0,\n outputTokens: 0,\n promptTokens: 0,\n completionTokens: 0,\n totalTokens: 0,\n reasoningTokens: 0,\n cachedInputTokens: 0,\n})\n\nexport const languageModelUsageSchema = z.object({\n inputTokens: z.number(),\n outputTokens: z.number(),\n promptTokens: z.number(),\n completionTokens: z.number(),\n totalTokens: z.number(),\n reasoningTokens: z.number(),\n cachedInputTokens: z.number(),\n})\n","export enum ParameterType {\n Text = 'text',\n Image = 'image',\n File = 'file',\n}\n\nexport const AGENT_TOOL_PREFIX = 'lat_agent'\nexport const LATITUDE_TOOL_PREFIX = 'lat_tool'\n\nexport enum LatitudeTool {\n RunCode = 'code',\n WebSearch = 'search',\n WebExtract = 'extract',\n Think = 'think',\n TODO = 'todo',\n}\n\nexport enum LatitudeToolInternalName {\n RunCode = 'lat_tool_run_code',\n WebSearch = 'lat_tool_web_search',\n WebExtract = 'lat_tool_web_extract',\n Think = 'think',\n TODO = 'todo_write',\n}\n\nexport const NOT_SIMULATABLE_LATITUDE_TOOLS = [\n LatitudeTool.Think,\n LatitudeTool.TODO,\n] as LatitudeTool[]\n\nexport const MAX_STEPS_CONFIG_NAME = 'maxSteps'\nexport const DEFAULT_MAX_STEPS = 20\nexport const ABSOLUTE_MAX_STEPS = 150\n\nconst capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1)\n\nexport type DiffValue = {\n newValue?: string\n oldValue?: string\n}\n\nexport const humanizeTool = (tool: string, suffix: boolean = true) => {\n if (tool.startsWith(AGENT_TOOL_PREFIX)) {\n const name = tool.replace(AGENT_TOOL_PREFIX, '').trim().split('_').join(' ')\n return suffix ? `${name} agent` : name\n }\n\n if (tool.startsWith(LATITUDE_TOOL_PREFIX)) {\n const name = tool\n .replace(LATITUDE_TOOL_PREFIX, '')\n .trim()\n .split('_')\n .join(' ')\n return suffix ? `${name} tool` : name\n }\n\n const name = tool.trim().split('_').map(capitalize).join(' ')\n return suffix ? `${name} tool` : name\n}\n","import { z } from 'zod'\n\nconst actualOutputConfiguration = z.object({\n messageSelection: z.enum(['last', 'all']), // Which assistant messages to select\n contentFilter: z\n .enum(['text', 'reasoning', 'image', 'file', 'tool_call'])\n .optional(),\n parsingFormat: z.enum(['string', 'json']),\n fieldAccessor: z.string().optional(), // Field accessor to get the output from if it's a key-value format\n})\nexport type ActualOutputConfiguration = z.infer<\n typeof actualOutputConfiguration\n>\n\nconst expectedOutputConfiguration = z.object({\n parsingFormat: z.enum(['string', 'json']),\n fieldAccessor: z.string().optional(), // Field accessor to get the output from if it's a key-value format\n})\nexport type ExpectedOutputConfiguration = z.infer<\n typeof expectedOutputConfiguration\n>\n\nexport const ACCESSIBLE_OUTPUT_FORMATS = ['json']\n\nexport const EVALUATION_TRIGGER_TARGETS = ['first', 'every', 'last'] as const\nexport type EvaluationTriggerTarget =\n (typeof EVALUATION_TRIGGER_TARGETS)[number]\n\nexport const DEFAULT_LAST_INTERACTION_DEBOUNCE_SECONDS = 120\nexport const LAST_INTERACTION_DEBOUNCE_MIN_SECONDS = 30\nexport const LAST_INTERACTION_DEBOUNCE_MAX_SECONDS = 60 * 60 * 24 // 1 day\n\nconst triggerConfiguration = z.object({\n target: z.enum(EVALUATION_TRIGGER_TARGETS),\n lastInteractionDebounce: z\n .number()\n .min(LAST_INTERACTION_DEBOUNCE_MIN_SECONDS)\n .max(LAST_INTERACTION_DEBOUNCE_MAX_SECONDS)\n .optional()\n .default(DEFAULT_LAST_INTERACTION_DEBOUNCE_SECONDS),\n})\nexport type TriggerConfiguration = z.infer<typeof triggerConfiguration>\n\nexport const baseEvaluationConfiguration = z.object({\n reverseScale: z.boolean(), // If true, lower is better, otherwise, higher is better\n actualOutput: actualOutputConfiguration,\n expectedOutput: expectedOutputConfiguration.optional(),\n trigger: triggerConfiguration.optional(),\n})\nexport const baseEvaluationResultMetadata = z.object({\n // configuration: Configuration snapshot is defined in every metric specification\n actualOutput: z.string(),\n expectedOutput: z.string().optional(),\n datasetLabel: z.string().optional(),\n})\nexport const baseEvaluationResultError = z.object({\n message: z.string(),\n})\n","import { z } from 'zod'\nimport { EvaluationResultSuccessValue, EvaluationType } from './index'\nimport {\n baseEvaluationConfiguration,\n baseEvaluationResultError,\n baseEvaluationResultMetadata,\n} from './shared'\n\nconst compositeEvaluationConfiguration = baseEvaluationConfiguration.extend({\n evaluationUuids: z.array(z.string()),\n minThreshold: z.number().optional(), // Threshold percentage\n maxThreshold: z.number().optional(), // Threshold percentage\n})\nconst compositeEvaluationResultMetadata = baseEvaluationResultMetadata.extend({\n results: z.record(\n z.string(), // Evaluation uuid\n z.object({\n uuid: z.string(), // Result uuid (for side effects)\n name: z.string(), // Evaluation name\n score: z.number(), // Normalized score\n reason: z.string(),\n passed: z.boolean(),\n }),\n ),\n})\nconst compositeEvaluationResultError = baseEvaluationResultError.extend({\n errors: z\n .record(\n z.string(), // Evaluation uuid\n z.object({\n uuid: z.string(), // Result uuid (for side effects)\n name: z.string(), // Evaluation name\n message: z.string(),\n }),\n )\n .optional(),\n})\n\n// AVERAGE\n\nconst compositeEvaluationAverageConfiguration =\n compositeEvaluationConfiguration.extend({})\nconst compositeEvaluationAverageResultMetadata =\n compositeEvaluationResultMetadata.extend({\n configuration: compositeEvaluationAverageConfiguration,\n })\nconst compositeEvaluationAverageResultError =\n compositeEvaluationResultError.extend({})\nexport const CompositeEvaluationAverageSpecification = {\n name: 'Average',\n description: 'Combines scores evenly. The resulting score is the average',\n configuration: compositeEvaluationAverageConfiguration,\n resultMetadata: compositeEvaluationAverageResultMetadata,\n resultError: compositeEvaluationAverageResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Composite,\n CompositeEvaluationMetric.Average\n >,\n ) => {\n let reason = ''\n\n const reasons = Object.entries(result.metadata.results).map(\n ([_, result]) => `${result.name}: ${result.reason}`,\n )\n\n reason = reasons.join('\\n\\n')\n\n return reason\n },\n requiresExpectedOutput: false,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type CompositeEvaluationAverageConfiguration = z.infer<\n typeof CompositeEvaluationAverageSpecification.configuration\n>\nexport type CompositeEvaluationAverageResultMetadata = z.infer<\n typeof CompositeEvaluationAverageSpecification.resultMetadata\n>\nexport type CompositeEvaluationAverageResultError = z.infer<\n typeof CompositeEvaluationAverageSpecification.resultError\n>\n\n// WEIGHTED\n\nconst compositeEvaluationWeightedConfiguration =\n compositeEvaluationConfiguration.extend({\n weights: z.record(\n z.string(), // Evaluation uuid\n z.number(), // Weight in percentage\n ),\n })\nconst compositeEvaluationWeightedResultMetadata =\n compositeEvaluationResultMetadata.extend({\n configuration: compositeEvaluationWeightedConfiguration,\n })\nconst compositeEvaluationWeightedResultError =\n compositeEvaluationResultError.extend({})\nexport const CompositeEvaluationWeightedSpecification = {\n name: 'Weighted',\n description:\n 'Combines scores using custom weights. The resulting score is the weighted blend',\n configuration: compositeEvaluationWeightedConfiguration,\n resultMetadata: compositeEvaluationWeightedResultMetadata,\n resultError: compositeEvaluationWeightedResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Composite,\n CompositeEvaluationMetric.Weighted\n >,\n ) => {\n let reason = ''\n\n const reasons = Object.entries(result.metadata.results).map(\n ([_, result]) => `${result.name}: ${result.reason}`,\n )\n\n reason = reasons.join('\\n\\n')\n\n return reason\n },\n requiresExpectedOutput: false,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type CompositeEvaluationWeightedConfiguration = z.infer<\n typeof CompositeEvaluationWeightedSpecification.configuration\n>\nexport type CompositeEvaluationWeightedResultMetadata = z.infer<\n typeof CompositeEvaluationWeightedSpecification.resultMetadata\n>\nexport type CompositeEvaluationWeightedResultError = z.infer<\n typeof CompositeEvaluationWeightedSpecification.resultError\n>\n\n// CUSTOM\n\nconst compositeEvaluationCustomConfiguration =\n compositeEvaluationConfiguration.extend({\n formula: z.string(),\n })\nconst compositeEvaluationCustomResultMetadata =\n compositeEvaluationResultMetadata.extend({\n configuration: compositeEvaluationCustomConfiguration,\n })\nconst compositeEvaluationCustomResultError =\n compositeEvaluationResultError.extend({})\nexport const CompositeEvaluationCustomSpecification = {\n name: 'Custom',\n description:\n 'Combines scores using a custom formula. The resulting score is the result of the expression',\n configuration: compositeEvaluationCustomConfiguration,\n resultMetadata: compositeEvaluationCustomResultMetadata,\n resultError: compositeEvaluationCustomResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Composite,\n CompositeEvaluationMetric.Custom\n >,\n ) => {\n let reason = ''\n\n const reasons = Object.entries(result.metadata.results).map(\n ([_, result]) => `${result.name}: ${result.reason}`,\n )\n\n reason = reasons.join('\\n\\n')\n\n return reason\n },\n requiresExpectedOutput: false,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type CompositeEvaluationCustomConfiguration = z.infer<\n typeof CompositeEvaluationCustomSpecification.configuration\n>\nexport type CompositeEvaluationCustomResultMetadata = z.infer<\n typeof CompositeEvaluationCustomSpecification.resultMetadata\n>\nexport type CompositeEvaluationCustomResultError = z.infer<\n typeof CompositeEvaluationCustomSpecification.resultError\n>\n\n/* ------------------------------------------------------------------------- */\n\nexport enum CompositeEvaluationMetric {\n Average = 'average',\n Weighted = 'weighted',\n Custom = 'custom',\n}\n\n// prettier-ignore\nexport type CompositeEvaluationConfiguration<M extends CompositeEvaluationMetric = CompositeEvaluationMetric> =\n M extends CompositeEvaluationMetric.Average ? CompositeEvaluationAverageConfiguration :\n M extends CompositeEvaluationMetric.Weighted ? CompositeEvaluationWeightedConfiguration :\n M extends CompositeEvaluationMetric.Custom ? CompositeEvaluationCustomConfiguration :\n never;\n\n// prettier-ignore\nexport type CompositeEvaluationResultMetadata<M extends CompositeEvaluationMetric = CompositeEvaluationMetric> = \n M extends CompositeEvaluationMetric.Average ? CompositeEvaluationAverageResultMetadata :\n M extends CompositeEvaluationMetric.Weighted ? CompositeEvaluationWeightedResultMetadata :\n M extends CompositeEvaluationMetric.Custom ? CompositeEvaluationCustomResultMetadata :\n never;\n\n// prettier-ignore\nexport type CompositeEvaluationResultError<M extends CompositeEvaluationMetric = CompositeEvaluationMetric> = \n M extends CompositeEvaluationMetric.Average ? CompositeEvaluationAverageResultError :\n M extends CompositeEvaluationMetric.Weighted ? CompositeEvaluationWeightedResultError :\n M extends CompositeEvaluationMetric.Custom ? CompositeEvaluationCustomResultError :\n never;\n\nexport const CompositeEvaluationSpecification = {\n name: 'Composite Score',\n description: 'Evaluate responses combining several evaluations at once',\n configuration: compositeEvaluationConfiguration,\n resultMetadata: compositeEvaluationResultMetadata,\n resultError: compositeEvaluationResultError,\n // prettier-ignore\n metrics: {\n [CompositeEvaluationMetric.Average]: CompositeEvaluationAverageSpecification,\n [CompositeEvaluationMetric.Weighted]: CompositeEvaluationWeightedSpecification,\n [CompositeEvaluationMetric.Custom]: CompositeEvaluationCustomSpecification,\n },\n} as const\n","import { z } from 'zod'\nimport { EvaluationResultSuccessValue, EvaluationType } from './index'\nimport {\n baseEvaluationConfiguration,\n baseEvaluationResultError,\n baseEvaluationResultMetadata,\n} from './shared'\n\nconst selectedContextSchema = z.object({\n messageIndex: z.number().int().nonnegative(),\n contentBlockIndex: z.number().int().nonnegative(),\n contentType: z.enum([\n 'text',\n 'reasoning',\n 'image',\n 'file',\n 'tool-call',\n 'tool-result',\n ]),\n textRange: z\n .object({\n start: z.number().int().nonnegative(),\n end: z.number().int().nonnegative(),\n })\n .optional(),\n selectedText: z.string().optional(),\n toolCallId: z.string().optional(),\n})\n\nexport type SelectedContext = z.infer<typeof selectedContextSchema>\n\nconst humanEvaluationConfiguration = baseEvaluationConfiguration.extend({\n enableControls: z.boolean().optional(), // UI annotation controls\n criteria: z.string().optional(),\n})\nconst humanEvaluationResultMetadata = baseEvaluationResultMetadata.extend({\n reason: z.string().optional(),\n enrichedReason: z.string().optional(),\n selectedContexts: z.array(selectedContextSchema).optional(),\n})\nconst humanEvaluationResultError = baseEvaluationResultError.extend({})\n\n// BINARY\n\nconst humanEvaluationBinaryConfiguration = humanEvaluationConfiguration.extend({\n passDescription: z.string().optional(),\n failDescription: z.string().optional(),\n})\nconst humanEvaluationBinaryResultMetadata =\n humanEvaluationResultMetadata.extend({\n configuration: humanEvaluationBinaryConfiguration,\n })\nconst humanEvaluationBinaryResultError = humanEvaluationResultError.extend({})\nexport const HumanEvaluationBinarySpecification = {\n name: 'Binary',\n description:\n 'Judges whether the response meets the criteria. The resulting score is \"passed\" or \"failed\"',\n configuration: humanEvaluationBinaryConfiguration,\n resultMetadata: humanEvaluationBinaryResultMetadata,\n resultError: humanEvaluationBinaryResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Human,\n HumanEvaluationMetric.Binary\n >,\n ) => result.metadata.reason,\n requiresExpectedOutput: false,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: false,\n supportsManualEvaluation: true,\n} as const\nexport type HumanEvaluationBinaryConfiguration = z.infer<\n typeof HumanEvaluationBinarySpecification.configuration\n>\nexport type HumanEvaluationBinaryResultMetadata = z.infer<\n typeof HumanEvaluationBinarySpecification.resultMetadata\n>\nexport type HumanEvaluationBinaryResultError = z.infer<\n typeof HumanEvaluationBinarySpecification.resultError\n>\n\n// RATING\n\nconst humanEvaluationRatingConfiguration = humanEvaluationConfiguration.extend({\n minRating: z.number(),\n minRatingDescription: z.string().optional(),\n maxRating: z.number(),\n maxRatingDescription: z.string().optional(),\n minThreshold: z.number().optional(), // Threshold in rating range\n maxThreshold: z.number().optional(), // Threshold in rating range\n})\nconst humanEvaluationRatingResultMetadata =\n humanEvaluationResultMetadata.extend({\n configuration: humanEvaluationRatingConfiguration,\n })\nconst humanEvaluationRatingResultError = humanEvaluationResultError.extend({})\nexport const HumanEvaluationRatingSpecification = {\n name: 'Rating',\n description:\n 'Judges the response by rating it under a criteria. The resulting score is the rating',\n configuration: humanEvaluationRatingConfiguration,\n resultMetadata: humanEvaluationRatingResultMetadata,\n resultError: humanEvaluationRatingResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Human,\n HumanEvaluationMetric.Rating\n >,\n ) => result.metadata.reason,\n requiresExpectedOutput: false,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: false,\n supportsManualEvaluation: true,\n} as const\nexport type HumanEvaluationRatingConfiguration = z.infer<\n typeof HumanEvaluationRatingSpecification.configuration\n>\nexport type HumanEvaluationRatingResultMetadata = z.infer<\n typeof HumanEvaluationRatingSpecification.resultMetadata\n>\nexport type HumanEvaluationRatingResultError = z.infer<\n typeof HumanEvaluationRatingSpecification.resultError\n>\n\n/* ------------------------------------------------------------------------- */\n\nexport enum HumanEvaluationMetric {\n Binary = 'binary',\n Rating = 'rating',\n}\n\n// prettier-ignore\nexport type HumanEvaluationConfiguration<M extends HumanEvaluationMetric = HumanEvaluationMetric> =\n M extends HumanEvaluationMetric.Binary ? HumanEvaluationBinaryConfiguration :\n M extends HumanEvaluationMetric.Rating ? HumanEvaluationRatingConfiguration :\n never;\n\n// prettier-ignore\nexport type HumanEvaluationResultMetadata<M extends HumanEvaluationMetric = HumanEvaluationMetric> =\n M extends HumanEvaluationMetric.Binary ? HumanEvaluationBinaryResultMetadata :\n M extends HumanEvaluationMetric.Rating ? HumanEvaluationRatingResultMetadata :\n never;\n\n// prettier-ignore\nexport type HumanEvaluationResultError<M extends HumanEvaluationMetric = HumanEvaluationMetric> =\n M extends HumanEvaluationMetric.Binary ? HumanEvaluationBinaryResultError :\n M extends HumanEvaluationMetric.Rating ? HumanEvaluationRatingResultError :\n never;\n\nexport const HumanEvaluationSpecification = {\n name: 'Human-in-the-Loop',\n description: 'Evaluate responses using a human as a judge',\n configuration: humanEvaluationConfiguration,\n resultMetadata: humanEvaluationResultMetadata,\n resultError: humanEvaluationResultError,\n // prettier-ignore\n metrics: {\n [HumanEvaluationMetric.Binary]: HumanEvaluationBinarySpecification,\n [HumanEvaluationMetric.Rating]: HumanEvaluationRatingSpecification,\n },\n} as const\n","import { z } from 'zod'\nimport { EvaluationResultSuccessValue, EvaluationType } from './index'\nimport {\n baseEvaluationConfiguration,\n baseEvaluationResultError,\n baseEvaluationResultMetadata,\n} from './shared'\n\nconst llmEvaluationConfiguration = baseEvaluationConfiguration.extend({\n provider: z.string(),\n model: z.string(),\n})\nconst llmEvaluationResultMetadata = baseEvaluationResultMetadata.extend({\n evaluationLogId: z.number(),\n reason: z.string(),\n tokens: z.number(),\n cost: z.number(),\n duration: z.number(),\n})\nconst llmEvaluationResultError = baseEvaluationResultError.extend({\n runErrorId: z.number().optional(),\n})\n\n// BINARY\n\nconst llmEvaluationBinaryConfiguration = llmEvaluationConfiguration.extend({\n criteria: z.string(),\n passDescription: z.string(),\n failDescription: z.string(),\n})\nconst llmEvaluationBinaryResultMetadata = llmEvaluationResultMetadata.extend({\n configuration: llmEvaluationBinaryConfiguration,\n})\nconst llmEvaluationBinaryResultError = llmEvaluationResultError.extend({})\nexport const LlmEvaluationBinarySpecification = {\n name: 'Binary',\n description:\n 'Judges whether the response meets the criteria. The resulting score is \"passed\" or \"failed\"',\n configuration: llmEvaluationBinaryConfiguration,\n resultMetadata: llmEvaluationBinaryResultMetadata,\n resultError: llmEvaluationBinaryResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Llm,\n LlmEvaluationMetric.Binary\n >,\n ) => {\n return result.metadata.reason\n },\n requiresExpectedOutput: false,\n supportsLiveEvaluation: true,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type LlmEvaluationBinaryConfiguration = z.infer<\n typeof LlmEvaluationBinarySpecification.configuration\n>\nexport type LlmEvaluationBinaryResultMetadata = z.infer<\n typeof LlmEvaluationBinarySpecification.resultMetadata\n>\nexport type LlmEvaluationBinaryResultError = z.infer<\n typeof LlmEvaluationBinarySpecification.resultError\n>\n\n// RATING\n\nconst llmEvaluationRatingConfiguration = llmEvaluationConfiguration.extend({\n criteria: z.string(),\n minRating: z.number(),\n minRatingDescription: z.string(),\n maxRating: z.number(),\n maxRatingDescription: z.string(),\n minThreshold: z.number().optional(), // Threshold in rating range\n maxThreshold: z.number().optional(), // Threshold in rating range\n})\nconst llmEvaluationRatingResultMetadata = llmEvaluationResultMetadata.extend({\n configuration: llmEvaluationRatingConfiguration,\n})\nconst llmEvaluationRatingResultError = llmEvaluationResultError.extend({})\nexport const LlmEvaluationRatingSpecification = {\n name: 'Rating',\n description:\n 'Judges the response by rating it under a criteria. The resulting score is the rating',\n configuration: llmEvaluationRatingConfiguration,\n resultMetadata: llmEvaluationRatingResultMetadata,\n resultError: llmEvaluationRatingResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Llm,\n LlmEvaluationMetric.Rating\n >,\n ) => {\n return result.metadata.reason\n },\n requiresExpectedOutput: false,\n supportsLiveEvaluation: true,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type LlmEvaluationRatingConfiguration = z.infer<\n typeof LlmEvaluationRatingSpecification.configuration\n>\nexport type LlmEvaluationRatingResultMetadata = z.infer<\n typeof LlmEvaluationRatingSpecification.resultMetadata\n>\nexport type LlmEvaluationRatingResultError = z.infer<\n typeof LlmEvaluationRatingSpecification.resultError\n>\n\n// COMPARISON\n\nconst llmEvaluationComparisonConfiguration = llmEvaluationConfiguration.extend({\n criteria: z.string(),\n passDescription: z.string(),\n failDescription: z.string(),\n minThreshold: z.number().optional(), // Threshold percentage\n maxThreshold: z.number().optional(), // Threshold percentage\n})\nconst llmEvaluationComparisonResultMetadata =\n llmEvaluationResultMetadata.extend({\n configuration: llmEvaluationComparisonConfiguration,\n })\nconst llmEvaluationComparisonResultError = llmEvaluationResultError.extend({})\nexport const LlmEvaluationComparisonSpecification = {\n name: 'Comparison',\n description:\n 'Judges the response by comparing the criteria to the expected output. The resulting score is the percentage of compared criteria that is met',\n configuration: llmEvaluationComparisonConfiguration,\n resultMetadata: llmEvaluationComparisonResultMetadata,\n resultError: llmEvaluationComparisonResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Llm,\n LlmEvaluationMetric.Comparison\n >,\n ) => {\n return result.metadata.reason\n },\n requiresExpectedOutput: true,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type LlmEvaluationComparisonConfiguration = z.infer<\n typeof LlmEvaluationComparisonSpecification.configuration\n>\nexport type LlmEvaluationComparisonResultMetadata = z.infer<\n typeof LlmEvaluationComparisonSpecification.resultMetadata\n>\nexport type LlmEvaluationComparisonResultError = z.infer<\n typeof LlmEvaluationComparisonSpecification.resultError\n>\n\n// CUSTOM\n\nconst llmEvaluationCustomConfiguration = llmEvaluationConfiguration.extend({\n prompt: z.string(),\n minScore: z.number(),\n maxScore: z.number(),\n minThreshold: z.number().optional(), // Threshold percentage\n maxThreshold: z.number().optional(), // Threshold percentage\n})\nconst llmEvaluationCustomResultMetadata = llmEvaluationResultMetadata.extend({\n configuration: llmEvaluationCustomConfiguration,\n})\nconst llmEvaluationCustomResultError = llmEvaluationResultError.extend({})\nexport const LlmEvaluationCustomSpecification = {\n name: 'Custom',\n description:\n 'Judges the response under a criteria using a custom prompt. The resulting score is the value of criteria that is met',\n configuration: llmEvaluationCustomConfiguration,\n resultMetadata: llmEvaluationCustomResultMetadata,\n resultError: llmEvaluationCustomResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Llm,\n LlmEvaluationMetric.Custom\n >,\n ) => {\n return result.metadata.reason\n },\n requiresExpectedOutput: false,\n supportsLiveEvaluation: true,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type LlmEvaluationCustomConfiguration = z.infer<\n typeof LlmEvaluationCustomSpecification.configuration\n>\nexport type LlmEvaluationCustomResultMetadata = z.infer<\n typeof LlmEvaluationCustomSpecification.resultMetadata\n>\nexport type LlmEvaluationCustomResultError = z.infer<\n typeof LlmEvaluationCustomSpecification.resultError\n>\n\nexport const LLM_EVALUATION_CUSTOM_PROMPT_DOCUMENTATION = `\n/*\n IMPORTANT: The evaluation MUST return an object with the score and reason fields.\n\n These are the available variables:\n - {{ actualOutput }} (string): The actual output to evaluate\n - {{ expectedOutput }} (string/undefined): The, optional, expected output to compare against\n - {{ conversation }} (string): The full conversation of the evaluated log\n\n - {{ messages }} (array of objects): All the messages of the conversation\n - {{ toolCalls }} (array of objects): All the tool calls of the conversation\n - {{ cost }} (number): The cost, in cents, of the evaluated log\n - {{ tokens }} (number): The tokens of the evaluated log\n - {{ duration }} (number): The duration, in seconds, of the evaluated log\n\n More info on messages and tool calls format in: https://docs.latitude.so/promptl/syntax/messages\n\n - {{ prompt }} (string): The prompt of the evaluated log\n - {{ config }} (object): The configuration of the evaluated log\n - {{ parameters }} (object): The parameters of the evaluated log\n\n More info on configuration and parameters format in: https://docs.latitude.so/promptl/syntax/configuration\n*/\n`.trim()\n\n// CUSTOM LABELED\n\nexport const LlmEvaluationCustomLabeledSpecification = {\n ...LlmEvaluationCustomSpecification,\n name: 'Custom (Labeled)',\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Llm,\n LlmEvaluationMetric.CustomLabeled\n >,\n ) => {\n return result.metadata.reason\n },\n requiresExpectedOutput: true,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\n\n/* ------------------------------------------------------------------------- */\n\nexport enum LlmEvaluationMetric {\n Binary = 'binary',\n Rating = 'rating',\n Comparison = 'comparison',\n Custom = 'custom',\n CustomLabeled = 'custom_labeled',\n}\n\nexport type LlmEvaluationMetricAnyCustom =\n | LlmEvaluationMetric.Custom\n | LlmEvaluationMetric.CustomLabeled\n\n// prettier-ignore\nexport type LlmEvaluationConfiguration<M extends LlmEvaluationMetric = LlmEvaluationMetric> =\n M extends LlmEvaluationMetric.Binary ? LlmEvaluationBinaryConfiguration :\n M extends LlmEvaluationMetric.Rating ? LlmEvaluationRatingConfiguration :\n M extends LlmEvaluationMetric.Comparison ? LlmEvaluationComparisonConfiguration :\n M extends LlmEvaluationMetric.Custom ? LlmEvaluationCustomConfiguration :\n M extends LlmEvaluationMetric.CustomLabeled ? LlmEvaluationCustomConfiguration :\n never;\n\n// prettier-ignore\nexport type LlmEvaluationResultMetadata<M extends LlmEvaluationMetric = LlmEvaluationMetric> =\n M extends LlmEvaluationMetric.Binary ? LlmEvaluationBinaryResultMetadata :\n M extends LlmEvaluationMetric.Rating ? LlmEvaluationRatingResultMetadata :\n M extends LlmEvaluationMetric.Comparison ? LlmEvaluationComparisonResultMetadata :\n M extends LlmEvaluationMetric.Custom ? LlmEvaluationCustomResultMetadata :\n M extends LlmEvaluationMetric.CustomLabeled ? LlmEvaluationCustomResultMetadata :\n never;\n\n// prettier-ignore\nexport type LlmEvaluationResultError<M extends LlmEvaluationMetric = LlmEvaluationMetric> =\n M extends LlmEvaluationMetric.Binary ? LlmEvaluationBinaryResultError :\n M extends LlmEvaluationMetric.Rating ? LlmEvaluationRatingResultError :\n M extends LlmEvaluationMetric.Comparison ? LlmEvaluationComparisonResultError :\n M extends LlmEvaluationMetric.Custom ? LlmEvaluationCustomResultError :\n M extends LlmEvaluationMetric.CustomLabeled ? LlmEvaluationCustomResultError :\n never;\n\nexport const LlmEvaluationSpecification = {\n name: 'LLM-as-a-Judge',\n description: 'Evaluate responses using an LLM as a judge',\n configuration: llmEvaluationConfiguration,\n resultMetadata: llmEvaluationResultMetadata,\n resultError: llmEvaluationResultError,\n // prettier-ignore\n metrics: {\n [LlmEvaluationMetric.Binary]: LlmEvaluationBinarySpecification,\n [LlmEvaluationMetric.Rating]: LlmEvaluationRatingSpecification,\n [LlmEvaluationMetric.Comparison]: LlmEvaluationComparisonSpecification,\n [LlmEvaluationMetric.Custom]: LlmEvaluationCustomSpecification,\n [LlmEvaluationMetric.CustomLabeled]: LlmEvaluationCustomLabeledSpecification,\n },\n} as const\n\nexport const LLM_EVALUATION_PROMPT_PARAMETERS = [\n 'actualOutput',\n 'expectedOutput',\n 'conversation',\n 'cost',\n 'tokens',\n 'duration',\n 'config',\n 'toolCalls',\n 'messages',\n 'prompt',\n 'parameters',\n 'context',\n 'response',\n] as const\n\nexport type LlmEvaluationPromptParameter =\n (typeof LLM_EVALUATION_PROMPT_PARAMETERS)[number]\n","import { z } from 'zod'\nimport { EvaluationResultSuccessValue, EvaluationType } from './index'\nimport {\n baseEvaluationConfiguration,\n baseEvaluationResultError,\n baseEvaluationResultMetadata,\n} from './shared'\n\nconst ruleEvaluationConfiguration = baseEvaluationConfiguration.extend({})\nconst ruleEvaluationResultMetadata = baseEvaluationResultMetadata.extend({\n reason: z.string().optional(),\n})\nconst ruleEvaluationResultError = baseEvaluationResultError.extend({})\n\n// EXACT MATCH\n\nconst ruleEvaluationExactMatchConfiguration =\n ruleEvaluationConfiguration.extend({\n caseInsensitive: z.boolean(),\n })\nconst ruleEvaluationExactMatchResultMetadata =\n ruleEvaluationResultMetadata.extend({\n configuration: ruleEvaluationExactMatchConfiguration,\n })\nconst ruleEvaluationExactMatchResultError = ruleEvaluationResultError.extend({})\nexport const RuleEvaluationExactMatchSpecification = {\n name: 'Exact Match',\n description:\n 'Checks if the response is exactly the same as the expected output. The resulting score is \"matched\" or \"unmatched\"',\n configuration: ruleEvaluationExactMatchConfiguration,\n resultMetadata: ruleEvaluationExactMatchResultMetadata,\n resultError: ruleEvaluationExactMatchResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Rule,\n RuleEvaluationMetric.ExactMatch\n >,\n ) => {\n let reason = ''\n\n if (result.score === 1) {\n reason = `Response is`\n } else {\n reason = `Response is not`\n }\n\n reason += ` exactly the same as '${result.metadata.expectedOutput}'`\n\n if (result.metadata.configuration.caseInsensitive) {\n reason += ' (comparison is case-insensitive)'\n }\n\n if (result.metadata.reason) {\n reason += `, because: ${result.metadata.reason}`\n }\n\n return reason + '.'\n },\n requiresExpectedOutput: true,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type RuleEvaluationExactMatchConfiguration = z.infer<\n typeof RuleEvaluationExactMatchSpecification.configuration\n>\nexport type RuleEvaluationExactMatchResultMetadata = z.infer<\n typeof RuleEvaluationExactMatchSpecification.resultMetadata\n>\nexport type RuleEvaluationExactMatchResultError = z.infer<\n typeof RuleEvaluationExactMatchSpecification.resultError\n>\n\n// REGULAR EXPRESSION\n\nconst ruleEvaluationRegularExpressionConfiguration =\n ruleEvaluationConfiguration.extend({\n pattern: z.string(),\n })\nconst ruleEvaluationRegularExpressionResultMetadata =\n ruleEvaluationResultMetadata.extend({\n configuration: ruleEvaluationRegularExpressionConfiguration,\n })\nconst ruleEvaluationRegularExpressionResultError =\n ruleEvaluationResultError.extend({})\nexport const RuleEvaluationRegularExpressionSpecification = {\n name: 'Regular Expression',\n description:\n 'Checks if the response matches the regular expression. The resulting score is \"matched\" or \"unmatched\"',\n configuration: ruleEvaluationRegularExpressionConfiguration,\n resultMetadata: ruleEvaluationRegularExpressionResultMetadata,\n resultError: ruleEvaluationRegularExpressionResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Rule,\n RuleEvaluationMetric.RegularExpression\n >,\n ) => {\n let reason = ''\n\n if (result.score === 1) {\n reason = `Response matches`\n } else {\n reason = `Response does not match`\n }\n\n reason += ` the regular expression \\`/${result.metadata.configuration.pattern}/gm\\``\n\n if (result.metadata.reason) {\n reason += `, because: ${result.metadata.reason}`\n }\n\n return reason + '.'\n },\n requiresExpectedOutput: false,\n supportsLiveEvaluation: true,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type RuleEvaluationRegularExpressionConfiguration = z.infer<\n typeof RuleEvaluationRegularExpressionSpecification.configuration\n>\nexport type RuleEvaluationRegularExpressionResultMetadata = z.infer<\n typeof RuleEvaluationRegularExpressionSpecification.resultMetadata\n>\nexport type RuleEvaluationRegularExpressionResultError = z.infer<\n typeof RuleEvaluationRegularExpressionSpecification.resultError\n>\n\n// SCHEMA VALIDATION\n\nconst ruleEvaluationSchemaValidationConfiguration =\n ruleEvaluationConfiguration.extend({\n format: z.enum(['json']),\n schema: z.string(),\n })\nconst ruleEvaluationSchemaValidationResultMetadata =\n ruleEvaluationResultMetadata.extend({\n configuration: ruleEvaluationSchemaValidationConfiguration,\n })\nconst ruleEvaluationSchemaValidationResultError =\n ruleEvaluationResultError.extend({})\nexport const RuleEvaluationSchemaValidationSpecification = {\n name: 'Schema Validation',\n description:\n 'Checks if the response follows the schema. The resulting score is \"valid\" or \"invalid\"',\n configuration: ruleEvaluationSchemaValidationConfiguration,\n resultMetadata: ruleEvaluationSchemaValidationResultMetadata,\n resultError: ruleEvaluationSchemaValidationResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Rule,\n RuleEvaluationMetric.SchemaValidation\n >,\n ) => {\n let reason = ''\n\n if (result.score === 1) {\n reason = `Response follows`\n } else {\n reason = `Response does not follow`\n }\n\n reason += ` the ${result.metadata.configuration.format.toUpperCase()} schema:\\n\\`\\`\\`\\n${result.metadata.configuration.schema}\\n\\`\\`\\``\n\n if (result.metadata.reason) {\n reason += `\\nbecause: ${result.metadata.reason}`\n }\n\n return reason + '.'\n },\n requiresExpectedOutput: false,\n supportsLiveEvaluation: true,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type RuleEvaluationSchemaValidationConfiguration = z.infer<\n typeof RuleEvaluationSchemaValidationSpecification.configuration\n>\nexport type RuleEvaluationSchemaValidationResultMetadata = z.infer<\n typeof RuleEvaluationSchemaValidationSpecification.resultMetadata\n>\nexport type RuleEvaluationSchemaValidationResultError = z.infer<\n typeof RuleEvaluationSchemaValidationSpecification.resultError\n>\n\n// LENGTH COUNT\n\nconst ruleEvaluationLengthCountConfiguration =\n ruleEvaluationConfiguration.extend({\n algorithm: z.enum(['character', 'word', 'sentence']),\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n })\nconst ruleEvaluationLengthCountResultMetadata =\n ruleEvaluationResultMetadata.extend({\n configuration: ruleEvaluationLengthCountConfiguration,\n })\nconst ruleEvaluationLengthCountResultError = ruleEvaluationResultError.extend(\n {},\n)\nexport const RuleEvaluationLengthCountSpecification = {\n name: 'Length Count',\n description:\n 'Checks if the response is of a certain length. The resulting score is the length of the response',\n configuration: ruleEvaluationLengthCountConfiguration,\n resultMetadata: ruleEvaluationLengthCountResultMetadata,\n resultError: ruleEvaluationLengthCountResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Rule,\n RuleEvaluationMetric.LengthCount\n >,\n ) => {\n let reason = `Response length is ${result.score} ${result.metadata.configuration.algorithm}s`\n\n if (result.hasPassed) {\n reason += ', which is'\n } else {\n reason += ', which is not'\n }\n\n reason += ` between ${result.metadata.configuration.minLength ?? 0} and ${result.metadata.configuration.maxLength ?? Infinity} ${result.metadata.configuration.algorithm}s`\n\n if (result.metadata.configuration.reverseScale) {\n reason += ' (shorter is better)'\n } else {\n reason += ' (longer is better)'\n }\n\n if (result.metadata.reason) {\n reason += `, because: ${result.metadata.reason}`\n }\n\n return reason + '.'\n },\n requiresExpectedOutput: false,\n supportsLiveEvaluation: true,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type RuleEvaluationLengthCountConfiguration = z.infer<\n typeof RuleEvaluationLengthCountSpecification.configuration\n>\nexport type RuleEvaluationLengthCountResultMetadata = z.infer<\n typeof RuleEvaluationLengthCountSpecification.resultMetadata\n>\nexport type RuleEvaluationLengthCountResultError = z.infer<\n typeof RuleEvaluationLengthCountSpecification.resultError\n>\n\n// LEXICAL OVERLAP\n\nconst ruleEvaluationLexicalOverlapConfiguration =\n ruleEvaluationConfiguration.extend({\n algorithm: z.enum(['substring', 'levenshtein_distance', 'rouge']),\n minOverlap: z.number().optional(), // Percentage of overlap\n maxOverlap: z.number().optional(), // Percentage of overlap\n })\nconst ruleEvaluationLexicalOverlapResultMetadata =\n ruleEvaluationResultMetadata.extend({\n configuration: ruleEvaluationLexicalOverlapConfiguration,\n })\nconst ruleEvaluationLexicalOverlapResultError =\n ruleEvaluationResultError.extend({})\nexport const RuleEvaluationLexicalOverlapSpecification = {\n name: 'Lexical Overlap',\n description:\n 'Checks if the response contains the expected output. The resulting score is the percentage of overlap',\n configuration: ruleEvaluationLexicalOverlapConfiguration,\n resultMetadata: ruleEvaluationLexicalOverlapResultMetadata,\n resultError: ruleEvaluationLexicalOverlapResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Rule,\n RuleEvaluationMetric.LexicalOverlap\n >,\n ) => {\n let reason = `Response lexical overlap with '${result.metadata.expectedOutput}' is ${result.score.toFixed(0)}%`\n\n if (result.hasPassed) {\n reason += ', which is'\n } else {\n reason += ', which is not'\n }\n\n reason += ` between ${(result.metadata.configuration.minOverlap ?? 0).toFixed(0)}% and ${(result.metadata.configuration.maxOverlap ?? 100).toFixed(0)}%`\n\n if (result.metadata.configuration.reverseScale) {\n reason += ' (lower is better)'\n } else {\n reason += ' (higher is better)'\n }\n\n if (result.metadata.reason) {\n reason += `, because: ${result.metadata.reason}`\n }\n\n return reason + '.'\n },\n requiresExpectedOutput: true,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type RuleEvaluationLexicalOverlapConfiguration = z.infer<\n typeof RuleEvaluationLexicalOverlapSpecification.configuration\n>\nexport type RuleEvaluationLexicalOverlapResultMetadata = z.infer<\n typeof RuleEvaluationLexicalOverlapSpecification.resultMetadata\n>\nexport type RuleEvaluationLexicalOverlapResultError = z.infer<\n typeof RuleEvaluationLexicalOverlapSpecification.resultError\n>\n\n// SEMANTIC SIMILARITY\n\nconst ruleEvaluationSemanticSimilarityConfiguration =\n ruleEvaluationConfiguration.extend({\n algorithm: z.enum(['cosine_distance']),\n minSimilarity: z.number().optional(), // Percentage of similarity\n maxSimilarity: z.number().optional(), // Percentage of similarity\n })\nconst ruleEvaluationSemanticSimilarityResultMetadata =\n ruleEvaluationResultMetadata.extend({\n configuration: ruleEvaluationSemanticSimilarityConfiguration,\n })\nconst ruleEvaluationSemanticSimilarityResultError =\n ruleEvaluationResultError.extend({})\nexport const RuleEvaluationSemanticSimilaritySpecification = {\n name: 'Semantic Similarity',\n description:\n 'Checks if the response is semantically similar to the expected output. The resulting score is the percentage of similarity',\n configuration: ruleEvaluationSemanticSimilarityConfiguration,\n resultMetadata: ruleEvaluationSemanticSimilarityResultMetadata,\n resultError: ruleEvaluationSemanticSimilarityResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Rule,\n RuleEvaluationMetric.SemanticSimilarity\n >,\n ) => {\n let reason = `Response semantic similarity with '${result.metadata.expectedOutput}' is ${result.score.toFixed(0)}%`\n\n if (result.hasPassed) {\n reason += ', which is'\n } else {\n reason += ', which is not'\n }\n\n reason += ` between ${(result.metadata.configuration.minSimilarity ?? 0).toFixed(0)}% and ${(result.metadata.configuration.maxSimilarity ?? 100).toFixed(0)}%`\n\n if (result.metadata.configuration.reverseScale) {\n reason += ' (lower is better)'\n } else {\n reason += ' (higher is better)'\n }\n\n if (result.metadata.reason) {\n reason += `, because: ${result.metadata.reason}`\n }\n\n return reason + '.'\n },\n requiresExpectedOutput: true,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type RuleEvaluationSemanticSimilarityConfiguration = z.infer<\n typeof RuleEvaluationSemanticSimilaritySpecification.configuration\n>\nexport type RuleEvaluationSemanticSimilarityResultMetadata = z.infer<\n typeof RuleEvaluationSemanticSimilaritySpecification.resultMetadata\n>\nexport type RuleEvaluationSemanticSimilarityResultError = z.infer<\n typeof RuleEvaluationSemanticSimilaritySpecification.resultError\n>\n\n// NUMERIC SIMILARITY\n\nconst ruleEvaluationNumericSimilarityConfiguration =\n ruleEvaluationConfiguration.extend({\n algorithm: z.enum(['relative_difference']),\n minSimilarity: z.number().optional(), // Percentage of similarity\n maxSimilarity: z.number().optional(), // Percentage of similarity\n })\nconst ruleEvaluationNumericSimilarityResultMetadata =\n ruleEvaluationResultMetadata.extend({\n configuration: ruleEvaluationNumericSimilarityConfiguration,\n })\nconst ruleEvaluationNumericSimilarityResultError =\n ruleEvaluationResultError.extend({})\nexport const RuleEvaluationNumericSimilaritySpecification = {\n name: 'Numeric Similarity',\n description:\n 'Checks if the response is numerically similar to the expected output. The resulting score is the percentage of similarity',\n configuration: ruleEvaluationNumericSimilarityConfiguration,\n resultMetadata: ruleEvaluationNumericSimilarityResultMetadata,\n resultError: ruleEvaluationNumericSimilarityResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Rule,\n RuleEvaluationMetric.NumericSimilarity\n >,\n ) => {\n let reason = `Response numeric similarity with '${result.metadata.expectedOutput}' is ${result.score.toFixed(0)}%`\n\n if (result.hasPassed) {\n reason += ', which is'\n } else {\n reason += ', which is not'\n }\n\n reason += ` between ${(result.metadata.configuration.minSimilarity ?? 0).toFixed(0)}% and ${(result.metadata.configuration.maxSimilarity ?? 100).toFixed(0)}%`\n\n if (result.metadata.configuration.reverseScale) {\n reason += ' (lower is better)'\n } else {\n reason += ' (higher is better)'\n }\n\n if (result.metadata.reason) {\n reason += `, because: ${result.metadata.reason}`\n }\n\n return reason + '.'\n },\n requiresExpectedOutput: true,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type RuleEvaluationNumericSimilarityConfiguration = z.infer<\n typeof RuleEvaluationNumericSimilaritySpecification.configuration\n>\nexport type RuleEvaluationNumericSimilarityResultMetadata = z.infer<\n typeof RuleEvaluationNumericSimilaritySpecification.resultMetadata\n>\nexport type RuleEvaluationNumericSimilarityResultError = z.infer<\n typeof RuleEvaluationNumericSimilaritySpecification.resultError\n>\n\n/* ------------------------------------------------------------------------- */\n\nexport enum RuleEvaluationMetric {\n ExactMatch = 'exact_match',\n RegularExpression = 'regular_expression',\n SchemaValidation = 'schema_validation',\n LengthCount = 'length_count',\n LexicalOverlap = 'lexical_overlap',\n SemanticSimilarity = 'semantic_similarity',\n NumericSimilarity = 'numeric_similarity',\n}\n\n// prettier-ignore\nexport type RuleEvaluationConfiguration<M extends RuleEvaluationMetric = RuleEvaluationMetric> = \n M extends RuleEvaluationMetric.ExactMatch ? RuleEvaluationExactMatchConfiguration :\n M extends RuleEvaluationMetric.RegularExpression ? RuleEvaluationRegularExpressionConfiguration :\n M extends RuleEvaluationMetric.SchemaValidation ? RuleEvaluationSchemaValidationConfiguration :\n M extends RuleEvaluationMetric.LengthCount ? RuleEvaluationLengthCountConfiguration :\n M extends RuleEvaluationMetric.LexicalOverlap ? RuleEvaluationLexicalOverlapConfiguration :\n M extends RuleEvaluationMetric.SemanticSimilarity ? RuleEvaluationSemanticSimilarityConfiguration :\n M extends RuleEvaluationMetric.NumericSimilarity ? RuleEvaluationNumericSimilarityConfiguration :\n never;\n\n// prettier-ignore\nexport type RuleEvaluationResultMetadata<M extends RuleEvaluationMetric = RuleEvaluationMetric> = \n M extends RuleEvaluationMetric.ExactMatch ? RuleEvaluationExactMatchResultMetadata :\n M extends RuleEvaluationMetric.RegularExpression ? RuleEvaluationRegularExpressionResultMetadata :\n M extends RuleEvaluationMetric.SchemaValidation ? RuleEvaluationSchemaValidationResultMetadata :\n M extends RuleEvaluationMetric.LengthCount ? RuleEvaluationLengthCountResultMetadata :\n M extends RuleEvaluationMetric.LexicalOverlap ? RuleEvaluationLexicalOverlapResultMetadata :\n M extends RuleEvaluationMetric.SemanticSimilarity ? RuleEvaluationSemanticSimilarityResultMetadata :\n M extends RuleEvaluationMetric.NumericSimilarity ? RuleEvaluationNumericSimilarityResultMetadata :\n never;\n\n// prettier-ignore\nexport type RuleEvaluationResultError<M extends RuleEvaluationMetric = RuleEvaluationMetric> = \n M extends RuleEvaluationMetric.ExactMatch ? RuleEvaluationExactMatchResultError :\n M extends RuleEvaluationMetric.RegularExpression ? RuleEvaluationRegularExpressionResultError :\n M extends RuleEvaluationMetric.SchemaValidation ? RuleEvaluationSchemaValidationResultError :\n M extends RuleEvaluationMetric.LengthCount ? RuleEvaluationLengthCountResultError :\n M extends RuleEvaluationMetric.LexicalOverlap ? RuleEvaluationLexicalOverlapResultError :\n M extends RuleEvaluationMetric.SemanticSimilarity ? RuleEvaluationSemanticSimilarityResultError :\n M extends RuleEvaluationMetric.NumericSimilarity ? RuleEvaluationNumericSimilarityResultError :\n never;\n\nexport const RuleEvaluationSpecification = {\n name: 'Programmatic Rule',\n description: 'Evaluate responses using a programmatic rule',\n configuration: ruleEvaluationConfiguration,\n resultMetadata: ruleEvaluationResultMetadata,\n resultError: ruleEvaluationResultError,\n // prettier-ignore\n metrics: {\n [RuleEvaluationMetric.ExactMatch]: RuleEvaluationExactMatchSpecification,\n [RuleEvaluationMetric.RegularExpression]: RuleEvaluationRegularExpressionSpecification,\n [RuleEvaluationMetric.SchemaValidation]: RuleEvaluationSchemaValidationSpecification,\n [RuleEvaluationMetric.LengthCount]: RuleEvaluationLengthCountSpecification,\n [RuleEvaluationMetric.LexicalOverlap]: RuleEvaluationLexicalOverlapSpecification,\n [RuleEvaluationMetric.SemanticSimilarity]: RuleEvaluationSemanticSimilaritySpecification,\n [RuleEvaluationMetric.NumericSimilarity]: RuleEvaluationNumericSimilaritySpecification,\n },\n} as const\n","import { z } from 'zod'\nimport {\n CompositeEvaluationConfiguration,\n CompositeEvaluationMetric,\n CompositeEvaluationResultError,\n CompositeEvaluationResultMetadata,\n CompositeEvaluationSpecification,\n} from './composite'\nimport {\n HumanEvaluationConfiguration,\n HumanEvaluationMetric,\n HumanEvaluationResultError,\n HumanEvaluationResultMetadata,\n HumanEvaluationSpecification,\n} from './human'\nimport {\n LlmEvaluationConfiguration,\n LlmEvaluationMetric,\n LlmEvaluationResultError,\n LlmEvaluationResultMetadata,\n LlmEvaluationSpecification,\n} from './llm'\nimport {\n RuleEvaluationConfiguration,\n RuleEvaluationMetric,\n RuleEvaluationResultError,\n RuleEvaluationResultMetadata,\n RuleEvaluationSpecification,\n} from './rule'\n\nexport * from './active'\nexport * from './composite'\nexport * from './human'\nexport * from './llm'\nexport * from './rule'\nexport * from './shared'\n\nexport enum EvaluationType {\n Rule = 'rule',\n Llm = 'llm',\n Human = 'human',\n Composite = 'composite',\n}\n\nexport const EvaluationTypeSchema = z.enum(EvaluationType)\n\n// prettier-ignore\nexport type EvaluationMetric<T extends EvaluationType = EvaluationType> =\n T extends EvaluationType.Rule ? RuleEvaluationMetric :\n T extends EvaluationType.Llm ? LlmEvaluationMetric :\n T extends EvaluationType.Human ? HumanEvaluationMetric :\n T extends EvaluationType.Composite ? CompositeEvaluationMetric :\n never;\n\nexport const EvaluationMetricSchema = z.union([\n z.enum(RuleEvaluationMetric),\n z.enum(LlmEvaluationMetric),\n z.enum(HumanEvaluationMetric),\n z.enum(CompositeEvaluationMetric),\n])\n\n// prettier-ignore\nexport type EvaluationConfiguration<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> =\n T extends EvaluationType.Rule ? RuleEvaluationConfiguration<M extends RuleEvaluationMetric ? M : never> :\n T extends EvaluationType.Llm ? LlmEvaluationConfiguration<M extends LlmEvaluationMetric ? M : never> :\n T extends EvaluationType.Human ? HumanEvaluationConfiguration<M extends HumanEvaluationMetric ? M : never> :\n T extends EvaluationType.Composite ? CompositeEvaluationConfiguration<M extends CompositeEvaluationMetric ? M : never> :\n never;\n\nexport const EvaluationConfigurationSchema = z.custom<EvaluationConfiguration>()\n\n// prettier-ignore\nexport type EvaluationResultMetadata<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> =\n T extends EvaluationType.Rule ? RuleEvaluationResultMetadata<M extends RuleEvaluationMetric ? M : never> :\n T extends EvaluationType.Llm ? LlmEvaluationResultMetadata<M extends LlmEvaluationMetric ? M : never> :\n T extends EvaluationType.Human ? HumanEvaluationResultMetadata<M extends HumanEvaluationMetric ? M : never> :\n T extends EvaluationType.Composite ? CompositeEvaluationResultMetadata<M extends CompositeEvaluationMetric ? M : never> :\n never;\n\n// prettier-ignore\nexport const EvaluationResultMetadataSchema = z.custom<EvaluationResultMetadata>()\n\n// prettier-ignore\nexport type EvaluationResultError<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> =\n T extends EvaluationType.Rule ? RuleEvaluationResultError<M extends RuleEvaluationMetric ? M : never> :\n T extends EvaluationType.Llm ? LlmEvaluationResultError<M extends LlmEvaluationMetric ? M : never> :\n T extends EvaluationType.Human ? HumanEvaluationResultError<M extends HumanEvaluationMetric ? M : never> :\n T extends EvaluationType.Composite ? CompositeEvaluationResultError<M extends CompositeEvaluationMetric ? M : never> :\n never;\n\n// prettier-ignore\nexport const EvaluationResultErrorSchema = z.custom<EvaluationResultError>()\n\ntype ZodSchema<_T = any> = z.ZodObject\n\nexport type EvaluationMetricSpecification<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> = {\n name: string\n description: string\n configuration: ZodSchema<EvaluationConfiguration<T, M>>\n resultMetadata: ZodSchema<EvaluationResultMetadata<T, M>>\n resultError: ZodSchema<EvaluationResultError<T, M>>\n resultReason: (result: EvaluationResultSuccessValue<T, M>) => string | undefined // prettier-ignore\n requiresExpectedOutput: boolean\n supportsLiveEvaluation: boolean\n supportsBatchEvaluation: boolean\n supportsManualEvaluation: boolean\n}\n\nexport type EvaluationSpecification<T extends EvaluationType = EvaluationType> =\n {\n name: string\n description: string\n configuration: ZodSchema<EvaluationConfiguration<T>>\n resultMetadata: ZodSchema<EvaluationResultMetadata<T>>\n resultError: ZodSchema<EvaluationResultError<T>>\n metrics: { [M in EvaluationMetric<T>]: EvaluationMetricSpecification<T, M> }\n }\n\nexport const EVALUATION_SPECIFICATIONS = {\n [EvaluationType.Rule]: RuleEvaluationSpecification,\n [EvaluationType.Llm]: LlmEvaluationSpecification,\n [EvaluationType.Human]: HumanEvaluationSpecification,\n [EvaluationType.Composite]: CompositeEvaluationSpecification,\n} as const satisfies {\n [T in EvaluationType]: EvaluationSpecification<T>\n}\ntype EvaluationSpecifications = typeof EVALUATION_SPECIFICATIONS\n\n// prettier-ignore\ntype EvaluationMetricSpecificationFilter<\n F extends keyof EvaluationMetricSpecification,\n T extends EvaluationType = EvaluationType\n> = { [K in EvaluationType]: {\n [M in keyof EvaluationSpecifications[K]['metrics']]:\n // @ts-expect-error F can indeed index M type\n EvaluationSpecifications[K]['metrics'][M][F] extends true ? M : never\n}[keyof EvaluationSpecifications[K]['metrics']]\n}[T] & EvaluationMetric<T>\n\nexport type LiveEvaluationMetric<T extends EvaluationType = EvaluationType> =\n EvaluationMetricSpecificationFilter<'supportsLiveEvaluation', T>\n\nexport type BatchEvaluationMetric<T extends EvaluationType = EvaluationType> =\n EvaluationMetricSpecificationFilter<'supportsBatchEvaluation', T>\n\nexport type ManualEvaluationMetric<T extends EvaluationType = EvaluationType> =\n EvaluationMetricSpecificationFilter<'supportsManualEvaluation', T>\n\nexport type AlignmentMetricMetadata = {\n // Hash used to identify the current configuration of the evaluation, used to detect if we can aggregate to the aligment metric or we have to re-calculate it\n alignmentHash: string\n confusionMatrix: {\n truePositives: number\n trueNegatives: number\n falsePositives: number\n falseNegatives: number\n }\n // Cutoff dates for incremental processing - ISO date strings\n lastProcessedPositiveSpanDate?: string\n lastProcessedNegativeSpanDate?: string\n // ISO date string indicating recalculation is in progress\n recalculatingAt?: string\n}\n\nexport type EvaluationV2<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> = {\n uuid: string\n versionId: number\n workspaceId: number\n commitId: number\n documentUuid: string\n issueId?: number | null\n name: string\n description: string\n type: T\n metric: M\n alignmentMetricMetadata?: AlignmentMetricMetadata | null\n configuration: EvaluationConfiguration<T, M>\n evaluateLiveLogs?: boolean | null\n createdAt: Date\n updatedAt: Date\n ignoredAt?: Date | null\n deletedAt?: Date | null\n}\n\nexport type EvaluationResultSuccessValue<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> = {\n score: number\n normalizedScore: number\n metadata: EvaluationResultMetadata<T, M>\n hasPassed: boolean\n error?: null\n}\n\nexport type EvaluationResultErrorValue<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> = {\n score?: null\n normalizedScore?: null\n metadata?: null\n hasPassed?: null\n error: EvaluationResultError<T, M>\n}\n\nexport type EvaluationResultValue<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> = EvaluationResultSuccessValue<T, M> | EvaluationResultErrorValue<T, M>\n\nexport type EvaluationResultV2<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> = {\n id: number\n uuid: string\n workspaceId: number\n commitId: number\n evaluationUuid: string\n type?: T | null\n metric?: M | null\n experimentId?: number | null\n datasetId?: number | null\n evaluatedRowId?: number | null\n evaluatedLogId?: number | null\n evaluatedSpanId?: string | null\n evaluatedTraceId?: string | null\n createdAt: Date\n updatedAt: Date\n} & EvaluationResultValue<T, M>\n\nexport type PublicManualEvaluationResultV2 = Pick<\n EvaluationResultV2<EvaluationType.Human, HumanEvaluationMetric>,\n | 'uuid'\n | 'score'\n | 'normalizedScore'\n | 'metadata'\n | 'hasPassed'\n | 'createdAt'\n | 'updatedAt'\n> & { versionUuid: string; error: string | null }\n\nexport type EvaluationSettings<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> = Pick<\n EvaluationV2<T, M>,\n 'name' | 'description' | 'type' | 'metric' | 'configuration'\n>\n\nexport const EvaluationSettingsSchema = z.object({\n name: z.string(),\n description: z.string(),\n type: EvaluationTypeSchema,\n metric: EvaluationMetricSchema,\n configuration: EvaluationConfigurationSchema,\n})\n\nexport type EvaluationOptions = Pick<EvaluationV2, 'evaluateLiveLogs'>\n\nexport const EvaluationOptionsSchema = z.object({\n evaluateLiveLogs: z.boolean().nullable().optional(),\n})\n\nexport const EVALUATION_SCORE_SCALE = 100\nexport const DEFAULT_DATASET_LABEL = 'output'\n","import { Config, Message, ToolCall } from '@latitude-data/constants/messages'\nimport { FinishReason } from 'ai'\nimport {\n ChainStepResponse,\n LegacyVercelSDKVersion4Usage,\n PromptSource,\n ProviderData,\n StreamEventTypes,\n StreamType,\n} from '..'\nimport { ChainError, RunErrorCodes } from '../errors'\n\nexport enum ChainEventTypes {\n ChainCompleted = 'chain-completed',\n ChainError = 'chain-error',\n ChainStarted = 'chain-started',\n IntegrationWakingUp = 'integration-waking-up',\n ProviderCompleted = 'provider-completed',\n ProviderStarted = 'provider-started',\n StepCompleted = 'step-completed',\n StepStarted = 'step-started',\n ToolCompleted = 'tool-completed',\n ToolResult = 'tool-result',\n ToolsStarted = 'tools-started',\n}\n\ninterface GenericLatitudeEventData {\n type: ChainEventTypes\n timestamp: number\n messages: Message[]\n uuid: string\n source?: PromptSource\n}\n\nexport interface LatitudeChainStartedEventData\n extends GenericLatitudeEventData {\n type: ChainEventTypes.ChainStarted\n}\n\nexport interface LatitudeStepStartedEventData extends GenericLatitudeEventData {\n type: ChainEventTypes.StepStarted\n}\n\nexport interface LatitudeProviderStartedEventData\n extends GenericLatitudeEventData {\n type: ChainEventTypes.ProviderStarted\n config: Config\n}\n\nexport interface LatitudeProviderCompletedEventData\n extends GenericLatitudeEventData {\n type: ChainEventTypes.ProviderCompleted\n // TODO: DEPRECATED, keeping it around for backwards compatibliity purposes\n // but it's not used for anything. Remove after March 2026.\n providerLogUuid: string\n tokenUsage: LegacyVercelSDKVersion4Usage\n finishReason: FinishReason\n response: ChainStepResponse<StreamType>\n}\n\nexport interface LatitudeToolsStartedEventData\n extends GenericLatitudeEventData {\n type: ChainEventTypes.ToolsStarted\n tools: ToolCall[]\n}\n\nexport interface LatitudeToolCompletedEventData\n extends GenericLatitudeEventData {\n type: ChainEventTypes.ToolCompleted\n}\n\nexport interface LatitudeStepCompletedEventData\n extends GenericLatitudeEventData {\n type: ChainEventTypes.StepCompleted\n}\n\nexport interface LatitudeChainCompletedEventData\n extends GenericLatitudeEventData {\n type: ChainEventTypes.ChainCompleted\n response: ChainStepResponse<StreamType> | undefined\n toolCalls: ToolCall[]\n tokenUsage: LegacyVercelSDKVersion4Usage\n finishReason: FinishReason\n}\n\nexport interface LatitudeChainErrorEventData extends GenericLatitudeEventData {\n type: ChainEventTypes.ChainError\n error: Error | ChainError<RunErrorCodes>\n}\n\nexport interface LatitudeIntegrationWakingUpEventData\n extends GenericLatitudeEventData {\n type: ChainEventTypes.IntegrationWakingUp\n integrationName: string\n}\n\nexport type LatitudeEventData =\n | LatitudeChainStartedEventData\n | LatitudeStepStartedEventData\n | LatitudeProviderStartedEventData\n | LatitudeProviderCompletedEventData\n | LatitudeToolsStartedEventData\n | LatitudeToolCompletedEventData\n | LatitudeStepCompletedEventData\n | LatitudeChainCompletedEventData\n | LatitudeChainErrorEventData\n | LatitudeIntegrationWakingUpEventData\n\n// Just a type helper for ChainStreamManager. Omit<LatitudeEventData, 'timestamp' | 'messages' | 'uuid'> does not work.\n// prettier-ignore\nexport type OmittedLatitudeEventData =\n | Omit<LatitudeChainStartedEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeStepStartedEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeProviderStartedEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeProviderCompletedEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeToolsStartedEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeToolCompletedEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeStepCompletedEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeChainCompletedEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeChainErrorEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeIntegrationWakingUpEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n\nexport type ChainEvent =\n | {\n event: StreamEventTypes.Latitude\n data: LatitudeEventData\n }\n | {\n event: StreamEventTypes.Provider\n data: ProviderData\n }\n","import { SimulationSettings } from './simulation'\nimport { z } from 'zod'\n\nexport const experimentVariantSchema = z.object({\n name: z.string(),\n provider: z.string(),\n model: z.string(),\n temperature: z.number(),\n})\n\nexport type ExperimentVariant = z.infer<typeof experimentVariantSchema>\n\n// Experiment ran from a dataset\nconst experimentDatasetSourceSchema = z.object({\n source: z.literal('dataset'),\n datasetId: z.number(),\n fromRow: z.number(),\n toRow: z.number(),\n datasetLabels: z.record(z.string(), z.string()),\n parametersMap: z.record(z.string(), z.number()),\n})\n\nexport type ExperimentDatasetSource = z.infer<\n typeof experimentDatasetSourceSchema\n>\n\n// Experiment ran from last logs (from commit and creation time of experiment)\nconst experimentLogsSourceSchema = z.object({\n source: z.literal('logs'),\n count: z.number(),\n})\n\nexport type ExperimentLogsSource = z.infer<typeof experimentLogsSourceSchema>\n\n// Experiment ran with manual parameters (currently only used for prompts with no parameters)\nconst experimentManualSourceSchema = z.object({\n source: z.literal('manual'),\n count: z.number(),\n parametersMap: z.record(z.string(), z.number()),\n})\n\nexport type ExperimentManualSource = z.infer<\n typeof experimentManualSourceSchema\n>\n\nexport const experimentParametersSourceSchema = z.discriminatedUnion('source', [\n experimentDatasetSourceSchema,\n experimentLogsSourceSchema,\n experimentManualSourceSchema,\n])\n\nexport type ExperimentParametersSource = z.infer<\n typeof experimentParametersSourceSchema\n>\n\nexport type ExperimentMetadata = {\n prompt: string\n promptHash: string\n count: number // Total number of to generate logs in the experiment\n parametersSource: ExperimentParametersSource\n simulationSettings?: SimulationSettings\n}\n\nexport type ExperimentScores = {\n [evaluationUuid: string]: {\n count: number\n totalScore: number\n totalNormalizedScore: number\n }\n}\n","export enum QuotaType {\n Seats = 'seats',\n Runs = 'runs',\n Credits = 'credits',\n}\n\nexport type Quota = number | 'unlimited'\n\nexport enum GrantSource {\n System = 'system',\n Subscription = 'subscription',\n Purchase = 'purchase',\n Reward = 'reward',\n Promocode = 'promocode',\n}\n\nexport type Grant = {\n id: number\n uuid: string // Idempotency key\n workspaceId: number\n referenceId: string\n source: GrantSource\n type: QuotaType\n amount: Quota\n balance: number\n expiresAt?: Date\n createdAt: Date\n updatedAt: Date\n}\n","import { DocumentTriggerStatus, DocumentTriggerType } from '.'\nimport { EvaluationType } from './evaluations'\n\nexport enum ModifiedDocumentType {\n Created = 'created',\n Updated = 'updated',\n UpdatedPath = 'updated_path',\n Deleted = 'deleted',\n}\n\nexport type ChangedDocument = {\n documentUuid: string\n path: string\n errors: number\n changeType: ModifiedDocumentType\n}\n\nexport type ChangedTrigger = {\n triggerUuid: string\n documentUuid: string\n triggerType: DocumentTriggerType\n changeType: ModifiedDocumentType\n status: DocumentTriggerStatus\n}\n\nexport type ChangedEvaluation = {\n evaluationUuid: string\n documentUuid: string\n name: string\n type: EvaluationType\n changeType: ModifiedDocumentType\n}\n\nexport type CommitChanges = {\n anyChanges: boolean\n hasIssues: boolean\n mainDocumentUuid: string | null | undefined // null if the main document was deleted, undefined if it did not change\n documents: {\n hasErrors: boolean\n all: ChangedDocument[]\n errors: ChangedDocument[]\n clean: ChangedDocument[]\n }\n triggers: {\n hasPending: boolean\n all: ChangedTrigger[]\n clean: ChangedTrigger[]\n pending: ChangedTrigger[]\n }\n evaluations: {\n all: ChangedEvaluation[]\n }\n}\n","export enum IntegrationType {\n Latitude = 'latitude',\n ExternalMCP = 'custom_mcp',\n Pipedream = 'pipedream',\n HostedMCP = 'mcp_server', // DEPRECATED: Do not use\n}\n\nexport type ActiveIntegrationType = Exclude<\n IntegrationType,\n IntegrationType.HostedMCP\n>\n\nexport enum HostedIntegrationType {\n Stripe = 'stripe',\n Slack = 'slack',\n Github = 'github',\n Notion = 'notion',\n Twitter = 'twitter',\n Airtable = 'airtable',\n Linear = 'linear',\n YoutubeCaptions = 'youtube_captions',\n Reddit = 'reddit',\n Telegram = 'telegram',\n Tinybird = 'tinybird',\n Perplexity = 'perplexity',\n\n AwsKbRetrieval = 'aws_kb_retrieval',\n BraveSearch = 'brave_search',\n EverArt = 'ever_art',\n Fetch = 'fetch',\n GitLab = 'gitlab',\n GoogleMaps = 'google_maps',\n Sentry = 'sentry',\n Puppeteer = 'puppeteer',\n Time = 'time',\n browserbase = 'browserbase',\n Neon = 'neon',\n Postgres = 'postgres',\n Supabase = 'supabase',\n Redis = 'redis',\n Jira = 'jira',\n Attio = 'attio',\n Ghost = 'ghost',\n Figma = 'figma',\n Hyperbrowser = 'hyperbrowser',\n Audiense = 'audiense',\n Apify = 'apify',\n Exa = 'exa',\n YepCode = 'yepcode',\n Monday = 'monday',\n\n AgentQL = 'agentql',\n AgentRPC = 'agentrpc',\n AstraDB = 'astra_db',\n Bankless = 'bankless',\n Bicscan = 'bicscan',\n Chargebee = 'chargebee',\n Chronulus = 'chronulus',\n CircleCI = 'circleci',\n Codacy = 'codacy',\n CodeLogic = 'codelogic',\n Convex = 'convex',\n Dart = 'dart',\n DevHubCMS = 'devhub_cms',\n Elasticsearch = 'elasticsearch',\n ESignatures = 'esignatures',\n Fewsats = 'fewsats',\n Firecrawl = 'firecrawl',\n\n Graphlit = 'graphlit',\n Heroku = 'heroku',\n IntegrationAppHubspot = 'integration_app_hubspot',\n\n LaraTranslate = 'lara_translate',\n Logfire = 'logfire',\n Langfuse = 'langfuse',\n LingoSupabase = 'lingo_supabase',\n Make = 'make',\n Meilisearch = 'meilisearch',\n Momento = 'momento',\n\n Neo4jAura = 'neo4j_aura',\n Octagon = 'octagon',\n\n Paddle = 'paddle',\n PayPal = 'paypal',\n Qdrant = 'qdrant',\n Raygun = 'raygun',\n Rember = 'rember',\n Riza = 'riza',\n Search1API = 'search1api',\n Semgrep = 'semgrep',\n\n Tavily = 'tavily',\n Unstructured = 'unstructured',\n Vectorize = 'vectorize',\n Xero = 'xero',\n Readwise = 'readwise',\n Airbnb = 'airbnb',\n Mintlify = 'mintlify',\n\n // Require all auth file :point_down:\n // Gmail = 'google_drive',\n // GoogleCalendar = 'google_drive',\n // GoogleDrive = 'google_drive',\n // GoogleWorkspace = 'google_workspace', // env vars not supported (?)\n\n // TODO: implement these\n // Wordpress = 'wordpress', // Not on OpenTools\n // Discord = 'discord', // Not on OpenTools\n // Intercom = 'intercom', // Not on OpenTools\n\n // Hubspot = 'hubspot', // Docker based\n // Loops = 'loops', // Does not exist\n}\n\ninterface IIntegrationReference {\n integrationName: string\n projectId: number\n commitId: number\n documentUuid: string\n}\n\ninterface TriggerReference extends IIntegrationReference {\n type: 'trigger'\n triggerUuid: string\n}\n\ninterface ToolReference extends IIntegrationReference {\n type: 'tool'\n}\n\nexport type IntegrationReference = TriggerReference | ToolReference\n","import { Message, ToolCall } from '@latitude-data/constants/messages'\nimport { PartialPromptConfig } from './ai'\n\nexport enum LogSources {\n API = 'api',\n AgentAsTool = 'agent_as_tool',\n Copilot = 'copilot',\n EmailTrigger = 'email_trigger',\n Evaluation = 'evaluation',\n Experiment = 'experiment',\n IntegrationTrigger = 'integration_trigger',\n Playground = 'playground',\n ScheduledTrigger = 'scheduled_trigger',\n SharedPrompt = 'shared_prompt',\n ShadowTest = 'shadow_test',\n ABTestChallenger = 'ab_test_challenger',\n User = 'user',\n Optimization = 'optimization',\n}\n\ntype Commit = {\n id: number\n uuid: string\n title: string\n description: string | null\n deletedAt: Date | null\n createdAt: Date\n updatedAt: Date\n projectId: number\n version: number | null\n userId: string\n mergedAt: Date | null\n mainDocumentUuid: string | null\n}\n\nexport type DocumentLog = {\n id: number\n uuid: string\n documentUuid: string\n commitId: number\n resolvedContent: string\n contentHash: string\n parameters: Record<string, unknown>\n customIdentifier: string | null\n duration: number | null\n source: LogSources | null\n createdAt: Date\n updatedAt: Date\n experimentId: number | null\n workspaceId: number | null\n}\n\nexport type DocumentLogWithMetadata = DocumentLog & {\n commit: Commit\n tokens: number | null\n duration: number | null\n costInMillicents: number | null\n}\n\nexport type RunErrorField = {\n code: string | null\n message: string | null\n details: string | null\n}\n\nexport type DocumentLogWithMetadataAndError = DocumentLogWithMetadata & {\n error: RunErrorField\n}\n\nexport type ProviderLog = {\n id: number\n uuid: string\n documentLogUuid: string | null\n providerId: number | null\n model: string | null\n finishReason: string | null\n config: PartialPromptConfig | null\n messages: Message[] | null\n responseObject: unknown | null\n responseText: string | null\n toolCalls: ToolCall[] | null\n tokens: number | null\n costInMillicents: number | null\n duration: number | null\n source: LogSources | null\n apiKeyId: number | null\n generatedAt: Date | null\n updatedAt: Date\n}\n\nexport type DocumentVersion = {\n id: number\n createdAt: Date\n updatedAt: Date\n deletedAt: Date | null\n documentUuid: string\n commitId: number\n path: string\n content: string\n resolvedContent: string | null\n contentHash: string | null\n datasetId: number | null\n datasetV2Id: number | null\n}\n\nexport type SimplifiedDocumentVersion = {\n documentUuid: string\n path: string\n content: string\n isDeleted: boolean\n}\n","import {\n EvaluationResultV2,\n EvaluationType,\n EvaluationV2,\n ManualEvaluationMetric,\n} from './evaluations'\nimport { LogSources } from './models'\nimport { MainSpanType, SpanWithDetails } from './tracing'\n\nexport type RunAnnotation<\n T extends EvaluationType = EvaluationType,\n M extends ManualEvaluationMetric<T> = ManualEvaluationMetric<T>,\n> = {\n result: EvaluationResultV2<T, M>\n evaluation: EvaluationV2<T, M>\n}\n\nexport type Run = {\n uuid: string\n queuedAt: Date\n startedAt?: Date\n endedAt?: Date\n caption?: string\n annotations?: RunAnnotation[]\n source?: LogSources\n span?: SpanWithDetails<MainSpanType>\n}\n\nexport type ActiveRun = Pick<\n Run,\n 'uuid' | 'queuedAt' | 'startedAt' | 'caption' | 'source'\n> & {\n documentUuid: string\n commitUuid: string\n}\nexport type CompletedRun = Required<Run>\n\nexport const RUN_CAPTION_SIZE = 150\n\nexport const ACTIVE_RUNS_BY_DOCUMENT_CACHE_KEY = (\n workspaceId: number,\n projectId: number,\n documentUuid: string,\n) => `runs:active:${workspaceId}:${projectId}:${documentUuid}`\nexport const ACTIVE_RUN_CACHE_TTL = 1 * 3 * 60 * 60 * 1000 // 3 hours\nexport const ACTIVE_RUN_CACHE_TTL_SECONDS = Math.floor(\n ACTIVE_RUN_CACHE_TTL / 1000,\n)\n\nexport const ACTIVE_RUN_STREAM_KEY = (runUuid: string) =>\n `run:active:${runUuid}:stream`\nexport const ACTIVE_RUN_STREAM_CAP = 100_000\n\nexport enum RunSourceGroup {\n Production = 'production',\n Playground = 'playground',\n}\n\nexport const RUN_SOURCES: Record<RunSourceGroup, LogSources[]> = {\n [RunSourceGroup.Production]: [\n LogSources.API,\n LogSources.ShadowTest,\n LogSources.ABTestChallenger,\n LogSources.EmailTrigger,\n LogSources.IntegrationTrigger,\n LogSources.ScheduledTrigger,\n LogSources.SharedPrompt,\n LogSources.User,\n ],\n [RunSourceGroup.Playground]: [LogSources.Playground, LogSources.Experiment],\n} as const\n","import { FinishReason } from 'ai'\nimport { LogSources } from '../models'\nimport { AssembledSpan } from './trace'\nimport { Message } from '../messages'\n\nexport enum SpanKind {\n Internal = 'internal',\n Server = 'server',\n Client = 'client',\n Producer = 'producer',\n Consumer = 'consumer',\n}\n\n// Note: loosely based on OpenTelemetry GenAI semantic conventions\nexport enum SpanType {\n // Latitude wrappers\n Prompt = 'prompt', // Running a prompt\n Chat = 'chat', // Continuing a conversation (adding messages)\n External = 'external', // Wrapping external generation code\n UnresolvedExternal = 'unresolved_external', // External span that needs path & potential version resolution\n\n // Added a HTTP span to capture raw HTTP requests and responses when running from Latitude\n Http = 'http', // Note: raw HTTP requests and responses\n\n // Any known span from supported specifications will be grouped into one of these types\n Completion = 'completion',\n Tool = 'tool', // Note: asynchronous tools such as agents are conversation segments\n Embedding = 'embedding',\n\n Unknown = 'unknown', // Other spans we don't care about\n}\n\nexport type SpanSpecification<_T extends SpanType = SpanType> = {\n name: string\n description: string\n isGenAI: boolean\n isHidden: boolean\n}\n\nexport const LIVE_EVALUABLE_SPAN_TYPES = [\n SpanType.Prompt,\n SpanType.External,\n SpanType.Chat,\n]\n\nexport type EvaluableSpanType =\n | SpanType.Prompt\n | SpanType.Chat\n | SpanType.External\n\nexport const SPAN_SPECIFICATIONS = {\n [SpanType.Prompt]: {\n name: 'Prompt',\n description: 'A prompt span',\n isGenAI: false,\n isHidden: false,\n },\n [SpanType.Chat]: {\n name: 'Chat',\n description: 'A chat continuation span',\n isGenAI: false,\n isHidden: false,\n },\n [SpanType.External]: {\n name: 'External',\n description: 'An external capture span',\n isGenAI: false,\n isHidden: false,\n },\n [SpanType.UnresolvedExternal]: {\n name: 'Unresolved External',\n description: 'An external span that needs path resolution before storage',\n isGenAI: false,\n isHidden: true,\n },\n [SpanType.Completion]: {\n name: 'Completion',\n description: 'A completion call',\n isGenAI: true,\n isHidden: false,\n },\n [SpanType.Embedding]: {\n name: 'Embedding',\n description: 'An embedding call',\n isGenAI: true,\n isHidden: false,\n },\n [SpanType.Tool]: {\n name: 'Tool',\n description: 'A tool call',\n isGenAI: true,\n isHidden: false,\n },\n [SpanType.Http]: {\n name: 'HTTP',\n description: 'An HTTP request',\n isGenAI: false,\n isHidden: true,\n },\n [SpanType.Unknown]: {\n name: 'Unknown',\n description: 'An unknown span',\n isGenAI: false,\n isHidden: true,\n },\n} as const satisfies {\n [T in SpanType]: SpanSpecification<T>\n}\n\nexport enum SpanStatus {\n Unset = 'unset',\n Ok = 'ok',\n Error = 'error',\n}\n\n// Note: get span attribute keys from @opentelemetry/semantic-conventions/incubating\nexport type SpanAttribute = string | number | boolean | SpanAttribute[]\n\nexport type SpanEvent = {\n name: string\n timestamp: Date\n attributes: Record<string, SpanAttribute>\n}\n\nexport type SpanLink = {\n traceId: string\n spanId: string\n attributes: Record<string, SpanAttribute>\n}\n\nexport type BaseSpanMetadata<T extends SpanType = SpanType> = {\n traceId: string\n spanId: string\n type: T\n attributes: Record<string, SpanAttribute>\n events: SpanEvent[]\n links: SpanLink[]\n}\n\nexport type ToolSpanMetadata = BaseSpanMetadata<SpanType.Tool> & {\n name: string\n call: {\n id: string\n arguments: Record<string, unknown>\n }\n // Fields below are optional if the span had an error\n result?: {\n value: unknown\n isError: boolean\n }\n}\n\nexport type PromptSpanMetadata = BaseSpanMetadata<SpanType.Prompt> & {\n documentLogUuid: string\n experimentUuid: string\n externalId: string\n parameters: Record<string, unknown>\n projectId: number\n promptUuid: string\n source: LogSources\n template: string\n testDeploymentId?: number\n versionUuid: string\n}\n\nexport type ChatSpanMetadata = BaseSpanMetadata<SpanType.Chat> & {\n documentLogUuid: string\n previousTraceId: string\n source: LogSources\n}\n\nexport type ExternalSpanMetadata = BaseSpanMetadata<SpanType.External> & {\n promptUuid: string\n documentLogUuid: string\n source: LogSources\n versionUuid?: string\n externalId?: string\n name?: string\n}\n\nexport type UnresolvedExternalSpanMetadata =\n BaseSpanMetadata<SpanType.UnresolvedExternal> & {\n promptPath: string\n projectId: number\n versionUuid?: string\n externalId?: string\n name?: string\n }\n\nexport type CompletionSpanMetadata = BaseSpanMetadata<SpanType.Completion> & {\n provider: string\n model: string\n configuration: Record<string, unknown>\n input: Message[]\n // Fields below are optional if the span had an error\n output?: Message[]\n tokens?: {\n prompt: number\n cached: number\n reasoning: number\n completion: number\n }\n cost?: number // Enriched when ingested\n finishReason?: FinishReason\n}\n\nexport type HttpSpanMetadata = BaseSpanMetadata<SpanType.Http> & {\n request: {\n method: string\n url: string\n headers: Record<string, string>\n body: string | Record<string, unknown>\n }\n // Fields below are optional if the span had an error\n response?: {\n status: number\n headers: Record<string, string>\n body: string | Record<string, unknown>\n }\n}\n\n// prettier-ignore\nexport type SpanMetadata<T extends SpanType = SpanType> =\n T extends SpanType.Tool ? ToolSpanMetadata :\n T extends SpanType.Prompt ? PromptSpanMetadata :\n T extends SpanType.Chat ? ChatSpanMetadata :\n T extends SpanType.External ? ExternalSpanMetadata :\n T extends SpanType.UnresolvedExternal ? UnresolvedExternalSpanMetadata :\n T extends SpanType.Completion ? CompletionSpanMetadata :\n T extends SpanType.Embedding ? BaseSpanMetadata<T> :\n T extends SpanType.Http ? HttpSpanMetadata :\n T extends SpanType.Unknown ? BaseSpanMetadata<T> :\n never;\n\nexport const SPAN_METADATA_STORAGE_KEY = (\n workspaceId: number,\n traceId: string,\n spanId: string,\n) => encodeURI(`workspaces/${workspaceId}/traces/${traceId}/${spanId}`)\nexport const SPAN_METADATA_CACHE_TTL = 24 * 60 * 60 // 1 day\n\nexport type Span<T extends SpanType = SpanType> = {\n id: string\n traceId: string\n segmentId?: string\n parentId?: string // Parent span identifier\n workspaceId: number\n projectId: number\n apiKeyId: number\n name: string\n kind: SpanKind\n type: T\n status: SpanStatus\n message?: string\n duration: number\n startedAt: Date\n endedAt: Date\n createdAt: Date\n updatedAt: Date\n documentLogUuid?: string\n documentUuid?: string\n commitUuid?: string\n experimentUuid?: string\n testDeploymentId?: number\n previousTraceId?: string\n\n source?: LogSources\n\n tokensPrompt?: number\n tokensCached?: number\n tokensReasoning?: number\n tokensCompletion?: number\n\n model?: string\n cost?: number\n}\n\nexport type PromptSpan = Omit<Span<SpanType.Prompt>, 'documentLogUuid'> & {\n documentLogUuid: string\n}\n\nexport type ChatSpan = Omit<Span<SpanType.Chat>, 'documentLogUuid'> & {\n documentLogUuid: string\n}\n\nexport type ExternalSpan = Omit<Span<SpanType.External>, 'documentLogUuid'> & {\n documentLogUuid: string\n}\n\nexport type SpanWithDetails<T extends SpanType = SpanType> = Span<T> & {\n metadata?: SpanMetadata<T> // Metadata is optional if it could not be uploaded\n}\n\nexport type SerializedSpanPair = {\n id: string\n traceId: string\n createdAt: string\n}\n\nexport type MainSpanType = SpanType.External | SpanType.Prompt | SpanType.Chat\nexport const MAIN_SPAN_TYPES = new Set([\n SpanType.Prompt,\n SpanType.Chat,\n SpanType.External,\n])\n\nexport type MainSpanMetadata =\n | PromptSpanMetadata\n | ChatSpanMetadata\n | ExternalSpanMetadata\n\nexport function isMainSpan(span: Span | SpanWithDetails | AssembledSpan) {\n return MAIN_SPAN_TYPES.has(span.type)\n}\n\nexport function isCompletionSpan(\n span: Span | SpanWithDetails | AssembledSpan,\n): span is AssembledSpan<SpanType.Completion> {\n return span.type === SpanType.Completion\n}\n","import { z } from 'zod'\nimport { Span, SpanMetadata, SpanType } from './span'\n\n// Note: Traces are unmaterialized but this context is used to propagate the trace\n// See www.w3.org/TR/trace-context and w3c.github.io/baggage\nexport const traceContextSchema = z.object({\n traceparent: z.string(), // <version>-<trace-id>-<span-id>-<trace-flags>\n tracestate: z.string().optional(), // <key>=urlencoded(<value>)[,<key>=urlencoded(<value>)]*\n baggage: z.string().optional(), // <key>=urlencoded(<value>)[,<key>=urlencoded(<value>)]*\n})\nexport type TraceContext = z.infer<typeof traceContextSchema>\n\nexport type AssembledSpan<T extends SpanType = SpanType> = Span<T> & {\n conversationId?: string\n children: AssembledSpan[]\n depth: number\n startOffset: number\n endOffset: number\n metadata?: SpanMetadata<T>\n}\n\n// Note: full trace structure ready to be drawn, parts are ordered by timestamp\nexport type AssembledTrace = {\n id: string\n conversationId?: string\n children: AssembledSpan[]\n spans: number\n duration: number\n startedAt: Date\n endedAt: Date\n}\n\nexport const TRACE_CACHE_TTL = 5 * 60 // 5 minutes\n","import {\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_RESPONSE_FINISH_REASONS,\n ATTR_GEN_AI_RESPONSE_ID,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_TOOL_CALL_ID,\n ATTR_GEN_AI_TOOL_DESCRIPTION,\n ATTR_GEN_AI_TOOL_NAME,\n ATTR_GEN_AI_TOOL_TYPE,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_OPERATION_NAME_VALUE_CHAT,\n GEN_AI_OPERATION_NAME_VALUE_CREATE_AGENT,\n GEN_AI_OPERATION_NAME_VALUE_EMBEDDINGS,\n GEN_AI_OPERATION_NAME_VALUE_EXECUTE_TOOL,\n GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT,\n GEN_AI_OPERATION_NAME_VALUE_INVOKE_AGENT,\n GEN_AI_OPERATION_NAME_VALUE_TEXT_COMPLETION,\n GEN_AI_OUTPUT_TYPE_VALUE_IMAGE,\n GEN_AI_OUTPUT_TYPE_VALUE_JSON,\n GEN_AI_OUTPUT_TYPE_VALUE_SPEECH,\n GEN_AI_OUTPUT_TYPE_VALUE_TEXT,\n} from '@opentelemetry/semantic-conventions/incubating'\n\nimport {\n ATTR_ERROR_TYPE,\n ATTR_EXCEPTION_MESSAGE,\n ATTR_EXCEPTION_TYPE,\n ATTR_HTTP_REQUEST_METHOD,\n ATTR_HTTP_RESPONSE_STATUS_CODE,\n ATTR_OTEL_SCOPE_NAME,\n ATTR_OTEL_SCOPE_VERSION,\n ATTR_OTEL_STATUS_CODE,\n ATTR_OTEL_STATUS_DESCRIPTION,\n ATTR_SERVICE_NAME,\n} from '@opentelemetry/semantic-conventions'\n\nimport { SpanAttribute } from './span'\n\nexport const ATTRIBUTES = {\n // Custom attributes added and used by Latitude spans (Prompt / External / Chat)\n LATITUDE: {\n name: 'latitude.name',\n type: 'latitude.type',\n documentUuid: 'latitude.document_uuid',\n promptPath: 'latitude.prompt_path',\n commitUuid: 'latitude.commit_uuid',\n documentLogUuid: 'latitude.document_log_uuid',\n projectId: 'latitude.project_id',\n experimentUuid: 'latitude.experiment_uuid',\n source: 'latitude.source',\n externalId: 'latitude.external_id',\n testDeploymentId: 'latitude.test_deployment_id',\n previousTraceId: 'latitude.previous_trace_id',\n\n internal: 'latitude.internal',\n\n // Custom additions to the GenAI semantic conventions (deprecated)\n request: {\n _root: 'gen_ai.request',\n model: 'gen_ai.request.model',\n configuration: 'gen_ai.request.configuration',\n template: 'gen_ai.request.template',\n parameters: 'gen_ai.request.parameters',\n messages: 'gen_ai.request.messages',\n systemPrompt: 'gen_ai.request.system',\n },\n response: {\n _root: 'gen_ai.response',\n messages: 'gen_ai.response.messages',\n },\n usage: {\n promptTokens: 'gen_ai.usage.prompt_tokens',\n cachedTokens: 'gen_ai.usage.cached_tokens',\n reasoningTokens: 'gen_ai.usage.reasoning_tokens',\n completionTokens: 'gen_ai.usage.completion_tokens',\n },\n },\n\n // Official OpenTelemetry semantic conventions\n OPENTELEMETRY: {\n SERVICE: {\n name: ATTR_SERVICE_NAME,\n },\n OTEL: {\n scope: {\n name: ATTR_OTEL_SCOPE_NAME,\n version: ATTR_OTEL_SCOPE_VERSION,\n },\n status: {\n code: ATTR_OTEL_STATUS_CODE,\n description: ATTR_OTEL_STATUS_DESCRIPTION,\n },\n },\n ERROR: {\n type: ATTR_ERROR_TYPE,\n },\n EXCEPTION: {\n message: ATTR_EXCEPTION_MESSAGE,\n type: ATTR_EXCEPTION_TYPE,\n },\n HTTP: {\n request: {\n url: 'http.request.url',\n body: 'http.request.body',\n header: 'http.request.header',\n headers: 'http.request.headers',\n method: ATTR_HTTP_REQUEST_METHOD,\n },\n response: {\n body: 'http.response.body',\n header: 'http.response.header',\n headers: 'http.response.headers',\n statusCode: ATTR_HTTP_RESPONSE_STATUS_CODE,\n },\n },\n\n // GenAI semantic conventions\n // https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/\n GEN_AI: {\n conversationId: 'gen_ai.conversation.id',\n operation: ATTR_GEN_AI_OPERATION_NAME,\n provider: 'gen_ai.provider.name', // openai; gcp.gen_ai; gcp.vertex_ai\n request: {\n _root: 'gen_ai.request', // Contains prompt configuration settings (temperature, model, max_tokens, etc.)\n },\n response: {\n id: ATTR_GEN_AI_RESPONSE_ID,\n model: ATTR_GEN_AI_RESPONSE_MODEL,\n finishReasons: ATTR_GEN_AI_RESPONSE_FINISH_REASONS,\n },\n usage: {\n inputTokens: ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n outputTokens: ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n },\n systemInstructions: 'gen_ai.system.instructions', // Contains the PARTS of the \"system message\"\n tool: {\n definitions: 'gen_ai.tool.definitions',\n call: {\n id: ATTR_GEN_AI_TOOL_CALL_ID,\n arguments: 'gen_ai.tool.call.arguments',\n result: 'gen_ai.tool.call.result',\n },\n name: ATTR_GEN_AI_TOOL_NAME,\n description: ATTR_GEN_AI_TOOL_DESCRIPTION,\n type: ATTR_GEN_AI_TOOL_TYPE,\n },\n input: {\n messages: 'gen_ai.input.messages',\n },\n output: {\n messages: 'gen_ai.output.messages',\n },\n _deprecated: {\n system: ATTR_GEN_AI_SYSTEM,\n tool: {\n name: ATTR_GEN_AI_TOOL_NAME,\n type: ATTR_GEN_AI_TOOL_TYPE,\n call: {\n name: 'gen_ai.tool.call.name',\n description: 'gen_ai.tool.call.description',\n type: 'gen_ai.tool.call.type',\n },\n result: {\n value: 'gen_ai.tool.result.value',\n isError: 'gen_ai.tool.result.is_error',\n },\n },\n prompt: {\n _root: 'gen_ai.prompt',\n index: (promptIndex: number) => ({\n role: `gen_ai.prompt.${promptIndex}.role`,\n content: `gen_ai.prompt.${promptIndex}.content`, // string or object\n toolCalls: (toolCallIndex: number) => ({\n id: `gen_ai.prompt.${promptIndex}.tool_calls.${toolCallIndex}.id`,\n name: `gen_ai.prompt.${promptIndex}.tool_calls.${toolCallIndex}.name`,\n arguments: `gen_ai.prompt.${promptIndex}.tool_calls.${toolCallIndex}.arguments`,\n }),\n tool: {\n callId: `gen_ai.prompt.${promptIndex}.tool_call_id`,\n toolName: `gen_ai.prompt.${promptIndex}.tool_name`,\n toolResult: `gen_ai.prompt.${promptIndex}.tool_result`,\n isError: `gen_ai.prompt.${promptIndex}.is_error`,\n },\n }),\n },\n completion: {\n _root: 'gen_ai.completion',\n index: (completionIndex: number) => ({\n role: `gen_ai.completion.${completionIndex}.role`,\n content: `gen_ai.completion.${completionIndex}.content`, // string or object\n toolCalls: (toolCallIndex: number) => ({\n id: `gen_ai.completion.${completionIndex}.tool_calls.${toolCallIndex}.id`,\n name: `gen_ai.completion.${completionIndex}.tool_calls.${toolCallIndex}.name`,\n arguments: `gen_ai.completion.${completionIndex}.tool_calls.${toolCallIndex}.arguments`,\n }),\n tool: {\n callId: `gen_ai.completion.${completionIndex}.tool_call_id`,\n toolName: `gen_ai.completion.${completionIndex}.tool_name`,\n toolResult: `gen_ai.completion.${completionIndex}.tool_result`,\n isError: `gen_ai.completion.${completionIndex}.is_error`,\n },\n }),\n },\n usage: {\n promptTokens: 'gen_ai.usage.prompt_tokens',\n completionTokens: 'gen_ai.usage.completion_tokens',\n },\n },\n },\n },\n\n // OpenInference (Arize/Phoenix)\n // https://arize-ai.github.io/openinference/spec/semantic_conventions.html\n OPENINFERENCE: {\n span: {\n kind: 'openinference.span.kind',\n },\n tool: {\n name: 'tool.name',\n },\n toolCall: {\n id: 'tool_call.id',\n function: {\n arguments: 'tool_call.function.arguments',\n result: 'tool_call.function.result',\n },\n },\n llm: {\n provider: 'llm.provider',\n system: 'llm.system', // Represents the provider!\n model: 'llm.model_name',\n inputMessages: 'llm.input_messages',\n outputMessages: 'llm.output_messages',\n invocationParameters: 'llm.invocation_parameters',\n prompts: 'llm.prompts', // llm.prompts.{index}.{role/content/...},\n completions: 'llm.completions', // llm.completions.{index}.{role/content/...},\n tools: 'llm.tools', // llm.tools.{index}.{name/arguments/result/...},\n tokenCount: {\n prompt: 'llm.token_count.prompt',\n promptDetails: {\n cacheInput: 'llm.token_count.prompt_details.cache_input',\n cacheRead: 'llm.token_count.prompt_details.cache_read',\n cacheWrite: 'llm.token_count.prompt_details.cache_write',\n },\n completionDetails: {\n reasoning: 'llm.token_count.completion_details.reasoning',\n },\n completion: 'llm.token_count.completion',\n },\n cost: {\n prompt: 'llm.cost.prompt',\n completion: 'llm.cost.completion',\n total: 'llm.cost.total',\n },\n },\n },\n\n // OpenLLMetry (Traceloop)\n // https://github.com/traceloop/openllmetry/blob/main/packages/opentelemetry-semantic-conventions-ai/opentelemetry/semconv_ai/__init__.py\n OPENLLMETRY: {\n llm: {\n request: {\n type: 'llm.request.type',\n },\n response: {\n finishReason: 'llm.response.finish_reason',\n stopReason: 'llm.response.stop_reason',\n },\n },\n usage: {\n cacheCreationInputTokens: 'gen_ai.usage.cache_creation_input_tokens',\n cacheReadInputTokens: 'gen_ai.usage.cache_read_input_tokens',\n },\n },\n\n // Vercel AI SDK\n // https://ai-sdk.dev/docs/ai-sdk-core/telemetry#span-details\n AI_SDK: {\n operationId: 'ai.operationId',\n model: {\n id: 'ai.model.id',\n provider: 'ai.model.provider',\n },\n request: {\n headers: {\n _root: 'ai.request.headers',\n },\n },\n response: {\n id: 'ai.response.id',\n model: 'ai.response.model',\n finishReason: 'ai.response.finishReason',\n text: 'ai.response.text',\n object: 'ai.response.object',\n toolCalls: 'ai.response.toolCalls',\n },\n toolCall: {\n name: 'ai.toolCall.name',\n id: 'ai.toolCall.id',\n args: 'ai.toolCall.args',\n result: 'ai.toolCall.result',\n },\n usage: {\n completionTokens: 'ai.usage.completionTokens',\n promptTokens: 'ai.usage.promptTokens',\n },\n settings: 'ai.settings',\n prompt: {\n messages: 'ai.prompt.messages',\n },\n },\n} as const\n\nexport const VALUES = {\n LATITUDE: {},\n OPENTELEMETRY: {\n GEN_AI: {\n operation: {\n chat: GEN_AI_OPERATION_NAME_VALUE_CHAT,\n createAgent: GEN_AI_OPERATION_NAME_VALUE_CREATE_AGENT,\n embeddings: GEN_AI_OPERATION_NAME_VALUE_EMBEDDINGS,\n executeTool: GEN_AI_OPERATION_NAME_VALUE_EXECUTE_TOOL,\n generateContent: GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT,\n invokeAgent: GEN_AI_OPERATION_NAME_VALUE_INVOKE_AGENT,\n textCompletion: GEN_AI_OPERATION_NAME_VALUE_TEXT_COMPLETION,\n },\n response: {\n finishReasons: {\n stop: 'stop',\n length: 'length',\n contentFilter: 'content_filter',\n toolCalls: 'tool_calls',\n error: 'error',\n other: 'other',\n unknown: 'unknown',\n },\n },\n output: {\n type: {\n image: GEN_AI_OUTPUT_TYPE_VALUE_IMAGE,\n json: GEN_AI_OUTPUT_TYPE_VALUE_JSON,\n speech: GEN_AI_OUTPUT_TYPE_VALUE_SPEECH,\n text: GEN_AI_OUTPUT_TYPE_VALUE_TEXT,\n },\n },\n tool: {\n type: {\n function: 'function',\n },\n },\n _deprecated: {\n operation: {\n tool: 'tool',\n completion: 'completion',\n embedding: 'embedding',\n retrieval: 'retrieval',\n reranking: 'reranking',\n },\n },\n },\n },\n OPENLLMETRY: {\n llm: {\n request: {\n // https://github.com/traceloop/openllmetry/blob/0fc734017197e48e988eaf54e20feaab8761f757/packages/opentelemetry-semantic-conventions-ai/opentelemetry/semconv_ai/__init__.py#L277\n type: {\n completion: 'completion',\n chat: 'chat',\n rerank: 'rerank',\n embedding: 'embedding',\n unknown: 'unknown',\n },\n },\n },\n },\n OPENINFERENCE: {\n span: {\n kind: {\n llm: 'LLM',\n chain: 'CHAIN',\n embedding: 'EMBEDDING',\n tool: 'TOOL',\n agent: 'AGENT',\n retriever: 'RETRIEVER',\n reranker: 'RERANKER',\n },\n },\n },\n AI_SDK: {\n // https://ai-sdk.dev/docs/ai-sdk-core/telemetry#span-details\n operationId: {\n // Vercel Wrappers (all contain at least one of the \"Completion\" operations)\n generateText: 'ai.generateText',\n streamText: 'ai.streamText',\n generateObject: 'ai.generateObject',\n streamObject: 'ai.streamObject',\n\n // Completions\n generateTextDoGenerate: 'ai.generateText.doGenerate',\n streamTextDoStream: 'ai.streamText.doStream',\n generateObjectDoGenerate: 'ai.generateObject.doGenerate',\n streamObjectDoStream: 'ai.streamObject.doStream',\n\n // Embeddings\n embed: 'ai.embed',\n embedDoEmbed: 'ai.embed.doEmbed',\n embedMany: 'ai.embed.embedMany',\n embedManyDoEmbed: 'ai.embed.embedMany.doEmbed',\n\n // Tool calling\n toolCall: 'ai.toolCall',\n },\n },\n} as const\n\n/**\n * Returns the first value found in the attributes object with one of the given keys.\n * If an attribute callback is provided,\n */\nexport function extractAttribute<T = string>({\n attributes,\n keys,\n serializer = (value) => String(value) as T,\n validation,\n}: {\n attributes: Record<string, SpanAttribute>\n keys: string[]\n serializer?: (value: unknown) => T\n validation?: (value: T) => boolean\n}): T | undefined {\n for (const key of keys) {\n if (key in attributes) {\n const value = serializer(attributes[key])\n if (!validation) return value\n if (validation(value)) return value\n }\n }\n return undefined\n}\n\nexport function extractAllAttributes<T = string>({\n attributes,\n keys,\n serializer = (value) => String(value) as T,\n validation,\n}: {\n attributes: Record<string, SpanAttribute>\n keys: string[]\n serializer?: (value: unknown) => T\n validation?: (value: T) => boolean\n}): T[] {\n const results: T[] = []\n for (const key of keys) {\n if (key in attributes) {\n const value = serializer(attributes[key])\n if (validation && !validation(value)) continue\n results.push(value)\n }\n }\n\n return results\n}\n","import { z } from 'zod'\n\nexport * from './span'\nexport * from './trace'\n\n/* Note: Instrumentation scopes from all language SDKs */\n\nexport const SCOPE_LATITUDE = 'so.latitude.instrumentation'\n\nexport enum InstrumentationScope {\n Manual = 'manual',\n Latitude = 'latitude',\n OpenAI = 'openai',\n Anthropic = 'anthropic',\n AzureOpenAI = 'azure', // Only python — js uses OpenAI instrumentation\n VercelAI = 'vercelai',\n VertexAI = 'vertexai',\n AIPlatform = 'aiplatform',\n MistralAI = 'mistralai', // Only python\n Bedrock = 'bedrock',\n Sagemaker = 'sagemaker', // Only python\n TogetherAI = 'togetherai',\n Replicate = 'replicate', // Only python\n Groq = 'groq', // Only python\n Cohere = 'cohere',\n LiteLLM = 'litellm', // Only python\n Langchain = 'langchain',\n LlamaIndex = 'llamaindex',\n DSPy = 'dspy', // Only python\n Haystack = 'haystack', // Only python\n Ollama = 'ollama', // Only python\n Transformers = 'transformers', // Only python\n AlephAlpha = 'alephalpha', // Only python\n}\n\n/* Note: Schemas for span ingestion following OpenTelemetry service request specification */\n\nexport namespace Otlp {\n export const attributeValueSchema = z.object({\n stringValue: z.string().optional(),\n intValue: z.number().optional(),\n boolValue: z.boolean().optional(),\n arrayValue: z\n .object({\n values: z.array(\n z.object({\n stringValue: z.string().optional(),\n intValue: z.number().optional(),\n boolValue: z.boolean().optional(),\n }),\n ),\n })\n .optional(),\n })\n export type AttributeValue = z.infer<typeof attributeValueSchema>\n\n export const attributeSchema = z.object({\n key: z.string(),\n value: attributeValueSchema,\n })\n export type Attribute = z.infer<typeof attributeSchema>\n\n export const eventSchema = z.object({\n name: z.string(),\n timeUnixNano: z.string(),\n attributes: z.array(attributeSchema).optional(),\n })\n export type Event = z.infer<typeof eventSchema>\n\n export const linkSchema = z.object({\n traceId: z.string(),\n spanId: z.string(),\n attributes: z.array(attributeSchema).optional(),\n })\n export type Link = z.infer<typeof linkSchema>\n\n export enum StatusCode {\n Unset = 0,\n Ok = 1,\n Error = 2,\n }\n\n export const statusSchema = z.object({\n code: z.number(),\n message: z.string().optional(),\n })\n export type Status = z.infer<typeof statusSchema>\n\n export enum SpanKind {\n Internal = 0,\n Server = 1,\n Client = 2,\n Producer = 3,\n Consumer = 4,\n }\n\n export const spanSchema = z.object({\n traceId: z.string(),\n spanId: z.string(),\n parentSpanId: z.string().optional(),\n name: z.string(),\n kind: z.number(),\n startTimeUnixNano: z.string(),\n endTimeUnixNano: z.string(),\n status: statusSchema.optional(),\n events: z.array(eventSchema).optional(),\n links: z.array(linkSchema).optional(),\n attributes: z.array(attributeSchema).optional(),\n })\n export type Span = z.infer<typeof spanSchema>\n\n export const scopeSchema = z.object({\n name: z.string(),\n version: z.string().optional(),\n })\n export type Scope = z.infer<typeof scopeSchema>\n\n export const scopeSpanSchema = z.object({\n scope: scopeSchema,\n spans: z.array(spanSchema),\n })\n export type ScopeSpan = z.infer<typeof scopeSpanSchema>\n\n export const resourceSchema = z.object({\n attributes: z.array(attributeSchema),\n })\n export type Resource = z.infer<typeof resourceSchema>\n\n export const resourceSpanSchema = z.object({\n resource: resourceSchema,\n scopeSpans: z.array(scopeSpanSchema),\n })\n export type ResourceSpan = z.infer<typeof resourceSpanSchema>\n\n export const serviceRequestSchema = z.object({\n resourceSpans: z.array(resourceSpanSchema),\n })\n export type ServiceRequest = z.infer<typeof serviceRequestSchema>\n}\n\nexport type SpanIngestionData = {\n ingestionId: string\n spans: Otlp.ResourceSpan[]\n}\n\n// prettier-ignore\nexport const SPAN_INGESTION_STORAGE_KEY = (\n ingestionId: string, // Note: using single id to avoid dangling folders\n) => encodeURI(`ingest/traces/${ingestionId}`)\n\nexport type SpanProcessingData = {\n span: Otlp.Span\n scope: Otlp.Scope\n resource: Otlp.Resource\n}\n\n// prettier-ignore\nexport const SPAN_PROCESSING_STORAGE_KEY = (\n processingId: string, // Note: using single id to avoid dangling folders\n) => encodeURI(`process/traces/${processingId}`)\n\nexport const TRACING_JOBS_MAX_ATTEMPTS = 3\nexport const TRACING_JOBS_DELAY_BETWEEN_CONFLICTS = () =>\n (Math.floor(Math.random() * 10) + 1) * 1000 // 1-10 random seconds in order to serialize conflicts (best effort)\n\nexport { ATTRIBUTES, VALUES } from './attributes'\n","import { z } from 'zod'\n\nexport const MAX_SIMULATION_TURNS = 10\n\nexport const globalGoalSourceSchema = z.object({\n type: z.literal('global'),\n value: z.string(),\n})\n\nexport const columnGoalSourceSchema = z.object({\n type: z.literal('column'),\n columnIndex: z.number(),\n})\n\nexport const simulatedUserGoalSourceSchema = z.discriminatedUnion('type', [\n globalGoalSourceSchema,\n columnGoalSourceSchema,\n])\n\nexport type SimulatedUserGoalSource = z.infer<\n typeof simulatedUserGoalSourceSchema\n>\n\nexport const SimulationSettingsSchema = z.object({\n simulateToolResponses: z.boolean().optional(),\n simulatedTools: z.array(z.string()).optional(), // Empty array means all tools are simulated (if simulateToolResponses is true).\n toolSimulationInstructions: z.string().optional(), // A prompt used to guide and generate the simulation result\n maxTurns: z.number().min(1).max(MAX_SIMULATION_TURNS).optional(), // The maximum number of turns to simulate. Default is 1, and any greater value will add a new user message to the simulated conversation.\n simulatedUserGoal: z.string().optional(), // Deprecated: Use simulatedUserGoalSource instead. Kept for backward compatibility.\n simulatedUserGoalSource: simulatedUserGoalSourceSchema.optional(), // The source for the simulated user goal (global text or dataset column).\n})\n\nexport type SimulationSettings = z.infer<typeof SimulationSettingsSchema>\n","import { z } from 'zod'\nimport { SimulationSettingsSchema } from './simulation'\n\nexport enum OptimizationEngine {\n Identity = 'identity',\n Gepa = 'gepa',\n}\n\nexport const OptimizationBudgetSchema = z.object({\n time: z.number().min(0).optional(),\n tokens: z.number().min(0).optional(),\n})\nexport type OptimizationBudget = z.infer<typeof OptimizationBudgetSchema>\n\nexport const OptimizationConfigurationSchema = z.object({\n parameters: z\n .record(\n z.string(),\n z.object({\n column: z.string().optional(), // Note: corresponding column in the user-provided trainset and testset\n isPii: z.boolean().optional(),\n }),\n )\n .optional(),\n simulation: SimulationSettingsSchema.optional(),\n scope: z\n .object({\n configuration: z.boolean().optional(),\n instructions: z.boolean().optional(),\n })\n .optional(),\n budget: OptimizationBudgetSchema.optional(),\n})\nexport type OptimizationConfiguration = z.infer<\n typeof OptimizationConfigurationSchema\n>\n\nexport const OPTIMIZATION_SCORE_SCALE = 1 // Note: most algorithms use floats with a scale of [0,1]\n\nexport const OPTIMIZATION_MAX_TIME = 2 * 60 * 60 // 2 hours\nexport const OPTIMIZATION_MAX_TOKENS = 100_000_000 // 100M tokens\n\nexport const OPTIMIZATION_CANCEL_TIMEOUT = 10 * 1000 // 10 seconds\n\nexport const OPTIMIZATION_DEFAULT_ERROR = 'Optimization cancelled'\nexport const OPTIMIZATION_CANCELLED_ERROR = 'Optimization cancelled by user'\n\nexport const OPTIMIZATION_MIN_ROWS = 4\nexport const OPTIMIZATION_TARGET_ROWS = 250 // Note: algorithms need a sufficient amount of data to generalize and converge to avoid noise and bias\nexport const OPTIMIZATION_MAX_ROWS = 1000\n\nexport const OPTIMIZATION_TESTSET_SPLIT = 0.7 // 70% trainset, 30% testset\nexport const OPTIMIZATION_VALSET_SPLIT = 0.5 // 50% testset, 50% valset\n","// TODO(tracing): deprecated\nexport const HEAD_COMMIT = 'live'\n\nexport enum Providers {\n OpenAI = 'openai',\n Anthropic = 'anthropic',\n Groq = 'groq',\n Mistral = 'mistral',\n Azure = 'azure',\n Google = 'google',\n GoogleVertex = 'google_vertex',\n AnthropicVertex = 'anthropic_vertex',\n Custom = 'custom',\n XAI = 'xai',\n AmazonBedrock = 'amazon_bedrock',\n DeepSeek = 'deepseek',\n Perplexity = 'perplexity',\n}\n\nexport enum DocumentType {\n Prompt = 'prompt',\n Agent = 'agent',\n}\n\nexport enum DocumentTriggerType {\n Email = 'email',\n Scheduled = 'scheduled',\n Integration = 'integration',\n}\n\nexport enum DocumentTriggerStatus {\n Pending = 'pending',\n Deployed = 'deployed',\n Deprecated = 'deprecated',\n}\n\nexport enum DocumentTriggerParameters {\n SenderEmail = 'senderEmail',\n SenderName = 'senderName',\n Subject = 'subject',\n Body = 'body',\n Attachments = 'attachments',\n}\n\n// TODO: Remove these\nexport * from './ai'\nexport * from './config'\nexport * from './evaluations'\nexport * from './events'\nexport * from './experiments'\nexport * from './grants'\nexport * from './helpers'\nexport * from './history'\nexport * from './integrations'\nexport * from './mcp'\nexport * from './models'\nexport * from './runs'\nexport * from './tools'\nexport * from './tracing'\nexport * from './optimizations'\nexport * from './simulation'\n\n// TODO: Move to env\nexport const EMAIL_TRIGGER_DOMAIN = 'run.latitude.so' as const\nexport const OPENAI_PROVIDER_ENDPOINTS = [\n 'responses',\n 'chat_completions', // (DEPRECATED)\n] as const\n\nexport type TodoListItem = {\n content: string\n id: string\n status: 'pending' | 'in_progress' | 'completed' | 'cancelled'\n}\n\nexport type TodoList = TodoListItem[]\n\nexport const DOCUMENT_PATH_REGEXP = /^([\\w-]+\\/)*([\\w-.])+$/\n","import { BaseInstrumentation } from '$telemetry/instrumentations/base'\nimport { toKebabCase, toSnakeCase } from '$telemetry/utils'\nimport {\n ATTRIBUTES,\n HEAD_COMMIT,\n LogSources,\n SPAN_SPECIFICATIONS,\n SpanType,\n TraceContext,\n VALUES,\n} from '@latitude-data/constants'\nimport * as otel from '@opentelemetry/api'\nimport { propagation, trace } from '@opentelemetry/api'\nimport { Provider, Translator } from 'rosetta-ai'\n\nconst translator = new Translator({\n filterEmptyMessages: true,\n providerMetadata: 'preserve',\n})\n\nexport type StartSpanOptions = {\n name?: string\n attributes?: otel.Attributes\n}\n\nexport type EndSpanOptions = {\n attributes?: otel.Attributes\n}\n\nexport type ErrorOptions = {\n attributes?: otel.Attributes\n}\n\nexport type StartToolSpanOptions = StartSpanOptions & {\n name: string\n call: {\n id: string\n arguments: Record<string, unknown>\n }\n}\n\nexport type EndToolSpanOptions = EndSpanOptions & {\n result: {\n value: unknown\n isError: boolean\n }\n}\n\nexport type StartCompletionSpanOptions = StartSpanOptions & {\n provider: string\n model: string\n configuration?: Record<string, unknown>\n input?: string | Record<string, unknown>[]\n versionUuid?: string\n promptUuid?: string\n experimentUuid?: string\n}\n\nexport type EndCompletionSpanOptions = EndSpanOptions & {\n output?: string | Record<string, unknown>[]\n tokens?: {\n prompt?: number\n cached?: number\n reasoning?: number\n completion?: number\n }\n finishReason?: string\n}\n\nexport type StartHttpSpanOptions = StartSpanOptions & {\n request: {\n method: string\n url: string\n headers: Record<string, string>\n body: string | Record<string, unknown>\n }\n}\n\nexport type EndHttpSpanOptions = EndSpanOptions & {\n response: {\n status: number\n headers: Record<string, string>\n body: string | Record<string, unknown>\n }\n}\n\nexport type PromptSpanOptions = StartSpanOptions & {\n documentLogUuid: string\n versionUuid?: string // Alias for commitUuid\n promptUuid: string // Alias for documentUuid\n projectId?: number\n experimentUuid?: string\n testDeploymentId?: number\n externalId?: string\n template: string\n parameters?: Record<string, unknown>\n source?: LogSources\n}\n\nexport type ChatSpanOptions = StartSpanOptions & {\n documentLogUuid: string\n previousTraceId: string\n source?: LogSources\n versionUuid?: string // Alias for commitUuid\n promptUuid?: string // Alias for documentUuid\n}\n\nexport type ExternalSpanOptions = StartSpanOptions & {\n promptUuid: string // Alias for documentUuid\n documentLogUuid: string\n source?: LogSources // Defaults to LogSources.API\n versionUuid?: string // Alias for commitUuid\n externalId?: string\n}\n\nexport type CaptureOptions = StartSpanOptions & {\n path: string // The document path\n projectId: number\n versionUuid?: string // Optional, defaults to HEAD commit\n conversationUuid?: string // Optional, if provided, will be used as the documentLogUuid\n}\n\nexport type ManualInstrumentationOptions = {\n provider?: Provider\n}\n\nexport class ManualInstrumentation implements BaseInstrumentation {\n private enabled: boolean\n private readonly tracer: otel.Tracer\n private readonly options: ManualInstrumentationOptions\n\n constructor(tracer: otel.Tracer, options?: ManualInstrumentationOptions) {\n this.enabled = false\n this.tracer = tracer\n this.options = options ?? {}\n }\n\n isEnabled() {\n return this.enabled\n }\n\n enable() {\n this.enabled = true\n }\n\n disable() {\n this.enabled = false\n }\n\n resume(ctx: TraceContext): otel.Context {\n const parts = ctx.traceparent.split('-')\n if (parts.length !== 4) {\n return otel.ROOT_CONTEXT\n }\n\n const [, traceId, spanId, flags] = parts\n if (!traceId || !spanId) {\n return otel.ROOT_CONTEXT\n }\n\n const spanContext: otel.SpanContext = {\n traceId,\n spanId,\n traceFlags: parseInt(flags ?? '01', 16),\n isRemote: true,\n }\n\n let context = trace.setSpanContext(otel.ROOT_CONTEXT, spanContext)\n\n if (ctx.baggage) {\n const baggageEntries: Record<string, otel.BaggageEntry> = {}\n for (const pair of ctx.baggage.split(',')) {\n const [key, value] = pair.split('=')\n if (key && value) {\n baggageEntries[key] = { value: decodeURIComponent(value) }\n }\n }\n const baggage = propagation.createBaggage(baggageEntries)\n context = propagation.setBaggage(context, baggage)\n }\n\n return context\n }\n\n private error(span: otel.Span, error: Error, options?: ErrorOptions) {\n options = options || {}\n\n span.recordException(error)\n span.setAttributes(options.attributes || {})\n span.setStatus({\n code: otel.SpanStatusCode.ERROR,\n message: error.message || undefined,\n })\n span.end()\n }\n\n private span<T extends SpanType>(\n ctx: otel.Context,\n name: string,\n type: T,\n options?: StartSpanOptions,\n ) {\n if (!this.enabled) {\n return {\n context: ctx,\n end: (_options?: EndSpanOptions) => {},\n fail: (_error: Error, _options?: ErrorOptions) => {},\n }\n }\n\n const start = options || {}\n\n let operation = undefined\n if (SPAN_SPECIFICATIONS[type].isGenAI) {\n operation = type\n }\n\n const span = this.tracer.startSpan(\n name,\n {\n attributes: {\n [ATTRIBUTES.LATITUDE.type]: type,\n ...(operation && {\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.operation]: operation,\n }),\n ...(start.attributes || {}),\n },\n kind: otel.SpanKind.CLIENT,\n },\n ctx,\n )\n\n const newCtx = trace.setSpan(ctx, span)\n\n return {\n context: newCtx,\n end: (options?: EndSpanOptions) => {\n const end = options || {}\n\n span.setAttributes(end.attributes || {})\n span.setStatus({ code: otel.SpanStatusCode.OK })\n span.end()\n },\n fail: (error: Error, options?: ErrorOptions) => {\n this.error(span, error, options)\n },\n }\n }\n\n unknown(ctx: otel.Context, options?: StartSpanOptions) {\n return this.span(\n ctx,\n options?.name || SPAN_SPECIFICATIONS[SpanType.Unknown].name,\n SpanType.Unknown,\n options,\n )\n }\n\n tool(ctx: otel.Context, options: StartToolSpanOptions) {\n const start = options\n\n let jsonArguments = ''\n try {\n jsonArguments = JSON.stringify(start.call.arguments)\n } catch (_error) {\n jsonArguments = '{}'\n }\n\n const span = this.span(ctx, start.name, SpanType.Tool, {\n attributes: {\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI._deprecated.tool.name]: start.name,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI._deprecated.tool.type]:\n VALUES.OPENTELEMETRY.GEN_AI.tool.type.function,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.tool.call.id]: start.call.id,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.tool.call.arguments]: jsonArguments,\n ...(start.attributes || {}),\n },\n })\n\n return {\n ...span,\n end: (options: EndToolSpanOptions) => {\n const end = options\n\n let stringResult = ''\n if (typeof end.result.value !== 'string') {\n try {\n stringResult = JSON.stringify(end.result.value)\n } catch (_error) {\n stringResult = '{}'\n }\n } else {\n stringResult = end.result.value\n }\n\n span.end({\n attributes: {\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI._deprecated.tool.result.value]:\n stringResult,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI._deprecated.tool.result.isError]:\n end.result.isError,\n ...(end.attributes || {}),\n },\n })\n },\n }\n }\n\n private attribifyConfiguration(\n direction: 'input' | 'output',\n configuration: Record<string, unknown>,\n ) {\n const prefix =\n direction === 'input'\n ? ATTRIBUTES.LATITUDE.request._root\n : ATTRIBUTES.LATITUDE.response._root\n\n const attributes: otel.Attributes = {}\n for (const key in configuration) {\n const field = toSnakeCase(key)\n let value = configuration[key]\n if (value === null || value === undefined) continue\n if (typeof value === 'object' && !Array.isArray(value)) {\n try {\n value = JSON.stringify(value)\n } catch (_error) {\n value = '{}'\n }\n }\n\n attributes[`${prefix}.${field}`] = value as any\n }\n\n return attributes\n }\n\n completion(ctx: otel.Context, options: StartCompletionSpanOptions) {\n const start = options\n\n const configuration = {\n ...(start.configuration ?? {}),\n model: start.model,\n }\n let jsonConfiguration = ''\n try {\n jsonConfiguration = JSON.stringify(configuration)\n } catch (_error) {\n jsonConfiguration = '{}'\n }\n const attrConfiguration = this.attribifyConfiguration(\n 'input',\n configuration,\n )\n\n const input = start.input ?? []\n let jsonSystem = ''\n let jsonInput = ''\n try {\n const translated = translator.translate(input, {\n from: this.options.provider,\n to: Provider.GenAI,\n direction: 'input',\n })\n jsonSystem = JSON.stringify(translated.system ?? [])\n jsonInput = JSON.stringify(translated.messages ?? [])\n } catch (_error) {\n jsonSystem = '[]'\n jsonInput = '[]'\n }\n\n const span = this.span(\n ctx,\n start.name || `${start.provider} / ${start.model}`,\n SpanType.Completion,\n {\n attributes: {\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI._deprecated.system]: start.provider,\n [ATTRIBUTES.LATITUDE.request.configuration]: jsonConfiguration,\n ...attrConfiguration,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.systemInstructions]: jsonSystem,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.input.messages]: jsonInput,\n ...(start.attributes || {}),\n [ATTRIBUTES.LATITUDE.commitUuid]: start.versionUuid,\n [ATTRIBUTES.LATITUDE.documentUuid]: start.promptUuid,\n [ATTRIBUTES.LATITUDE.experimentUuid]: start.experimentUuid,\n },\n },\n )\n\n return {\n ...span,\n end: (options?: EndCompletionSpanOptions) => {\n const end = options ?? {}\n\n const output = end.output ?? []\n let jsonOutput = ''\n try {\n const translated = translator.translate(output, {\n from: this.options.provider,\n to: Provider.GenAI,\n direction: 'output',\n })\n jsonOutput = JSON.stringify(translated.messages ?? [])\n } catch (_error) {\n jsonOutput = '[]'\n }\n\n const tokens = {\n prompt: end.tokens?.prompt ?? 0,\n cached: end.tokens?.cached ?? 0,\n reasoning: end.tokens?.reasoning ?? 0,\n completion: end.tokens?.completion ?? 0,\n }\n const inputTokens = tokens.prompt + tokens.cached\n const outputTokens = tokens.reasoning + tokens.completion\n const finishReason = end.finishReason ?? ''\n\n span.end({\n attributes: {\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.output.messages]: jsonOutput,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.usage.inputTokens]: inputTokens,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.usage.outputTokens]: outputTokens,\n [ATTRIBUTES.LATITUDE.usage.promptTokens]: tokens.prompt,\n [ATTRIBUTES.LATITUDE.usage.cachedTokens]: tokens.cached,\n [ATTRIBUTES.LATITUDE.usage.reasoningTokens]: tokens.reasoning,\n [ATTRIBUTES.LATITUDE.usage.completionTokens]: tokens.completion,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.response.model]: start.model,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.response.finishReasons]: [\n finishReason,\n ],\n ...(end.attributes || {}),\n },\n })\n },\n }\n }\n\n embedding(ctx: otel.Context, options?: StartSpanOptions) {\n return this.span(\n ctx,\n options?.name || SPAN_SPECIFICATIONS[SpanType.Embedding].name,\n SpanType.Embedding,\n options,\n )\n }\n\n private attribifyHeaders(\n direction: 'request' | 'response',\n headers: Record<string, string>,\n ) {\n const prefix =\n direction === 'request'\n ? ATTRIBUTES.OPENTELEMETRY.HTTP.request.header\n : ATTRIBUTES.OPENTELEMETRY.HTTP.response.header\n\n const attributes: otel.Attributes = {}\n for (const key in headers) {\n const field = toKebabCase(key)\n const value = headers[key]\n if (value === null || value === undefined) continue\n\n attributes[`${prefix}.${field}`] = value as any\n }\n\n return attributes\n }\n\n http(ctx: otel.Context, options: StartHttpSpanOptions) {\n const start = options\n\n const method = start.request.method.toUpperCase()\n\n // Note: do not serialize headers as a single attribute because fields won't be redacted\n const attrHeaders = this.attribifyHeaders('request', start.request.headers)\n\n let finalBody = ''\n if (typeof start.request.body === 'string') {\n finalBody = start.request.body\n } else {\n try {\n finalBody = JSON.stringify(start.request.body)\n } catch (_error) {\n finalBody = '{}'\n }\n }\n\n const span = this.span(\n ctx,\n start.name || `${method} ${start.request.url}`,\n SpanType.Http,\n {\n attributes: {\n [ATTRIBUTES.OPENTELEMETRY.HTTP.request.method]: method,\n [ATTRIBUTES.OPENTELEMETRY.HTTP.request.url]: start.request.url,\n ...attrHeaders,\n [ATTRIBUTES.OPENTELEMETRY.HTTP.request.body]: finalBody,\n ...(start.attributes || {}),\n },\n },\n )\n\n return {\n ...span,\n end: (options: EndHttpSpanOptions) => {\n const end = options\n\n // Note: do not serialize headers as a single attribute because fields won't be redacted\n const attrHeaders = this.attribifyHeaders(\n 'response',\n end.response.headers,\n )\n\n let finalBody = ''\n if (typeof end.response.body === 'string') {\n finalBody = end.response.body\n } else {\n try {\n finalBody = JSON.stringify(end.response.body)\n } catch (_error) {\n finalBody = '{}'\n }\n }\n\n span.end({\n attributes: {\n [ATTRIBUTES.OPENTELEMETRY.HTTP.response.statusCode]:\n end.response.status,\n ...attrHeaders,\n [ATTRIBUTES.OPENTELEMETRY.HTTP.response.body]: finalBody,\n ...(end.attributes || {}),\n },\n })\n },\n }\n }\n\n prompt(\n ctx: otel.Context,\n {\n documentLogUuid,\n versionUuid,\n promptUuid,\n projectId,\n experimentUuid,\n testDeploymentId,\n externalId,\n template,\n parameters,\n name,\n source,\n ...rest\n }: PromptSpanOptions,\n ) {\n let jsonParameters = ''\n try {\n jsonParameters = JSON.stringify(parameters || {})\n } catch (_error) {\n jsonParameters = '{}'\n }\n\n const attributes = {\n [ATTRIBUTES.LATITUDE.request.template]: template,\n [ATTRIBUTES.LATITUDE.request.parameters]: jsonParameters,\n [ATTRIBUTES.LATITUDE.commitUuid]: versionUuid || HEAD_COMMIT,\n [ATTRIBUTES.LATITUDE.documentUuid]: promptUuid,\n [ATTRIBUTES.LATITUDE.projectId]: projectId,\n [ATTRIBUTES.LATITUDE.documentLogUuid]: documentLogUuid,\n ...(experimentUuid && {\n [ATTRIBUTES.LATITUDE.experimentUuid]: experimentUuid,\n }),\n ...(testDeploymentId && {\n [ATTRIBUTES.LATITUDE.testDeploymentId]: testDeploymentId,\n }),\n ...(externalId && { [ATTRIBUTES.LATITUDE.externalId]: externalId }),\n ...(source && { [ATTRIBUTES.LATITUDE.source]: source }),\n ...(rest.attributes || {}),\n }\n\n return this.span(ctx, name || `prompt-${promptUuid}`, SpanType.Prompt, {\n attributes,\n })\n }\n\n chat(\n ctx: otel.Context,\n {\n documentLogUuid,\n previousTraceId,\n source,\n name,\n versionUuid,\n promptUuid,\n ...rest\n }: ChatSpanOptions,\n ) {\n const attributes = {\n [ATTRIBUTES.LATITUDE.documentLogUuid]: documentLogUuid,\n [ATTRIBUTES.LATITUDE.previousTraceId]: previousTraceId,\n ...(versionUuid && { [ATTRIBUTES.LATITUDE.commitUuid]: versionUuid }),\n ...(promptUuid && { [ATTRIBUTES.LATITUDE.documentUuid]: promptUuid }),\n ...(source && { [ATTRIBUTES.LATITUDE.source]: source }),\n ...(rest.attributes || {}),\n }\n\n return this.span(ctx, name || `chat-${documentLogUuid}`, SpanType.Chat, {\n attributes,\n })\n }\n\n external(\n ctx: otel.Context,\n {\n promptUuid,\n documentLogUuid,\n source,\n versionUuid,\n externalId,\n name,\n ...rest\n }: ExternalSpanOptions,\n ) {\n const attributes = {\n [ATTRIBUTES.LATITUDE.documentUuid]: promptUuid,\n [ATTRIBUTES.LATITUDE.documentLogUuid]: documentLogUuid,\n [ATTRIBUTES.LATITUDE.source]: source ?? LogSources.API,\n ...(versionUuid && { [ATTRIBUTES.LATITUDE.commitUuid]: versionUuid }),\n ...(externalId && { [ATTRIBUTES.LATITUDE.externalId]: externalId }),\n ...(rest.attributes || {}),\n }\n\n return this.span(ctx, name || `external-${promptUuid}`, SpanType.External, {\n attributes,\n })\n }\n\n unresolvedExternal(\n ctx: otel.Context,\n {\n path,\n projectId,\n versionUuid,\n conversationUuid,\n name,\n ...rest\n }: CaptureOptions,\n ) {\n const attributes = {\n [ATTRIBUTES.LATITUDE.promptPath]: path,\n [ATTRIBUTES.LATITUDE.projectId]: projectId,\n ...(versionUuid && { [ATTRIBUTES.LATITUDE.commitUuid]: versionUuid }),\n ...(conversationUuid && {\n [ATTRIBUTES.LATITUDE.documentLogUuid]: conversationUuid,\n }),\n ...(rest.attributes || {}),\n }\n\n return this.span(\n ctx,\n name || `capture-${path}`,\n SpanType.UnresolvedExternal,\n { attributes },\n )\n }\n}\n","import { BaseInstrumentation } from '$telemetry/instrumentations/base'\nimport { ManualInstrumentation } from '$telemetry/instrumentations/manual'\nimport { VALUES } from '@latitude-data/constants'\nimport type { Latitude } from '@latitude-data/sdk'\nimport type { Tracer } from '@opentelemetry/api'\nimport { context } from '@opentelemetry/api'\nimport type { AdapterMessageType } from 'promptl-ai'\nimport { v4 as uuid } from 'uuid'\n\nexport type LatitudeInstrumentationOptions = {\n module: typeof Latitude\n completions?: boolean\n}\n\nexport class LatitudeInstrumentation implements BaseInstrumentation {\n private readonly options: LatitudeInstrumentationOptions\n private readonly manualTelemetry: ManualInstrumentation\n\n constructor(tracer: Tracer, options: LatitudeInstrumentationOptions) {\n this.manualTelemetry = new ManualInstrumentation(tracer)\n this.options = options\n }\n\n isEnabled() {\n return this.manualTelemetry.isEnabled()\n }\n\n enable() {\n this.manualTelemetry.enable()\n this.options.module.instrument(this)\n }\n\n disable() {\n this.manualTelemetry.disable()\n this.options.module.uninstrument()\n }\n\n private countTokens<M extends AdapterMessageType>(messages: M[]) {\n let length = 0\n\n for (const message of messages) {\n if (!('content' in message)) continue\n if (typeof message.content === 'string') {\n length += message.content.length\n } else if (Array.isArray(message.content)) {\n for (const content of message.content) {\n if (content.type === 'text') {\n length += content.text.length\n }\n }\n }\n }\n\n // Note: this is an estimation to not bundle a tokenizer\n return Math.ceil(length / 4)\n }\n\n async wrapRenderChain<F extends Latitude['renderChain']>(\n fn: F,\n ...args: Parameters<F>\n ): Promise<Awaited<ReturnType<F>>> {\n const { prompt, parameters } = args[0]\n\n const $prompt = this.manualTelemetry.prompt(context.active(), {\n documentLogUuid: uuid(),\n versionUuid: prompt.versionUuid,\n promptUuid: prompt.uuid,\n template: prompt.content,\n parameters: parameters,\n })\n\n let result\n try {\n result = await context.with(\n $prompt.context,\n async () => await ((fn as any)(...args) as ReturnType<F>),\n )\n } catch (error) {\n $prompt.fail(error as Error)\n throw error\n }\n\n $prompt.end()\n\n return result\n }\n\n async wrapRenderCompletion<F extends Latitude['renderCompletion']>(\n fn: F,\n ...args: Parameters<F>\n ): Promise<Awaited<ReturnType<F>>> {\n if (!this.options.completions) {\n return await ((fn as any)(...args) as ReturnType<F>)\n }\n\n const { provider, config, messages } = args[0]\n const model = (config.model as string) || 'unknown'\n\n const $completion = this.manualTelemetry.completion(context.active(), {\n name: `${provider} / ${model}`,\n provider: provider,\n model: model,\n configuration: config,\n input: messages as Record<string, unknown>[],\n })\n\n let result\n try {\n result = await context.with(\n $completion.context,\n async () => await ((fn as any)(...args) as ReturnType<F>),\n )\n } catch (error) {\n $completion.fail(error as Error)\n throw error\n }\n\n // Note: enhance, this is just an estimation\n const promptTokens = this.countTokens(messages)\n const completionTokens = this.countTokens(result.messages)\n\n $completion.end({\n output: result.messages as Record<string, unknown>[],\n tokens: {\n prompt: promptTokens,\n cached: 0,\n reasoning: 0,\n completion: completionTokens,\n },\n finishReason:\n result.toolRequests.length > 0\n ? VALUES.OPENTELEMETRY.GEN_AI.response.finishReasons.toolCalls\n : VALUES.OPENTELEMETRY.GEN_AI.response.finishReasons.stop,\n })\n\n return result\n }\n\n async wrapRenderTool<F extends Latitude['renderTool']>(\n fn: F,\n ...args: Parameters<F>\n ): Promise<Awaited<ReturnType<F>>> {\n const { toolRequest } = args[0]\n\n const $tool = this.manualTelemetry.tool(context.active(), {\n name: toolRequest.toolName,\n call: {\n id: toolRequest.toolCallId,\n arguments: toolRequest.toolArguments,\n },\n })\n\n let result\n try {\n result = await context.with(\n $tool.context,\n async () => await ((fn as any)(...args) as ReturnType<F>),\n )\n } catch (error) {\n $tool.fail(error as Error)\n throw error\n }\n\n $tool.end({\n result: {\n value: result.result,\n isError: result.isError,\n },\n })\n\n return result\n }\n}\n","export enum LatitudeErrorCodes {\n UnexpectedError = 'UnexpectedError',\n OverloadedError = 'OverloadedError',\n RateLimitError = 'RateLimitError',\n UnauthorizedError = 'UnauthorizedError',\n ForbiddenError = 'ForbiddenError',\n BadRequestError = 'BadRequestError',\n NotFoundError = 'NotFoundError',\n ConflictError = 'ConflictError',\n UnprocessableEntityError = 'UnprocessableEntityError',\n NotImplementedError = 'NotImplementedError',\n PaymentRequiredError = 'PaymentRequiredError',\n AbortedError = 'AbortedError',\n BillingError = 'BillingError',\n}\n\nexport type LatitudeErrorDetails = {\n [key: string | number | symbol]: string[] | string | undefined\n}\n\n// NOTE: If you add a new error code, please add it to the pg enum in models/runErrors.ts\nexport enum RunErrorCodes {\n AIProviderConfigError = 'ai_provider_config_error',\n AIRunError = 'ai_run_error',\n ChainCompileError = 'chain_compile_error',\n DefaultProviderExceededQuota = 'default_provider_exceeded_quota_error',\n DefaultProviderInvalidModel = 'default_provider_invalid_model_error',\n DocumentConfigError = 'document_config_error',\n ErrorGeneratingMockToolResult = 'error_generating_mock_tool_result',\n FailedToWakeUpIntegrationError = 'failed_to_wake_up_integration_error',\n InvalidResponseFormatError = 'invalid_response_format_error',\n MaxStepCountExceededError = 'max_step_count_exceeded_error',\n MissingProvider = 'missing_provider_error',\n RateLimit = 'rate_limit_error',\n Unknown = 'unknown_error',\n UnsupportedProviderResponseTypeError = 'unsupported_provider_response_type_error',\n PaymentRequiredError = 'payment_required_error',\n AbortError = 'abort_error',\n\n // DEPRECATED, but do not delete\n EvaluationRunMissingProviderLogError = 'ev_run_missing_provider_log_error',\n EvaluationRunMissingWorkspaceError = 'ev_run_missing_workspace_error',\n EvaluationRunResponseJsonFormatError = 'ev_run_response_json_format_error',\n EvaluationRunUnsupportedResultTypeError = 'ev_run_unsupported_result_type_error',\n}\n// NOTE: If you add a new error code, please add it to the pg enum in models/runErrors.ts\n\nexport type RunErrorDetails<C extends RunErrorCodes> =\n C extends RunErrorCodes.ChainCompileError\n ? { compileCode: string; message: string }\n : C extends RunErrorCodes.Unknown\n ? { stack: string }\n : never\n\nexport enum ApiErrorCodes {\n HTTPException = 'http_exception',\n InternalServerError = 'internal_server_error',\n}\n\nexport type DbErrorRef = {\n entityUuid: string\n entityType: string\n}\n\nexport type ApiErrorJsonResponse = {\n name: string\n message: string\n details: object\n errorCode: ApiResponseCode\n dbErrorRef?: DbErrorRef\n}\nexport type ApiResponseCode = RunErrorCodes | ApiErrorCodes | LatitudeErrorCodes\n","import {\n LatitudeErrorCodes,\n LatitudeErrorDetails,\n RunErrorCodes,\n} from './constants'\n\nexport type LatitudeErrorDto = {\n name: LatitudeErrorCodes\n code: RunErrorCodes\n status: number\n message: string\n details: Record<string, unknown>\n}\n\nexport class LatitudeError extends Error {\n statusCode: number = 500\n name: string = LatitudeErrorCodes.UnexpectedError\n headers: Record<string, string> = {}\n\n public details: LatitudeErrorDetails\n\n constructor(\n message: string,\n details?: LatitudeErrorDetails,\n status?: number,\n name?: string,\n ) {\n super(message)\n this.details = details ?? {}\n this.statusCode = status ?? this.statusCode\n this.name = name ?? this.constructor.name\n }\n\n serialize(): LatitudeErrorDto {\n return {\n name: this.name as LatitudeErrorCodes,\n code: this.name as RunErrorCodes,\n status: this.statusCode,\n message: this.message,\n details: this.details,\n }\n }\n\n static deserialize(json: LatitudeErrorDto): LatitudeError {\n return new LatitudeError(\n json.message,\n json.details as LatitudeErrorDetails,\n json.status,\n json.name,\n )\n }\n}\n\nexport class OverloadedError extends LatitudeError {\n public statusCode = 429\n public name = LatitudeErrorCodes.OverloadedError\n}\n\nexport class AbortedError extends LatitudeError {\n public statusCode = 499\n public reason = 'Client Closed Request'\n public name = LatitudeErrorCodes.AbortedError\n constructor(message: string = 'Operation was aborted') {\n super(message)\n this.reason = message\n }\n}\n\nexport class ConflictError extends LatitudeError {\n public statusCode = 409\n public name = LatitudeErrorCodes.ConflictError\n}\n\nexport class UnprocessableEntityError extends LatitudeError {\n public statusCode = 422\n public name = LatitudeErrorCodes.UnprocessableEntityError\n\n constructor(message: string, details: LatitudeErrorDetails = {}) {\n super(message, details)\n }\n}\n\nexport class NotFoundError extends LatitudeError {\n public statusCode = 404\n public name = LatitudeErrorCodes.NotFoundError\n}\n\nexport class BadRequestError extends LatitudeError {\n public statusCode = 400\n public name = LatitudeErrorCodes.BadRequestError\n}\n\nexport class ForbiddenError extends LatitudeError {\n public statusCode = 403\n public name = LatitudeErrorCodes.ForbiddenError\n}\n\nexport class UnauthorizedError extends LatitudeError {\n public statusCode = 401\n public name = LatitudeErrorCodes.UnauthorizedError\n}\nexport class RateLimitError extends LatitudeError {\n public statusCode = 429\n public name = LatitudeErrorCodes.RateLimitError\n\n constructor(\n message: string,\n retryAfter?: number,\n limit?: number,\n remaining?: number,\n resetTime?: number,\n ) {\n super(message)\n\n this.headers = {}\n if (retryAfter !== undefined) {\n this.headers['Retry-After'] = retryAfter.toString()\n }\n if (limit !== undefined) {\n this.headers['X-RateLimit-Limit'] = limit.toString()\n }\n if (remaining !== undefined) {\n this.headers['X-RateLimit-Remaining'] = remaining.toString()\n }\n if (resetTime !== undefined) {\n this.headers['X-RateLimit-Reset'] = resetTime.toString()\n }\n }\n}\n\nexport class NotImplementedError extends LatitudeError {\n public statusCode = 501\n public name = LatitudeErrorCodes.NotImplementedError\n}\n\nexport class PaymentRequiredError extends LatitudeError {\n public statusCode = 402\n public name = LatitudeErrorCodes.PaymentRequiredError\n}\n\nexport type BillingErrorTags = {\n workspaceId?: number\n userEmail?: string\n stripeCustomerId?: string\n plan?: string\n}\n\n/**\n * Error class for billing-related failures (Stripe API errors, etc.).\n * Includes tags for error tracking in Datadog.\n */\nexport class BillingError extends LatitudeError {\n public statusCode = 400\n public name = LatitudeErrorCodes.BillingError\n public tags: BillingErrorTags\n public originalError?: Error\n\n constructor(\n message: string,\n {\n tags = {},\n originalError,\n }: {\n tags?: BillingErrorTags\n originalError?: Error\n } = {},\n ) {\n super(message, {\n workspaceId: tags.workspaceId?.toString(),\n userEmail: tags.userEmail,\n stripeCustomerId: tags.stripeCustomerId,\n plan: tags.plan,\n })\n this.tags = tags\n this.originalError = originalError\n }\n}\n\nexport const databaseErrorCodes = {\n foreignKeyViolation: '23503',\n uniqueViolation: '23505',\n lockNotAvailable: '55P03',\n}\n","import { env } from '$telemetry/env'\nimport {\n BaseInstrumentation,\n CaptureOptions,\n ChatSpanOptions,\n ExternalSpanOptions,\n LatitudeInstrumentation,\n LatitudeInstrumentationOptions,\n ManualInstrumentation,\n ManualInstrumentationOptions,\n PromptSpanOptions,\n StartCompletionSpanOptions,\n StartHttpSpanOptions,\n StartSpanOptions,\n StartToolSpanOptions,\n} from '$telemetry/instrumentations'\nimport { DEFAULT_REDACT_SPAN_PROCESSOR } from '$telemetry/sdk/redact'\nimport {\n DOCUMENT_PATH_REGEXP,\n InstrumentationScope,\n SCOPE_LATITUDE,\n TraceContext,\n} from '@latitude-data/constants'\nimport { BadRequestError } from '@latitude-data/constants/errors'\nimport type * as latitude from '@latitude-data/sdk'\nimport * as otel from '@opentelemetry/api'\nimport { context, propagation, TextMapPropagator } from '@opentelemetry/api'\nimport {\n ALLOW_ALL_BAGGAGE_KEYS,\n BaggageSpanProcessor,\n} from '@opentelemetry/baggage-span-processor'\nimport { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks'\nimport {\n CompositePropagator,\n W3CBaggagePropagator,\n W3CTraceContextPropagator,\n} from '@opentelemetry/core'\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'\nimport { registerInstrumentations } from '@opentelemetry/instrumentation'\nimport { Resource } from '@opentelemetry/resources'\nimport {\n BatchSpanProcessor,\n NodeTracerProvider,\n SimpleSpanProcessor,\n SpanExporter,\n SpanProcessor,\n} from '@opentelemetry/sdk-trace-node'\nimport { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions'\nimport { AnthropicInstrumentation } from '@traceloop/instrumentation-anthropic'\nimport { BedrockInstrumentation } from '@traceloop/instrumentation-bedrock'\nimport { CohereInstrumentation } from '@traceloop/instrumentation-cohere'\nimport { LangChainInstrumentation } from '@traceloop/instrumentation-langchain'\nimport { LlamaIndexInstrumentation } from '@traceloop/instrumentation-llamaindex'\nimport { OpenAIInstrumentation } from '@traceloop/instrumentation-openai'\nimport { TogetherInstrumentation } from '@traceloop/instrumentation-together'\nimport {\n AIPlatformInstrumentation,\n VertexAIInstrumentation,\n} from '@traceloop/instrumentation-vertexai'\n\nconst TRACES_URL = `${env.GATEWAY_BASE_URL}/api/v3/traces`\nconst SERVICE_NAME = process.env.npm_package_name || 'unknown'\nconst SCOPE_VERSION = process.env.npm_package_version || 'unknown'\n\nexport type TelemetryContext = otel.Context\nexport const BACKGROUND = () => otel.ROOT_CONTEXT\n\nclass SpanFactory {\n private readonly telemetry: ManualInstrumentation\n\n constructor(telemetry: ManualInstrumentation) {\n this.telemetry = telemetry\n }\n\n span(options?: StartSpanOptions, ctx?: TelemetryContext) {\n return this.telemetry.unknown(ctx ?? context.active(), options)\n }\n\n tool(options: StartToolSpanOptions, ctx?: TelemetryContext) {\n return this.telemetry.tool(ctx ?? context.active(), options)\n }\n\n completion(options: StartCompletionSpanOptions, ctx?: TelemetryContext) {\n return this.telemetry.completion(ctx ?? context.active(), options)\n }\n\n embedding(options?: StartSpanOptions, ctx?: TelemetryContext) {\n return this.telemetry.embedding(ctx ?? context.active(), options)\n }\n\n http(options: StartHttpSpanOptions, ctx?: TelemetryContext) {\n return this.telemetry.http(ctx ?? context.active(), options)\n }\n\n prompt(options: PromptSpanOptions, ctx?: TelemetryContext) {\n return this.telemetry.prompt(ctx ?? context.active(), options)\n }\n\n chat(options: ChatSpanOptions, ctx?: TelemetryContext) {\n return this.telemetry.chat(ctx ?? context.active(), options)\n }\n\n external(options: ExternalSpanOptions, ctx?: TelemetryContext) {\n return this.telemetry.external(ctx ?? context.active(), options)\n }\n}\n\nclass ContextManager {\n private readonly telemetry: ManualInstrumentation\n\n constructor(telemetry: ManualInstrumentation) {\n this.telemetry = telemetry\n }\n\n resume(ctx: TraceContext) {\n return this.telemetry.resume(ctx)\n }\n\n active() {\n return context.active()\n }\n\n with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n ctx: TelemetryContext,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n return context.with(ctx, fn, thisArg, ...args)\n }\n}\n\nclass InstrumentationManager {\n private readonly instrumentations: BaseInstrumentation[]\n\n constructor(instrumentations: BaseInstrumentation[]) {\n this.instrumentations = instrumentations\n }\n\n enable() {\n this.instrumentations.forEach((instrumentation) => {\n if (!instrumentation.isEnabled()) instrumentation.enable()\n })\n }\n\n disable() {\n this.instrumentations.forEach((instrumentation) => {\n if (instrumentation.isEnabled()) instrumentation.disable()\n })\n }\n}\n\nclass TracerManager {\n private readonly nodeProvider: NodeTracerProvider\n private readonly scopeVersion: string\n\n constructor(nodeProvider: NodeTracerProvider, scopeVersion: string) {\n this.nodeProvider = nodeProvider\n this.scopeVersion = scopeVersion\n }\n\n get(scope: Instrumentation) {\n return this.provider(scope).getTracer('')\n }\n\n provider(scope: Instrumentation) {\n return new ScopedTracerProvider(\n `${SCOPE_LATITUDE}.${scope}`,\n this.scopeVersion,\n this.nodeProvider,\n )\n }\n}\n\nclass ScopedTracerProvider implements otel.TracerProvider {\n private readonly scope: string\n private readonly version: string\n private readonly provider: otel.TracerProvider\n\n constructor(scope: string, version: string, provider: otel.TracerProvider) {\n this.scope = scope\n this.version = version\n this.provider = provider\n }\n\n getTracer(_name: string, _version?: string, options?: otel.TracerOptions) {\n return this.provider.getTracer(this.scope, this.version, options)\n }\n}\n\nclass LifecycleManager {\n private readonly nodeProvider: NodeTracerProvider\n private readonly exporter: SpanExporter\n\n constructor(nodeProvider: NodeTracerProvider, exporter: SpanExporter) {\n this.nodeProvider = nodeProvider\n this.exporter = exporter\n }\n\n async flush() {\n await this.nodeProvider.forceFlush()\n await this.exporter.forceFlush?.()\n }\n\n async shutdown() {\n await this.flush()\n await this.nodeProvider.shutdown()\n await this.exporter.shutdown?.()\n }\n}\n\nexport const DEFAULT_SPAN_EXPORTER = (apiKey: string) =>\n new OTLPTraceExporter({\n url: TRACES_URL,\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n timeoutMillis: 30 * 1000,\n })\n\n// Note: Only exporting typescript instrumentations\nexport enum Instrumentation {\n Anthropic = InstrumentationScope.Anthropic,\n AIPlatform = InstrumentationScope.AIPlatform,\n Bedrock = InstrumentationScope.Bedrock,\n Cohere = InstrumentationScope.Cohere,\n Langchain = InstrumentationScope.Langchain,\n Latitude = InstrumentationScope.Latitude,\n LlamaIndex = InstrumentationScope.LlamaIndex,\n Manual = InstrumentationScope.Manual,\n OpenAI = InstrumentationScope.OpenAI,\n TogetherAI = InstrumentationScope.TogetherAI,\n VertexAI = InstrumentationScope.VertexAI,\n}\n\nexport type TelemetryOptions = {\n disableBatch?: boolean\n exporter?: SpanExporter\n processors?: SpanProcessor[]\n propagators?: TextMapPropagator[]\n instrumentations?: {\n [Instrumentation.Latitude]?:\n | typeof latitude.Latitude\n | LatitudeInstrumentationOptions\n\n // Note: These are all typed as 'any' because using the actual expected types will cause\n // type errors when the version installed in the package is even slightly different than\n // the version used in the project.\n [Instrumentation.AIPlatform]?: any\n [Instrumentation.Anthropic]?: any\n [Instrumentation.Bedrock]?: any\n [Instrumentation.Cohere]?: any\n [Instrumentation.OpenAI]?: any\n [Instrumentation.LlamaIndex]?: any\n [Instrumentation.TogetherAI]?: any\n [Instrumentation.VertexAI]?: any\n [Instrumentation.Langchain]?: {\n callbackManagerModule?: any\n }\n [Instrumentation.Manual]?: ManualInstrumentationOptions\n }\n}\n\nexport class LatitudeTelemetry {\n private options: TelemetryOptions\n private nodeProvider: NodeTracerProvider\n private manualInstrumentation: ManualInstrumentation\n private instrumentationsList: BaseInstrumentation[]\n\n readonly span: SpanFactory\n readonly context: ContextManager\n readonly instrumentation: InstrumentationManager\n readonly tracer: TracerManager\n private readonly lifecycle: LifecycleManager\n\n constructor(apiKey: string, options?: TelemetryOptions) {\n this.options = options || {}\n\n if (!this.options.exporter) {\n this.options.exporter = DEFAULT_SPAN_EXPORTER(apiKey)\n }\n\n context.setGlobalContextManager(\n new AsyncLocalStorageContextManager().enable(),\n )\n\n propagation.setGlobalPropagator(\n new CompositePropagator({\n propagators: [\n ...(this.options.propagators || []),\n new W3CTraceContextPropagator(),\n new W3CBaggagePropagator(),\n ],\n }),\n )\n\n this.nodeProvider = new NodeTracerProvider({\n resource: new Resource({ [ATTR_SERVICE_NAME]: SERVICE_NAME }),\n })\n\n this.lifecycle = new LifecycleManager(\n this.nodeProvider,\n this.options.exporter,\n )\n\n // Note: important, must run before the exporter span processors\n this.nodeProvider.addSpanProcessor(\n new BaggageSpanProcessor(ALLOW_ALL_BAGGAGE_KEYS),\n )\n\n if (this.options.processors) {\n this.options.processors.forEach((processor) => {\n this.nodeProvider.addSpanProcessor(processor)\n })\n } else {\n this.nodeProvider.addSpanProcessor(DEFAULT_REDACT_SPAN_PROCESSOR())\n }\n\n if (this.options.disableBatch) {\n this.nodeProvider.addSpanProcessor(\n new SimpleSpanProcessor(this.options.exporter),\n )\n } else {\n this.nodeProvider.addSpanProcessor(\n new BatchSpanProcessor(this.options.exporter),\n )\n }\n\n this.nodeProvider.register()\n\n process.on('SIGTERM', async () => this.shutdown)\n process.on('SIGINT', async () => this.shutdown)\n\n this.manualInstrumentation = null as unknown as ManualInstrumentation\n this.instrumentationsList = []\n this.tracer = new TracerManager(this.nodeProvider, SCOPE_VERSION)\n this.initInstrumentations()\n this.instrumentation = new InstrumentationManager(this.instrumentationsList)\n this.instrumentation.enable()\n\n this.span = new SpanFactory(this.manualInstrumentation)\n this.context = new ContextManager(this.manualInstrumentation)\n }\n\n async flush() {\n await this.lifecycle.flush()\n }\n\n async shutdown() {\n await this.lifecycle.shutdown()\n }\n\n // TODO(tracing): auto instrument outgoing HTTP requests\n private initInstrumentations() {\n this.instrumentationsList = []\n\n const tracer = this.tracer.get(Instrumentation.Manual)\n this.manualInstrumentation = new ManualInstrumentation(\n tracer,\n this.options.instrumentations?.manual,\n )\n this.instrumentationsList.push(this.manualInstrumentation)\n\n const latitude = this.options.instrumentations?.latitude\n if (latitude) {\n const tracer = this.tracer.get(Instrumentation.Latitude)\n const instrumentation = new LatitudeInstrumentation(\n tracer,\n typeof latitude === 'object' ? latitude : { module: latitude },\n )\n this.instrumentationsList.push(instrumentation)\n }\n\n type InstrumentationClass =\n | typeof AnthropicInstrumentation\n | typeof AIPlatformInstrumentation\n | typeof BedrockInstrumentation\n | typeof CohereInstrumentation\n | typeof LangChainInstrumentation\n | typeof LlamaIndexInstrumentation\n | typeof OpenAIInstrumentation\n | typeof TogetherInstrumentation\n | typeof VertexAIInstrumentation\n\n const configureInstrumentation = (\n instrumentationType: Instrumentation,\n InstrumentationConstructor: InstrumentationClass,\n instrumentationOptions?: { enrichTokens?: boolean },\n ) => {\n const providerPkg = this.options.instrumentations?.[instrumentationType]\n if (!providerPkg) return\n\n const provider = this.tracer.provider(instrumentationType)\n const instrumentation = new InstrumentationConstructor(instrumentationOptions) // prettier-ignore\n instrumentation.setTracerProvider(provider)\n instrumentation.manuallyInstrument(providerPkg)\n registerInstrumentations({\n instrumentations: [instrumentation],\n tracerProvider: provider,\n })\n this.instrumentationsList.push(instrumentation)\n }\n\n configureInstrumentation(Instrumentation.Anthropic, AnthropicInstrumentation) // prettier-ignore\n configureInstrumentation(Instrumentation.AIPlatform, AIPlatformInstrumentation) // prettier-ignore\n configureInstrumentation(Instrumentation.Bedrock, BedrockInstrumentation) // prettier-ignore\n configureInstrumentation(Instrumentation.Cohere, CohereInstrumentation) // prettier-ignore\n configureInstrumentation(Instrumentation.Langchain, LangChainInstrumentation) // prettier-ignore\n configureInstrumentation(Instrumentation.LlamaIndex, LlamaIndexInstrumentation) // prettier-ignore\n // NOTE: `stream: true` in OpenAI make enrichTokens fail, so disabling.\n configureInstrumentation(Instrumentation.OpenAI, OpenAIInstrumentation, { enrichTokens: false }) // prettier-ignore\n configureInstrumentation(Instrumentation.TogetherAI, TogetherInstrumentation, { enrichTokens: false }) // prettier-ignore\n configureInstrumentation(Instrumentation.VertexAI, VertexAIInstrumentation) // prettier-ignore\n }\n\n async capture<T>(\n options: CaptureOptions,\n fn: (ctx: TelemetryContext) => T | Promise<T>,\n ): Promise<T> {\n if (!DOCUMENT_PATH_REGEXP.test(options.path)) {\n throw new BadRequestError(\n \"Invalid path, no spaces. Only letters, numbers, '.', '-' and '_'\",\n )\n }\n\n const span = this.manualInstrumentation.unresolvedExternal(\n BACKGROUND(),\n options,\n )\n\n let result\n try {\n result = await context.with(\n span.context,\n async () => await fn(span.context),\n )\n } catch (error) {\n span.fail(error as Error)\n throw error\n }\n\n span.end()\n\n return result\n }\n}\n"],"names":["z","ATTR_HTTP_REQUEST_METHOD","ATTR_HTTP_RESPONSE_STATUS_CODE","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_RESPONSE_FINISH_REASONS","ATTR_GEN_AI_USAGE_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","ATTR_GEN_AI_TOOL_CALL_ID","ATTR_GEN_AI_SYSTEM","ATTR_GEN_AI_TOOL_NAME","ATTR_GEN_AI_TOOL_TYPE","Translator","otel","trace","propagation","Provider","context","uuid","OTLPTraceExporter","Instrumentation","AsyncLocalStorageContextManager","CompositePropagator","W3CTraceContextPropagator","W3CBaggagePropagator","NodeTracerProvider","Resource","ATTR_SERVICE_NAME","BaggageSpanProcessor","ALLOW_ALL_BAGGAGE_KEYS","SimpleSpanProcessor","BatchSpanProcessor","instrumentation","registerInstrumentations","AnthropicInstrumentation","AIPlatformInstrumentation","BedrockInstrumentation","CohereInstrumentation","LangChainInstrumentation","LlamaIndexInstrumentation","OpenAIInstrumentation","TogetherInstrumentation","VertexAIInstrumentation"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MAQa,mBAAmB,CAAA;AACtB,IAAA,OAAO;AAEf,IAAA,WAAA,CAAY,OAAmC,EAAA;AAC7C,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO;AAEtB,QAAA,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE;AACjB,YAAA,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,CAAC,UAAkB,EAAE,MAAW,KAAK,QAAQ;QACnE;IACF;IAEA,OAAO,CAAC,KAAmB,EAAE,QAAsB,EAAA;;IAEnD;AAEA,IAAA,KAAK,CAAC,IAAkB,EAAA;AACtB,QAAA,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;AACtE,QAAA,KAAK,MAAM,KAAK,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AAK,EAAE,CAAC,CAAA;AAChG,QAAA,wBAAwB,CAACpB,uBAAe,CAAC,UAAU,EAAEqB,+CAAuB,EAAE,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAA;QACtG,wBAAwB,CAACrB,uBAAe,CAAC,QAAQ,EAAEsB,+CAAuB,CAAC,CAAA;IAC7E;AAEA,IAAA,MAAM,OAAO,CACX,OAAuB,EACvB,EAA6C,EAAA;QAE7C,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;AAC5C,YAAA,MAAM,IAAI,eAAe,CACvB,kEAAkE,CACnE;QACH;AAEA,QAAA,MAAM,IAAI,GAAG,IAAI,CAAC,qBAAqB,CAAC,kBAAkB,CACxD,UAAU,EAAE,EACZ,OAAO,CACR;AAED,QAAA,IAAI,MAAM;AACV,QAAA,IAAI;YACF,MAAM,GAAG,MAAMzB,YAAO,CAAC,IAAI,CACzB,IAAI,CAAC,OAAO,EACZ,YAAY,MAAM,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CACnC;QACH;QAAE,OAAO,KAAK,EAAE;AACd,YAAA,IAAI,CAAC,IAAI,CAAC,KAAc,CAAC;AACzB,YAAA,MAAM,KAAK;QACb;QAEA,IAAI,CAAC,GAAG,EAAE;AAEV,QAAA,OAAO,MAAM;IACf;AACD;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../../../../src/sdk/redact.ts","../../../../src/env/env.ts","../../../../src/utils/utils.ts","../../../../../../constants/src/ai.ts","../../../../../../constants/src/config.ts","../../../../../../constants/src/evaluations/shared.ts","../../../../../../constants/src/evaluations/composite.ts","../../../../../../constants/src/evaluations/human.ts","../../../../../../constants/src/evaluations/llm.ts","../../../../../../constants/src/evaluations/rule.ts","../../../../../../constants/src/evaluations/index.ts","../../../../../../constants/src/events/events.ts","../../../../../../constants/src/experiments.ts","../../../../../../constants/src/grants.ts","../../../../../../constants/src/history.ts","../../../../../../constants/src/integrations.ts","../../../../../../constants/src/models.ts","../../../../../../constants/src/runs.ts","../../../../../../constants/src/tracing/span.ts","../../../../../../constants/src/tracing/trace.ts","../../../../../../constants/src/tracing/attributes.ts","../../../../../../constants/src/tracing/index.ts","../../../../../../constants/src/simulation.ts","../../../../../../constants/src/optimizations.ts","../../../../../../constants/src/index.ts","../../../../src/instrumentations/manual.ts","../../../../src/instrumentations/latitude.ts","../../../../../../constants/src/errors/constants.ts","../../../../../../constants/src/errors/latitudeError.ts","../../../../src/sdk/sdk.ts"],"sourcesContent":["import * as otel from '@opentelemetry/api'\nimport { ReadableSpan, SpanProcessor } from '@opentelemetry/sdk-trace-node'\n\nexport interface RedactSpanProcessorOptions {\n attributes: (string | RegExp)[]\n mask?: (attribute: string, value: any) => string\n}\n\nexport class RedactSpanProcessor implements SpanProcessor {\n private options: RedactSpanProcessorOptions\n\n constructor(options: RedactSpanProcessorOptions) {\n this.options = options\n\n if (!options.mask) {\n this.options.mask = (_attribute: string, _value: any) => '******'\n }\n }\n\n onStart(_span: ReadableSpan, _context: otel.Context): void {\n // Noop\n }\n\n onEnd(span: ReadableSpan): void {\n Object.assign(span.attributes, this.redactAttributes(span.attributes))\n for (const event of span.events) {\n if (!event.attributes) continue\n Object.assign(event.attributes, this.redactAttributes(event.attributes))\n }\n for (const link of span.links) {\n if (!link.attributes) continue\n Object.assign(link.attributes, this.redactAttributes(link.attributes))\n }\n }\n\n forceFlush(): Promise<void> {\n return Promise.resolve()\n }\n\n shutdown(): Promise<void> {\n return Promise.resolve()\n }\n\n private shouldRedact(attribute: string) {\n return this.options.attributes.some((pattern) => {\n if (typeof pattern === 'string') {\n return attribute === pattern\n } else if (pattern instanceof RegExp) {\n return pattern.test(attribute)\n }\n return false\n })\n }\n\n private redactAttributes(attributes: otel.Attributes) {\n const redacted: otel.Attributes = {}\n\n for (const [key, value] of Object.entries(attributes)) {\n if (this.shouldRedact(key)) {\n redacted[key] = this.options.mask!(key, value)\n }\n }\n\n return redacted\n }\n}\n\nexport const DEFAULT_REDACT_SPAN_PROCESSOR = () =>\n new RedactSpanProcessor({\n attributes: [\n /^.*auth.*$/i,\n /^.*authorization.*$/i,\n /^(?!gen_ai\\.).*usage.*$/i,\n /^(?!gen_ai\\.).*token.*$/i,\n /^.*secret.*$/i,\n /^.*key.*$/i,\n /^.*password.*$/i,\n /^.*cookie.*$/i,\n /^.*session.*$/i,\n /^.*credential.*$/i,\n /^.*signature.*$/i,\n /^.*oauth.*$/i,\n /^.*saml.*$/i,\n /^.*openid.*$/i,\n /^.*refresh.*$/i,\n /^.*jwt.*$/i,\n /^.*otp.*$/i,\n /^.*mfa.*$/i,\n /^.*csrf.*$/i,\n /^.*xsrf.*$/i,\n /^.*refresh.*$/i,\n /^.*x[-_]forwarded[-_]for.*$/i,\n /^.*x[-_]real[-_]ip.*$/i,\n ],\n })\n","const DEFAULT_GATEWAY_BASE_URL =\n {\n production: 'https://gateway.latitude.so',\n development: 'http://localhost:8787',\n test: 'http://localhost:8787',\n }[process.env.NODE_ENV ?? 'development'] ?? 'http://localhost:8787'\n\nfunction GET_GATEWAY_BASE_URL() {\n if (process.env.GATEWAY_BASE_URL) {\n return process.env.GATEWAY_BASE_URL\n }\n\n if (!process.env.GATEWAY_HOSTNAME) {\n return DEFAULT_GATEWAY_BASE_URL\n }\n\n const protocol = process.env.GATEWAY_SSL ? 'https' : 'http'\n const port = process.env.GATEWAY_PORT ?? (process.env.GATEWAY_SSL ? 443 : 80)\n const hostname = process.env.GATEWAY_HOSTNAME\n\n return `${protocol}://${hostname}:${port}`\n}\n\nexport const env = { GATEWAY_BASE_URL: GET_GATEWAY_BASE_URL() } as const\n","export function toSnakeCase(str: string) {\n return str\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[^A-Za-z0-9]+/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_+|_+$/g, '')\n .toLowerCase()\n}\n\nexport function toKebabCase(input: string) {\n return input\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/[^A-Za-z0-9]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-+|-+$/g, '')\n .toLowerCase()\n}\n","import { Message, ToolCall } from '@latitude-data/constants/messages'\nimport { FinishReason, TextStreamPart, Tool } from 'ai'\nimport { JSONSchema7 } from 'json-schema'\nimport { z } from 'zod'\nimport { Providers } from '.'\nimport {\n LegacyVercelSDKVersion4Usage as LanguageModelUsage,\n LegacyResponseMessage,\n type ReplaceTextDelta,\n} from './ai/vercelSdkV5ToV4'\nimport { ParameterType } from './config'\nimport { LatitudeEventData } from './events'\nimport { AzureConfig, LatitudePromptConfig } from './latitudePromptSchema'\n\nexport type PromptSource = {\n commitUuid?: string\n documentUuid?: string\n evaluationUuid?: string\n}\n\nexport type AgentToolsMap = Record<string, string> // { [toolName]: agentPath }\n\nexport type ToolDefinition = JSONSchema7 & {\n description: string\n parameters: {\n type: 'object'\n properties: Record<string, JSONSchema7>\n required?: string[]\n additionalProperties: boolean\n }\n}\n\nexport type VercelProviderTool = {\n type: 'provider-defined'\n id: `${string}.${string}`\n name: string\n args: Record<string, unknown>\n inputSchema: Tool['inputSchema']\n}\n\nexport type VercelTools = Record<string, ToolDefinition | VercelProviderTool>\n\nexport type ToolDefinitionsMap = Record<string, ToolDefinition>\nexport type ToolsItem =\n | ToolDefinitionsMap // - tool_name: <tool_definition>\n | string // - latitude/* (no spaces)\n\n// Config supported by Vercel\nexport type VercelConfig = {\n provider: string\n model: string\n url?: string\n cacheControl?: boolean\n schema?: JSONSchema7\n parameters?: Record<string, { type: ParameterType }>\n tools?: VercelTools\n azure?: AzureConfig\n /**\n * DEPRECATED: Legacy before SDK v5. Use `maxOutputTokens` instead.\n */\n maxTokens?: number\n maxOutputTokens?: number\n\n /**\n * Max steps the run can take.\n */\n maxSteps?: number\n}\n\nexport type PartialPromptConfig = Omit<LatitudePromptConfig, 'provider'>\n\nexport type VercelChunk = TextStreamPart<any> // Original Vercel SDK v5 type\n\nexport type ProviderData = ReplaceTextDelta<VercelChunk>\n\nexport type ChainEventDto = ProviderData | LatitudeEventData\n\nexport type AssertedStreamType = 'text' | Record<string | symbol, unknown>\nexport type ChainCallResponseDto<S extends AssertedStreamType = 'text'> =\n S extends 'text'\n ? ChainStepTextResponse\n : S extends Record<string | symbol, unknown>\n ? ChainStepObjectResponse<S>\n : never\n\nexport type ChainEventDtoResponse =\n | Omit<ChainStepResponse<'object'>, 'providerLog'>\n | Omit<ChainStepResponse<'text'>, 'providerLog'>\n\nexport type StreamType = 'object' | 'text'\n\ntype BaseResponse = {\n text: string\n usage: LanguageModelUsage\n documentLogUuid?: string\n model: string\n provider: Providers\n cost: number\n input: Message[]\n output: LegacyResponseMessage[]\n}\n\nexport type ChainStepTextResponse = BaseResponse & {\n streamType: 'text'\n reasoning?: string | undefined\n toolCalls: ToolCall[] | null\n}\n\nexport type ChainStepObjectResponse<S extends Record<string, unknown> = any> =\n BaseResponse & {\n streamType: 'object'\n object: S\n }\n\nexport type ChainStepResponse<T extends StreamType> = T extends 'text'\n ? ChainStepTextResponse\n : T extends 'object'\n ? ChainStepObjectResponse\n : never\n\nexport enum StreamEventTypes {\n Latitude = 'latitude-event',\n Provider = 'provider-event',\n}\n\nexport type RunSyncAPIResponse<S extends AssertedStreamType = 'text'> = {\n uuid: string\n conversation: Message[]\n response: ChainCallResponseDto<S>\n source?: PromptSource\n}\n\nexport type ChatSyncAPIResponse<S extends AssertedStreamType = 'text'> =\n RunSyncAPIResponse<S>\n\nexport const toolCallResponseSchema = z.object({\n id: z.string(),\n name: z.string(),\n result: z.unknown(),\n isError: z.boolean().optional(),\n text: z.string().optional(),\n})\n\nexport type ToolCallResponse = z.infer<typeof toolCallResponseSchema>\n\nexport const FINISH_REASON_DETAILS = {\n stop: {\n name: 'Stop',\n description:\n 'Generation ended naturally, either the model thought it was done, or it emitted a user-supplied stop-sequence, before hitting any limits.',\n },\n length: {\n name: 'Length',\n description:\n 'The model hit a hard token boundary in the overall context window, so output was truncated.',\n },\n 'content-filter': {\n name: 'Content Filter',\n description:\n \"The provider's safety filters flagged part of the prospective text (hate, sexual, self-harm, violence, etc.), so generation was withheld, returning early.\",\n },\n 'tool-calls': {\n name: 'Tool Calls',\n description:\n 'Instead of generating text, the assistant asked for one or more declared tools to run; your code should handle them before asking the model to continue.',\n },\n error: {\n name: 'Error',\n description:\n 'The generation terminated because the provider encountered an error. This could be due to a variety of reasons, including timeouts, server issues, or problems with the input data.',\n },\n other: {\n name: 'Other',\n description:\n 'The generation ended without a specific reason. This could be due to a variety of reasons, including timeouts, server issues, or problems with the input data.',\n },\n unknown: {\n name: 'Unknown',\n description: `The provider returned a finish-reason not yet standardized. Check out the provider's documentation for more information.`,\n },\n} as const satisfies {\n [R in FinishReason]: {\n name: string\n description: string\n }\n}\n\nexport type ToolResultPayload = {\n value: unknown\n isError: boolean\n}\n\nexport * from './ai/vercelSdkV5ToV4'\n\nexport const EMPTY_USAGE = () =>\n ({\n inputTokens: 0,\n outputTokens: 0,\n promptTokens: 0,\n completionTokens: 0,\n totalTokens: 0,\n reasoningTokens: 0,\n cachedInputTokens: 0,\n }) satisfies LanguageModelUsage\n\nexport const languageModelUsageSchema = z.object({\n inputTokens: z.number(),\n outputTokens: z.number(),\n promptTokens: z.number(),\n completionTokens: z.number(),\n totalTokens: z.number(),\n reasoningTokens: z.number(),\n cachedInputTokens: z.number(),\n})\n\nexport function sumUsage(...usages: LanguageModelUsage[]) {\n return usages.reduce(\n (acc, usage) => ({\n inputTokens: acc.inputTokens + usage.inputTokens,\n outputTokens: acc.outputTokens + usage.outputTokens,\n promptTokens: acc.promptTokens + usage.promptTokens,\n completionTokens: acc.completionTokens + usage.completionTokens,\n totalTokens: acc.totalTokens + usage.totalTokens,\n reasoningTokens: acc.reasoningTokens + usage.reasoningTokens,\n cachedInputTokens: acc.cachedInputTokens + usage.cachedInputTokens,\n }),\n EMPTY_USAGE(),\n )\n}\n","export enum ParameterType {\n Text = 'text',\n Image = 'image',\n File = 'file',\n}\n\nexport const AGENT_TOOL_PREFIX = 'lat_agent'\nexport const LATITUDE_TOOL_PREFIX = 'lat_tool'\n\nexport enum LatitudeTool {\n RunCode = 'code',\n WebSearch = 'search',\n WebExtract = 'extract',\n Think = 'think',\n TODO = 'todo',\n}\n\nexport enum LatitudeToolInternalName {\n RunCode = 'lat_tool_run_code',\n WebSearch = 'lat_tool_web_search',\n WebExtract = 'lat_tool_web_extract',\n Think = 'think',\n TODO = 'todo_write',\n}\n\nexport const NOT_SIMULATABLE_LATITUDE_TOOLS = [\n LatitudeTool.Think,\n LatitudeTool.TODO,\n] as LatitudeTool[]\n\nexport const MAX_STEPS_CONFIG_NAME = 'maxSteps'\nexport const DEFAULT_MAX_STEPS = 20\nexport const ABSOLUTE_MAX_STEPS = 150\n\nconst capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1)\n\nexport type DiffValue = {\n newValue?: string\n oldValue?: string\n}\n\nexport const humanizeTool = (tool: string, suffix: boolean = true) => {\n if (tool.startsWith(AGENT_TOOL_PREFIX)) {\n const name = tool.replace(AGENT_TOOL_PREFIX, '').trim().split('_').join(' ')\n return suffix ? `${name} agent` : name\n }\n\n if (tool.startsWith(LATITUDE_TOOL_PREFIX)) {\n const name = tool\n .replace(LATITUDE_TOOL_PREFIX, '')\n .trim()\n .split('_')\n .join(' ')\n return suffix ? `${name} tool` : name\n }\n\n const name = tool.trim().split('_').map(capitalize).join(' ')\n return suffix ? `${name} tool` : name\n}\n","import { z } from 'zod'\n\nconst actualOutputConfiguration = z.object({\n messageSelection: z.enum(['last', 'all']), // Which assistant messages to select\n contentFilter: z\n .enum(['text', 'reasoning', 'image', 'file', 'tool_call'])\n .optional(),\n parsingFormat: z.enum(['string', 'json']),\n fieldAccessor: z.string().optional(), // Field accessor to get the output from if it's a key-value format\n})\nexport type ActualOutputConfiguration = z.infer<\n typeof actualOutputConfiguration\n>\n\nconst expectedOutputConfiguration = z.object({\n parsingFormat: z.enum(['string', 'json']),\n fieldAccessor: z.string().optional(), // Field accessor to get the output from if it's a key-value format\n})\nexport type ExpectedOutputConfiguration = z.infer<\n typeof expectedOutputConfiguration\n>\n\nexport const ACCESSIBLE_OUTPUT_FORMATS = ['json']\n\nexport const EVALUATION_TRIGGER_TARGETS = ['first', 'every', 'last'] as const\nexport type EvaluationTriggerTarget =\n (typeof EVALUATION_TRIGGER_TARGETS)[number]\n\nexport const DEFAULT_LAST_INTERACTION_DEBOUNCE_SECONDS = 120\nexport const LAST_INTERACTION_DEBOUNCE_MIN_SECONDS = 30\nexport const LAST_INTERACTION_DEBOUNCE_MAX_SECONDS = 60 * 60 * 24 // 1 day\n\nexport const DEFAULT_EVALUATION_SAMPLE_RATE = 100\nexport const MIN_EVALUATION_SAMPLE_RATE = 0 // 0%\nexport const MAX_EVALUATION_SAMPLE_RATE = 100 // 100%\n\nconst triggerConfiguration = z.object({\n target: z.enum(EVALUATION_TRIGGER_TARGETS),\n lastInteractionDebounce: z\n .number()\n .min(LAST_INTERACTION_DEBOUNCE_MIN_SECONDS)\n .max(LAST_INTERACTION_DEBOUNCE_MAX_SECONDS)\n .optional(),\n sampleRate: z\n .number()\n .int()\n .min(MIN_EVALUATION_SAMPLE_RATE)\n .max(MAX_EVALUATION_SAMPLE_RATE)\n .optional(),\n})\nexport type TriggerConfiguration = z.infer<typeof triggerConfiguration>\n\nexport const baseEvaluationConfiguration = z.object({\n reverseScale: z.boolean(), // If true, lower is better, otherwise, higher is better\n actualOutput: actualOutputConfiguration,\n expectedOutput: expectedOutputConfiguration.optional(),\n trigger: triggerConfiguration.optional(),\n})\nexport const baseEvaluationResultMetadata = z.object({\n // configuration: Configuration snapshot is defined in every metric specification\n actualOutput: z.string(),\n expectedOutput: z.string().optional(),\n datasetLabel: z.string().optional(),\n})\nexport const baseEvaluationResultError = z.object({\n message: z.string(),\n})\n","import { z } from 'zod'\nimport { EvaluationResultSuccessValue, EvaluationType } from './index'\nimport {\n baseEvaluationConfiguration,\n baseEvaluationResultError,\n baseEvaluationResultMetadata,\n} from './shared'\n\nconst compositeEvaluationConfiguration = baseEvaluationConfiguration.extend({\n evaluationUuids: z.array(z.string()),\n minThreshold: z.number().optional(), // Threshold percentage\n maxThreshold: z.number().optional(), // Threshold percentage\n})\nconst compositeEvaluationResultMetadata = baseEvaluationResultMetadata.extend({\n results: z.record(\n z.string(), // Evaluation uuid\n z.object({\n uuid: z.string(), // Result uuid (for side effects)\n name: z.string(), // Evaluation name\n score: z.number(), // Normalized score\n reason: z.string(),\n passed: z.boolean(),\n tokens: z.number().optional(), // Optional llm evaluation usage\n }),\n ),\n})\nconst compositeEvaluationResultError = baseEvaluationResultError.extend({\n errors: z\n .record(\n z.string(), // Evaluation uuid\n z.object({\n uuid: z.string(), // Result uuid (for side effects)\n name: z.string(), // Evaluation name\n message: z.string(),\n }),\n )\n .optional(),\n})\n\n// AVERAGE\n\nconst compositeEvaluationAverageConfiguration =\n compositeEvaluationConfiguration.extend({})\nconst compositeEvaluationAverageResultMetadata =\n compositeEvaluationResultMetadata.extend({\n configuration: compositeEvaluationAverageConfiguration,\n })\nconst compositeEvaluationAverageResultError =\n compositeEvaluationResultError.extend({})\nexport const CompositeEvaluationAverageSpecification = {\n name: 'Average',\n description: 'Combines scores evenly. The resulting score is the average',\n configuration: compositeEvaluationAverageConfiguration,\n resultMetadata: compositeEvaluationAverageResultMetadata,\n resultError: compositeEvaluationAverageResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Composite,\n CompositeEvaluationMetric.Average\n >,\n ) => {\n let reason = ''\n\n const reasons = Object.entries(result.metadata.results).map(\n ([_, result]) => `${result.name}: ${result.reason}`,\n )\n\n reason = reasons.join('\\n\\n')\n\n return reason\n },\n resultUsage: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Composite,\n CompositeEvaluationMetric.Average\n >,\n ) => {\n return Object.values(result.metadata.results).reduce((acc, result) => {\n return acc + (result.tokens ?? 0)\n }, 0)\n },\n requiresExpectedOutput: false,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type CompositeEvaluationAverageConfiguration = z.infer<\n typeof CompositeEvaluationAverageSpecification.configuration\n>\nexport type CompositeEvaluationAverageResultMetadata = z.infer<\n typeof CompositeEvaluationAverageSpecification.resultMetadata\n>\nexport type CompositeEvaluationAverageResultError = z.infer<\n typeof CompositeEvaluationAverageSpecification.resultError\n>\n\n// WEIGHTED\n\nconst compositeEvaluationWeightedConfiguration =\n compositeEvaluationConfiguration.extend({\n weights: z.record(\n z.string(), // Evaluation uuid\n z.number(), // Weight in percentage\n ),\n })\nconst compositeEvaluationWeightedResultMetadata =\n compositeEvaluationResultMetadata.extend({\n configuration: compositeEvaluationWeightedConfiguration,\n })\nconst compositeEvaluationWeightedResultError =\n compositeEvaluationResultError.extend({})\nexport const CompositeEvaluationWeightedSpecification = {\n name: 'Weighted',\n description:\n 'Combines scores using custom weights. The resulting score is the weighted blend',\n configuration: compositeEvaluationWeightedConfiguration,\n resultMetadata: compositeEvaluationWeightedResultMetadata,\n resultError: compositeEvaluationWeightedResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Composite,\n CompositeEvaluationMetric.Weighted\n >,\n ) => {\n let reason = ''\n\n const reasons = Object.entries(result.metadata.results).map(\n ([_, result]) => `${result.name}: ${result.reason}`,\n )\n\n reason = reasons.join('\\n\\n')\n\n return reason\n },\n resultUsage: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Composite,\n CompositeEvaluationMetric.Weighted\n >,\n ) => {\n return Object.values(result.metadata.results).reduce((acc, result) => {\n return acc + (result.tokens ?? 0)\n }, 0)\n },\n requiresExpectedOutput: false,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type CompositeEvaluationWeightedConfiguration = z.infer<\n typeof CompositeEvaluationWeightedSpecification.configuration\n>\nexport type CompositeEvaluationWeightedResultMetadata = z.infer<\n typeof CompositeEvaluationWeightedSpecification.resultMetadata\n>\nexport type CompositeEvaluationWeightedResultError = z.infer<\n typeof CompositeEvaluationWeightedSpecification.resultError\n>\n\n// CUSTOM\n\nconst compositeEvaluationCustomConfiguration =\n compositeEvaluationConfiguration.extend({\n formula: z.string(),\n })\nconst compositeEvaluationCustomResultMetadata =\n compositeEvaluationResultMetadata.extend({\n configuration: compositeEvaluationCustomConfiguration,\n })\nconst compositeEvaluationCustomResultError =\n compositeEvaluationResultError.extend({})\nexport const CompositeEvaluationCustomSpecification = {\n name: 'Custom',\n description:\n 'Combines scores using a custom formula. The resulting score is the result of the expression',\n configuration: compositeEvaluationCustomConfiguration,\n resultMetadata: compositeEvaluationCustomResultMetadata,\n resultError: compositeEvaluationCustomResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Composite,\n CompositeEvaluationMetric.Custom\n >,\n ) => {\n let reason = ''\n\n const reasons = Object.entries(result.metadata.results).map(\n ([_, result]) => `${result.name}: ${result.reason}`,\n )\n\n reason = reasons.join('\\n\\n')\n\n return reason\n },\n resultUsage: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Composite,\n CompositeEvaluationMetric.Custom\n >,\n ) => {\n return Object.values(result.metadata.results).reduce((acc, result) => {\n return acc + (result.tokens ?? 0)\n }, 0)\n },\n requiresExpectedOutput: false,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type CompositeEvaluationCustomConfiguration = z.infer<\n typeof CompositeEvaluationCustomSpecification.configuration\n>\nexport type CompositeEvaluationCustomResultMetadata = z.infer<\n typeof CompositeEvaluationCustomSpecification.resultMetadata\n>\nexport type CompositeEvaluationCustomResultError = z.infer<\n typeof CompositeEvaluationCustomSpecification.resultError\n>\n\n/* ------------------------------------------------------------------------- */\n\nexport enum CompositeEvaluationMetric {\n Average = 'average',\n Weighted = 'weighted',\n Custom = 'custom',\n}\n\n// prettier-ignore\nexport type CompositeEvaluationConfiguration<M extends CompositeEvaluationMetric = CompositeEvaluationMetric> =\n M extends CompositeEvaluationMetric.Average ? CompositeEvaluationAverageConfiguration :\n M extends CompositeEvaluationMetric.Weighted ? CompositeEvaluationWeightedConfiguration :\n M extends CompositeEvaluationMetric.Custom ? CompositeEvaluationCustomConfiguration :\n never;\n\n// prettier-ignore\nexport type CompositeEvaluationResultMetadata<M extends CompositeEvaluationMetric = CompositeEvaluationMetric> = \n M extends CompositeEvaluationMetric.Average ? CompositeEvaluationAverageResultMetadata :\n M extends CompositeEvaluationMetric.Weighted ? CompositeEvaluationWeightedResultMetadata :\n M extends CompositeEvaluationMetric.Custom ? CompositeEvaluationCustomResultMetadata :\n never;\n\n// prettier-ignore\nexport type CompositeEvaluationResultError<M extends CompositeEvaluationMetric = CompositeEvaluationMetric> = \n M extends CompositeEvaluationMetric.Average ? CompositeEvaluationAverageResultError :\n M extends CompositeEvaluationMetric.Weighted ? CompositeEvaluationWeightedResultError :\n M extends CompositeEvaluationMetric.Custom ? CompositeEvaluationCustomResultError :\n never;\n\nexport const CompositeEvaluationSpecification = {\n name: 'Composite Score',\n description: 'Evaluate responses combining several evaluations at once',\n configuration: compositeEvaluationConfiguration,\n resultMetadata: compositeEvaluationResultMetadata,\n resultError: compositeEvaluationResultError,\n // prettier-ignore\n metrics: {\n [CompositeEvaluationMetric.Average]: CompositeEvaluationAverageSpecification,\n [CompositeEvaluationMetric.Weighted]: CompositeEvaluationWeightedSpecification,\n [CompositeEvaluationMetric.Custom]: CompositeEvaluationCustomSpecification,\n },\n} as const\n","import { z } from 'zod'\nimport { EvaluationResultSuccessValue, EvaluationType } from './index'\nimport {\n baseEvaluationConfiguration,\n baseEvaluationResultError,\n baseEvaluationResultMetadata,\n} from './shared'\n\nconst selectedContextSchema = z.object({\n messageIndex: z.number().int().nonnegative(),\n contentBlockIndex: z.number().int().nonnegative(),\n contentType: z.enum([\n 'text',\n 'reasoning',\n 'image',\n 'file',\n 'tool-call',\n 'tool-result',\n ]),\n textRange: z\n .object({\n start: z.number().int().nonnegative(),\n end: z.number().int().nonnegative(),\n })\n .optional(),\n selectedText: z.string().optional(),\n toolCallId: z.string().optional(),\n})\n\nexport type SelectedContext = z.infer<typeof selectedContextSchema>\n\nconst humanEvaluationConfiguration = baseEvaluationConfiguration.extend({\n enableControls: z.boolean().optional(), // UI annotation controls\n criteria: z.string().optional(),\n})\nconst humanEvaluationResultMetadata = baseEvaluationResultMetadata.extend({\n reason: z.string().optional(),\n enrichedReason: z.string().optional(),\n selectedContexts: z.array(selectedContextSchema).optional(),\n})\nconst humanEvaluationResultError = baseEvaluationResultError.extend({})\n\n// BINARY\n\nconst humanEvaluationBinaryConfiguration = humanEvaluationConfiguration.extend({\n passDescription: z.string().optional(),\n failDescription: z.string().optional(),\n})\nconst humanEvaluationBinaryResultMetadata =\n humanEvaluationResultMetadata.extend({\n configuration: humanEvaluationBinaryConfiguration,\n })\nconst humanEvaluationBinaryResultError = humanEvaluationResultError.extend({})\nexport const HumanEvaluationBinarySpecification = {\n name: 'Binary',\n description:\n 'Judges whether the response meets the criteria. The resulting score is \"passed\" or \"failed\"',\n configuration: humanEvaluationBinaryConfiguration,\n resultMetadata: humanEvaluationBinaryResultMetadata,\n resultError: humanEvaluationBinaryResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Human,\n HumanEvaluationMetric.Binary\n >,\n ) => result.metadata.reason,\n requiresExpectedOutput: false,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: false,\n supportsManualEvaluation: true,\n} as const\nexport type HumanEvaluationBinaryConfiguration = z.infer<\n typeof HumanEvaluationBinarySpecification.configuration\n>\nexport type HumanEvaluationBinaryResultMetadata = z.infer<\n typeof HumanEvaluationBinarySpecification.resultMetadata\n>\nexport type HumanEvaluationBinaryResultError = z.infer<\n typeof HumanEvaluationBinarySpecification.resultError\n>\n\n// RATING\n\nconst humanEvaluationRatingConfiguration = humanEvaluationConfiguration.extend({\n minRating: z.number(),\n minRatingDescription: z.string().optional(),\n maxRating: z.number(),\n maxRatingDescription: z.string().optional(),\n minThreshold: z.number().optional(), // Threshold in rating range\n maxThreshold: z.number().optional(), // Threshold in rating range\n})\nconst humanEvaluationRatingResultMetadata =\n humanEvaluationResultMetadata.extend({\n configuration: humanEvaluationRatingConfiguration,\n })\nconst humanEvaluationRatingResultError = humanEvaluationResultError.extend({})\nexport const HumanEvaluationRatingSpecification = {\n name: 'Rating',\n description:\n 'Judges the response by rating it under a criteria. The resulting score is the rating',\n configuration: humanEvaluationRatingConfiguration,\n resultMetadata: humanEvaluationRatingResultMetadata,\n resultError: humanEvaluationRatingResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Human,\n HumanEvaluationMetric.Rating\n >,\n ) => result.metadata.reason,\n requiresExpectedOutput: false,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: false,\n supportsManualEvaluation: true,\n} as const\nexport type HumanEvaluationRatingConfiguration = z.infer<\n typeof HumanEvaluationRatingSpecification.configuration\n>\nexport type HumanEvaluationRatingResultMetadata = z.infer<\n typeof HumanEvaluationRatingSpecification.resultMetadata\n>\nexport type HumanEvaluationRatingResultError = z.infer<\n typeof HumanEvaluationRatingSpecification.resultError\n>\n\n/* ------------------------------------------------------------------------- */\n\nexport enum HumanEvaluationMetric {\n Binary = 'binary',\n Rating = 'rating',\n}\n\n// prettier-ignore\nexport type HumanEvaluationConfiguration<M extends HumanEvaluationMetric = HumanEvaluationMetric> =\n M extends HumanEvaluationMetric.Binary ? HumanEvaluationBinaryConfiguration :\n M extends HumanEvaluationMetric.Rating ? HumanEvaluationRatingConfiguration :\n never;\n\n// prettier-ignore\nexport type HumanEvaluationResultMetadata<M extends HumanEvaluationMetric = HumanEvaluationMetric> =\n M extends HumanEvaluationMetric.Binary ? HumanEvaluationBinaryResultMetadata :\n M extends HumanEvaluationMetric.Rating ? HumanEvaluationRatingResultMetadata :\n never;\n\n// prettier-ignore\nexport type HumanEvaluationResultError<M extends HumanEvaluationMetric = HumanEvaluationMetric> =\n M extends HumanEvaluationMetric.Binary ? HumanEvaluationBinaryResultError :\n M extends HumanEvaluationMetric.Rating ? HumanEvaluationRatingResultError :\n never;\n\nexport const HumanEvaluationSpecification = {\n name: 'Human-in-the-Loop',\n description: 'Evaluate responses using a human as a judge',\n configuration: humanEvaluationConfiguration,\n resultMetadata: humanEvaluationResultMetadata,\n resultError: humanEvaluationResultError,\n // prettier-ignore\n metrics: {\n [HumanEvaluationMetric.Binary]: HumanEvaluationBinarySpecification,\n [HumanEvaluationMetric.Rating]: HumanEvaluationRatingSpecification,\n },\n} as const\n","import { z } from 'zod'\nimport { EvaluationResultSuccessValue, EvaluationType } from './index'\nimport {\n baseEvaluationConfiguration,\n baseEvaluationResultError,\n baseEvaluationResultMetadata,\n} from './shared'\n\nconst llmEvaluationConfiguration = baseEvaluationConfiguration.extend({\n provider: z.string(),\n model: z.string(),\n})\nconst llmEvaluationResultMetadata = baseEvaluationResultMetadata.extend({\n evaluationLogId: z.number(),\n reason: z.string(),\n tokens: z.number(),\n cost: z.number(),\n duration: z.number(),\n})\nconst llmEvaluationResultError = baseEvaluationResultError.extend({\n runErrorId: z.number().optional(),\n})\n\n// BINARY\n\nconst llmEvaluationBinaryConfiguration = llmEvaluationConfiguration.extend({\n criteria: z.string(),\n passDescription: z.string(),\n failDescription: z.string(),\n})\nconst llmEvaluationBinaryResultMetadata = llmEvaluationResultMetadata.extend({\n configuration: llmEvaluationBinaryConfiguration,\n})\nconst llmEvaluationBinaryResultError = llmEvaluationResultError.extend({})\nexport const LlmEvaluationBinarySpecification = {\n name: 'Binary',\n description:\n 'Judges whether the response meets the criteria. The resulting score is \"passed\" or \"failed\"',\n configuration: llmEvaluationBinaryConfiguration,\n resultMetadata: llmEvaluationBinaryResultMetadata,\n resultError: llmEvaluationBinaryResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Llm,\n LlmEvaluationMetric.Binary\n >,\n ) => result.metadata.reason,\n resultUsage: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Llm,\n LlmEvaluationMetric.Binary\n >,\n ) => result.metadata.tokens,\n requiresExpectedOutput: false,\n supportsLiveEvaluation: true,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type LlmEvaluationBinaryConfiguration = z.infer<\n typeof LlmEvaluationBinarySpecification.configuration\n>\nexport type LlmEvaluationBinaryResultMetadata = z.infer<\n typeof LlmEvaluationBinarySpecification.resultMetadata\n>\nexport type LlmEvaluationBinaryResultError = z.infer<\n typeof LlmEvaluationBinarySpecification.resultError\n>\n\n// RATING\n\nconst llmEvaluationRatingConfiguration = llmEvaluationConfiguration.extend({\n criteria: z.string(),\n minRating: z.number(),\n minRatingDescription: z.string(),\n maxRating: z.number(),\n maxRatingDescription: z.string(),\n minThreshold: z.number().optional(), // Threshold in rating range\n maxThreshold: z.number().optional(), // Threshold in rating range\n})\nconst llmEvaluationRatingResultMetadata = llmEvaluationResultMetadata.extend({\n configuration: llmEvaluationRatingConfiguration,\n})\nconst llmEvaluationRatingResultError = llmEvaluationResultError.extend({})\nexport const LlmEvaluationRatingSpecification = {\n name: 'Rating',\n description:\n 'Judges the response by rating it under a criteria. The resulting score is the rating',\n configuration: llmEvaluationRatingConfiguration,\n resultMetadata: llmEvaluationRatingResultMetadata,\n resultError: llmEvaluationRatingResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Llm,\n LlmEvaluationMetric.Rating\n >,\n ) => result.metadata.reason,\n resultUsage: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Llm,\n LlmEvaluationMetric.Rating\n >,\n ) => result.metadata.tokens,\n requiresExpectedOutput: false,\n supportsLiveEvaluation: true,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type LlmEvaluationRatingConfiguration = z.infer<\n typeof LlmEvaluationRatingSpecification.configuration\n>\nexport type LlmEvaluationRatingResultMetadata = z.infer<\n typeof LlmEvaluationRatingSpecification.resultMetadata\n>\nexport type LlmEvaluationRatingResultError = z.infer<\n typeof LlmEvaluationRatingSpecification.resultError\n>\n\n// COMPARISON\n\nconst llmEvaluationComparisonConfiguration = llmEvaluationConfiguration.extend({\n criteria: z.string(),\n passDescription: z.string(),\n failDescription: z.string(),\n minThreshold: z.number().optional(), // Threshold percentage\n maxThreshold: z.number().optional(), // Threshold percentage\n})\nconst llmEvaluationComparisonResultMetadata =\n llmEvaluationResultMetadata.extend({\n configuration: llmEvaluationComparisonConfiguration,\n })\nconst llmEvaluationComparisonResultError = llmEvaluationResultError.extend({})\nexport const LlmEvaluationComparisonSpecification = {\n name: 'Comparison',\n description:\n 'Judges the response by comparing the criteria to the expected output. The resulting score is the percentage of compared criteria that is met',\n configuration: llmEvaluationComparisonConfiguration,\n resultMetadata: llmEvaluationComparisonResultMetadata,\n resultError: llmEvaluationComparisonResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Llm,\n LlmEvaluationMetric.Comparison\n >,\n ) => result.metadata.reason,\n resultUsage: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Llm,\n LlmEvaluationMetric.Comparison\n >,\n ) => result.metadata.tokens,\n requiresExpectedOutput: true,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type LlmEvaluationComparisonConfiguration = z.infer<\n typeof LlmEvaluationComparisonSpecification.configuration\n>\nexport type LlmEvaluationComparisonResultMetadata = z.infer<\n typeof LlmEvaluationComparisonSpecification.resultMetadata\n>\nexport type LlmEvaluationComparisonResultError = z.infer<\n typeof LlmEvaluationComparisonSpecification.resultError\n>\n\n// CUSTOM\n\nconst llmEvaluationCustomConfiguration = llmEvaluationConfiguration.extend({\n prompt: z.string(),\n minScore: z.number(),\n maxScore: z.number(),\n minThreshold: z.number().optional(), // Threshold percentage\n maxThreshold: z.number().optional(), // Threshold percentage\n})\nconst llmEvaluationCustomResultMetadata = llmEvaluationResultMetadata.extend({\n configuration: llmEvaluationCustomConfiguration,\n})\nconst llmEvaluationCustomResultError = llmEvaluationResultError.extend({})\nexport const LlmEvaluationCustomSpecification = {\n name: 'Custom',\n description:\n 'Judges the response under a criteria using a custom prompt. The resulting score is the value of criteria that is met',\n configuration: llmEvaluationCustomConfiguration,\n resultMetadata: llmEvaluationCustomResultMetadata,\n resultError: llmEvaluationCustomResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Llm,\n LlmEvaluationMetric.Custom\n >,\n ) => result.metadata.reason,\n resultUsage: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Llm,\n LlmEvaluationMetric.Custom\n >,\n ) => result.metadata.tokens,\n requiresExpectedOutput: false,\n supportsLiveEvaluation: true,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type LlmEvaluationCustomConfiguration = z.infer<\n typeof LlmEvaluationCustomSpecification.configuration\n>\nexport type LlmEvaluationCustomResultMetadata = z.infer<\n typeof LlmEvaluationCustomSpecification.resultMetadata\n>\nexport type LlmEvaluationCustomResultError = z.infer<\n typeof LlmEvaluationCustomSpecification.resultError\n>\n\nexport const LLM_EVALUATION_CUSTOM_PROMPT_DOCUMENTATION = `\n/*\n IMPORTANT: The evaluation MUST return an object with the score and reason fields.\n\n These are the available variables:\n - {{ actualOutput }} (string): The actual output to evaluate\n - {{ expectedOutput }} (string/undefined): The, optional, expected output to compare against\n - {{ conversation }} (string): The full conversation of the evaluated trace\n\n - {{ cost }} (number): The cost, in millicents, of the evaluated trace\n - {{ tokens }} (object): The token usage of the evaluated trace ({ prompt, cached, reasoning, completion })\n - {{ duration }} (number): The duration, in milliseconds, of the evaluated trace\n\n - {{ prompt }} (string): The prompt of the evaluated trace\n - {{ parameters }} (object): The parameters of the evaluated trace\n*/\n`.trim()\n\n// CUSTOM LABELED\n\nexport const LlmEvaluationCustomLabeledSpecification = {\n ...LlmEvaluationCustomSpecification,\n name: 'Custom (Labeled)',\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Llm,\n LlmEvaluationMetric.CustomLabeled\n >,\n ) => result.metadata.reason,\n resultUsage: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Llm,\n LlmEvaluationMetric.CustomLabeled\n >,\n ) => result.metadata.tokens,\n requiresExpectedOutput: true,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\n\n/* ------------------------------------------------------------------------- */\n\nexport enum LlmEvaluationMetric {\n Binary = 'binary',\n Rating = 'rating',\n Comparison = 'comparison',\n Custom = 'custom',\n CustomLabeled = 'custom_labeled',\n}\n\nexport type LlmEvaluationMetricAnyCustom =\n | LlmEvaluationMetric.Custom\n | LlmEvaluationMetric.CustomLabeled\n\n// prettier-ignore\nexport type LlmEvaluationConfiguration<M extends LlmEvaluationMetric = LlmEvaluationMetric> =\n M extends LlmEvaluationMetric.Binary ? LlmEvaluationBinaryConfiguration :\n M extends LlmEvaluationMetric.Rating ? LlmEvaluationRatingConfiguration :\n M extends LlmEvaluationMetric.Comparison ? LlmEvaluationComparisonConfiguration :\n M extends LlmEvaluationMetric.Custom ? LlmEvaluationCustomConfiguration :\n M extends LlmEvaluationMetric.CustomLabeled ? LlmEvaluationCustomConfiguration :\n never;\n\n// prettier-ignore\nexport type LlmEvaluationResultMetadata<M extends LlmEvaluationMetric = LlmEvaluationMetric> =\n M extends LlmEvaluationMetric.Binary ? LlmEvaluationBinaryResultMetadata :\n M extends LlmEvaluationMetric.Rating ? LlmEvaluationRatingResultMetadata :\n M extends LlmEvaluationMetric.Comparison ? LlmEvaluationComparisonResultMetadata :\n M extends LlmEvaluationMetric.Custom ? LlmEvaluationCustomResultMetadata :\n M extends LlmEvaluationMetric.CustomLabeled ? LlmEvaluationCustomResultMetadata :\n never;\n\n// prettier-ignore\nexport type LlmEvaluationResultError<M extends LlmEvaluationMetric = LlmEvaluationMetric> =\n M extends LlmEvaluationMetric.Binary ? LlmEvaluationBinaryResultError :\n M extends LlmEvaluationMetric.Rating ? LlmEvaluationRatingResultError :\n M extends LlmEvaluationMetric.Comparison ? LlmEvaluationComparisonResultError :\n M extends LlmEvaluationMetric.Custom ? LlmEvaluationCustomResultError :\n M extends LlmEvaluationMetric.CustomLabeled ? LlmEvaluationCustomResultError :\n never;\n\nexport const LlmEvaluationSpecification = {\n name: 'LLM-as-a-Judge',\n description: 'Evaluate responses using an LLM as a judge',\n configuration: llmEvaluationConfiguration,\n resultMetadata: llmEvaluationResultMetadata,\n resultError: llmEvaluationResultError,\n // prettier-ignore\n metrics: {\n [LlmEvaluationMetric.Binary]: LlmEvaluationBinarySpecification,\n [LlmEvaluationMetric.Rating]: LlmEvaluationRatingSpecification,\n [LlmEvaluationMetric.Comparison]: LlmEvaluationComparisonSpecification,\n [LlmEvaluationMetric.Custom]: LlmEvaluationCustomSpecification,\n [LlmEvaluationMetric.CustomLabeled]: LlmEvaluationCustomLabeledSpecification,\n },\n} as const\n\nexport const LLM_EVALUATION_PROMPT_PARAMETERS = [\n 'actualOutput',\n 'expectedOutput',\n 'conversation',\n 'tokens',\n 'cost',\n 'duration',\n 'prompt',\n 'parameters',\n] as const\n\nexport type LlmEvaluationPromptParameter =\n (typeof LLM_EVALUATION_PROMPT_PARAMETERS)[number]\n","import { z } from 'zod'\nimport { EvaluationResultSuccessValue, EvaluationType } from './index'\nimport {\n baseEvaluationConfiguration,\n baseEvaluationResultError,\n baseEvaluationResultMetadata,\n} from './shared'\n\nconst ruleEvaluationConfiguration = baseEvaluationConfiguration.extend({})\nconst ruleEvaluationResultMetadata = baseEvaluationResultMetadata.extend({\n reason: z.string().optional(),\n})\nconst ruleEvaluationResultError = baseEvaluationResultError.extend({})\n\n// EXACT MATCH\n\nconst ruleEvaluationExactMatchConfiguration =\n ruleEvaluationConfiguration.extend({\n caseInsensitive: z.boolean(),\n })\nconst ruleEvaluationExactMatchResultMetadata =\n ruleEvaluationResultMetadata.extend({\n configuration: ruleEvaluationExactMatchConfiguration,\n })\nconst ruleEvaluationExactMatchResultError = ruleEvaluationResultError.extend({})\nexport const RuleEvaluationExactMatchSpecification = {\n name: 'Exact Match',\n description:\n 'Checks if the response is exactly the same as the expected output. The resulting score is \"matched\" or \"unmatched\"',\n configuration: ruleEvaluationExactMatchConfiguration,\n resultMetadata: ruleEvaluationExactMatchResultMetadata,\n resultError: ruleEvaluationExactMatchResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Rule,\n RuleEvaluationMetric.ExactMatch\n >,\n ) => {\n let reason = ''\n\n if (result.score === 1) {\n reason = `Response is`\n } else {\n reason = `Response is not`\n }\n\n reason += ` exactly the same as '${result.metadata.expectedOutput}'`\n\n if (result.metadata.configuration.caseInsensitive) {\n reason += ' (comparison is case-insensitive)'\n }\n\n if (result.metadata.reason) {\n reason += `, because: ${result.metadata.reason}`\n }\n\n return reason + '.'\n },\n requiresExpectedOutput: true,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type RuleEvaluationExactMatchConfiguration = z.infer<\n typeof RuleEvaluationExactMatchSpecification.configuration\n>\nexport type RuleEvaluationExactMatchResultMetadata = z.infer<\n typeof RuleEvaluationExactMatchSpecification.resultMetadata\n>\nexport type RuleEvaluationExactMatchResultError = z.infer<\n typeof RuleEvaluationExactMatchSpecification.resultError\n>\n\n// REGULAR EXPRESSION\n\nconst ruleEvaluationRegularExpressionConfiguration =\n ruleEvaluationConfiguration.extend({\n pattern: z.string(),\n })\nconst ruleEvaluationRegularExpressionResultMetadata =\n ruleEvaluationResultMetadata.extend({\n configuration: ruleEvaluationRegularExpressionConfiguration,\n })\nconst ruleEvaluationRegularExpressionResultError =\n ruleEvaluationResultError.extend({})\nexport const RuleEvaluationRegularExpressionSpecification = {\n name: 'Regular Expression',\n description:\n 'Checks if the response matches the regular expression. The resulting score is \"matched\" or \"unmatched\"',\n configuration: ruleEvaluationRegularExpressionConfiguration,\n resultMetadata: ruleEvaluationRegularExpressionResultMetadata,\n resultError: ruleEvaluationRegularExpressionResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Rule,\n RuleEvaluationMetric.RegularExpression\n >,\n ) => {\n let reason = ''\n\n if (result.score === 1) {\n reason = `Response matches`\n } else {\n reason = `Response does not match`\n }\n\n reason += ` the regular expression \\`/${result.metadata.configuration.pattern}/gm\\``\n\n if (result.metadata.reason) {\n reason += `, because: ${result.metadata.reason}`\n }\n\n return reason + '.'\n },\n requiresExpectedOutput: false,\n supportsLiveEvaluation: true,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type RuleEvaluationRegularExpressionConfiguration = z.infer<\n typeof RuleEvaluationRegularExpressionSpecification.configuration\n>\nexport type RuleEvaluationRegularExpressionResultMetadata = z.infer<\n typeof RuleEvaluationRegularExpressionSpecification.resultMetadata\n>\nexport type RuleEvaluationRegularExpressionResultError = z.infer<\n typeof RuleEvaluationRegularExpressionSpecification.resultError\n>\n\n// SCHEMA VALIDATION\n\nconst ruleEvaluationSchemaValidationConfiguration =\n ruleEvaluationConfiguration.extend({\n format: z.enum(['json']),\n schema: z.string(),\n })\nconst ruleEvaluationSchemaValidationResultMetadata =\n ruleEvaluationResultMetadata.extend({\n configuration: ruleEvaluationSchemaValidationConfiguration,\n })\nconst ruleEvaluationSchemaValidationResultError =\n ruleEvaluationResultError.extend({})\nexport const RuleEvaluationSchemaValidationSpecification = {\n name: 'Schema Validation',\n description:\n 'Checks if the response follows the schema. The resulting score is \"valid\" or \"invalid\"',\n configuration: ruleEvaluationSchemaValidationConfiguration,\n resultMetadata: ruleEvaluationSchemaValidationResultMetadata,\n resultError: ruleEvaluationSchemaValidationResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Rule,\n RuleEvaluationMetric.SchemaValidation\n >,\n ) => {\n let reason = ''\n\n if (result.score === 1) {\n reason = `Response follows`\n } else {\n reason = `Response does not follow`\n }\n\n reason += ` the ${result.metadata.configuration.format.toUpperCase()} schema:\\n\\`\\`\\`\\n${result.metadata.configuration.schema}\\n\\`\\`\\``\n\n if (result.metadata.reason) {\n reason += `\\nbecause: ${result.metadata.reason}`\n }\n\n return reason + '.'\n },\n requiresExpectedOutput: false,\n supportsLiveEvaluation: true,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type RuleEvaluationSchemaValidationConfiguration = z.infer<\n typeof RuleEvaluationSchemaValidationSpecification.configuration\n>\nexport type RuleEvaluationSchemaValidationResultMetadata = z.infer<\n typeof RuleEvaluationSchemaValidationSpecification.resultMetadata\n>\nexport type RuleEvaluationSchemaValidationResultError = z.infer<\n typeof RuleEvaluationSchemaValidationSpecification.resultError\n>\n\n// LENGTH COUNT\n\nconst ruleEvaluationLengthCountConfiguration =\n ruleEvaluationConfiguration.extend({\n algorithm: z.enum(['character', 'word', 'sentence']),\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n })\nconst ruleEvaluationLengthCountResultMetadata =\n ruleEvaluationResultMetadata.extend({\n configuration: ruleEvaluationLengthCountConfiguration,\n })\nconst ruleEvaluationLengthCountResultError = ruleEvaluationResultError.extend(\n {},\n)\nexport const RuleEvaluationLengthCountSpecification = {\n name: 'Length Count',\n description:\n 'Checks if the response is of a certain length. The resulting score is the length of the response',\n configuration: ruleEvaluationLengthCountConfiguration,\n resultMetadata: ruleEvaluationLengthCountResultMetadata,\n resultError: ruleEvaluationLengthCountResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Rule,\n RuleEvaluationMetric.LengthCount\n >,\n ) => {\n let reason = `Response length is ${result.score} ${result.metadata.configuration.algorithm}s`\n\n if (result.hasPassed) {\n reason += ', which is'\n } else {\n reason += ', which is not'\n }\n\n reason += ` between ${result.metadata.configuration.minLength ?? 0} and ${result.metadata.configuration.maxLength ?? Infinity} ${result.metadata.configuration.algorithm}s`\n\n if (result.metadata.configuration.reverseScale) {\n reason += ' (shorter is better)'\n } else {\n reason += ' (longer is better)'\n }\n\n if (result.metadata.reason) {\n reason += `, because: ${result.metadata.reason}`\n }\n\n return reason + '.'\n },\n requiresExpectedOutput: false,\n supportsLiveEvaluation: true,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type RuleEvaluationLengthCountConfiguration = z.infer<\n typeof RuleEvaluationLengthCountSpecification.configuration\n>\nexport type RuleEvaluationLengthCountResultMetadata = z.infer<\n typeof RuleEvaluationLengthCountSpecification.resultMetadata\n>\nexport type RuleEvaluationLengthCountResultError = z.infer<\n typeof RuleEvaluationLengthCountSpecification.resultError\n>\n\n// LEXICAL OVERLAP\n\nconst ruleEvaluationLexicalOverlapConfiguration =\n ruleEvaluationConfiguration.extend({\n algorithm: z.enum(['substring', 'levenshtein_distance', 'rouge']),\n minOverlap: z.number().optional(), // Percentage of overlap\n maxOverlap: z.number().optional(), // Percentage of overlap\n })\nconst ruleEvaluationLexicalOverlapResultMetadata =\n ruleEvaluationResultMetadata.extend({\n configuration: ruleEvaluationLexicalOverlapConfiguration,\n })\nconst ruleEvaluationLexicalOverlapResultError =\n ruleEvaluationResultError.extend({})\nexport const RuleEvaluationLexicalOverlapSpecification = {\n name: 'Lexical Overlap',\n description:\n 'Checks if the response contains the expected output. The resulting score is the percentage of overlap',\n configuration: ruleEvaluationLexicalOverlapConfiguration,\n resultMetadata: ruleEvaluationLexicalOverlapResultMetadata,\n resultError: ruleEvaluationLexicalOverlapResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Rule,\n RuleEvaluationMetric.LexicalOverlap\n >,\n ) => {\n let reason = `Response lexical overlap with '${result.metadata.expectedOutput}' is ${result.score.toFixed(0)}%`\n\n if (result.hasPassed) {\n reason += ', which is'\n } else {\n reason += ', which is not'\n }\n\n reason += ` between ${(result.metadata.configuration.minOverlap ?? 0).toFixed(0)}% and ${(result.metadata.configuration.maxOverlap ?? 100).toFixed(0)}%`\n\n if (result.metadata.configuration.reverseScale) {\n reason += ' (lower is better)'\n } else {\n reason += ' (higher is better)'\n }\n\n if (result.metadata.reason) {\n reason += `, because: ${result.metadata.reason}`\n }\n\n return reason + '.'\n },\n requiresExpectedOutput: true,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type RuleEvaluationLexicalOverlapConfiguration = z.infer<\n typeof RuleEvaluationLexicalOverlapSpecification.configuration\n>\nexport type RuleEvaluationLexicalOverlapResultMetadata = z.infer<\n typeof RuleEvaluationLexicalOverlapSpecification.resultMetadata\n>\nexport type RuleEvaluationLexicalOverlapResultError = z.infer<\n typeof RuleEvaluationLexicalOverlapSpecification.resultError\n>\n\n// SEMANTIC SIMILARITY\n\nconst ruleEvaluationSemanticSimilarityConfiguration =\n ruleEvaluationConfiguration.extend({\n algorithm: z.enum(['cosine_distance']),\n minSimilarity: z.number().optional(), // Percentage of similarity\n maxSimilarity: z.number().optional(), // Percentage of similarity\n })\nconst ruleEvaluationSemanticSimilarityResultMetadata =\n ruleEvaluationResultMetadata.extend({\n configuration: ruleEvaluationSemanticSimilarityConfiguration,\n })\nconst ruleEvaluationSemanticSimilarityResultError =\n ruleEvaluationResultError.extend({})\nexport const RuleEvaluationSemanticSimilaritySpecification = {\n name: 'Semantic Similarity',\n description:\n 'Checks if the response is semantically similar to the expected output. The resulting score is the percentage of similarity',\n configuration: ruleEvaluationSemanticSimilarityConfiguration,\n resultMetadata: ruleEvaluationSemanticSimilarityResultMetadata,\n resultError: ruleEvaluationSemanticSimilarityResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Rule,\n RuleEvaluationMetric.SemanticSimilarity\n >,\n ) => {\n let reason = `Response semantic similarity with '${result.metadata.expectedOutput}' is ${result.score.toFixed(0)}%`\n\n if (result.hasPassed) {\n reason += ', which is'\n } else {\n reason += ', which is not'\n }\n\n reason += ` between ${(result.metadata.configuration.minSimilarity ?? 0).toFixed(0)}% and ${(result.metadata.configuration.maxSimilarity ?? 100).toFixed(0)}%`\n\n if (result.metadata.configuration.reverseScale) {\n reason += ' (lower is better)'\n } else {\n reason += ' (higher is better)'\n }\n\n if (result.metadata.reason) {\n reason += `, because: ${result.metadata.reason}`\n }\n\n return reason + '.'\n },\n requiresExpectedOutput: true,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type RuleEvaluationSemanticSimilarityConfiguration = z.infer<\n typeof RuleEvaluationSemanticSimilaritySpecification.configuration\n>\nexport type RuleEvaluationSemanticSimilarityResultMetadata = z.infer<\n typeof RuleEvaluationSemanticSimilaritySpecification.resultMetadata\n>\nexport type RuleEvaluationSemanticSimilarityResultError = z.infer<\n typeof RuleEvaluationSemanticSimilaritySpecification.resultError\n>\n\n// NUMERIC SIMILARITY\n\nconst ruleEvaluationNumericSimilarityConfiguration =\n ruleEvaluationConfiguration.extend({\n algorithm: z.enum(['relative_difference']),\n minSimilarity: z.number().optional(), // Percentage of similarity\n maxSimilarity: z.number().optional(), // Percentage of similarity\n })\nconst ruleEvaluationNumericSimilarityResultMetadata =\n ruleEvaluationResultMetadata.extend({\n configuration: ruleEvaluationNumericSimilarityConfiguration,\n })\nconst ruleEvaluationNumericSimilarityResultError =\n ruleEvaluationResultError.extend({})\nexport const RuleEvaluationNumericSimilaritySpecification = {\n name: 'Numeric Similarity',\n description:\n 'Checks if the response is numerically similar to the expected output. The resulting score is the percentage of similarity',\n configuration: ruleEvaluationNumericSimilarityConfiguration,\n resultMetadata: ruleEvaluationNumericSimilarityResultMetadata,\n resultError: ruleEvaluationNumericSimilarityResultError,\n resultReason: (\n result: EvaluationResultSuccessValue<\n EvaluationType.Rule,\n RuleEvaluationMetric.NumericSimilarity\n >,\n ) => {\n let reason = `Response numeric similarity with '${result.metadata.expectedOutput}' is ${result.score.toFixed(0)}%`\n\n if (result.hasPassed) {\n reason += ', which is'\n } else {\n reason += ', which is not'\n }\n\n reason += ` between ${(result.metadata.configuration.minSimilarity ?? 0).toFixed(0)}% and ${(result.metadata.configuration.maxSimilarity ?? 100).toFixed(0)}%`\n\n if (result.metadata.configuration.reverseScale) {\n reason += ' (lower is better)'\n } else {\n reason += ' (higher is better)'\n }\n\n if (result.metadata.reason) {\n reason += `, because: ${result.metadata.reason}`\n }\n\n return reason + '.'\n },\n requiresExpectedOutput: true,\n supportsLiveEvaluation: false,\n supportsBatchEvaluation: true,\n supportsManualEvaluation: false,\n} as const\nexport type RuleEvaluationNumericSimilarityConfiguration = z.infer<\n typeof RuleEvaluationNumericSimilaritySpecification.configuration\n>\nexport type RuleEvaluationNumericSimilarityResultMetadata = z.infer<\n typeof RuleEvaluationNumericSimilaritySpecification.resultMetadata\n>\nexport type RuleEvaluationNumericSimilarityResultError = z.infer<\n typeof RuleEvaluationNumericSimilaritySpecification.resultError\n>\n\n/* ------------------------------------------------------------------------- */\n\nexport enum RuleEvaluationMetric {\n ExactMatch = 'exact_match',\n RegularExpression = 'regular_expression',\n SchemaValidation = 'schema_validation',\n LengthCount = 'length_count',\n LexicalOverlap = 'lexical_overlap',\n SemanticSimilarity = 'semantic_similarity',\n NumericSimilarity = 'numeric_similarity',\n}\n\n// prettier-ignore\nexport type RuleEvaluationConfiguration<M extends RuleEvaluationMetric = RuleEvaluationMetric> = \n M extends RuleEvaluationMetric.ExactMatch ? RuleEvaluationExactMatchConfiguration :\n M extends RuleEvaluationMetric.RegularExpression ? RuleEvaluationRegularExpressionConfiguration :\n M extends RuleEvaluationMetric.SchemaValidation ? RuleEvaluationSchemaValidationConfiguration :\n M extends RuleEvaluationMetric.LengthCount ? RuleEvaluationLengthCountConfiguration :\n M extends RuleEvaluationMetric.LexicalOverlap ? RuleEvaluationLexicalOverlapConfiguration :\n M extends RuleEvaluationMetric.SemanticSimilarity ? RuleEvaluationSemanticSimilarityConfiguration :\n M extends RuleEvaluationMetric.NumericSimilarity ? RuleEvaluationNumericSimilarityConfiguration :\n never;\n\n// prettier-ignore\nexport type RuleEvaluationResultMetadata<M extends RuleEvaluationMetric = RuleEvaluationMetric> = \n M extends RuleEvaluationMetric.ExactMatch ? RuleEvaluationExactMatchResultMetadata :\n M extends RuleEvaluationMetric.RegularExpression ? RuleEvaluationRegularExpressionResultMetadata :\n M extends RuleEvaluationMetric.SchemaValidation ? RuleEvaluationSchemaValidationResultMetadata :\n M extends RuleEvaluationMetric.LengthCount ? RuleEvaluationLengthCountResultMetadata :\n M extends RuleEvaluationMetric.LexicalOverlap ? RuleEvaluationLexicalOverlapResultMetadata :\n M extends RuleEvaluationMetric.SemanticSimilarity ? RuleEvaluationSemanticSimilarityResultMetadata :\n M extends RuleEvaluationMetric.NumericSimilarity ? RuleEvaluationNumericSimilarityResultMetadata :\n never;\n\n// prettier-ignore\nexport type RuleEvaluationResultError<M extends RuleEvaluationMetric = RuleEvaluationMetric> = \n M extends RuleEvaluationMetric.ExactMatch ? RuleEvaluationExactMatchResultError :\n M extends RuleEvaluationMetric.RegularExpression ? RuleEvaluationRegularExpressionResultError :\n M extends RuleEvaluationMetric.SchemaValidation ? RuleEvaluationSchemaValidationResultError :\n M extends RuleEvaluationMetric.LengthCount ? RuleEvaluationLengthCountResultError :\n M extends RuleEvaluationMetric.LexicalOverlap ? RuleEvaluationLexicalOverlapResultError :\n M extends RuleEvaluationMetric.SemanticSimilarity ? RuleEvaluationSemanticSimilarityResultError :\n M extends RuleEvaluationMetric.NumericSimilarity ? RuleEvaluationNumericSimilarityResultError :\n never;\n\nexport const RuleEvaluationSpecification = {\n name: 'Programmatic Rule',\n description: 'Evaluate responses using a programmatic rule',\n configuration: ruleEvaluationConfiguration,\n resultMetadata: ruleEvaluationResultMetadata,\n resultError: ruleEvaluationResultError,\n // prettier-ignore\n metrics: {\n [RuleEvaluationMetric.ExactMatch]: RuleEvaluationExactMatchSpecification,\n [RuleEvaluationMetric.RegularExpression]: RuleEvaluationRegularExpressionSpecification,\n [RuleEvaluationMetric.SchemaValidation]: RuleEvaluationSchemaValidationSpecification,\n [RuleEvaluationMetric.LengthCount]: RuleEvaluationLengthCountSpecification,\n [RuleEvaluationMetric.LexicalOverlap]: RuleEvaluationLexicalOverlapSpecification,\n [RuleEvaluationMetric.SemanticSimilarity]: RuleEvaluationSemanticSimilaritySpecification,\n [RuleEvaluationMetric.NumericSimilarity]: RuleEvaluationNumericSimilaritySpecification,\n },\n} as const\n","import { z } from 'zod'\nimport {\n CompositeEvaluationConfiguration,\n CompositeEvaluationMetric,\n CompositeEvaluationResultError,\n CompositeEvaluationResultMetadata,\n CompositeEvaluationSpecification,\n} from './composite'\nimport {\n HumanEvaluationConfiguration,\n HumanEvaluationMetric,\n HumanEvaluationResultError,\n HumanEvaluationResultMetadata,\n HumanEvaluationSpecification,\n} from './human'\nimport {\n LlmEvaluationConfiguration,\n LlmEvaluationMetric,\n LlmEvaluationResultError,\n LlmEvaluationResultMetadata,\n LlmEvaluationSpecification,\n} from './llm'\nimport {\n RuleEvaluationConfiguration,\n RuleEvaluationMetric,\n RuleEvaluationResultError,\n RuleEvaluationResultMetadata,\n RuleEvaluationSpecification,\n} from './rule'\n\nexport * from './active'\nexport * from './composite'\nexport * from './human'\nexport * from './llm'\nexport * from './rule'\nexport * from './shared'\n\nexport enum EvaluationType {\n Rule = 'rule',\n Llm = 'llm',\n Human = 'human',\n Composite = 'composite',\n}\n\nexport const EvaluationTypeSchema = z.enum(EvaluationType)\n\n// prettier-ignore\nexport type EvaluationMetric<T extends EvaluationType = EvaluationType> =\n T extends EvaluationType.Rule ? RuleEvaluationMetric :\n T extends EvaluationType.Llm ? LlmEvaluationMetric :\n T extends EvaluationType.Human ? HumanEvaluationMetric :\n T extends EvaluationType.Composite ? CompositeEvaluationMetric :\n never;\n\nexport const EvaluationMetricSchema = z.union([\n z.enum(RuleEvaluationMetric),\n z.enum(LlmEvaluationMetric),\n z.enum(HumanEvaluationMetric),\n z.enum(CompositeEvaluationMetric),\n])\n\n// prettier-ignore\nexport type EvaluationConfiguration<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> =\n T extends EvaluationType.Rule ? RuleEvaluationConfiguration<M extends RuleEvaluationMetric ? M : never> :\n T extends EvaluationType.Llm ? LlmEvaluationConfiguration<M extends LlmEvaluationMetric ? M : never> :\n T extends EvaluationType.Human ? HumanEvaluationConfiguration<M extends HumanEvaluationMetric ? M : never> :\n T extends EvaluationType.Composite ? CompositeEvaluationConfiguration<M extends CompositeEvaluationMetric ? M : never> :\n never;\n\nexport const EvaluationConfigurationSchema = z.custom<EvaluationConfiguration>()\n\n// prettier-ignore\nexport type EvaluationResultMetadata<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> =\n T extends EvaluationType.Rule ? RuleEvaluationResultMetadata<M extends RuleEvaluationMetric ? M : never> :\n T extends EvaluationType.Llm ? LlmEvaluationResultMetadata<M extends LlmEvaluationMetric ? M : never> :\n T extends EvaluationType.Human ? HumanEvaluationResultMetadata<M extends HumanEvaluationMetric ? M : never> :\n T extends EvaluationType.Composite ? CompositeEvaluationResultMetadata<M extends CompositeEvaluationMetric ? M : never> :\n never;\n\n// prettier-ignore\nexport const EvaluationResultMetadataSchema = z.custom<EvaluationResultMetadata>()\n\n// prettier-ignore\nexport type EvaluationResultError<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> =\n T extends EvaluationType.Rule ? RuleEvaluationResultError<M extends RuleEvaluationMetric ? M : never> :\n T extends EvaluationType.Llm ? LlmEvaluationResultError<M extends LlmEvaluationMetric ? M : never> :\n T extends EvaluationType.Human ? HumanEvaluationResultError<M extends HumanEvaluationMetric ? M : never> :\n T extends EvaluationType.Composite ? CompositeEvaluationResultError<M extends CompositeEvaluationMetric ? M : never> :\n never;\n\n// prettier-ignore\nexport const EvaluationResultErrorSchema = z.custom<EvaluationResultError>()\n\ntype ZodSchema<_T = any> = z.ZodObject\n\nexport type EvaluationMetricSpecification<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> = {\n name: string\n description: string\n configuration: ZodSchema<EvaluationConfiguration<T, M>>\n resultMetadata: ZodSchema<EvaluationResultMetadata<T, M>>\n resultError: ZodSchema<EvaluationResultError<T, M>>\n resultReason: (result: EvaluationResultSuccessValue<T, M>) => string | undefined // prettier-ignore\n resultUsage?: (result: EvaluationResultSuccessValue<T, M>) => number | undefined // prettier-ignore\n requiresExpectedOutput: boolean\n supportsLiveEvaluation: boolean\n supportsBatchEvaluation: boolean\n supportsManualEvaluation: boolean\n}\n\nexport type EvaluationSpecification<T extends EvaluationType = EvaluationType> =\n {\n name: string\n description: string\n configuration: ZodSchema<EvaluationConfiguration<T>>\n resultMetadata: ZodSchema<EvaluationResultMetadata<T>>\n resultError: ZodSchema<EvaluationResultError<T>>\n metrics: { [M in EvaluationMetric<T>]: EvaluationMetricSpecification<T, M> }\n }\n\nexport const EVALUATION_SPECIFICATIONS = {\n [EvaluationType.Rule]: RuleEvaluationSpecification,\n [EvaluationType.Llm]: LlmEvaluationSpecification,\n [EvaluationType.Human]: HumanEvaluationSpecification,\n [EvaluationType.Composite]: CompositeEvaluationSpecification,\n} as const satisfies {\n [T in EvaluationType]: EvaluationSpecification<T>\n}\ntype EvaluationSpecifications = typeof EVALUATION_SPECIFICATIONS\n\n// prettier-ignore\ntype EvaluationMetricSpecificationFilter<\n F extends keyof EvaluationMetricSpecification,\n T extends EvaluationType = EvaluationType\n> = { [K in EvaluationType]: {\n [M in keyof EvaluationSpecifications[K]['metrics']]:\n // @ts-expect-error F can indeed index M type\n EvaluationSpecifications[K]['metrics'][M][F] extends true ? M : never\n}[keyof EvaluationSpecifications[K]['metrics']]\n}[T] & EvaluationMetric<T>\n\nexport type LiveEvaluationMetric<T extends EvaluationType = EvaluationType> =\n EvaluationMetricSpecificationFilter<'supportsLiveEvaluation', T>\n\nexport type BatchEvaluationMetric<T extends EvaluationType = EvaluationType> =\n EvaluationMetricSpecificationFilter<'supportsBatchEvaluation', T>\n\nexport type ManualEvaluationMetric<T extends EvaluationType = EvaluationType> =\n EvaluationMetricSpecificationFilter<'supportsManualEvaluation', T>\n\nexport type AlignmentMetricMetadata = {\n // Hash used to identify the current configuration of the evaluation, used to detect if we can aggregate to the aligment metric or we have to re-calculate it\n alignmentHash: string\n confusionMatrix: {\n truePositives: number\n trueNegatives: number\n falsePositives: number\n falseNegatives: number\n }\n // Cutoff dates for incremental processing - ISO date strings\n lastProcessedPositiveSpanDate?: string\n lastProcessedNegativeSpanDate?: string\n // ISO date string indicating recalculation is in progress\n recalculatingAt?: string\n}\n\nexport type EvaluationV2<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> = {\n uuid: string\n versionId: number\n workspaceId: number\n commitId: number\n documentUuid: string\n issueId?: number | null\n name: string\n description: string\n type: T\n metric: M\n alignmentMetricMetadata?: AlignmentMetricMetadata | null\n configuration: EvaluationConfiguration<T, M>\n evaluateLiveLogs?: boolean | null\n createdAt: Date\n updatedAt: Date\n ignoredAt?: Date | null\n deletedAt?: Date | null\n}\n\nexport type EvaluationResultSuccessValue<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> = {\n score: number\n normalizedScore: number\n metadata: EvaluationResultMetadata<T, M>\n hasPassed: boolean\n error?: null\n}\n\nexport type EvaluationResultErrorValue<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> = {\n score?: null\n normalizedScore?: null\n metadata?: null\n hasPassed?: null\n error: EvaluationResultError<T, M>\n}\n\nexport type EvaluationResultValue<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> = EvaluationResultSuccessValue<T, M> | EvaluationResultErrorValue<T, M>\n\nexport type EvaluationResultV2<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> = {\n id: number\n uuid: string\n workspaceId: number\n commitId: number\n evaluationUuid: string\n type?: T | null\n metric?: M | null\n experimentId?: number | null\n datasetId?: number | null\n evaluatedRowId?: number | null\n evaluatedSpanId?: string | null\n evaluatedTraceId?: string | null\n createdAt: Date\n updatedAt: Date\n} & EvaluationResultValue<T, M>\n\nexport type PublicManualEvaluationResultV2 = Pick<\n EvaluationResultV2<EvaluationType.Human, HumanEvaluationMetric>,\n | 'uuid'\n | 'score'\n | 'normalizedScore'\n | 'metadata'\n | 'hasPassed'\n | 'createdAt'\n | 'updatedAt'\n> & { versionUuid: string; error: string | null }\n\nexport type EvaluationSettings<\n T extends EvaluationType = EvaluationType,\n M extends EvaluationMetric<T> = EvaluationMetric<T>,\n> = Pick<\n EvaluationV2<T, M>,\n 'name' | 'description' | 'type' | 'metric' | 'configuration'\n>\n\nexport const EvaluationSettingsSchema = z.object({\n name: z.string(),\n description: z.string(),\n type: EvaluationTypeSchema,\n metric: EvaluationMetricSchema,\n configuration: EvaluationConfigurationSchema,\n})\n\nexport type EvaluationOptions = Pick<EvaluationV2, 'evaluateLiveLogs'>\n\nexport const EvaluationOptionsSchema = z.object({\n evaluateLiveLogs: z.boolean().nullable().optional(),\n})\n\nexport const EVALUATION_SCORE_SCALE = 100\nexport const DEFAULT_DATASET_LABEL = 'output'\n","import { Config, Message, ToolCall } from '@latitude-data/constants/messages'\nimport { FinishReason } from 'ai'\nimport {\n ChainStepResponse,\n LegacyVercelSDKVersion4Usage,\n PromptSource,\n ProviderData,\n StreamEventTypes,\n StreamType,\n} from '..'\nimport { ChainError, RunErrorCodes } from '../errors'\n\nexport enum ChainEventTypes {\n ChainCompleted = 'chain-completed',\n ChainError = 'chain-error',\n ChainStarted = 'chain-started',\n IntegrationWakingUp = 'integration-waking-up',\n ProviderCompleted = 'provider-completed',\n ProviderStarted = 'provider-started',\n StepCompleted = 'step-completed',\n StepStarted = 'step-started',\n ToolCompleted = 'tool-completed',\n ToolResult = 'tool-result',\n ToolsStarted = 'tools-started',\n}\n\ninterface GenericLatitudeEventData {\n type: ChainEventTypes\n timestamp: number\n messages: Message[]\n uuid: string\n source?: PromptSource\n}\n\nexport interface LatitudeChainStartedEventData\n extends GenericLatitudeEventData {\n type: ChainEventTypes.ChainStarted\n}\n\nexport interface LatitudeStepStartedEventData extends GenericLatitudeEventData {\n type: ChainEventTypes.StepStarted\n}\n\nexport interface LatitudeProviderStartedEventData\n extends GenericLatitudeEventData {\n type: ChainEventTypes.ProviderStarted\n config: Config\n}\n\nexport interface LatitudeProviderCompletedEventData\n extends GenericLatitudeEventData {\n type: ChainEventTypes.ProviderCompleted\n // TODO: DEPRECATED, keeping it around for backwards compatibliity purposes\n // but it's not used for anything. Remove after March 2026.\n providerLogUuid: string\n tokenUsage: LegacyVercelSDKVersion4Usage\n finishReason: FinishReason\n response: ChainStepResponse<StreamType>\n}\n\nexport interface LatitudeToolsStartedEventData\n extends GenericLatitudeEventData {\n type: ChainEventTypes.ToolsStarted\n tools: ToolCall[]\n}\n\nexport interface LatitudeToolCompletedEventData\n extends GenericLatitudeEventData {\n type: ChainEventTypes.ToolCompleted\n}\n\nexport interface LatitudeStepCompletedEventData\n extends GenericLatitudeEventData {\n type: ChainEventTypes.StepCompleted\n}\n\nexport interface LatitudeChainCompletedEventData\n extends GenericLatitudeEventData {\n type: ChainEventTypes.ChainCompleted\n response: ChainStepResponse<StreamType> | undefined\n toolCalls: ToolCall[]\n tokenUsage: LegacyVercelSDKVersion4Usage\n finishReason: FinishReason\n}\n\nexport interface LatitudeChainErrorEventData extends GenericLatitudeEventData {\n type: ChainEventTypes.ChainError\n error: Error | ChainError<RunErrorCodes>\n}\n\nexport interface LatitudeIntegrationWakingUpEventData\n extends GenericLatitudeEventData {\n type: ChainEventTypes.IntegrationWakingUp\n integrationName: string\n}\n\nexport type LatitudeEventData =\n | LatitudeChainStartedEventData\n | LatitudeStepStartedEventData\n | LatitudeProviderStartedEventData\n | LatitudeProviderCompletedEventData\n | LatitudeToolsStartedEventData\n | LatitudeToolCompletedEventData\n | LatitudeStepCompletedEventData\n | LatitudeChainCompletedEventData\n | LatitudeChainErrorEventData\n | LatitudeIntegrationWakingUpEventData\n\n// Just a type helper for ChainStreamManager. Omit<LatitudeEventData, 'timestamp' | 'messages' | 'uuid'> does not work.\n// prettier-ignore\nexport type OmittedLatitudeEventData =\n | Omit<LatitudeChainStartedEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeStepStartedEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeProviderStartedEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeProviderCompletedEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeToolsStartedEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeToolCompletedEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeStepCompletedEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeChainCompletedEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeChainErrorEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n | Omit<LatitudeIntegrationWakingUpEventData, 'timestamp' | 'messages' | 'uuid' | 'source'>\n\nexport type ChainEvent =\n | {\n event: StreamEventTypes.Latitude\n data: LatitudeEventData\n }\n | {\n event: StreamEventTypes.Provider\n data: ProviderData\n }\n","import { SimulationSettings } from './simulation'\nimport { z } from 'zod'\n\nexport const experimentVariantSchema = z.object({\n name: z.string(),\n provider: z.string(),\n model: z.string(),\n temperature: z.number(),\n})\n\nexport type ExperimentVariant = z.infer<typeof experimentVariantSchema>\n\n// Experiment ran from a dataset\nconst experimentDatasetSourceSchema = z.object({\n source: z.literal('dataset'),\n datasetId: z.number(),\n fromRow: z.number(),\n toRow: z.number(),\n datasetLabels: z.record(z.string(), z.string()),\n parametersMap: z.record(z.string(), z.number()),\n})\n\nexport type ExperimentDatasetSource = z.infer<\n typeof experimentDatasetSourceSchema\n>\n\n// Experiment ran from last logs (from commit and creation time of experiment)\nconst experimentLogsSourceSchema = z.object({\n source: z.literal('logs'),\n count: z.number(),\n})\n\nexport type ExperimentLogsSource = z.infer<typeof experimentLogsSourceSchema>\n\n// Experiment ran with manual parameters (currently only used for prompts with no parameters)\nconst experimentManualSourceSchema = z.object({\n source: z.literal('manual'),\n count: z.number(),\n parametersMap: z.record(z.string(), z.number()),\n})\n\nexport type ExperimentManualSource = z.infer<\n typeof experimentManualSourceSchema\n>\n\nexport const experimentParametersSourceSchema = z.discriminatedUnion('source', [\n experimentDatasetSourceSchema,\n experimentLogsSourceSchema,\n experimentManualSourceSchema,\n])\n\nexport type ExperimentParametersSource = z.infer<\n typeof experimentParametersSourceSchema\n>\n\nexport type ExperimentMetadata = {\n prompt: string\n promptHash: string\n count: number // Total number of to generate logs in the experiment\n parametersSource: ExperimentParametersSource\n simulationSettings?: SimulationSettings\n}\n\nexport type ExperimentScores = {\n [evaluationUuid: string]: {\n count: number\n totalScore: number\n totalNormalizedScore: number\n }\n}\n","export enum QuotaType {\n Seats = 'seats',\n Runs = 'runs',\n Credits = 'credits',\n}\n\nexport type Quota = number | 'unlimited'\n\nexport enum GrantSource {\n System = 'system',\n Subscription = 'subscription',\n Purchase = 'purchase',\n Reward = 'reward',\n Promocode = 'promocode',\n}\n\nexport type Grant = {\n id: number\n uuid: string // Idempotency key\n workspaceId: number\n referenceId: string\n source: GrantSource\n type: QuotaType\n amount: Quota\n balance: number\n expiresAt?: Date\n createdAt: Date\n updatedAt: Date\n}\n","import { DocumentTriggerStatus, DocumentTriggerType } from '.'\nimport { EvaluationType } from './evaluations'\n\nexport enum ModifiedDocumentType {\n Created = 'created',\n Updated = 'updated',\n UpdatedPath = 'updated_path',\n Deleted = 'deleted',\n}\n\nexport type ChangedDocument = {\n documentUuid: string\n path: string\n errors: number\n changeType: ModifiedDocumentType\n}\n\nexport type ChangedTrigger = {\n triggerUuid: string\n documentUuid: string\n triggerType: DocumentTriggerType\n changeType: ModifiedDocumentType\n status: DocumentTriggerStatus\n}\n\nexport type ChangedEvaluation = {\n evaluationUuid: string\n documentUuid: string\n name: string\n type: EvaluationType\n changeType: ModifiedDocumentType\n}\n\nexport type CommitChanges = {\n anyChanges: boolean\n hasIssues: boolean\n mainDocumentUuid: string | null | undefined // null if the main document was deleted, undefined if it did not change\n documents: {\n hasErrors: boolean\n all: ChangedDocument[]\n errors: ChangedDocument[]\n clean: ChangedDocument[]\n }\n triggers: {\n hasPending: boolean\n all: ChangedTrigger[]\n clean: ChangedTrigger[]\n pending: ChangedTrigger[]\n }\n evaluations: {\n all: ChangedEvaluation[]\n }\n}\n","export enum IntegrationType {\n Latitude = 'latitude',\n ExternalMCP = 'custom_mcp',\n Pipedream = 'pipedream',\n HostedMCP = 'mcp_server', // DEPRECATED: Do not use\n}\n\nexport type ActiveIntegrationType = Exclude<\n IntegrationType,\n IntegrationType.HostedMCP\n>\n\nexport enum HostedIntegrationType {\n Stripe = 'stripe',\n Slack = 'slack',\n Github = 'github',\n Notion = 'notion',\n Twitter = 'twitter',\n Airtable = 'airtable',\n Linear = 'linear',\n YoutubeCaptions = 'youtube_captions',\n Reddit = 'reddit',\n Telegram = 'telegram',\n Tinybird = 'tinybird',\n Perplexity = 'perplexity',\n\n AwsKbRetrieval = 'aws_kb_retrieval',\n BraveSearch = 'brave_search',\n EverArt = 'ever_art',\n Fetch = 'fetch',\n GitLab = 'gitlab',\n GoogleMaps = 'google_maps',\n Sentry = 'sentry',\n Puppeteer = 'puppeteer',\n Time = 'time',\n browserbase = 'browserbase',\n Neon = 'neon',\n Postgres = 'postgres',\n Supabase = 'supabase',\n Redis = 'redis',\n Jira = 'jira',\n Attio = 'attio',\n Ghost = 'ghost',\n Figma = 'figma',\n Hyperbrowser = 'hyperbrowser',\n Audiense = 'audiense',\n Apify = 'apify',\n Exa = 'exa',\n YepCode = 'yepcode',\n Monday = 'monday',\n\n AgentQL = 'agentql',\n AgentRPC = 'agentrpc',\n AstraDB = 'astra_db',\n Bankless = 'bankless',\n Bicscan = 'bicscan',\n Chargebee = 'chargebee',\n Chronulus = 'chronulus',\n CircleCI = 'circleci',\n Codacy = 'codacy',\n CodeLogic = 'codelogic',\n Convex = 'convex',\n Dart = 'dart',\n DevHubCMS = 'devhub_cms',\n Elasticsearch = 'elasticsearch',\n ESignatures = 'esignatures',\n Fewsats = 'fewsats',\n Firecrawl = 'firecrawl',\n\n Graphlit = 'graphlit',\n Heroku = 'heroku',\n IntegrationAppHubspot = 'integration_app_hubspot',\n\n LaraTranslate = 'lara_translate',\n Logfire = 'logfire',\n Langfuse = 'langfuse',\n LingoSupabase = 'lingo_supabase',\n Make = 'make',\n Meilisearch = 'meilisearch',\n Momento = 'momento',\n\n Neo4jAura = 'neo4j_aura',\n Octagon = 'octagon',\n\n Paddle = 'paddle',\n PayPal = 'paypal',\n Qdrant = 'qdrant',\n Raygun = 'raygun',\n Rember = 'rember',\n Riza = 'riza',\n Search1API = 'search1api',\n Semgrep = 'semgrep',\n\n Tavily = 'tavily',\n Unstructured = 'unstructured',\n Vectorize = 'vectorize',\n Xero = 'xero',\n Readwise = 'readwise',\n Airbnb = 'airbnb',\n Mintlify = 'mintlify',\n\n // Require all auth file :point_down:\n // Gmail = 'google_drive',\n // GoogleCalendar = 'google_drive',\n // GoogleDrive = 'google_drive',\n // GoogleWorkspace = 'google_workspace', // env vars not supported (?)\n\n // TODO: implement these\n // Wordpress = 'wordpress', // Not on OpenTools\n // Discord = 'discord', // Not on OpenTools\n // Intercom = 'intercom', // Not on OpenTools\n\n // Hubspot = 'hubspot', // Docker based\n // Loops = 'loops', // Does not exist\n}\n\ninterface IIntegrationReference {\n integrationName: string\n projectId: number\n commitId: number\n documentUuid: string\n}\n\ninterface TriggerReference extends IIntegrationReference {\n type: 'trigger'\n triggerUuid: string\n}\n\ninterface ToolReference extends IIntegrationReference {\n type: 'tool'\n}\n\nexport type IntegrationReference = TriggerReference | ToolReference\n","import { Message, ToolCall } from '@latitude-data/constants/messages'\nimport { PartialPromptConfig } from './ai'\n\nexport enum LogSources {\n API = 'api',\n AgentAsTool = 'agent_as_tool',\n Copilot = 'copilot',\n EmailTrigger = 'email_trigger',\n Evaluation = 'evaluation',\n Experiment = 'experiment',\n IntegrationTrigger = 'integration_trigger',\n Playground = 'playground',\n ScheduledTrigger = 'scheduled_trigger',\n SharedPrompt = 'shared_prompt',\n ShadowTest = 'shadow_test',\n ABTestChallenger = 'ab_test_challenger',\n User = 'user',\n Optimization = 'optimization',\n}\n\ntype Commit = {\n id: number\n uuid: string\n title: string\n description: string | null\n deletedAt: Date | null\n createdAt: Date\n updatedAt: Date\n projectId: number\n version: number | null\n userId: string\n mergedAt: Date | null\n mainDocumentUuid: string | null\n}\n\nexport type DocumentLog = {\n id: number\n uuid: string\n documentUuid: string\n commitId: number\n resolvedContent: string\n contentHash: string\n parameters: Record<string, unknown>\n customIdentifier: string | null\n duration: number | null\n source: LogSources | null\n createdAt: Date\n updatedAt: Date\n experimentId: number | null\n workspaceId: number | null\n}\n\nexport type DocumentLogWithMetadata = DocumentLog & {\n commit: Commit\n tokens: number | null\n duration: number | null\n costInMillicents: number | null\n}\n\nexport type RunErrorField = {\n code: string | null\n message: string | null\n details: string | null\n}\n\nexport type DocumentLogWithMetadataAndError = DocumentLogWithMetadata & {\n error: RunErrorField\n}\n\nexport type ProviderLog = {\n id: number\n uuid: string\n documentLogUuid: string | null\n providerId: number | null\n model: string | null\n finishReason: string | null\n config: PartialPromptConfig | null\n messages: Message[] | null\n responseObject: unknown | null\n responseText: string | null\n toolCalls: ToolCall[] | null\n tokens: number | null\n costInMillicents: number | null\n duration: number | null\n source: LogSources | null\n apiKeyId: number | null\n generatedAt: Date | null\n updatedAt: Date\n}\n\nexport type DocumentVersion = {\n id: number\n createdAt: Date\n updatedAt: Date\n deletedAt: Date | null\n documentUuid: string\n commitId: number\n path: string\n content: string\n resolvedContent: string | null\n contentHash: string | null\n datasetId: number | null\n datasetV2Id: number | null\n}\n\nexport type SimplifiedDocumentVersion = {\n documentUuid: string\n path: string\n content: string\n isDeleted: boolean\n}\n","import {\n EvaluationResultV2,\n EvaluationType,\n EvaluationV2,\n ManualEvaluationMetric,\n} from './evaluations'\nimport { LogSources } from './models'\nimport { MainSpanType, SpanWithDetails } from './tracing'\n\nexport type RunAnnotation<\n T extends EvaluationType = EvaluationType,\n M extends ManualEvaluationMetric<T> = ManualEvaluationMetric<T>,\n> = {\n result: EvaluationResultV2<T, M>\n evaluation: EvaluationV2<T, M>\n}\n\nexport type Run = {\n uuid: string\n queuedAt: Date\n startedAt?: Date\n endedAt?: Date\n caption?: string\n annotations?: RunAnnotation[]\n source?: LogSources\n span?: SpanWithDetails<MainSpanType>\n}\n\nexport type ActiveRun = Pick<\n Run,\n 'uuid' | 'queuedAt' | 'startedAt' | 'caption' | 'source'\n> & {\n documentUuid: string\n commitUuid: string\n}\nexport type CompletedRun = Required<Run>\n\nexport const RUN_CAPTION_SIZE = 150\n\nexport const ACTIVE_RUNS_BY_DOCUMENT_CACHE_KEY = (\n workspaceId: number,\n projectId: number,\n documentUuid: string,\n) => `runs:active:${workspaceId}:${projectId}:${documentUuid}`\nexport const ACTIVE_RUN_CACHE_TTL = 1 * 3 * 60 * 60 * 1000 // 3 hours\nexport const ACTIVE_RUN_CACHE_TTL_SECONDS = Math.floor(\n ACTIVE_RUN_CACHE_TTL / 1000,\n)\n\nexport const ACTIVE_RUN_STREAM_KEY = (runUuid: string) =>\n `run:active:${runUuid}:stream`\nexport const ACTIVE_RUN_STREAM_CAP = 100_000\n\nexport enum RunSourceGroup {\n Production = 'production',\n Playground = 'playground',\n}\n\nexport const RUN_SOURCES: Record<RunSourceGroup, LogSources[]> = {\n [RunSourceGroup.Production]: [\n LogSources.API,\n LogSources.ShadowTest,\n LogSources.ABTestChallenger,\n LogSources.EmailTrigger,\n LogSources.IntegrationTrigger,\n LogSources.ScheduledTrigger,\n LogSources.SharedPrompt,\n LogSources.User,\n ],\n [RunSourceGroup.Playground]: [LogSources.Playground, LogSources.Experiment],\n} as const\n","import { FinishReason } from 'ai'\nimport { Message } from '../messages'\nimport { LogSources } from '../models'\nimport { AssembledSpan } from './trace'\n\nexport enum SpanKind {\n Internal = 'internal',\n Server = 'server',\n Client = 'client',\n Producer = 'producer',\n Consumer = 'consumer',\n}\n\n// Note: loosely based on OpenTelemetry GenAI semantic conventions\nexport enum SpanType {\n // Latitude wrappers\n Prompt = 'prompt', // Running a prompt\n Chat = 'chat', // Continuing a conversation (adding messages)\n External = 'external', // Wrapping external generation code\n UnresolvedExternal = 'unresolved_external', // External span that needs path & potential version resolution\n\n // Added a HTTP span to capture raw HTTP requests and responses when running from Latitude\n Http = 'http', // Note: raw HTTP requests and responses\n\n // Any known span from supported specifications will be grouped into one of these types\n Completion = 'completion',\n Tool = 'tool', // Note: asynchronous tools such as agents are conversation segments\n Embedding = 'embedding',\n\n Unknown = 'unknown', // Other spans we don't care about\n}\n\nexport type SpanSpecification<_T extends SpanType = SpanType> = {\n name: string\n description: string\n isGenAI: boolean\n isHidden: boolean\n}\n\nexport const LIVE_EVALUABLE_SPAN_TYPES = [\n SpanType.Prompt,\n SpanType.External,\n SpanType.Chat,\n]\n\nexport type EvaluableSpanType =\n | SpanType.Prompt\n | SpanType.Chat\n | SpanType.External\n\nexport const SPAN_SPECIFICATIONS = {\n [SpanType.Prompt]: {\n name: 'Prompt',\n description: 'A prompt span',\n isGenAI: false,\n isHidden: false,\n },\n [SpanType.Chat]: {\n name: 'Chat',\n description: 'A chat continuation span',\n isGenAI: false,\n isHidden: false,\n },\n [SpanType.External]: {\n name: 'External',\n description: 'An external capture span',\n isGenAI: false,\n isHidden: false,\n },\n [SpanType.UnresolvedExternal]: {\n name: 'Unresolved External',\n description: 'An external span that needs path resolution before storage',\n isGenAI: false,\n isHidden: true,\n },\n [SpanType.Completion]: {\n name: 'Completion',\n description: 'A completion call',\n isGenAI: true,\n isHidden: false,\n },\n [SpanType.Embedding]: {\n name: 'Embedding',\n description: 'An embedding call',\n isGenAI: true,\n isHidden: false,\n },\n [SpanType.Tool]: {\n name: 'Tool',\n description: 'A tool call',\n isGenAI: true,\n isHidden: false,\n },\n [SpanType.Http]: {\n name: 'HTTP',\n description: 'An HTTP request',\n isGenAI: false,\n isHidden: true,\n },\n [SpanType.Unknown]: {\n name: 'Unknown',\n description: 'An unknown span',\n isGenAI: false,\n isHidden: true,\n },\n} as const satisfies {\n [T in SpanType]: SpanSpecification<T>\n}\n\nexport enum SpanStatus {\n Unset = 'unset',\n Ok = 'ok',\n Error = 'error',\n}\n\n// Note: get span attribute keys from @opentelemetry/semantic-conventions/incubating\nexport type SpanAttribute = string | number | boolean | SpanAttribute[]\n\nexport type SpanEvent = {\n name: string\n timestamp: Date\n attributes: Record<string, SpanAttribute>\n}\n\nexport type SpanLink = {\n traceId: string\n spanId: string\n attributes: Record<string, SpanAttribute>\n}\n\nexport type CompletionSpanTokens = {\n prompt: number\n cached: number\n reasoning: number\n completion: number\n}\n\nexport type BaseSpanMetadata<T extends SpanType = SpanType> = {\n traceId: string\n spanId: string\n type: T\n attributes: Record<string, SpanAttribute>\n events: SpanEvent[]\n links: SpanLink[]\n}\n\nexport type SpanReferenceMetadata = {\n source?: LogSources\n documentLogUuid?: string\n promptUuid?: string\n versionUuid?: string\n experimentUuid?: string\n projectId?: number\n testDeploymentId?: number\n previousTraceId?: string\n}\n\nexport type ToolSpanMetadata = BaseSpanMetadata<SpanType.Tool> &\n SpanReferenceMetadata & {\n name: string\n call: {\n id: string\n arguments: Record<string, unknown>\n }\n // Fields below are optional if the span had an error\n result?: {\n value: unknown\n isError: boolean\n }\n }\n\nexport type PromptSpanMetadata = BaseSpanMetadata<SpanType.Prompt> &\n SpanReferenceMetadata & {\n documentLogUuid: string\n experimentUuid?: string\n externalId?: string\n parameters: Record<string, unknown>\n projectId: number\n promptUuid: string\n source: LogSources\n template: string\n testDeploymentId?: number\n versionUuid: string\n }\n\nexport type ChatSpanMetadata = BaseSpanMetadata<SpanType.Chat> &\n SpanReferenceMetadata & {\n documentLogUuid: string\n previousTraceId: string\n source: LogSources\n }\n\nexport type ExternalSpanMetadata = BaseSpanMetadata<SpanType.External> &\n SpanReferenceMetadata & {\n promptUuid: string\n documentLogUuid: string\n source: LogSources\n versionUuid?: string\n externalId?: string\n name?: string\n }\n\nexport type UnresolvedExternalSpanMetadata =\n BaseSpanMetadata<SpanType.UnresolvedExternal> &\n SpanReferenceMetadata & {\n promptPath: string\n projectId: number\n versionUuid?: string\n externalId?: string\n name?: string\n }\n\nexport type CompletionSpanMetadata = BaseSpanMetadata<SpanType.Completion> &\n SpanReferenceMetadata & {\n provider: string\n model: string\n configuration: Record<string, unknown>\n input: Message[]\n // Fields below are optional if the span had an error\n output?: Message[]\n tokens?: CompletionSpanTokens\n cost?: number // Enriched when ingested\n finishReason?: FinishReason\n }\n\nexport type HttpSpanMetadata = BaseSpanMetadata<SpanType.Http> &\n SpanReferenceMetadata & {\n request: {\n method: string\n url: string\n headers: Record<string, string>\n body: string | Record<string, unknown>\n }\n // Fields below are optional if the span had an error\n response?: {\n status: number\n headers: Record<string, string>\n body: string | Record<string, unknown>\n }\n }\n\n// prettier-ignore\nexport type SpanMetadata<T extends SpanType = SpanType> =\n T extends SpanType.Tool ? ToolSpanMetadata :\n T extends SpanType.Prompt ? PromptSpanMetadata :\n T extends SpanType.Chat ? ChatSpanMetadata :\n T extends SpanType.External ? ExternalSpanMetadata :\n T extends SpanType.UnresolvedExternal ? UnresolvedExternalSpanMetadata :\n T extends SpanType.Completion ? CompletionSpanMetadata :\n T extends SpanType.Embedding ? BaseSpanMetadata<T> & SpanReferenceMetadata :\n T extends SpanType.Http ? HttpSpanMetadata :\n T extends SpanType.Unknown ? BaseSpanMetadata<T> & SpanReferenceMetadata :\n never;\n\nexport const SPAN_METADATA_STORAGE_KEY = (\n workspaceId: number,\n traceId: string,\n spanId: string,\n) => encodeURI(`workspaces/${workspaceId}/traces/${traceId}/${spanId}`)\nexport const SPAN_METADATA_CACHE_TTL = 24 * 60 * 60 // 1 day\n\nexport type Span<T extends SpanType = SpanType> = {\n id: string\n traceId: string\n segmentId?: string\n parentId?: string // Parent span identifier\n workspaceId: number\n projectId: number\n apiKeyId: number\n name: string\n kind: SpanKind\n type: T\n status: SpanStatus\n message?: string\n duration: number\n startedAt: Date\n endedAt: Date\n createdAt: Date\n updatedAt: Date\n documentLogUuid?: string\n documentUuid?: string\n commitUuid?: string\n experimentUuid?: string\n testDeploymentId?: number\n previousTraceId?: string\n\n source?: LogSources\n\n tokensPrompt?: number\n tokensCached?: number\n tokensReasoning?: number\n tokensCompletion?: number\n\n model?: string\n cost?: number\n}\n\nexport type PromptSpan = Omit<Span<SpanType.Prompt>, 'documentLogUuid'> & {\n documentLogUuid: string\n}\n\nexport type ChatSpan = Omit<Span<SpanType.Chat>, 'documentLogUuid'> & {\n documentLogUuid: string\n}\n\nexport type ExternalSpan = Omit<Span<SpanType.External>, 'documentLogUuid'> & {\n documentLogUuid: string\n}\n\nexport type SpanWithDetails<T extends SpanType = SpanType> = Span<T> & {\n metadata?: SpanMetadata<T> // Metadata is optional if it could not be uploaded\n}\n\nexport type SerializedSpanPair = {\n id: string\n traceId: string\n createdAt: string\n}\n\nexport type MainSpanType = SpanType.External | SpanType.Prompt | SpanType.Chat\nexport const MAIN_SPAN_TYPES: Set<MainSpanType> = new Set([\n SpanType.Prompt,\n SpanType.Chat,\n SpanType.External,\n])\n\nexport type MainSpanMetadata =\n | PromptSpanMetadata\n | ChatSpanMetadata\n | ExternalSpanMetadata\n\nexport function isMainSpan(span: Span | SpanWithDetails | AssembledSpan) {\n return MAIN_SPAN_TYPES.has(span.type as MainSpanType)\n}\n\nexport function isCompletionSpan(\n span: Span | SpanWithDetails | AssembledSpan,\n): span is AssembledSpan<SpanType.Completion> {\n return span.type === SpanType.Completion\n}\n","import { z } from 'zod'\nimport { Span, SpanMetadata, SpanType } from './span'\n\n// Note: Traces are unmaterialized but this context is used to propagate the trace\n// See www.w3.org/TR/trace-context and w3c.github.io/baggage\nexport const traceContextSchema = z.object({\n traceparent: z.string(), // <version>-<trace-id>-<span-id>-<trace-flags>\n tracestate: z.string().optional(), // <key>=urlencoded(<value>)[,<key>=urlencoded(<value>)]*\n baggage: z.string().optional(), // <key>=urlencoded(<value>)[,<key>=urlencoded(<value>)]*\n})\nexport type TraceContext = z.infer<typeof traceContextSchema>\n\nexport type AssembledSpan<T extends SpanType = SpanType> = Span<T> & {\n conversationId?: string\n children: AssembledSpan[]\n depth: number\n startOffset: number\n endOffset: number\n metadata?: SpanMetadata<T>\n}\n\n// Note: full trace structure ready to be drawn, parts are ordered by timestamp\nexport type AssembledTrace = {\n id: string\n conversationId?: string\n children: AssembledSpan[]\n spans: number\n duration: number\n startedAt: Date\n endedAt: Date\n}\n\nexport const TRACE_CACHE_TTL = 5 * 60 // 5 minutes\n","import {\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_RESPONSE_FINISH_REASONS,\n ATTR_GEN_AI_RESPONSE_ID,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_TOOL_CALL_ID,\n ATTR_GEN_AI_TOOL_DESCRIPTION,\n ATTR_GEN_AI_TOOL_NAME,\n ATTR_GEN_AI_TOOL_TYPE,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_OPERATION_NAME_VALUE_CHAT,\n GEN_AI_OPERATION_NAME_VALUE_CREATE_AGENT,\n GEN_AI_OPERATION_NAME_VALUE_EMBEDDINGS,\n GEN_AI_OPERATION_NAME_VALUE_EXECUTE_TOOL,\n GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT,\n GEN_AI_OPERATION_NAME_VALUE_INVOKE_AGENT,\n GEN_AI_OPERATION_NAME_VALUE_TEXT_COMPLETION,\n GEN_AI_OUTPUT_TYPE_VALUE_IMAGE,\n GEN_AI_OUTPUT_TYPE_VALUE_JSON,\n GEN_AI_OUTPUT_TYPE_VALUE_SPEECH,\n GEN_AI_OUTPUT_TYPE_VALUE_TEXT,\n} from '@opentelemetry/semantic-conventions/incubating'\n\nimport {\n ATTR_ERROR_TYPE,\n ATTR_EXCEPTION_MESSAGE,\n ATTR_EXCEPTION_TYPE,\n ATTR_HTTP_REQUEST_METHOD,\n ATTR_HTTP_RESPONSE_STATUS_CODE,\n ATTR_OTEL_SCOPE_NAME,\n ATTR_OTEL_SCOPE_VERSION,\n ATTR_OTEL_STATUS_CODE,\n ATTR_OTEL_STATUS_DESCRIPTION,\n ATTR_SERVICE_NAME,\n} from '@opentelemetry/semantic-conventions'\n\nimport { SpanAttribute } from './span'\n\nexport const ATTRIBUTES = {\n // Custom attributes added and used by Latitude spans (Prompt / External / Chat)\n LATITUDE: {\n name: 'latitude.name',\n type: 'latitude.type',\n documentUuid: 'latitude.document_uuid',\n promptPath: 'latitude.prompt_path',\n commitUuid: 'latitude.commit_uuid',\n documentLogUuid: 'latitude.document_log_uuid',\n projectId: 'latitude.project_id',\n experimentUuid: 'latitude.experiment_uuid',\n source: 'latitude.source',\n externalId: 'latitude.external_id',\n testDeploymentId: 'latitude.test_deployment_id',\n previousTraceId: 'latitude.previous_trace_id',\n\n internal: 'latitude.internal',\n\n // Custom additions to the GenAI semantic conventions (deprecated)\n request: {\n _root: 'gen_ai.request',\n model: 'gen_ai.request.model',\n configuration: 'gen_ai.request.configuration',\n template: 'gen_ai.request.template',\n parameters: 'gen_ai.request.parameters',\n messages: 'gen_ai.request.messages',\n systemPrompt: 'gen_ai.request.system',\n },\n response: {\n _root: 'gen_ai.response',\n messages: 'gen_ai.response.messages',\n },\n usage: {\n promptTokens: 'gen_ai.usage.prompt_tokens',\n cachedTokens: 'gen_ai.usage.cached_tokens',\n reasoningTokens: 'gen_ai.usage.reasoning_tokens',\n completionTokens: 'gen_ai.usage.completion_tokens',\n },\n },\n\n // Official OpenTelemetry semantic conventions\n OPENTELEMETRY: {\n SERVICE: {\n name: ATTR_SERVICE_NAME,\n },\n OTEL: {\n scope: {\n name: ATTR_OTEL_SCOPE_NAME,\n version: ATTR_OTEL_SCOPE_VERSION,\n },\n status: {\n code: ATTR_OTEL_STATUS_CODE,\n description: ATTR_OTEL_STATUS_DESCRIPTION,\n },\n },\n ERROR: {\n type: ATTR_ERROR_TYPE,\n },\n EXCEPTION: {\n message: ATTR_EXCEPTION_MESSAGE,\n type: ATTR_EXCEPTION_TYPE,\n },\n HTTP: {\n request: {\n url: 'http.request.url',\n body: 'http.request.body',\n header: 'http.request.header',\n headers: 'http.request.headers',\n method: ATTR_HTTP_REQUEST_METHOD,\n },\n response: {\n body: 'http.response.body',\n header: 'http.response.header',\n headers: 'http.response.headers',\n statusCode: ATTR_HTTP_RESPONSE_STATUS_CODE,\n },\n },\n\n // GenAI semantic conventions\n // https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/\n GEN_AI: {\n conversationId: 'gen_ai.conversation.id',\n operation: ATTR_GEN_AI_OPERATION_NAME,\n provider: 'gen_ai.provider.name', // openai; gcp.gen_ai; gcp.vertex_ai\n request: {\n _root: 'gen_ai.request', // Contains prompt configuration settings (temperature, model, max_tokens, etc.)\n },\n response: {\n id: ATTR_GEN_AI_RESPONSE_ID,\n model: ATTR_GEN_AI_RESPONSE_MODEL,\n finishReasons: ATTR_GEN_AI_RESPONSE_FINISH_REASONS,\n },\n usage: {\n inputTokens: ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n outputTokens: ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n },\n systemInstructions: 'gen_ai.system.instructions', // Contains the PARTS of the \"system message\"\n tool: {\n definitions: 'gen_ai.tool.definitions',\n call: {\n id: ATTR_GEN_AI_TOOL_CALL_ID,\n arguments: 'gen_ai.tool.call.arguments',\n result: 'gen_ai.tool.call.result',\n },\n name: ATTR_GEN_AI_TOOL_NAME,\n description: ATTR_GEN_AI_TOOL_DESCRIPTION,\n type: ATTR_GEN_AI_TOOL_TYPE,\n },\n input: {\n messages: 'gen_ai.input.messages',\n },\n output: {\n messages: 'gen_ai.output.messages',\n },\n _deprecated: {\n system: ATTR_GEN_AI_SYSTEM,\n tool: {\n name: ATTR_GEN_AI_TOOL_NAME,\n type: ATTR_GEN_AI_TOOL_TYPE,\n call: {\n name: 'gen_ai.tool.call.name',\n description: 'gen_ai.tool.call.description',\n type: 'gen_ai.tool.call.type',\n },\n result: {\n value: 'gen_ai.tool.result.value',\n isError: 'gen_ai.tool.result.is_error',\n },\n },\n prompt: {\n _root: 'gen_ai.prompt',\n index: (promptIndex: number) => ({\n role: `gen_ai.prompt.${promptIndex}.role`,\n content: `gen_ai.prompt.${promptIndex}.content`, // string or object\n toolCalls: (toolCallIndex: number) => ({\n id: `gen_ai.prompt.${promptIndex}.tool_calls.${toolCallIndex}.id`,\n name: `gen_ai.prompt.${promptIndex}.tool_calls.${toolCallIndex}.name`,\n arguments: `gen_ai.prompt.${promptIndex}.tool_calls.${toolCallIndex}.arguments`,\n }),\n tool: {\n callId: `gen_ai.prompt.${promptIndex}.tool_call_id`,\n toolName: `gen_ai.prompt.${promptIndex}.tool_name`,\n toolResult: `gen_ai.prompt.${promptIndex}.tool_result`,\n isError: `gen_ai.prompt.${promptIndex}.is_error`,\n },\n }),\n },\n completion: {\n _root: 'gen_ai.completion',\n index: (completionIndex: number) => ({\n role: `gen_ai.completion.${completionIndex}.role`,\n content: `gen_ai.completion.${completionIndex}.content`, // string or object\n toolCalls: (toolCallIndex: number) => ({\n id: `gen_ai.completion.${completionIndex}.tool_calls.${toolCallIndex}.id`,\n name: `gen_ai.completion.${completionIndex}.tool_calls.${toolCallIndex}.name`,\n arguments: `gen_ai.completion.${completionIndex}.tool_calls.${toolCallIndex}.arguments`,\n }),\n tool: {\n callId: `gen_ai.completion.${completionIndex}.tool_call_id`,\n toolName: `gen_ai.completion.${completionIndex}.tool_name`,\n toolResult: `gen_ai.completion.${completionIndex}.tool_result`,\n isError: `gen_ai.completion.${completionIndex}.is_error`,\n },\n }),\n },\n usage: {\n promptTokens: 'gen_ai.usage.prompt_tokens',\n completionTokens: 'gen_ai.usage.completion_tokens',\n },\n },\n },\n },\n\n // OpenInference (Arize/Phoenix)\n // https://arize-ai.github.io/openinference/spec/semantic_conventions.html\n OPENINFERENCE: {\n span: {\n kind: 'openinference.span.kind',\n },\n tool: {\n name: 'tool.name',\n },\n toolCall: {\n id: 'tool_call.id',\n function: {\n arguments: 'tool_call.function.arguments',\n result: 'tool_call.function.result',\n },\n },\n llm: {\n provider: 'llm.provider',\n system: 'llm.system', // Represents the provider!\n model: 'llm.model_name',\n inputMessages: 'llm.input_messages',\n outputMessages: 'llm.output_messages',\n invocationParameters: 'llm.invocation_parameters',\n prompts: 'llm.prompts', // llm.prompts.{index}.{role/content/...},\n completions: 'llm.completions', // llm.completions.{index}.{role/content/...},\n tools: 'llm.tools', // llm.tools.{index}.{name/arguments/result/...},\n tokenCount: {\n prompt: 'llm.token_count.prompt',\n promptDetails: {\n cacheInput: 'llm.token_count.prompt_details.cache_input',\n cacheRead: 'llm.token_count.prompt_details.cache_read',\n cacheWrite: 'llm.token_count.prompt_details.cache_write',\n },\n completionDetails: {\n reasoning: 'llm.token_count.completion_details.reasoning',\n },\n completion: 'llm.token_count.completion',\n },\n cost: {\n prompt: 'llm.cost.prompt',\n completion: 'llm.cost.completion',\n total: 'llm.cost.total',\n },\n },\n },\n\n // OpenLLMetry (Traceloop)\n // https://github.com/traceloop/openllmetry/blob/main/packages/opentelemetry-semantic-conventions-ai/opentelemetry/semconv_ai/__init__.py\n OPENLLMETRY: {\n llm: {\n request: {\n type: 'llm.request.type',\n },\n response: {\n finishReason: 'llm.response.finish_reason',\n stopReason: 'llm.response.stop_reason',\n },\n },\n usage: {\n cacheCreationInputTokens: 'gen_ai.usage.cache_creation_input_tokens',\n cacheReadInputTokens: 'gen_ai.usage.cache_read_input_tokens',\n },\n },\n\n // Vercel AI SDK\n // https://ai-sdk.dev/docs/ai-sdk-core/telemetry#span-details\n AI_SDK: {\n operationId: 'ai.operationId',\n model: {\n id: 'ai.model.id',\n provider: 'ai.model.provider',\n },\n request: {\n headers: {\n _root: 'ai.request.headers',\n },\n },\n response: {\n id: 'ai.response.id',\n model: 'ai.response.model',\n finishReason: 'ai.response.finishReason',\n text: 'ai.response.text',\n object: 'ai.response.object',\n toolCalls: 'ai.response.toolCalls',\n },\n toolCall: {\n name: 'ai.toolCall.name',\n id: 'ai.toolCall.id',\n args: 'ai.toolCall.args',\n result: 'ai.toolCall.result',\n },\n usage: {\n completionTokens: 'ai.usage.completionTokens',\n promptTokens: 'ai.usage.promptTokens',\n },\n settings: 'ai.settings',\n prompt: {\n messages: 'ai.prompt.messages',\n },\n },\n} as const\n\nexport const VALUES = {\n LATITUDE: {},\n OPENTELEMETRY: {\n GEN_AI: {\n operation: {\n chat: GEN_AI_OPERATION_NAME_VALUE_CHAT,\n createAgent: GEN_AI_OPERATION_NAME_VALUE_CREATE_AGENT,\n embeddings: GEN_AI_OPERATION_NAME_VALUE_EMBEDDINGS,\n executeTool: GEN_AI_OPERATION_NAME_VALUE_EXECUTE_TOOL,\n generateContent: GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT,\n invokeAgent: GEN_AI_OPERATION_NAME_VALUE_INVOKE_AGENT,\n textCompletion: GEN_AI_OPERATION_NAME_VALUE_TEXT_COMPLETION,\n },\n response: {\n finishReasons: {\n stop: 'stop',\n length: 'length',\n contentFilter: 'content_filter',\n toolCalls: 'tool_calls',\n error: 'error',\n other: 'other',\n unknown: 'unknown',\n },\n },\n output: {\n type: {\n image: GEN_AI_OUTPUT_TYPE_VALUE_IMAGE,\n json: GEN_AI_OUTPUT_TYPE_VALUE_JSON,\n speech: GEN_AI_OUTPUT_TYPE_VALUE_SPEECH,\n text: GEN_AI_OUTPUT_TYPE_VALUE_TEXT,\n },\n },\n tool: {\n type: {\n function: 'function',\n },\n },\n _deprecated: {\n operation: {\n tool: 'tool',\n completion: 'completion',\n embedding: 'embedding',\n retrieval: 'retrieval',\n reranking: 'reranking',\n },\n },\n },\n },\n OPENLLMETRY: {\n llm: {\n request: {\n // https://github.com/traceloop/openllmetry/blob/0fc734017197e48e988eaf54e20feaab8761f757/packages/opentelemetry-semantic-conventions-ai/opentelemetry/semconv_ai/__init__.py#L277\n type: {\n completion: 'completion',\n chat: 'chat',\n rerank: 'rerank',\n embedding: 'embedding',\n unknown: 'unknown',\n },\n },\n },\n },\n OPENINFERENCE: {\n span: {\n kind: {\n llm: 'LLM',\n chain: 'CHAIN',\n embedding: 'EMBEDDING',\n tool: 'TOOL',\n agent: 'AGENT',\n retriever: 'RETRIEVER',\n reranker: 'RERANKER',\n },\n },\n },\n AI_SDK: {\n // https://ai-sdk.dev/docs/ai-sdk-core/telemetry#span-details\n operationId: {\n // Vercel Wrappers (all contain at least one of the \"Completion\" operations)\n generateText: 'ai.generateText',\n streamText: 'ai.streamText',\n generateObject: 'ai.generateObject',\n streamObject: 'ai.streamObject',\n\n // Completions\n generateTextDoGenerate: 'ai.generateText.doGenerate',\n streamTextDoStream: 'ai.streamText.doStream',\n generateObjectDoGenerate: 'ai.generateObject.doGenerate',\n streamObjectDoStream: 'ai.streamObject.doStream',\n\n // Embeddings\n embed: 'ai.embed',\n embedDoEmbed: 'ai.embed.doEmbed',\n embedMany: 'ai.embed.embedMany',\n embedManyDoEmbed: 'ai.embed.embedMany.doEmbed',\n\n // Tool calling\n toolCall: 'ai.toolCall',\n },\n },\n} as const\n\n/**\n * Returns the first value found in the attributes object with one of the given keys.\n * If an attribute callback is provided,\n */\nexport function extractAttribute<T = string>({\n attributes,\n keys,\n serializer = (value) => String(value) as T,\n validation,\n}: {\n attributes: Record<string, SpanAttribute>\n keys: string[]\n serializer?: (value: unknown) => T\n validation?: (value: T) => boolean\n}): T | undefined {\n for (const key of keys) {\n if (key in attributes) {\n const value = serializer(attributes[key])\n if (!validation) return value\n if (validation(value)) return value\n }\n }\n return undefined\n}\n\nexport function extractAllAttributes<T = string>({\n attributes,\n keys,\n serializer = (value) => String(value) as T,\n validation,\n}: {\n attributes: Record<string, SpanAttribute>\n keys: string[]\n serializer?: (value: unknown) => T\n validation?: (value: T) => boolean\n}): T[] {\n const results: T[] = []\n for (const key of keys) {\n if (key in attributes) {\n const value = serializer(attributes[key])\n if (validation && !validation(value)) continue\n results.push(value)\n }\n }\n\n return results\n}\n","import { z } from 'zod'\n\nexport * from './span'\nexport * from './trace'\n\n/* Note: Instrumentation scopes from all language SDKs */\n\nexport const SCOPE_LATITUDE = 'so.latitude.instrumentation'\n\nexport enum InstrumentationScope {\n Manual = 'manual',\n Latitude = 'latitude',\n OpenAI = 'openai',\n Anthropic = 'anthropic',\n AzureOpenAI = 'azure', // Only python — js uses OpenAI instrumentation\n VercelAI = 'vercelai',\n VertexAI = 'vertexai',\n AIPlatform = 'aiplatform',\n MistralAI = 'mistralai', // Only python\n Bedrock = 'bedrock',\n Sagemaker = 'sagemaker', // Only python\n TogetherAI = 'togetherai',\n Replicate = 'replicate', // Only python\n Groq = 'groq', // Only python\n Cohere = 'cohere',\n LiteLLM = 'litellm', // Only python\n Langchain = 'langchain',\n LlamaIndex = 'llamaindex',\n DSPy = 'dspy', // Only python\n Haystack = 'haystack', // Only python\n Ollama = 'ollama', // Only python\n Transformers = 'transformers', // Only python\n AlephAlpha = 'alephalpha', // Only python\n}\n\n/* Note: Schemas for span ingestion following OpenTelemetry service request specification */\n\nexport namespace Otlp {\n export const attributeValueSchema = z.object({\n stringValue: z.string().optional(),\n intValue: z.number().optional(),\n boolValue: z.boolean().optional(),\n arrayValue: z\n .object({\n values: z.array(\n z.object({\n stringValue: z.string().optional(),\n intValue: z.number().optional(),\n boolValue: z.boolean().optional(),\n }),\n ),\n })\n .optional(),\n })\n export type AttributeValue = z.infer<typeof attributeValueSchema>\n\n export const attributeSchema = z.object({\n key: z.string(),\n value: attributeValueSchema,\n })\n export type Attribute = z.infer<typeof attributeSchema>\n\n export const eventSchema = z.object({\n name: z.string(),\n timeUnixNano: z.string(),\n attributes: z.array(attributeSchema).optional(),\n })\n export type Event = z.infer<typeof eventSchema>\n\n export const linkSchema = z.object({\n traceId: z.string(),\n spanId: z.string(),\n attributes: z.array(attributeSchema).optional(),\n })\n export type Link = z.infer<typeof linkSchema>\n\n export enum StatusCode {\n Unset = 0,\n Ok = 1,\n Error = 2,\n }\n\n export const statusSchema = z.object({\n code: z.number(),\n message: z.string().optional(),\n })\n export type Status = z.infer<typeof statusSchema>\n\n export enum SpanKind {\n Internal = 0,\n Server = 1,\n Client = 2,\n Producer = 3,\n Consumer = 4,\n }\n\n export const spanSchema = z.object({\n traceId: z.string(),\n spanId: z.string(),\n parentSpanId: z.string().optional(),\n name: z.string(),\n kind: z.number(),\n startTimeUnixNano: z.string(),\n endTimeUnixNano: z.string(),\n status: statusSchema.optional(),\n events: z.array(eventSchema).optional(),\n links: z.array(linkSchema).optional(),\n attributes: z.array(attributeSchema).optional(),\n })\n export type Span = z.infer<typeof spanSchema>\n\n export const scopeSchema = z.object({\n name: z.string(),\n version: z.string().optional(),\n })\n export type Scope = z.infer<typeof scopeSchema>\n\n export const scopeSpanSchema = z.object({\n scope: scopeSchema,\n spans: z.array(spanSchema),\n })\n export type ScopeSpan = z.infer<typeof scopeSpanSchema>\n\n export const resourceSchema = z.object({\n attributes: z.array(attributeSchema),\n })\n export type Resource = z.infer<typeof resourceSchema>\n\n export const resourceSpanSchema = z.object({\n resource: resourceSchema,\n scopeSpans: z.array(scopeSpanSchema),\n })\n export type ResourceSpan = z.infer<typeof resourceSpanSchema>\n\n export const serviceRequestSchema = z.object({\n resourceSpans: z.array(resourceSpanSchema),\n })\n export type ServiceRequest = z.infer<typeof serviceRequestSchema>\n}\n\nexport type SpanIngestionData = {\n ingestionId: string\n spans: Otlp.ResourceSpan[]\n}\n\n// prettier-ignore\nexport const SPAN_INGESTION_STORAGE_KEY = (\n ingestionId: string, // Note: using single id to avoid dangling folders\n) => encodeURI(`ingest/traces/${ingestionId}`)\n\nexport type SpanProcessingData = {\n span: Otlp.Span\n scope: Otlp.Scope\n resource: Otlp.Resource\n}\n\n// prettier-ignore\nexport const SPAN_PROCESSING_STORAGE_KEY = (\n processingId: string, // Note: using single id to avoid dangling folders\n) => encodeURI(`process/traces/${processingId}`)\n\nexport const TRACING_JOBS_MAX_ATTEMPTS = 3\nexport const TRACING_JOBS_DELAY_BETWEEN_CONFLICTS = () =>\n (Math.floor(Math.random() * 10) + 1) * 1000 // 1-10 random seconds in order to serialize conflicts (best effort)\n\nexport { ATTRIBUTES, VALUES } from './attributes'\n","import { z } from 'zod'\n\nexport const MAX_SIMULATION_TURNS = 10\n\nexport const globalGoalSourceSchema = z.object({\n type: z.literal('global'),\n value: z.string(),\n})\n\nexport const columnGoalSourceSchema = z.object({\n type: z.literal('column'),\n columnIndex: z.number(),\n})\n\nexport const simulatedUserGoalSourceSchema = z.discriminatedUnion('type', [\n globalGoalSourceSchema,\n columnGoalSourceSchema,\n])\n\nexport type SimulatedUserGoalSource = z.infer<\n typeof simulatedUserGoalSourceSchema\n>\n\nexport const SimulationSettingsSchema = z.object({\n simulateToolResponses: z.boolean().optional(),\n simulatedTools: z.array(z.string()).optional(), // Empty array means all tools are simulated (if simulateToolResponses is true).\n toolSimulationInstructions: z.string().optional(), // A prompt used to guide and generate the simulation result\n maxTurns: z.number().min(1).max(MAX_SIMULATION_TURNS).optional(), // The maximum number of turns to simulate. Default is 1, and any greater value will add a new user message to the simulated conversation.\n simulatedUserGoal: z.string().optional(), // Deprecated: Use simulatedUserGoalSource instead. Kept for backward compatibility.\n simulatedUserGoalSource: simulatedUserGoalSourceSchema.optional(), // The source for the simulated user goal (global text or dataset column).\n})\n\nexport type SimulationSettings = z.infer<typeof SimulationSettingsSchema>\n","import { z } from 'zod'\nimport { SimulationSettingsSchema } from './simulation'\n\nexport enum OptimizationEngine {\n Identity = 'identity',\n Gepa = 'gepa',\n}\n\nexport const OptimizationBudgetSchema = z.object({\n time: z.number().min(0).optional(),\n tokens: z.number().min(0).optional(),\n})\nexport type OptimizationBudget = z.infer<typeof OptimizationBudgetSchema>\n\nexport const OptimizationConfigurationSchema = z.object({\n dataset: z\n .object({\n target: z.number().min(0).optional(), // Note: number of rows to curate when not provided by the user\n label: z.string().optional(), // Note: expected output column when using a labeled evaluation\n })\n .optional(),\n parameters: z\n .record(\n z.string(),\n z.object({\n column: z.string().optional(), // Note: corresponding column in the user-provided trainset and testset\n isPii: z.boolean().optional(),\n }),\n )\n .optional(),\n simulation: SimulationSettingsSchema.optional(),\n scope: z\n .object({\n configuration: z.boolean().optional(),\n instructions: z.boolean().optional(),\n })\n .optional(),\n budget: OptimizationBudgetSchema.optional(),\n})\nexport type OptimizationConfiguration = z.infer<\n typeof OptimizationConfigurationSchema\n>\n\nexport const OPTIMIZATION_SCORE_SCALE = 1 // Note: most algorithms use floats with a scale of [0,1]\n\nexport const OPTIMIZATION_MAX_TIME = 2 * 60 * 60 // 2 hours\nexport const OPTIMIZATION_MAX_TOKENS = 100_000_000 // 100M tokens\n\nexport const OPTIMIZATION_CANCEL_TIMEOUT = 10 * 1000 // 10 seconds\n\nexport const OPTIMIZATION_DEFAULT_ERROR = 'Optimization cancelled'\nexport const OPTIMIZATION_CANCELLED_ERROR = 'Optimization cancelled by user'\n\nexport const OPTIMIZATION_MIN_ROWS = 4\nexport const OPTIMIZATION_MAX_ROWS = 1000\n\nexport const OPTIMIZATION_TESTSET_SPLIT = 0.7 // 70% trainset, 30% testset\nexport const OPTIMIZATION_VALSET_SPLIT = 0.5 // 50% testset, 50% valset\n","// TODO(tracing): deprecated\nexport const HEAD_COMMIT = 'live'\n\nexport enum Providers {\n OpenAI = 'openai',\n Anthropic = 'anthropic',\n Groq = 'groq',\n Mistral = 'mistral',\n Azure = 'azure',\n Google = 'google',\n GoogleVertex = 'google_vertex',\n AnthropicVertex = 'anthropic_vertex',\n Custom = 'custom',\n XAI = 'xai',\n AmazonBedrock = 'amazon_bedrock',\n DeepSeek = 'deepseek',\n Perplexity = 'perplexity',\n}\n\nexport enum DocumentType {\n Prompt = 'prompt',\n Agent = 'agent',\n}\n\nexport enum DocumentTriggerType {\n Email = 'email',\n Scheduled = 'scheduled',\n Integration = 'integration',\n}\n\nexport enum DocumentTriggerStatus {\n Pending = 'pending',\n Deployed = 'deployed',\n Deprecated = 'deprecated',\n}\n\nexport enum DocumentTriggerParameters {\n SenderEmail = 'senderEmail',\n SenderName = 'senderName',\n Subject = 'subject',\n Body = 'body',\n Attachments = 'attachments',\n}\n\n// TODO: Remove these\nexport * from './ai'\nexport * from './config'\nexport * from './evaluations'\nexport * from './events'\nexport * from './experiments'\nexport * from './grants'\nexport * from './helpers'\nexport * from './history'\nexport * from './integrations'\nexport * from './mcp'\nexport * from './models'\nexport * from './runs'\nexport * from './tools'\nexport * from './tracing'\nexport * from './optimizations'\nexport * from './simulation'\nexport * from './messages'\n\n// TODO: Move to env\nexport const EMAIL_TRIGGER_DOMAIN = 'run.latitude.so' as const\nexport const OPENAI_PROVIDER_ENDPOINTS = [\n 'responses',\n 'chat_completions', // (DEPRECATED)\n] as const\n\nexport type TodoListItem = {\n content: string\n id: string\n status: 'pending' | 'in_progress' | 'completed' | 'cancelled'\n}\n\nexport type TodoList = TodoListItem[]\n\nexport const DOCUMENT_PATH_REGEXP = /^([\\w-]+\\/)*([\\w-.])+$/\n","import { BaseInstrumentation } from '$telemetry/instrumentations/base'\nimport { toKebabCase, toSnakeCase } from '$telemetry/utils'\nimport {\n ATTRIBUTES,\n HEAD_COMMIT,\n LogSources,\n SPAN_SPECIFICATIONS,\n SpanType,\n TraceContext,\n VALUES,\n} from '@latitude-data/constants'\nimport * as otel from '@opentelemetry/api'\nimport { propagation, trace } from '@opentelemetry/api'\nimport { Provider, Translator } from 'rosetta-ai'\n\nconst translator = new Translator({\n filterEmptyMessages: true,\n providerMetadata: 'preserve',\n})\n\nexport type StartSpanOptions = {\n name?: string\n attributes?: otel.Attributes\n}\n\nexport type EndSpanOptions = {\n attributes?: otel.Attributes\n}\n\nexport type ErrorOptions = {\n attributes?: otel.Attributes\n}\n\nexport type StartToolSpanOptions = StartSpanOptions & {\n name: string\n call: {\n id: string\n arguments: Record<string, unknown>\n }\n}\n\nexport type EndToolSpanOptions = EndSpanOptions & {\n result: {\n value: unknown\n isError: boolean\n }\n}\n\nexport type StartCompletionSpanOptions = StartSpanOptions & {\n provider: string\n model: string\n configuration?: Record<string, unknown>\n input?: string | Record<string, unknown>[]\n versionUuid?: string\n promptUuid?: string\n experimentUuid?: string\n}\n\nexport type EndCompletionSpanOptions = EndSpanOptions & {\n output?: string | Record<string, unknown>[]\n tokens?: {\n prompt?: number\n cached?: number\n reasoning?: number\n completion?: number\n }\n finishReason?: string\n}\n\nexport type StartHttpSpanOptions = StartSpanOptions & {\n request: {\n method: string\n url: string\n headers: Record<string, string>\n body: string | Record<string, unknown>\n }\n}\n\nexport type EndHttpSpanOptions = EndSpanOptions & {\n response: {\n status: number\n headers: Record<string, string>\n body: string | Record<string, unknown>\n }\n}\n\nexport type PromptSpanOptions = StartSpanOptions & {\n documentLogUuid: string\n versionUuid?: string // Alias for commitUuid\n promptUuid: string // Alias for documentUuid\n projectId?: number\n experimentUuid?: string\n testDeploymentId?: number\n externalId?: string\n template: string\n parameters?: Record<string, unknown>\n source?: LogSources\n}\n\nexport type ChatSpanOptions = StartSpanOptions & {\n documentLogUuid: string\n previousTraceId: string\n source?: LogSources\n versionUuid?: string // Alias for commitUuid\n promptUuid?: string // Alias for documentUuid\n}\n\nexport type ExternalSpanOptions = StartSpanOptions & {\n promptUuid: string // Alias for documentUuid\n documentLogUuid: string\n source?: LogSources // Defaults to LogSources.API\n versionUuid?: string // Alias for commitUuid\n externalId?: string\n}\n\nexport type CaptureOptions = StartSpanOptions & {\n path: string // The document path\n projectId: number\n versionUuid?: string // Optional, defaults to HEAD commit\n conversationUuid?: string // Optional, if provided, will be used as the documentLogUuid\n}\n\nexport type ManualInstrumentationOptions = {\n provider?: Provider\n}\n\nexport class ManualInstrumentation implements BaseInstrumentation {\n private enabled: boolean\n private readonly tracer: otel.Tracer\n private readonly options: ManualInstrumentationOptions\n\n constructor(tracer: otel.Tracer, options?: ManualInstrumentationOptions) {\n this.enabled = false\n this.tracer = tracer\n this.options = options ?? {}\n }\n\n isEnabled() {\n return this.enabled\n }\n\n enable() {\n this.enabled = true\n }\n\n disable() {\n this.enabled = false\n }\n\n resume(ctx: TraceContext): otel.Context {\n const parts = ctx.traceparent.split('-')\n if (parts.length !== 4) {\n return otel.ROOT_CONTEXT\n }\n\n const [, traceId, spanId, flags] = parts\n if (!traceId || !spanId) {\n return otel.ROOT_CONTEXT\n }\n\n const spanContext: otel.SpanContext = {\n traceId,\n spanId,\n traceFlags: parseInt(flags ?? '01', 16),\n isRemote: true,\n }\n\n let context = trace.setSpanContext(otel.ROOT_CONTEXT, spanContext)\n\n if (ctx.baggage) {\n const baggageEntries: Record<string, otel.BaggageEntry> = {}\n for (const pair of ctx.baggage.split(',')) {\n const [key, value] = pair.split('=')\n if (key && value) {\n baggageEntries[key] = { value: decodeURIComponent(value) }\n }\n }\n const baggage = propagation.createBaggage(baggageEntries)\n context = propagation.setBaggage(context, baggage)\n }\n\n return context\n }\n\n private error(span: otel.Span, error: Error, options?: ErrorOptions) {\n options = options || {}\n\n span.recordException(error)\n span.setAttributes(options.attributes || {})\n span.setStatus({\n code: otel.SpanStatusCode.ERROR,\n message: error.message || undefined,\n })\n span.end()\n }\n\n private span<T extends SpanType>(\n ctx: otel.Context,\n name: string,\n type: T,\n options?: StartSpanOptions,\n ) {\n if (!this.enabled) {\n return {\n context: ctx,\n end: (_options?: EndSpanOptions) => {},\n fail: (_error: Error, _options?: ErrorOptions) => {},\n }\n }\n\n const start = options || {}\n\n let operation = undefined\n if (SPAN_SPECIFICATIONS[type].isGenAI) {\n operation = type\n }\n\n const span = this.tracer.startSpan(\n name,\n {\n attributes: {\n [ATTRIBUTES.LATITUDE.type]: type,\n ...(operation && {\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.operation]: operation,\n }),\n ...(start.attributes || {}),\n },\n kind: otel.SpanKind.CLIENT,\n },\n ctx,\n )\n\n const newCtx = trace.setSpan(ctx, span)\n\n return {\n context: newCtx,\n end: (options?: EndSpanOptions) => {\n const end = options || {}\n\n span.setAttributes(end.attributes || {})\n span.setStatus({ code: otel.SpanStatusCode.OK })\n span.end()\n },\n fail: (error: Error, options?: ErrorOptions) => {\n this.error(span, error, options)\n },\n }\n }\n\n unknown(ctx: otel.Context, options?: StartSpanOptions) {\n return this.span(\n ctx,\n options?.name || SPAN_SPECIFICATIONS[SpanType.Unknown].name,\n SpanType.Unknown,\n options,\n )\n }\n\n tool(ctx: otel.Context, options: StartToolSpanOptions) {\n const start = options\n\n let jsonArguments = ''\n try {\n jsonArguments = JSON.stringify(start.call.arguments)\n } catch (_error) {\n jsonArguments = '{}'\n }\n\n const span = this.span(ctx, start.name, SpanType.Tool, {\n attributes: {\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI._deprecated.tool.name]: start.name,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI._deprecated.tool.type]:\n VALUES.OPENTELEMETRY.GEN_AI.tool.type.function,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.tool.call.id]: start.call.id,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.tool.call.arguments]: jsonArguments,\n ...(start.attributes || {}),\n },\n })\n\n return {\n ...span,\n end: (options: EndToolSpanOptions) => {\n const end = options\n\n let stringResult = ''\n if (typeof end.result.value !== 'string') {\n try {\n stringResult = JSON.stringify(end.result.value)\n } catch (_error) {\n stringResult = '{}'\n }\n } else {\n stringResult = end.result.value\n }\n\n span.end({\n attributes: {\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI._deprecated.tool.result.value]:\n stringResult,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI._deprecated.tool.result.isError]:\n end.result.isError,\n ...(end.attributes || {}),\n },\n })\n },\n }\n }\n\n private attribifyConfiguration(\n direction: 'input' | 'output',\n configuration: Record<string, unknown>,\n ) {\n const prefix =\n direction === 'input'\n ? ATTRIBUTES.LATITUDE.request._root\n : ATTRIBUTES.LATITUDE.response._root\n\n const attributes: otel.Attributes = {}\n for (const key in configuration) {\n const field = toSnakeCase(key)\n let value = configuration[key]\n if (value === null || value === undefined) continue\n if (typeof value === 'object' && !Array.isArray(value)) {\n try {\n value = JSON.stringify(value)\n } catch (_error) {\n value = '{}'\n }\n }\n\n attributes[`${prefix}.${field}`] = value as any\n }\n\n return attributes\n }\n\n completion(ctx: otel.Context, options: StartCompletionSpanOptions) {\n const start = options\n\n const configuration = {\n ...(start.configuration ?? {}),\n model: start.model,\n }\n let jsonConfiguration = ''\n try {\n jsonConfiguration = JSON.stringify(configuration)\n } catch (_error) {\n jsonConfiguration = '{}'\n }\n const attrConfiguration = this.attribifyConfiguration(\n 'input',\n configuration,\n )\n\n const input = start.input ?? []\n let jsonSystem = ''\n let jsonInput = ''\n try {\n const translated = translator.translate(input, {\n from: this.options.provider,\n to: Provider.GenAI,\n direction: 'input',\n })\n jsonSystem = JSON.stringify(translated.system ?? [])\n jsonInput = JSON.stringify(translated.messages ?? [])\n } catch (_error) {\n jsonSystem = '[]'\n jsonInput = '[]'\n }\n\n const span = this.span(\n ctx,\n start.name || `${start.provider} / ${start.model}`,\n SpanType.Completion,\n {\n attributes: {\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI._deprecated.system]: start.provider,\n [ATTRIBUTES.LATITUDE.request.configuration]: jsonConfiguration,\n ...attrConfiguration,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.systemInstructions]: jsonSystem,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.input.messages]: jsonInput,\n ...(start.attributes || {}),\n [ATTRIBUTES.LATITUDE.commitUuid]: start.versionUuid,\n [ATTRIBUTES.LATITUDE.documentUuid]: start.promptUuid,\n [ATTRIBUTES.LATITUDE.experimentUuid]: start.experimentUuid,\n },\n },\n )\n\n return {\n ...span,\n end: (options?: EndCompletionSpanOptions) => {\n const end = options ?? {}\n\n const output = end.output ?? []\n let jsonOutput = ''\n try {\n const translated = translator.translate(output, {\n from: this.options.provider,\n to: Provider.GenAI,\n direction: 'output',\n })\n jsonOutput = JSON.stringify(translated.messages ?? [])\n } catch (_error) {\n jsonOutput = '[]'\n }\n\n const tokens = {\n prompt: end.tokens?.prompt ?? 0,\n cached: end.tokens?.cached ?? 0,\n reasoning: end.tokens?.reasoning ?? 0,\n completion: end.tokens?.completion ?? 0,\n }\n const inputTokens = tokens.prompt + tokens.cached\n const outputTokens = tokens.reasoning + tokens.completion\n const finishReason = end.finishReason ?? ''\n\n span.end({\n attributes: {\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.output.messages]: jsonOutput,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.usage.inputTokens]: inputTokens,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.usage.outputTokens]: outputTokens,\n [ATTRIBUTES.LATITUDE.usage.promptTokens]: tokens.prompt,\n [ATTRIBUTES.LATITUDE.usage.cachedTokens]: tokens.cached,\n [ATTRIBUTES.LATITUDE.usage.reasoningTokens]: tokens.reasoning,\n [ATTRIBUTES.LATITUDE.usage.completionTokens]: tokens.completion,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.response.model]: start.model,\n [ATTRIBUTES.OPENTELEMETRY.GEN_AI.response.finishReasons]: [\n finishReason,\n ],\n ...(end.attributes || {}),\n },\n })\n },\n }\n }\n\n embedding(ctx: otel.Context, options?: StartSpanOptions) {\n return this.span(\n ctx,\n options?.name || SPAN_SPECIFICATIONS[SpanType.Embedding].name,\n SpanType.Embedding,\n options,\n )\n }\n\n private attribifyHeaders(\n direction: 'request' | 'response',\n headers: Record<string, string>,\n ) {\n const prefix =\n direction === 'request'\n ? ATTRIBUTES.OPENTELEMETRY.HTTP.request.header\n : ATTRIBUTES.OPENTELEMETRY.HTTP.response.header\n\n const attributes: otel.Attributes = {}\n for (const key in headers) {\n const field = toKebabCase(key)\n const value = headers[key]\n if (value === null || value === undefined) continue\n\n attributes[`${prefix}.${field}`] = value as any\n }\n\n return attributes\n }\n\n http(ctx: otel.Context, options: StartHttpSpanOptions) {\n const start = options\n\n const method = start.request.method.toUpperCase()\n\n // Note: do not serialize headers as a single attribute because fields won't be redacted\n const attrHeaders = this.attribifyHeaders('request', start.request.headers)\n\n let finalBody = ''\n if (typeof start.request.body === 'string') {\n finalBody = start.request.body\n } else {\n try {\n finalBody = JSON.stringify(start.request.body)\n } catch (_error) {\n finalBody = '{}'\n }\n }\n\n const span = this.span(\n ctx,\n start.name || `${method} ${start.request.url}`,\n SpanType.Http,\n {\n attributes: {\n [ATTRIBUTES.OPENTELEMETRY.HTTP.request.method]: method,\n [ATTRIBUTES.OPENTELEMETRY.HTTP.request.url]: start.request.url,\n ...attrHeaders,\n [ATTRIBUTES.OPENTELEMETRY.HTTP.request.body]: finalBody,\n ...(start.attributes || {}),\n },\n },\n )\n\n return {\n ...span,\n end: (options: EndHttpSpanOptions) => {\n const end = options\n\n // Note: do not serialize headers as a single attribute because fields won't be redacted\n const attrHeaders = this.attribifyHeaders(\n 'response',\n end.response.headers,\n )\n\n let finalBody = ''\n if (typeof end.response.body === 'string') {\n finalBody = end.response.body\n } else {\n try {\n finalBody = JSON.stringify(end.response.body)\n } catch (_error) {\n finalBody = '{}'\n }\n }\n\n span.end({\n attributes: {\n [ATTRIBUTES.OPENTELEMETRY.HTTP.response.statusCode]:\n end.response.status,\n ...attrHeaders,\n [ATTRIBUTES.OPENTELEMETRY.HTTP.response.body]: finalBody,\n ...(end.attributes || {}),\n },\n })\n },\n }\n }\n\n prompt(\n ctx: otel.Context,\n {\n documentLogUuid,\n versionUuid,\n promptUuid,\n projectId,\n experimentUuid,\n testDeploymentId,\n externalId,\n template,\n parameters,\n name,\n source,\n ...rest\n }: PromptSpanOptions,\n ) {\n let jsonParameters = ''\n try {\n jsonParameters = JSON.stringify(parameters || {})\n } catch (_error) {\n jsonParameters = '{}'\n }\n\n const attributes = {\n [ATTRIBUTES.LATITUDE.request.template]: template,\n [ATTRIBUTES.LATITUDE.request.parameters]: jsonParameters,\n [ATTRIBUTES.LATITUDE.commitUuid]: versionUuid || HEAD_COMMIT,\n [ATTRIBUTES.LATITUDE.documentUuid]: promptUuid,\n [ATTRIBUTES.LATITUDE.projectId]: projectId,\n [ATTRIBUTES.LATITUDE.documentLogUuid]: documentLogUuid,\n ...(experimentUuid && {\n [ATTRIBUTES.LATITUDE.experimentUuid]: experimentUuid,\n }),\n ...(testDeploymentId && {\n [ATTRIBUTES.LATITUDE.testDeploymentId]: testDeploymentId,\n }),\n ...(externalId && { [ATTRIBUTES.LATITUDE.externalId]: externalId }),\n ...(source && { [ATTRIBUTES.LATITUDE.source]: source }),\n ...(rest.attributes || {}),\n }\n\n return this.span(ctx, name || `prompt-${promptUuid}`, SpanType.Prompt, {\n attributes,\n })\n }\n\n chat(\n ctx: otel.Context,\n {\n documentLogUuid,\n previousTraceId,\n source,\n name,\n versionUuid,\n promptUuid,\n ...rest\n }: ChatSpanOptions,\n ) {\n const attributes = {\n [ATTRIBUTES.LATITUDE.documentLogUuid]: documentLogUuid,\n [ATTRIBUTES.LATITUDE.previousTraceId]: previousTraceId,\n ...(versionUuid && { [ATTRIBUTES.LATITUDE.commitUuid]: versionUuid }),\n ...(promptUuid && { [ATTRIBUTES.LATITUDE.documentUuid]: promptUuid }),\n ...(source && { [ATTRIBUTES.LATITUDE.source]: source }),\n ...(rest.attributes || {}),\n }\n\n return this.span(ctx, name || `chat-${documentLogUuid}`, SpanType.Chat, {\n attributes,\n })\n }\n\n external(\n ctx: otel.Context,\n {\n promptUuid,\n documentLogUuid,\n source,\n versionUuid,\n externalId,\n name,\n ...rest\n }: ExternalSpanOptions,\n ) {\n const attributes = {\n [ATTRIBUTES.LATITUDE.documentUuid]: promptUuid,\n [ATTRIBUTES.LATITUDE.documentLogUuid]: documentLogUuid,\n [ATTRIBUTES.LATITUDE.source]: source ?? LogSources.API,\n ...(versionUuid && { [ATTRIBUTES.LATITUDE.commitUuid]: versionUuid }),\n ...(externalId && { [ATTRIBUTES.LATITUDE.externalId]: externalId }),\n ...(rest.attributes || {}),\n }\n\n return this.span(ctx, name || `external-${promptUuid}`, SpanType.External, {\n attributes,\n })\n }\n\n // TODO(tracing): deprecate\n unresolvedExternal(\n ctx: otel.Context,\n {\n path,\n projectId,\n versionUuid,\n conversationUuid,\n name,\n ...rest\n }: CaptureOptions,\n ) {\n const attributes = {\n [ATTRIBUTES.LATITUDE.promptPath]: path,\n [ATTRIBUTES.LATITUDE.projectId]: projectId,\n ...(versionUuid && { [ATTRIBUTES.LATITUDE.commitUuid]: versionUuid }),\n ...(conversationUuid && {\n [ATTRIBUTES.LATITUDE.documentLogUuid]: conversationUuid,\n }),\n ...(rest.attributes || {}),\n }\n\n return this.span(\n ctx,\n name || `capture-${path}`,\n SpanType.UnresolvedExternal,\n { attributes },\n )\n }\n}\n","import { BaseInstrumentation } from '$telemetry/instrumentations/base'\nimport { ManualInstrumentation } from '$telemetry/instrumentations/manual'\nimport { VALUES } from '@latitude-data/constants'\nimport type { Latitude } from '@latitude-data/sdk'\nimport type { Tracer } from '@opentelemetry/api'\nimport { context } from '@opentelemetry/api'\nimport type { AdapterMessageType } from 'promptl-ai'\nimport { v4 as uuid } from 'uuid'\n\nexport type LatitudeInstrumentationOptions = {\n module: typeof Latitude\n completions?: boolean\n}\n\nexport class LatitudeInstrumentation implements BaseInstrumentation {\n private readonly options: LatitudeInstrumentationOptions\n private readonly manualTelemetry: ManualInstrumentation\n\n constructor(tracer: Tracer, options: LatitudeInstrumentationOptions) {\n this.manualTelemetry = new ManualInstrumentation(tracer)\n this.options = options\n }\n\n isEnabled() {\n return this.manualTelemetry.isEnabled()\n }\n\n enable() {\n this.manualTelemetry.enable()\n this.options.module.instrument(this)\n }\n\n disable() {\n this.manualTelemetry.disable()\n this.options.module.uninstrument()\n }\n\n private countTokens<M extends AdapterMessageType>(messages: M[]) {\n let length = 0\n\n for (const message of messages) {\n if (!('content' in message)) continue\n if (typeof message.content === 'string') {\n length += message.content.length\n } else if (Array.isArray(message.content)) {\n for (const content of message.content) {\n if (content.type === 'text') {\n length += content.text.length\n }\n }\n }\n }\n\n // Note: this is an estimation to not bundle a tokenizer\n return Math.ceil(length / 4)\n }\n\n async wrapRenderChain<F extends Latitude['renderChain']>(\n fn: F,\n ...args: Parameters<F>\n ): Promise<Awaited<ReturnType<F>>> {\n const { prompt, parameters } = args[0]\n\n const $prompt = this.manualTelemetry.prompt(context.active(), {\n documentLogUuid: uuid(),\n versionUuid: prompt.versionUuid,\n promptUuid: prompt.uuid,\n template: prompt.content,\n parameters: parameters,\n })\n\n let result\n try {\n result = await context.with(\n $prompt.context,\n async () => await ((fn as any)(...args) as ReturnType<F>),\n )\n } catch (error) {\n $prompt.fail(error as Error)\n throw error\n }\n\n $prompt.end()\n\n return result\n }\n\n async wrapRenderCompletion<F extends Latitude['renderCompletion']>(\n fn: F,\n ...args: Parameters<F>\n ): Promise<Awaited<ReturnType<F>>> {\n if (!this.options.completions) {\n return await ((fn as any)(...args) as ReturnType<F>)\n }\n\n const { provider, config, messages } = args[0]\n const model = (config.model as string) || 'unknown'\n\n const $completion = this.manualTelemetry.completion(context.active(), {\n name: `${provider} / ${model}`,\n provider: provider,\n model: model,\n configuration: config,\n input: messages as Record<string, unknown>[],\n })\n\n let result\n try {\n result = await context.with(\n $completion.context,\n async () => await ((fn as any)(...args) as ReturnType<F>),\n )\n } catch (error) {\n $completion.fail(error as Error)\n throw error\n }\n\n // Note: enhance, this is just an estimation\n const promptTokens = this.countTokens(messages)\n const completionTokens = this.countTokens(result.messages)\n\n $completion.end({\n output: result.messages as Record<string, unknown>[],\n tokens: {\n prompt: promptTokens,\n cached: 0,\n reasoning: 0,\n completion: completionTokens,\n },\n finishReason:\n result.toolRequests.length > 0\n ? VALUES.OPENTELEMETRY.GEN_AI.response.finishReasons.toolCalls\n : VALUES.OPENTELEMETRY.GEN_AI.response.finishReasons.stop,\n })\n\n return result\n }\n\n async wrapRenderTool<F extends Latitude['renderTool']>(\n fn: F,\n ...args: Parameters<F>\n ): Promise<Awaited<ReturnType<F>>> {\n const { toolRequest } = args[0]\n\n const $tool = this.manualTelemetry.tool(context.active(), {\n name: toolRequest.toolName,\n call: {\n id: toolRequest.toolCallId,\n arguments: toolRequest.toolArguments,\n },\n })\n\n let result\n try {\n result = await context.with(\n $tool.context,\n async () => await ((fn as any)(...args) as ReturnType<F>),\n )\n } catch (error) {\n $tool.fail(error as Error)\n throw error\n }\n\n $tool.end({\n result: {\n value: result.result,\n isError: result.isError,\n },\n })\n\n return result\n }\n}\n","export enum LatitudeErrorCodes {\n UnexpectedError = 'UnexpectedError',\n OverloadedError = 'OverloadedError',\n RateLimitError = 'RateLimitError',\n UnauthorizedError = 'UnauthorizedError',\n ForbiddenError = 'ForbiddenError',\n BadRequestError = 'BadRequestError',\n NotFoundError = 'NotFoundError',\n ConflictError = 'ConflictError',\n UnprocessableEntityError = 'UnprocessableEntityError',\n NotImplementedError = 'NotImplementedError',\n PaymentRequiredError = 'PaymentRequiredError',\n AbortedError = 'AbortedError',\n BillingError = 'BillingError',\n}\n\nexport type LatitudeErrorDetails = {\n [key: string | number | symbol]: string[] | string | undefined\n}\n\n// NOTE: If you add a new error code, please add it to the pg enum in models/runErrors.ts\nexport enum RunErrorCodes {\n AIProviderConfigError = 'ai_provider_config_error',\n AIRunError = 'ai_run_error',\n ChainCompileError = 'chain_compile_error',\n DefaultProviderExceededQuota = 'default_provider_exceeded_quota_error',\n DefaultProviderInvalidModel = 'default_provider_invalid_model_error',\n DocumentConfigError = 'document_config_error',\n ErrorGeneratingMockToolResult = 'error_generating_mock_tool_result',\n FailedToWakeUpIntegrationError = 'failed_to_wake_up_integration_error',\n InvalidResponseFormatError = 'invalid_response_format_error',\n MaxStepCountExceededError = 'max_step_count_exceeded_error',\n MissingProvider = 'missing_provider_error',\n RateLimit = 'rate_limit_error',\n Unknown = 'unknown_error',\n UnsupportedProviderResponseTypeError = 'unsupported_provider_response_type_error',\n PaymentRequiredError = 'payment_required_error',\n AbortError = 'abort_error',\n\n // DEPRECATED, but do not delete\n EvaluationRunMissingProviderLogError = 'ev_run_missing_provider_log_error',\n EvaluationRunMissingWorkspaceError = 'ev_run_missing_workspace_error',\n EvaluationRunResponseJsonFormatError = 'ev_run_response_json_format_error',\n EvaluationRunUnsupportedResultTypeError = 'ev_run_unsupported_result_type_error',\n}\n// NOTE: If you add a new error code, please add it to the pg enum in models/runErrors.ts\n\nexport type RunErrorDetails<C extends RunErrorCodes> =\n C extends RunErrorCodes.ChainCompileError\n ? { compileCode: string; message: string }\n : C extends RunErrorCodes.Unknown\n ? { stack: string }\n : never\n\nexport enum ApiErrorCodes {\n HTTPException = 'http_exception',\n InternalServerError = 'internal_server_error',\n}\n\nexport type DbErrorRef = {\n entityUuid: string\n entityType: string\n}\n\nexport type ApiErrorJsonResponse = {\n name: string\n message: string\n details: object\n errorCode: ApiResponseCode\n dbErrorRef?: DbErrorRef\n}\nexport type ApiResponseCode = RunErrorCodes | ApiErrorCodes | LatitudeErrorCodes\n","import {\n LatitudeErrorCodes,\n LatitudeErrorDetails,\n RunErrorCodes,\n} from './constants'\n\nexport type LatitudeErrorDto = {\n name: LatitudeErrorCodes\n code: RunErrorCodes\n status: number\n message: string\n details: Record<string, unknown>\n}\n\nexport class LatitudeError extends Error {\n statusCode: number = 500\n name: string = LatitudeErrorCodes.UnexpectedError\n headers: Record<string, string> = {}\n\n public details: LatitudeErrorDetails\n\n constructor(\n message: string,\n details?: LatitudeErrorDetails,\n status?: number,\n name?: string,\n ) {\n super(message)\n this.details = details ?? {}\n this.statusCode = status ?? this.statusCode\n this.name = name ?? this.constructor.name\n }\n\n serialize(): LatitudeErrorDto {\n return {\n name: this.name as LatitudeErrorCodes,\n code: this.name as RunErrorCodes,\n status: this.statusCode,\n message: this.message,\n details: this.details,\n }\n }\n\n static deserialize(json: LatitudeErrorDto): LatitudeError {\n return new LatitudeError(\n json.message,\n json.details as LatitudeErrorDetails,\n json.status,\n json.name,\n )\n }\n}\n\nexport class OverloadedError extends LatitudeError {\n public statusCode = 429\n public name = LatitudeErrorCodes.OverloadedError\n}\n\nexport class AbortedError extends LatitudeError {\n public statusCode = 499\n public reason = 'Client Closed Request'\n public name = LatitudeErrorCodes.AbortedError\n constructor(message: string = 'Operation was aborted') {\n super(message)\n this.reason = message\n }\n}\n\nexport class ConflictError extends LatitudeError {\n public statusCode = 409\n public name = LatitudeErrorCodes.ConflictError\n}\n\nexport class UnprocessableEntityError extends LatitudeError {\n public statusCode = 422\n public name = LatitudeErrorCodes.UnprocessableEntityError\n\n constructor(message: string, details: LatitudeErrorDetails = {}) {\n super(message, details)\n }\n}\n\nexport class NotFoundError extends LatitudeError {\n public statusCode = 404\n public name = LatitudeErrorCodes.NotFoundError\n}\n\nexport class BadRequestError extends LatitudeError {\n public statusCode = 400\n public name = LatitudeErrorCodes.BadRequestError\n}\n\nexport class ForbiddenError extends LatitudeError {\n public statusCode = 403\n public name = LatitudeErrorCodes.ForbiddenError\n}\n\nexport class UnauthorizedError extends LatitudeError {\n public statusCode = 401\n public name = LatitudeErrorCodes.UnauthorizedError\n}\nexport class RateLimitError extends LatitudeError {\n public statusCode = 429\n public name = LatitudeErrorCodes.RateLimitError\n\n constructor(\n message: string,\n retryAfter?: number,\n limit?: number,\n remaining?: number,\n resetTime?: number,\n ) {\n super(message)\n\n this.headers = {}\n if (retryAfter !== undefined) {\n this.headers['Retry-After'] = retryAfter.toString()\n }\n if (limit !== undefined) {\n this.headers['X-RateLimit-Limit'] = limit.toString()\n }\n if (remaining !== undefined) {\n this.headers['X-RateLimit-Remaining'] = remaining.toString()\n }\n if (resetTime !== undefined) {\n this.headers['X-RateLimit-Reset'] = resetTime.toString()\n }\n }\n}\n\nexport class NotImplementedError extends LatitudeError {\n public statusCode = 501\n public name = LatitudeErrorCodes.NotImplementedError\n}\n\nexport class PaymentRequiredError extends LatitudeError {\n public statusCode = 402\n public name = LatitudeErrorCodes.PaymentRequiredError\n}\n\nexport type BillingErrorTags = {\n workspaceId?: number\n userEmail?: string\n stripeCustomerId?: string\n plan?: string\n}\n\n/**\n * Error class for billing-related failures (Stripe API errors, etc.).\n * Includes tags for error tracking in Datadog.\n */\nexport class BillingError extends LatitudeError {\n public statusCode = 400\n public name = LatitudeErrorCodes.BillingError\n public tags: BillingErrorTags\n public originalError?: Error\n\n constructor(\n message: string,\n {\n tags = {},\n originalError,\n }: {\n tags?: BillingErrorTags\n originalError?: Error\n } = {},\n ) {\n super(message, {\n workspaceId: tags.workspaceId?.toString(),\n userEmail: tags.userEmail,\n stripeCustomerId: tags.stripeCustomerId,\n plan: tags.plan,\n })\n this.tags = tags\n this.originalError = originalError\n }\n}\n\nexport const databaseErrorCodes = {\n foreignKeyViolation: '23503',\n uniqueViolation: '23505',\n lockNotAvailable: '55P03',\n}\n","import { env } from '$telemetry/env'\nimport {\n BaseInstrumentation,\n CaptureOptions,\n ChatSpanOptions,\n ExternalSpanOptions,\n LatitudeInstrumentation,\n LatitudeInstrumentationOptions,\n ManualInstrumentation,\n ManualInstrumentationOptions,\n PromptSpanOptions,\n StartCompletionSpanOptions,\n StartHttpSpanOptions,\n StartSpanOptions,\n StartToolSpanOptions,\n} from '$telemetry/instrumentations'\nimport { DEFAULT_REDACT_SPAN_PROCESSOR } from '$telemetry/sdk/redact'\nimport {\n ATTRIBUTES,\n DOCUMENT_PATH_REGEXP,\n InstrumentationScope,\n SCOPE_LATITUDE,\n TraceContext,\n} from '@latitude-data/constants'\nimport { BadRequestError } from '@latitude-data/constants/errors'\nimport type * as latitude from '@latitude-data/sdk'\nimport * as otel from '@opentelemetry/api'\nimport { context, propagation, TextMapPropagator } from '@opentelemetry/api'\nimport {\n ALLOW_ALL_BAGGAGE_KEYS,\n BaggageSpanProcessor,\n} from '@opentelemetry/baggage-span-processor'\nimport { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks'\nimport {\n CompositePropagator,\n W3CBaggagePropagator,\n W3CTraceContextPropagator,\n} from '@opentelemetry/core'\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'\nimport { registerInstrumentations } from '@opentelemetry/instrumentation'\nimport { Resource } from '@opentelemetry/resources'\nimport {\n BatchSpanProcessor,\n NodeTracerProvider,\n SimpleSpanProcessor,\n SpanExporter,\n SpanProcessor,\n} from '@opentelemetry/sdk-trace-node'\nimport { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions'\nimport { AnthropicInstrumentation } from '@traceloop/instrumentation-anthropic'\nimport { BedrockInstrumentation } from '@traceloop/instrumentation-bedrock'\nimport { CohereInstrumentation } from '@traceloop/instrumentation-cohere'\nimport { LangChainInstrumentation } from '@traceloop/instrumentation-langchain'\nimport { LlamaIndexInstrumentation } from '@traceloop/instrumentation-llamaindex'\nimport { OpenAIInstrumentation } from '@traceloop/instrumentation-openai'\nimport { TogetherInstrumentation } from '@traceloop/instrumentation-together'\nimport {\n AIPlatformInstrumentation,\n VertexAIInstrumentation,\n} from '@traceloop/instrumentation-vertexai'\n\nconst TRACES_URL = `${env.GATEWAY_BASE_URL}/api/v3/traces`\nconst SERVICE_NAME = process.env.npm_package_name || 'unknown'\nconst SCOPE_VERSION = process.env.npm_package_version || 'unknown'\n\nexport type TelemetryContext = otel.Context\nexport const BACKGROUND = () => otel.ROOT_CONTEXT\n\nclass SpanFactory {\n private readonly telemetry: ManualInstrumentation\n\n constructor(telemetry: ManualInstrumentation) {\n this.telemetry = telemetry\n }\n\n span(options?: StartSpanOptions, ctx?: TelemetryContext) {\n return this.telemetry.unknown(ctx ?? context.active(), options)\n }\n\n tool(options: StartToolSpanOptions, ctx?: TelemetryContext) {\n return this.telemetry.tool(ctx ?? context.active(), options)\n }\n\n completion(options: StartCompletionSpanOptions, ctx?: TelemetryContext) {\n return this.telemetry.completion(ctx ?? context.active(), options)\n }\n\n embedding(options?: StartSpanOptions, ctx?: TelemetryContext) {\n return this.telemetry.embedding(ctx ?? context.active(), options)\n }\n\n http(options: StartHttpSpanOptions, ctx?: TelemetryContext) {\n return this.telemetry.http(ctx ?? context.active(), options)\n }\n\n prompt(options: PromptSpanOptions, ctx?: TelemetryContext) {\n return this.telemetry.prompt(ctx ?? context.active(), options)\n }\n\n chat(options: ChatSpanOptions, ctx?: TelemetryContext) {\n return this.telemetry.chat(ctx ?? context.active(), options)\n }\n\n external(options: ExternalSpanOptions, ctx?: TelemetryContext) {\n return this.telemetry.external(ctx ?? context.active(), options)\n }\n}\n\nclass ContextManager {\n private readonly telemetry: ManualInstrumentation\n\n constructor(telemetry: ManualInstrumentation) {\n this.telemetry = telemetry\n }\n\n resume(ctx: TraceContext) {\n return this.telemetry.resume(ctx)\n }\n\n active() {\n return context.active()\n }\n\n with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n ctx: TelemetryContext,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n return context.with(ctx, fn, thisArg, ...args)\n }\n}\n\nclass InstrumentationManager {\n private readonly instrumentations: BaseInstrumentation[]\n\n constructor(instrumentations: BaseInstrumentation[]) {\n this.instrumentations = instrumentations\n }\n\n enable() {\n this.instrumentations.forEach((instrumentation) => {\n if (!instrumentation.isEnabled()) instrumentation.enable()\n })\n }\n\n disable() {\n this.instrumentations.forEach((instrumentation) => {\n if (instrumentation.isEnabled()) instrumentation.disable()\n })\n }\n}\n\nclass TracerManager {\n private readonly nodeProvider: NodeTracerProvider\n private readonly scopeVersion: string\n\n constructor(nodeProvider: NodeTracerProvider, scopeVersion: string) {\n this.nodeProvider = nodeProvider\n this.scopeVersion = scopeVersion\n }\n\n get(scope: Instrumentation) {\n return this.provider(scope).getTracer('')\n }\n\n provider(scope: Instrumentation) {\n return new ScopedTracerProvider(\n `${SCOPE_LATITUDE}.${scope}`,\n this.scopeVersion,\n this.nodeProvider,\n )\n }\n}\n\nclass ScopedTracerProvider implements otel.TracerProvider {\n private readonly scope: string\n private readonly version: string\n private readonly provider: otel.TracerProvider\n\n constructor(scope: string, version: string, provider: otel.TracerProvider) {\n this.scope = scope\n this.version = version\n this.provider = provider\n }\n\n getTracer(_name: string, _version?: string, options?: otel.TracerOptions) {\n return this.provider.getTracer(this.scope, this.version, options)\n }\n}\n\nclass LifecycleManager {\n private readonly nodeProvider: NodeTracerProvider\n private readonly exporter: SpanExporter\n\n constructor(nodeProvider: NodeTracerProvider, exporter: SpanExporter) {\n this.nodeProvider = nodeProvider\n this.exporter = exporter\n }\n\n async flush() {\n await this.nodeProvider.forceFlush()\n await this.exporter.forceFlush?.()\n }\n\n async shutdown() {\n await this.flush()\n await this.nodeProvider.shutdown()\n await this.exporter.shutdown?.()\n }\n}\n\nexport const DEFAULT_SPAN_EXPORTER = (apiKey: string) =>\n new OTLPTraceExporter({\n url: TRACES_URL,\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n timeoutMillis: 30 * 1000,\n })\n\n// Note: Only exporting typescript instrumentations\nexport enum Instrumentation {\n Anthropic = InstrumentationScope.Anthropic,\n AIPlatform = InstrumentationScope.AIPlatform,\n Bedrock = InstrumentationScope.Bedrock,\n Cohere = InstrumentationScope.Cohere,\n Langchain = InstrumentationScope.Langchain,\n Latitude = InstrumentationScope.Latitude,\n LlamaIndex = InstrumentationScope.LlamaIndex,\n Manual = InstrumentationScope.Manual,\n OpenAI = InstrumentationScope.OpenAI,\n TogetherAI = InstrumentationScope.TogetherAI,\n VertexAI = InstrumentationScope.VertexAI,\n}\n\nexport type TelemetryOptions = {\n disableBatch?: boolean\n exporter?: SpanExporter\n processors?: SpanProcessor[]\n propagators?: TextMapPropagator[]\n instrumentations?: {\n [Instrumentation.Latitude]?:\n | typeof latitude.Latitude\n | LatitudeInstrumentationOptions\n\n // Note: These are all typed as 'any' because using the actual expected types will cause\n // type errors when the version installed in the package is even slightly different than\n // the version used in the project.\n [Instrumentation.AIPlatform]?: any\n [Instrumentation.Anthropic]?: any\n [Instrumentation.Bedrock]?: any\n [Instrumentation.Cohere]?: any\n [Instrumentation.OpenAI]?: any\n [Instrumentation.LlamaIndex]?: any\n [Instrumentation.TogetherAI]?: any\n [Instrumentation.VertexAI]?: any\n [Instrumentation.Langchain]?: {\n callbackManagerModule?: any\n }\n [Instrumentation.Manual]?: ManualInstrumentationOptions\n }\n}\n\nexport class LatitudeTelemetry {\n private options: TelemetryOptions\n private nodeProvider: NodeTracerProvider\n private manualInstrumentation: ManualInstrumentation\n private instrumentationsList: BaseInstrumentation[]\n\n readonly span: SpanFactory\n readonly context: ContextManager\n readonly instrumentation: InstrumentationManager\n readonly tracer: TracerManager\n private readonly lifecycle: LifecycleManager\n\n constructor(apiKey: string, options?: TelemetryOptions) {\n this.options = options || {}\n\n if (!this.options.exporter) {\n this.options.exporter = DEFAULT_SPAN_EXPORTER(apiKey)\n }\n\n context.setGlobalContextManager(\n new AsyncLocalStorageContextManager().enable(),\n )\n\n propagation.setGlobalPropagator(\n new CompositePropagator({\n propagators: [\n ...(this.options.propagators || []),\n new W3CTraceContextPropagator(),\n new W3CBaggagePropagator(),\n ],\n }),\n )\n\n this.nodeProvider = new NodeTracerProvider({\n resource: new Resource({ [ATTR_SERVICE_NAME]: SERVICE_NAME }),\n })\n\n this.lifecycle = new LifecycleManager(\n this.nodeProvider,\n this.options.exporter,\n )\n\n // Note: important, must run before the exporter span processors\n this.nodeProvider.addSpanProcessor(\n new BaggageSpanProcessor(ALLOW_ALL_BAGGAGE_KEYS),\n )\n\n if (this.options.processors) {\n this.options.processors.forEach((processor) => {\n this.nodeProvider.addSpanProcessor(processor)\n })\n } else {\n this.nodeProvider.addSpanProcessor(DEFAULT_REDACT_SPAN_PROCESSOR())\n }\n\n if (this.options.disableBatch) {\n this.nodeProvider.addSpanProcessor(\n new SimpleSpanProcessor(this.options.exporter),\n )\n } else {\n this.nodeProvider.addSpanProcessor(\n new BatchSpanProcessor(this.options.exporter),\n )\n }\n\n this.nodeProvider.register()\n\n process.on('SIGTERM', async () => this.shutdown)\n process.on('SIGINT', async () => this.shutdown)\n\n this.manualInstrumentation = null as unknown as ManualInstrumentation\n this.instrumentationsList = []\n this.tracer = new TracerManager(this.nodeProvider, SCOPE_VERSION)\n this.initInstrumentations()\n this.instrumentation = new InstrumentationManager(this.instrumentationsList)\n this.instrumentation.enable()\n\n this.span = new SpanFactory(this.manualInstrumentation)\n this.context = new ContextManager(this.manualInstrumentation)\n }\n\n async flush() {\n await this.lifecycle.flush()\n }\n\n async shutdown() {\n await this.lifecycle.shutdown()\n }\n\n // TODO(tracing): auto instrument outgoing HTTP requests\n private initInstrumentations() {\n this.instrumentationsList = []\n\n const tracer = this.tracer.get(Instrumentation.Manual)\n this.manualInstrumentation = new ManualInstrumentation(\n tracer,\n this.options.instrumentations?.manual,\n )\n this.instrumentationsList.push(this.manualInstrumentation)\n\n const latitude = this.options.instrumentations?.latitude\n if (latitude) {\n const tracer = this.tracer.get(Instrumentation.Latitude)\n const instrumentation = new LatitudeInstrumentation(\n tracer,\n typeof latitude === 'object' ? latitude : { module: latitude },\n )\n this.instrumentationsList.push(instrumentation)\n }\n\n type InstrumentationClass =\n | typeof AnthropicInstrumentation\n | typeof AIPlatformInstrumentation\n | typeof BedrockInstrumentation\n | typeof CohereInstrumentation\n | typeof LangChainInstrumentation\n | typeof LlamaIndexInstrumentation\n | typeof OpenAIInstrumentation\n | typeof TogetherInstrumentation\n | typeof VertexAIInstrumentation\n\n const configureInstrumentation = (\n instrumentationType: Instrumentation,\n InstrumentationConstructor: InstrumentationClass,\n instrumentationOptions?: { enrichTokens?: boolean },\n ) => {\n const providerPkg = this.options.instrumentations?.[instrumentationType]\n if (!providerPkg) return\n\n const provider = this.tracer.provider(instrumentationType)\n const instrumentation = new InstrumentationConstructor(instrumentationOptions) // prettier-ignore\n instrumentation.setTracerProvider(provider)\n instrumentation.manuallyInstrument(providerPkg)\n registerInstrumentations({\n instrumentations: [instrumentation],\n tracerProvider: provider,\n })\n this.instrumentationsList.push(instrumentation)\n }\n\n configureInstrumentation(Instrumentation.Anthropic, AnthropicInstrumentation) // prettier-ignore\n configureInstrumentation(Instrumentation.AIPlatform, AIPlatformInstrumentation) // prettier-ignore\n configureInstrumentation(Instrumentation.Bedrock, BedrockInstrumentation) // prettier-ignore\n configureInstrumentation(Instrumentation.Cohere, CohereInstrumentation) // prettier-ignore\n configureInstrumentation(Instrumentation.Langchain, LangChainInstrumentation) // prettier-ignore\n configureInstrumentation(Instrumentation.LlamaIndex, LlamaIndexInstrumentation) // prettier-ignore\n // NOTE: `stream: true` in OpenAI make enrichTokens fail, so disabling.\n configureInstrumentation(Instrumentation.OpenAI, OpenAIInstrumentation, { enrichTokens: false }) // prettier-ignore\n configureInstrumentation(Instrumentation.TogetherAI, TogetherInstrumentation, { enrichTokens: false }) // prettier-ignore\n configureInstrumentation(Instrumentation.VertexAI, VertexAIInstrumentation) // prettier-ignore\n }\n\n async capture<T>(\n options: CaptureOptions,\n fn: (ctx: TelemetryContext) => T | Promise<T>,\n ): Promise<T> {\n if (!DOCUMENT_PATH_REGEXP.test(options.path)) {\n throw new BadRequestError(\n \"Invalid path, no spaces. Only letters, numbers, '.', '-' and '_'\",\n )\n }\n\n const captureBaggageEntries: Record<string, otel.BaggageEntry> = {\n [ATTRIBUTES.LATITUDE.promptPath]: { value: options.path },\n [ATTRIBUTES.LATITUDE.projectId]: { value: String(options.projectId) },\n }\n\n if (options.versionUuid) {\n captureBaggageEntries[ATTRIBUTES.LATITUDE.commitUuid] = {\n value: options.versionUuid,\n }\n }\n\n if (options.conversationUuid) {\n captureBaggageEntries[ATTRIBUTES.LATITUDE.documentLogUuid] = {\n value: options.conversationUuid,\n }\n }\n\n const captureContext = propagation.setBaggage(\n BACKGROUND(),\n propagation.createBaggage(captureBaggageEntries),\n )\n\n const span = this.manualInstrumentation.unresolvedExternal(\n captureContext,\n options,\n )\n\n let result\n try {\n result = await context.with(\n span.context,\n async () => await fn(span.context),\n )\n } catch (error) {\n span.fail(error as Error)\n throw error\n }\n\n span.end()\n\n return result\n }\n}\n"],"names":["z","ATTR_HTTP_REQUEST_METHOD","ATTR_HTTP_RESPONSE_STATUS_CODE","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_RESPONSE_FINISH_REASONS","ATTR_GEN_AI_USAGE_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","ATTR_GEN_AI_TOOL_CALL_ID","ATTR_GEN_AI_SYSTEM","ATTR_GEN_AI_TOOL_NAME","ATTR_GEN_AI_TOOL_TYPE","Translator","otel","trace","propagation","Provider","context","uuid","OTLPTraceExporter","Instrumentation","AsyncLocalStorageContextManager","CompositePropagator","W3CTraceContextPropagator","W3CBaggagePropagator","NodeTracerProvider","Resource","ATTR_SERVICE_NAME","BaggageSpanProcessor","ALLOW_ALL_BAGGAGE_KEYS","SimpleSpanProcessor","BatchSpanProcessor","instrumentation","registerInstrumentations","AnthropicInstrumentation","AIPlatformInstrumentation","BedrockInstrumentation","CohereInstrumentation","LangChainInstrumentation","LlamaIndexInstrumentation","OpenAIInstrumentation","TogetherInstrumentation","VertexAIInstrumentation"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MAQa,mBAAmB,CAAA;AACtB,IAAA,OAAO;AAEf,IAAA,WAAA,CAAY,OAAmC,EAAA;AAC7C,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO;AAEtB,QAAA,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE;AACjB,YAAA,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,CAAC,UAAkB,EAAE,MAAW,KAAK,QAAQ;QACnE;IACF;IAEA,OAAO,CAAC,KAAmB,EAAE,QAAsB,EAAA;;IAEnD;AAEA,IAAA,KAAK,CAAC,IAAkB,EAAA;AACtB,QAAA,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;AACtE,QAAA,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,EAAE;YAC/B,IAAI,CAAC,KAAK,CAAC,UAAU;gBAAE;AACvB,YAAA,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAC1E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