@jaypie/llm 1.1.22 → 1.1.24

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.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/constants.ts","../src/tools/Toolkit.class.ts","../src/types/LlmProvider.interface.ts","../src/util/formatOperateMessage.ts","../src/util/formatOperateInput.ts","../src/util/logger.ts","../src/util/maxTurnsFromOptions.ts","../src/util/naturalZodSchema.ts","../src/util/random.ts","../src/util/tryParseNumber.ts","../src/providers/openai/operate.ts","../src/providers/openai/utils.ts","../src/providers/openai/OpenAiProvider.class.ts","../src/providers/anthropic/utils.ts","../src/providers/anthropic/types.ts","../src/providers/AnthropicProvider.class.ts","../src/Llm.ts","../src/tools/random.ts","../src/tools/roll.ts","../src/tools/time.ts","../src/tools/weather.ts","../src/tools/index.ts"],"sourcesContent":["export const PROVIDER = {\n ANTHROPIC: {\n MODEL: {\n CLAUDE_3_HAIKU: \"claude-3-5-haiku-latest\" as const,\n CLAUDE_3_OPUS: \"claude-3-opus-latest\" as const,\n CLAUDE_3_SONNET: \"claude-3-5-sonnet-latest\" as const,\n DEFAULT: \"claude-3-5-sonnet-latest\" as const,\n },\n NAME: \"anthropic\" as const,\n PROMPT: {\n AI: \"\\n\\nAssistant:\" as const,\n HUMAN: \"\\n\\nHuman:\" as const,\n },\n ROLE: {\n ASSISTANT: \"assistant\" as const,\n SYSTEM: \"system\" as const,\n USER: \"user\" as const,\n },\n MAX_TOKENS: {\n DEFAULT: 4096 as const,\n },\n TOOLS: {\n SCHEMA_VERSION: \"v2\" as const,\n },\n },\n OPENAI: {\n MODEL: {\n DEFAULT: \"gpt-4o\" as const,\n GPT_4: \"gpt-4\" as const,\n GPT_4_O_MINI: \"gpt-4o-mini\" as const,\n GPT_4_O: \"gpt-4o\" as const,\n GPT_4_5: \"gpt-4.5-preview\" as const,\n O1: \"o1\" as const,\n O1_MINI: \"o1-mini\" as const,\n O1_PRO: \"o1-pro\" as const,\n O3_MINI: \"o3-mini\" as const,\n O3_MINI_HIGH: \"o3-mini-high\" as const,\n },\n NAME: \"openai\" as const,\n },\n} as const;\n\nexport type LlmProviderName =\n | typeof PROVIDER.OPENAI.NAME\n | typeof PROVIDER.ANTHROPIC.NAME;\n\n// Last: Defaults\nexport const DEFAULT = {\n PROVIDER: PROVIDER.OPENAI,\n} as const;\n","import { JAYPIE, log as jaypieLog, resolveValue } from \"@jaypie/core\";\n\nimport { LlmTool } from \"../types/LlmTool.interface\";\n\nconst DEFAULT_TOOL_TYPE = \"function\";\n\nconst log = jaypieLog.lib({ lib: JAYPIE.LIB.LLM });\n\ntype LogFunction = (\n message: string,\n context: { name: string; args: any },\n) => void | Promise<void>;\n\nfunction logToolMessage(message: string, context: { name: string; args: any }) {\n log.trace.var({ [context.name]: message });\n}\n\nexport interface ToolkitOptions {\n explain?: boolean;\n log?: boolean | LogFunction;\n}\n\nexport class Toolkit {\n private readonly _tools: LlmTool[];\n private readonly _options: ToolkitOptions;\n private readonly explain: boolean;\n private readonly log: boolean | LogFunction;\n\n constructor(tools: LlmTool[], options?: ToolkitOptions) {\n this._tools = tools;\n this._options = options || {};\n this.explain = this._options.explain ? true : false;\n this.log = this._options.log !== undefined ? this._options.log : true;\n }\n\n get tools(): Omit<LlmTool, \"call\">[] {\n return this._tools.map((tool) => {\n const toolCopy: any = { ...tool };\n delete toolCopy.call;\n delete toolCopy.message;\n\n if (this.explain && toolCopy.parameters?.type === \"object\") {\n if (toolCopy.parameters?.properties) {\n if (!toolCopy.parameters.properties.__Explanation) {\n toolCopy.parameters.properties.__Explanation = {\n type: \"string\",\n description: `Clearly state why the tool is being called and what larger question it helps answer. For example, \"I am checking the location API because the user asked for nearby pizza and I need coordinates to proceed\"`,\n };\n }\n }\n }\n\n // Set default type if not provided\n if (!toolCopy.type) {\n toolCopy.type = DEFAULT_TOOL_TYPE;\n }\n\n return toolCopy;\n });\n }\n\n async call({ name, arguments: args }: { name: string; arguments: string }) {\n const tool = this._tools.find((t) => t.name === name);\n if (!tool) {\n throw new Error(`Tool '${name}' not found`);\n }\n\n let parsedArgs;\n try {\n parsedArgs = JSON.parse(args);\n if (this.explain) {\n delete parsedArgs.__Explanation;\n }\n } catch {\n parsedArgs = args;\n }\n\n if (this.log !== false) {\n try {\n const context: { name: string; args: any; explanation?: string } = {\n name,\n args: parsedArgs,\n };\n let message: string;\n\n if (this.explain) {\n context.explanation = parsedArgs.__Explanation;\n }\n\n if (tool.message) {\n if (typeof tool.message === \"string\") {\n log.trace(\"[Toolkit] Tool provided string message\");\n message = tool.message;\n } else if (typeof tool.message === \"function\") {\n log.trace(\"[Toolkit] Tool provided function message\");\n log.trace(\"[Toolkit] Resolving message result\");\n message = await resolveValue(tool.message(parsedArgs, { name }));\n } else {\n log.warn(\"[Toolkit] Tool provided unknown message type\");\n message = String(tool.message);\n }\n } else {\n log.trace(\"[Toolkit] Log tool call with default message\");\n message = `${tool.name}:${JSON.stringify(parsedArgs)}`;\n }\n\n if (typeof this.log === \"function\") {\n log.trace(\"[Toolkit] Log tool call with custom logger\");\n await resolveValue(this.log(message, context));\n } else {\n log.trace(\"[Toolkit] Log tool call with default logger\");\n logToolMessage(message, context);\n }\n } catch (error) {\n log.error(\"[Toolkit] Caught error during logToolCall\");\n log.var({ error });\n log.debug(\"[Toolkit] Continuing...\");\n }\n }\n\n return await resolveValue(tool.call(parsedArgs));\n }\n\n extend(\n tools: LlmTool[],\n options: {\n warn?: boolean;\n replace?: boolean;\n log?: boolean | LogFunction;\n explain?: boolean;\n } = {},\n ): this {\n for (const tool of tools) {\n const existingIndex = this._tools.findIndex((t) => t.name === tool.name);\n if (existingIndex !== -1) {\n if (options.replace === false) {\n continue;\n }\n if (options.warn !== false) {\n if (typeof this.log === \"function\") {\n this.log(\n `[Toolkit] Tool '${tool.name}' already exists, replacing with new tool`,\n { name: tool.name, args: {} },\n );\n } else if (this.log) {\n log.warn(\n `[Toolkit] Tool '${tool.name}' already exists, replacing with new tool`,\n );\n }\n }\n this._tools[existingIndex] = tool;\n } else {\n this._tools.push(tool);\n }\n }\n if (Object.prototype.hasOwnProperty.call(options, \"log\")) {\n (this as any).log = options.log;\n }\n if (Object.prototype.hasOwnProperty.call(options, \"explain\")) {\n (this as any).explain = options.explain;\n }\n return this;\n }\n}\n","import {\n AnyValue,\n JsonObject,\n JsonReturn,\n NaturalMap,\n NaturalSchema,\n} from \"@jaypie/types\";\nimport { z } from \"zod\";\nimport { LlmTool } from \"./LlmTool.interface.js\";\nimport { Toolkit } from \"../tools/Toolkit.class.js\";\n\n// Enums\n\nexport enum LlmMessageRole {\n Assistant = \"assistant\",\n Developer = \"developer\",\n System = \"system\",\n User = \"user\",\n}\n\nexport enum LlmMessageType {\n FunctionCall = \"function_call\",\n FunctionCallOutput = \"function_call_output\",\n InputFile = \"input_file\",\n InputImage = \"input_image\",\n InputText = \"input_text\",\n ItemReference = \"item_reference\",\n Message = \"message\",\n OutputText = \"output_text\",\n Refusal = \"refusal\",\n}\n\nexport enum LlmResponseStatus {\n Completed = \"completed\",\n Incomplete = \"incomplete\",\n InProgress = \"in_progress\",\n}\n\n// Errors\n\ninterface LlmError {\n detail?: string;\n status: number | string;\n title: string;\n}\n\n// Input\n\ninterface LlmInputContentFile {\n type: LlmMessageType.InputFile;\n file_data: File;\n file_id?: string;\n filename?: string;\n}\n\ninterface LlmInputContentImage {\n type: LlmMessageType.InputImage;\n detail: File;\n file_id?: string;\n image_url?: string;\n}\n\ninterface LlmInputContentText {\n type: LlmMessageType.InputText;\n text: string;\n}\n\ntype LlmInputContent =\n | LlmInputContentFile\n | LlmInputContentImage\n | LlmInputContentText;\n\n/**\n * Represents the \"Input message object\" in the \"input item list\"\n * from [OpenAI Responses API](https://platform.openai.com/docs/api-reference/responses/create)\n */\nexport interface LlmInputMessage {\n content: string | Array<LlmInputContent>;\n role: LlmMessageRole;\n type: LlmMessageType.Message;\n}\n\n// Output\nexport interface LlmOutputContentText {\n annotations?: AnyValue[];\n text: string;\n type: LlmMessageType.OutputText;\n}\n\ninterface LlmOutputRefusal {\n refusal: string;\n type: LlmMessageType.Refusal;\n}\n\ntype LlmOutputContent = LlmOutputContentText | LlmOutputRefusal;\n\n/**\n * Represents the \"Output message object\" in the \"input item list\"\n * from [OpenAI Responses API](https://platform.openai.com/docs/api-reference/responses/create)\n */\nexport interface LlmOutputMessage {\n content: string | Array<LlmOutputContent>;\n id?: string;\n role: LlmMessageRole.Assistant;\n status?: LlmResponseStatus;\n type?: LlmMessageType.Message;\n}\n\ntype LlmOutputItem = LlmToolCall | LlmToolResult | LlmOutputMessage;\n\ntype LlmOutput = LlmOutputItem[];\n\n// Tools\n\nexport interface LlmToolCall {\n arguments: string;\n call_id: string;\n id: string;\n name: string;\n type: LlmMessageType.FunctionCall;\n status: LlmResponseStatus;\n}\nexport interface LlmToolResult {\n call_id: string;\n output: string;\n status?: LlmResponseStatus;\n type: LlmMessageType.FunctionCallOutput;\n}\n\ninterface LlmItemReference {\n type: LlmMessageType.ItemReference;\n id: string;\n}\n\n// Options\n\nexport type LlmHistoryItem =\n | LlmInputMessage\n | LlmItemReference\n | LlmOutputItem\n | LlmToolResult;\n\nexport type LlmHistory = LlmHistoryItem[];\n\nexport interface LlmMessageOptions {\n data?: NaturalMap;\n model?: string;\n placeholders?: {\n message?: boolean;\n system?: boolean;\n };\n response?: NaturalSchema | z.ZodType;\n system?: string;\n}\n\nexport interface LlmOperateOptions {\n data?: NaturalMap;\n explain?: boolean;\n format?: JsonObject | NaturalSchema | z.ZodType;\n history?: LlmHistory;\n hooks?: {\n afterEachModelResponse?: ({\n input,\n options,\n providerRequest,\n providerResponse,\n content,\n usage,\n }: {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: any;\n providerResponse: any;\n content: string | JsonObject;\n usage: LlmUsage;\n }) => unknown | Promise<unknown>;\n afterEachTool?: ({\n result,\n toolName,\n args,\n }: {\n result: unknown;\n toolName: string;\n args: string;\n }) => unknown | Promise<unknown>;\n beforeEachModelRequest?: ({\n input,\n options,\n providerRequest,\n }: {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: any;\n }) => unknown | Promise<unknown>;\n beforeEachTool?: ({\n toolName,\n args,\n }: {\n toolName: string;\n args: string;\n }) => unknown | Promise<unknown>;\n onRetryableModelError?: ({\n input,\n options,\n providerRequest,\n error,\n }: {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: any;\n error: any;\n }) => unknown | Promise<unknown>;\n onToolError?: ({\n error,\n toolName,\n args,\n }: {\n error: Error;\n toolName: string;\n args: string;\n }) => unknown | Promise<unknown>;\n onUnrecoverableModelError?: ({\n input,\n options,\n providerRequest,\n error,\n }: {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: any;\n error: any;\n }) => unknown | Promise<unknown>;\n };\n instructions?: string;\n model?: string;\n placeholders?: {\n input?: boolean;\n instructions?: boolean;\n system?: boolean;\n };\n providerOptions?: JsonObject;\n system?: string;\n tools?: LlmTool[] | Toolkit;\n turns?: boolean | number;\n user?: string;\n}\n\nexport interface LlmOptions {\n apiKey?: string;\n model?: string;\n}\n\n// Responses\n\nexport interface LlmUsageItem {\n input: number;\n output: number;\n reasoning: number;\n total: number;\n provider?: string;\n model?: string;\n}\n\nexport type LlmUsage = LlmUsageItem[];\n\nexport interface LlmOperateResponse {\n content?: string | JsonObject;\n error?: LlmError;\n history: LlmHistory;\n model?: string;\n output: LlmOutput;\n provider?: string;\n responses: JsonReturn[];\n status: LlmResponseStatus;\n usage: LlmUsage;\n}\n\n// Main\n\nexport interface LlmProvider {\n operate?(\n input: string | LlmHistory | LlmInputMessage,\n options?: LlmOperateOptions,\n ): Promise<LlmOperateResponse>;\n send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject>;\n}\n","import { placeholders } from \"@jaypie/core\";\nimport {\n LlmInputMessage,\n LlmMessageRole,\n LlmMessageType,\n} from \"../types/LlmProvider.interface.js\";\nimport { NaturalMap } from \"@jaypie/types\";\n\n/**\n * Options for formatOperateMessage function\n */\nexport interface FormatOperateMessageOptions {\n /**\n * Data to use for placeholder substitution\n */\n data?: NaturalMap;\n\n /**\n * Role to use for the message\n */\n role?: LlmMessageRole;\n}\n\n/**\n * Converts a string to a standardized LlmInputMessage\n * @param input - String to format\n * @param options - Optional configuration\n * @param options.data - Data to use for placeholder substitution\n * @param options.role - Role to use for the message (defaults to User)\n * @returns LlmInputMessage\n */\nexport function formatOperateMessage(\n input: string,\n options?: FormatOperateMessageOptions,\n): LlmInputMessage {\n const content = options?.data ? placeholders(input, options.data) : input;\n\n return {\n content,\n role: options?.role || LlmMessageRole.User,\n type: LlmMessageType.Message,\n };\n}\n","import {\n LlmHistory,\n LlmInputMessage,\n LlmMessageRole,\n} from \"../types/LlmProvider.interface.js\";\nimport { NaturalMap } from \"@jaypie/types\";\nimport { formatOperateMessage } from \"./formatOperateMessage.js\";\n\n/**\n * Options for formatOperateInput function\n */\nexport interface FormatOperateInputOptions {\n /**\n * Data to use for placeholder substitution\n */\n data?: NaturalMap;\n\n /**\n * Role to use when converting a string to LlmInputMessage\n */\n role?: LlmMessageRole;\n}\n\n/**\n * Converts various input types to a standardized LlmHistory format\n * @param input - String, LlmInputMessage, or LlmHistory to format\n * @param options - Optional configuration\n * @param options.data - Data to use for placeholder substitution\n * @param options.role - Role to use when converting a string to LlmInputMessage (defaults to User)\n * @returns Standardized LlmHistory array\n */\nexport function formatOperateInput(\n input: string | LlmInputMessage | LlmHistory,\n options?: FormatOperateInputOptions,\n): LlmHistory {\n // If input is already LlmHistory, return it\n if (Array.isArray(input)) {\n return input;\n }\n\n // If input is a string, convert it to LlmInputMessage\n if (typeof input === \"string\") {\n return [formatOperateMessage(input, options)];\n }\n\n // If input is LlmInputMessage, apply placeholders if data is provided\n if (options?.data && typeof input.content === \"string\") {\n return [\n formatOperateMessage(input.content, {\n data: options.data,\n role: input.role || options?.role,\n }),\n ];\n }\n\n // Otherwise, just wrap the input in an array\n return [input];\n}\n","import { JAYPIE, log as defaultLog } from \"@jaypie/core\";\n\nexport const getLogger = () => defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\nexport const log = getLogger();\n","import { LlmOperateOptions } from \"../types/LlmProvider.interface.js\";\n\n// Turn policy constants\nexport const MAX_TURNS_ABSOLUTE_LIMIT = 72;\nexport const MAX_TURNS_DEFAULT_LIMIT = 12;\n\n/**\n * Determines the maximum number of turns based on the provided options\n *\n * @param options - The LLM operate options\n * @returns The maximum number of turns\n */\nexport function maxTurnsFromOptions(options: LlmOperateOptions): number {\n // Default to single turn (1) when turns are disabled\n\n // Handle the turns parameter\n if (options.turns === undefined) {\n // Default to default limit when undefined\n return MAX_TURNS_DEFAULT_LIMIT;\n } else if (options.turns === true) {\n // Explicitly set to true\n return MAX_TURNS_DEFAULT_LIMIT;\n } else if (typeof options.turns === \"number\") {\n if (options.turns > 0) {\n // Positive number - use that limit (capped at absolute limit)\n return Math.min(options.turns, MAX_TURNS_ABSOLUTE_LIMIT);\n } else if (options.turns < 0) {\n // Negative number - use default limit\n return MAX_TURNS_DEFAULT_LIMIT;\n }\n // If turns is 0, return 1 (disabled)\n return 1;\n }\n // All other values (false, null, etc.) will return 1 (disabled)\n return 1;\n}\n","import { z } from \"zod\";\nimport { NaturalSchema } from \"@jaypie/types\";\n\nexport function naturalZodSchema(definition: NaturalSchema): z.ZodTypeAny {\n if (Array.isArray(definition)) {\n if (definition.length === 0) {\n // Handle empty array - accept any[]\n return z.array(z.any());\n } else if (definition.length === 1) {\n // Handle array types\n const itemType = definition[0];\n switch (itemType) {\n case String:\n return z.array(z.string());\n case Number:\n return z.array(z.number());\n case Boolean:\n return z.array(z.boolean());\n default:\n if (typeof itemType === \"object\") {\n // Handle array of objects\n return z.array(naturalZodSchema(itemType));\n }\n // Handle enum arrays\n return z.enum(definition as [string, ...string[]]);\n }\n } else {\n // Handle enum arrays\n return z.enum(definition as [string, ...string[]]);\n }\n } else if (definition && typeof definition === \"object\") {\n if (Object.keys(definition).length === 0) {\n // Handle empty object - accept any key-value pairs\n return z.record(z.string(), z.any());\n } else {\n // Handle object with properties\n const schemaShape: Record<string, z.ZodTypeAny> = {};\n for (const [key, value] of Object.entries(definition)) {\n schemaShape[key] = naturalZodSchema(value);\n }\n return z.object(schemaShape);\n }\n } else {\n switch (definition) {\n case String:\n return z.string();\n case Number:\n return z.number();\n case Boolean:\n return z.boolean();\n case Object:\n return z.record(z.string(), z.any());\n case Array:\n return z.array(z.any());\n default:\n throw new Error(`Unsupported type: ${definition}`);\n }\n }\n}\n","import RandomLib from \"random\";\nimport { ConfigurationError } from \"@jaypie/errors\";\n\n//\n// Types\n//\n\ninterface RandomOptions {\n min?: number;\n max?: number;\n mean?: number;\n stddev?: number;\n integer?: boolean;\n start?: number;\n seed?: string;\n precision?: number;\n currency?: boolean;\n}\n\ntype RandomFunction = {\n (options?: RandomOptions): number;\n};\n\n//\n// Constants\n//\n\nexport const DEFAULT_MIN = 0;\nexport const DEFAULT_MAX = 1;\n\n//\n// Helper Functions\n//\n\n/**\n * Clamps a number between optional minimum and maximum values\n * @param num - The number to clamp\n * @param min - Optional minimum value\n * @param max - Optional maximum value\n * @returns The clamped number\n */\nconst clamp = (num: number, min?: number, max?: number): number => {\n let result = num;\n if (typeof min === \"number\") result = Math.max(result, min);\n if (typeof max === \"number\") result = Math.min(result, max);\n return result;\n};\n\n/**\n * Validates that min is not greater than max\n * @param min - Optional minimum value\n * @param max - Optional maximum value\n * @throws {ConfigurationError} If min is greater than max\n */\nconst validateBounds = (\n min: number | undefined,\n max: number | undefined,\n): void => {\n if (typeof min === \"number\" && typeof max === \"number\" && min > max) {\n throw new ConfigurationError(\n `Invalid bounds: min (${min}) cannot be greater than max (${max})`,\n );\n }\n};\n\n//\n// Main\n//\n\n/**\n * Creates a random number generator with optional seeding\n *\n * @param defaultSeed - Seed string for the default RNG\n * @returns A function that generates random numbers based on provided options\n *\n * @example\n * const rng = random(\"default-seed\");\n *\n * // Generate a random float between 0 and 1\n * const basic = rng();\n *\n * // Generate an integer between 1 and 10\n * const integer = rng({ min: 1, max: 10, integer: true });\n *\n * // Generate from normal distribution\n * const normal = rng({ mean: 50, stddev: 10 });\n *\n * // Use consistent seeding\n * const seeded = rng({ seed: \"my-seed\" });\n */\nexport function random(defaultSeed?: string): RandomFunction {\n // Initialize default seeded RNG\n const defaultRng = RandomLib.clone(defaultSeed);\n\n // Store per-seed RNGs\n const seedMap = new Map<string, ReturnType<typeof RandomLib.clone>>();\n\n const rngFn = ({\n min,\n max: providedMax,\n mean,\n stddev,\n integer = false,\n start = 0,\n seed,\n precision,\n currency = false,\n }: RandomOptions = {}): number => {\n // Select the appropriate RNG based on seed\n const rng = seed\n ? seedMap.get(seed) ||\n (() => {\n const newRng = RandomLib.clone(seed);\n seedMap.set(seed, newRng);\n return newRng;\n })()\n : defaultRng;\n\n // If only min is set, set max to min*2, but keep track of whether max was provided\n let max = providedMax;\n if (typeof min === \"number\" && typeof max !== \"number\") {\n max = min * 2;\n }\n\n validateBounds(min, max);\n\n // Determine effective precision based on parameters\n const getEffectivePrecision = (): number | undefined => {\n if (integer) return 0;\n\n const precisions: number[] = [];\n if (typeof precision === \"number\" && precision >= 0) {\n precisions.push(precision);\n }\n if (currency) {\n precisions.push(2);\n }\n\n // Return the lowest precision if any are set, undefined otherwise\n return precisions.length > 0 ? Math.min(...precisions) : undefined;\n };\n\n // Helper function to apply precision\n const applyPrecision = (value: number): number => {\n const effectivePrecision = getEffectivePrecision();\n if (typeof effectivePrecision === \"number\") {\n const factor = Math.pow(10, effectivePrecision);\n return Math.round(value * factor) / factor;\n }\n return value;\n };\n\n // Use normal distribution if both mean and stddev are provided\n if (typeof mean === \"number\" && typeof stddev === \"number\") {\n const normalDist = rng.normal(mean, stddev);\n const value = normalDist();\n\n // Only clamp if min/max are defined\n const clampedValue = clamp(value, min, providedMax);\n\n // Switch to uniform distribution only if both bounds were explicitly provided and exceeded\n if (\n typeof min === \"number\" &&\n typeof providedMax === \"number\" &&\n clampedValue !== value\n ) {\n const baseValue = integer ? rng.int(min, max) : rng.float(min, max);\n return applyPrecision(start + baseValue);\n }\n\n return applyPrecision(\n start + (integer ? Math.round(clampedValue) : clampedValue),\n );\n }\n\n // For uniform distribution, use defaults if min/max are undefined\n const uniformMin = typeof min === \"number\" ? min : DEFAULT_MIN;\n const uniformMax = typeof max === \"number\" ? max : DEFAULT_MAX;\n\n const baseValue = integer\n ? rng.int(uniformMin, uniformMax)\n : rng.float(uniformMin, uniformMax);\n return applyPrecision(start + baseValue);\n };\n\n return rngFn;\n}\n","/**\n * Options for tryParseNumber function\n */\nexport interface TryParseNumberOptions {\n /**\n * Default value to return if parsing fails or results in NaN\n */\n defaultValue?: number;\n /**\n * Function to call with warning message if parsing fails or results in NaN\n */\n warnFunction?: (message: string) => void;\n}\n\n/**\n * Helper function to safely call a function that might throw\n * @param fn Function to call safely\n */\nfunction callSafely(fn: () => void): void {\n try {\n fn();\n } catch {\n // Silently catch any errors from the function\n }\n}\n\n/**\n * Attempts to parse a value as a number. Returns the original input if parsing fails or results in NaN.\n * @param input - The value to attempt to parse as a number\n * @param options - Optional configuration\n * @param options.defaultValue - Default value to return if parsing fails or results in NaN\n * @param options.warnFunction - Function to call with warning message if parsing fails or results in NaN\n * @returns The parsed number, defaultValue (if specified and parsing fails), or the original input\n */\nexport function tryParseNumber(\n input: unknown,\n options?: TryParseNumberOptions,\n): number | unknown {\n if (input === null || input === undefined) {\n return input;\n }\n\n try {\n const parsed = Number(input);\n\n if (Number.isNaN(parsed)) {\n if (options?.warnFunction) {\n const warningMessage = `Failed to parse \"${String(input)}\" as number`;\n callSafely(() => options.warnFunction!(warningMessage));\n }\n\n return typeof options?.defaultValue === \"number\"\n ? options.defaultValue\n : input;\n }\n\n return parsed;\n } catch (error: unknown) {\n if (options?.warnFunction) {\n let errorMessage = \"\";\n if (error instanceof Error) {\n errorMessage = error.message;\n }\n const warningMessage = `Error parsing \"${String(input)}\" as number${errorMessage ? \"; \" + errorMessage : \"\"}`;\n callSafely(() => options.warnFunction!(warningMessage));\n }\n\n return typeof options?.defaultValue === \"number\"\n ? options.defaultValue\n : input;\n }\n}\n","import { resolveValue, sleep, placeholders } from \"@jaypie/core\";\nimport { BadGatewayError, TooManyRequestsError } from \"@jaypie/errors\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport {\n APIConnectionError,\n APIConnectionTimeoutError,\n APIUserAbortError,\n AuthenticationError,\n BadRequestError,\n ConflictError,\n InternalServerError,\n NotFoundError,\n OpenAI,\n PermissionDeniedError,\n RateLimitError,\n UnprocessableEntityError,\n} from \"openai\";\nimport { zodResponseFormat } from \"openai/helpers/zod\";\nimport { z } from \"zod\";\nimport { PROVIDER } from \"../../constants.js\";\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport { OpenAIRawResponse } from \"./types.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageType,\n LlmMessageRole,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmResponseStatus,\n LlmToolResult,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmTool } from \"../../types/LlmTool.interface.js\";\nimport {\n formatOperateInput,\n log,\n maxTurnsFromOptions,\n naturalZodSchema,\n} from \"../../util\";\n\n//\n//\n// Types\n//\n\n/**\n * OpenAI request options type that includes model and input properties\n */\nexport type OpenAiRequestOptions = Omit<LlmOperateOptions, \"tools\"> & {\n model: string;\n input: LlmInputMessage | LlmHistory;\n text?: unknown;\n tools?: Omit<LlmTool, \"call\">[];\n};\n\n//\n//\n// Constants\n//\n\nexport const MAX_RETRIES_ABSOLUTE_LIMIT = 72;\nexport const MAX_RETRIES_DEFAULT_LIMIT = 6;\n\n// Retry policy constants\nconst INITIAL_RETRY_DELAY_MS = 1000; // 1 second\nconst MAX_RETRY_DELAY_MS = 32000; // 32 seconds\nconst RETRY_BACKOFF_FACTOR = 2; // Exponential backoff multiplier\n\nconst RETRYABLE_ERRORS = [\n APIConnectionError,\n APIConnectionTimeoutError,\n InternalServerError,\n];\n\nconst NOT_RETRYABLE_ERRORS = [\n APIUserAbortError,\n AuthenticationError,\n BadRequestError,\n ConflictError,\n NotFoundError,\n PermissionDeniedError,\n RateLimitError,\n UnprocessableEntityError,\n];\n\nconst ERROR = {\n BAD_FUNCTION_CALL: \"Bad Function Call\",\n};\n\n//\n//\n// Helpers\n//\n\n/**\n * Creates content string for function calls\n */\nfunction createFunctionCallContent(output: any): string {\n return `${LlmMessageType.FunctionCall}:${output.name}${output.arguments}#${output.call_id}`;\n}\n\n/**\n * Extracts content from OpenAI response output array\n */\nfunction extractContentFromResponse(\n currentResponse: OpenAIRawResponse,\n options?: LlmOperateOptions,\n): any {\n if (!currentResponse.output || !Array.isArray(currentResponse.output)) {\n return \"\";\n }\n\n for (const output of currentResponse.output) {\n if (output.type === LlmMessageType.Message) {\n if (\n output.content?.[0] &&\n output.content[0].type === LlmMessageType.OutputText\n ) {\n const rawContent = output.content[0].text;\n\n // If format is provided, try to parse the content as JSON\n if (options?.format && typeof rawContent === \"string\") {\n try {\n const parsedContent = JSON.parse(rawContent);\n return parsedContent;\n } catch (error) {\n // If parsing fails, keep the original string content\n log.debug(\"Failed to parse formatted response as JSON\");\n log.var({ error });\n return rawContent;\n }\n }\n\n return rawContent;\n }\n }\n if (output.type === LlmMessageType.FunctionCall) {\n return createFunctionCallContent(output);\n }\n }\n\n return \"\";\n}\n\n/**\n * Creates the request options for the OpenAI API call\n *\n * @param input - The formatted input messages\n * @param options - The LLM operation options\n * @returns The request options for the OpenAI API\n */\nexport function createRequestOptions(\n input: LlmInputMessage | LlmHistory,\n options: LlmOperateOptions = {},\n): OpenAiRequestOptions {\n const requestOptions: OpenAiRequestOptions = {\n model: options?.model || PROVIDER.OPENAI.MODEL.DEFAULT,\n input,\n };\n\n // Add user if provided\n if (options?.user) {\n requestOptions.user = options.user;\n }\n\n // Add any provider-specific options\n if (options?.providerOptions) {\n Object.assign(requestOptions, options.providerOptions);\n }\n\n // Handle instructions or system message\n if (options?.instructions) {\n // Apply placeholders to instructions if data is provided and placeholders.instructions is undefined or true\n requestOptions.instructions =\n options.data &&\n (options.placeholders?.instructions === undefined ||\n options.placeholders?.instructions)\n ? placeholders(options.instructions, options.data)\n : options.instructions;\n }\n\n // Handle developer message as system message\n // @ts-expect-error Testing invalid option\n if (options?.developer) {\n log.warn(\n \"Developer message provided but not supported. Using as system message.\",\n );\n // @ts-expect-error Testing invalid option\n requestOptions.system = options.developer;\n }\n\n // Handle structured output format\n if (options?.format) {\n // Check if format is a JsonObject with type \"json_schema\"\n if (\n typeof options.format === \"object\" &&\n options.format !== null &&\n !Array.isArray(options.format) &&\n (options.format as JsonObject).type === \"json_schema\"\n ) {\n // Direct pass-through for JsonObject with type \"json_schema\"\n requestOptions.text = {\n format: options.format,\n };\n } else {\n // Convert NaturalSchema to Zod schema if needed\n const zodSchema =\n options.format instanceof z.ZodType\n ? options.format\n : naturalZodSchema(options.format as NaturalSchema);\n const responseFormat = zodResponseFormat(zodSchema, \"response\");\n\n // Set up structured output format in the format expected by the test\n requestOptions.text = {\n format: {\n name: responseFormat.json_schema.name,\n schema: responseFormat.json_schema.schema,\n strict: responseFormat.json_schema.strict,\n type: responseFormat.type,\n },\n };\n }\n }\n\n // Handle tools - either as LlmTool[] or Toolkit\n if (options.tools) {\n let toolkit: Toolkit | undefined;\n\n if (options.tools instanceof Toolkit) {\n // If toolkit is already provided, use it directly\n toolkit = options.tools;\n } else if (Array.isArray(options.tools) && options.tools.length > 0) {\n // If array of tools provided, create toolkit from them\n const explain = options?.explain ?? false;\n toolkit = new Toolkit(options.tools, { explain });\n }\n\n if (toolkit) {\n requestOptions.tools = toolkit.tools;\n }\n }\n\n return requestOptions;\n}\n\n//\n//\n// Main\n//\n\nexport async function operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n context: { client: OpenAI; maxRetries?: number } = {\n client: new OpenAI(),\n },\n): Promise<LlmOperateResponse> {\n //\n //\n // Setup\n //\n\n const openai = context.client;\n\n if (!context.maxRetries) {\n context.maxRetries = MAX_RETRIES_DEFAULT_LIMIT;\n }\n\n let retryCount = 0;\n let retryDelay = INITIAL_RETRY_DELAY_MS;\n const maxRetries = Math.min(context.maxRetries, MAX_RETRIES_ABSOLUTE_LIMIT);\n\n const returnResponse: LlmOperateResponse = {\n history: [],\n model: options?.model || PROVIDER.OPENAI.MODEL.DEFAULT,\n output: [],\n provider: PROVIDER.OPENAI.NAME,\n responses: [],\n status: LlmResponseStatus.InProgress,\n usage: [], // Initialize as empty array, will add entry for each response\n };\n\n // Convert string input to array format with placeholders if needed\n let currentInput: LlmHistory = formatOperateInput(input);\n if (\n options?.data &&\n (options.placeholders?.input === undefined || options.placeholders?.input)\n ) {\n currentInput = formatOperateInput(input, {\n data: options?.data,\n });\n }\n\n // If history is provided, merge it with currentInput\n if (options.history) {\n currentInput = [...options.history, ...currentInput];\n }\n\n // If system message is provided, add it to the beginning of the input\n if (options?.system) {\n const systemMessage =\n options.data && options.placeholders?.system !== false\n ? placeholders(options.system, options.data)\n : options.system;\n\n // Create system message\n const systemInputMessage: LlmInputMessage = {\n content: systemMessage,\n role: LlmMessageRole.System,\n type: LlmMessageType.Message,\n };\n\n // Check if history starts with an identical system message\n const firstMessage = currentInput[0];\n const isIdenticalSystemMessage =\n firstMessage?.type === LlmMessageType.Message &&\n firstMessage?.role === LlmMessageRole.System &&\n firstMessage?.content === systemMessage;\n\n // Only prepend if not identical\n if (!isIdenticalSystemMessage) {\n // Remove any existing system message from the beginning\n if (\n currentInput[0]?.type === LlmMessageType.Message &&\n currentInput[0]?.role === LlmMessageRole.System\n ) {\n currentInput = currentInput.slice(1);\n }\n currentInput = [systemInputMessage, ...currentInput];\n }\n }\n\n // Initialize history with currentInput\n returnResponse.history = [...currentInput];\n\n // Determine max turns from options\n const maxTurns = maxTurnsFromOptions(options);\n const enableMultipleTurns = maxTurns > 1;\n let currentTurn = 0;\n\n // Build request options outside the retry loop\n const requestOptions = createRequestOptions(currentInput, options);\n\n // OpenAI Multi-turn Loop\n while (currentTurn < maxTurns) {\n currentTurn++;\n retryCount = 0;\n retryDelay = INITIAL_RETRY_DELAY_MS;\n\n // OpenAI Retry Loop\n while (true) {\n try {\n // Log appropriate message based on turn number\n if (currentTurn > 1) {\n log.trace(`[operate] Calling OpenAI Responses API - ${currentTurn}`);\n } else {\n log.trace(\"[operate] Calling OpenAI Responses API\");\n }\n\n // Execute beforeEachModelRequest hook if defined\n if (options.hooks?.beforeEachModelRequest) {\n await resolveValue(\n options.hooks.beforeEachModelRequest({\n input,\n options,\n providerRequest: requestOptions,\n }),\n );\n }\n\n // Use type assertion to handle the OpenAI SDK response type\n const currentResponse = (await openai.responses.create(\n // @ts-expect-error error claims missing non-required id, status\n requestOptions,\n )) as unknown as OpenAIRawResponse;\n\n if (retryCount > 0) {\n log.debug(`OpenAI API call succeeded after ${retryCount} retries`);\n }\n // Add the response to the responses array\n returnResponse.responses.push(currentResponse);\n\n // Add a new usage entry for each response instead of accumulating\n if (currentResponse.usage) {\n // Create new usage item for this response\n returnResponse.usage.push({\n input: currentResponse.usage.input_tokens || 0,\n output: currentResponse.usage.output_tokens || 0,\n total: currentResponse.usage.total_tokens || 0,\n reasoning:\n currentResponse.usage.output_tokens_details?.reasoning_tokens ||\n 0,\n provider: PROVIDER.OPENAI.NAME,\n model: options?.model || PROVIDER.OPENAI.MODEL.DEFAULT,\n });\n }\n\n // Execute afterEachModelResponse hook immediately after usage processing\n if (options.hooks?.afterEachModelResponse) {\n const extractedContent = extractContentFromResponse(\n currentResponse,\n options,\n );\n await resolveValue(\n options.hooks.afterEachModelResponse({\n input,\n options,\n providerRequest: requestOptions,\n providerResponse: currentResponse,\n content: extractedContent || \"\",\n usage: returnResponse.usage,\n }),\n );\n }\n\n // Check if we need to process function calls for multi-turn conversations\n let hasFunctionCall = false;\n\n try {\n if (currentResponse.output && Array.isArray(currentResponse.output)) {\n // New OpenAI API format with output array\n for (const output of currentResponse.output) {\n returnResponse.output.push(output);\n returnResponse.history.push(output);\n if (output.type === LlmMessageType.FunctionCall) {\n hasFunctionCall = true;\n\n let toolkit: Toolkit | undefined;\n\n // Initialize toolkit for multi-turn function calling\n if (options.tools) {\n if (options.tools instanceof Toolkit) {\n // If toolkit is already provided, use it directly\n toolkit = options.tools;\n } else if (\n Array.isArray(options.tools) &&\n options.tools.length > 0\n ) {\n // If array of tools provided, create toolkit from them\n const explain = options?.explain ?? false;\n toolkit = new Toolkit(options.tools, { explain });\n }\n }\n\n if (toolkit && enableMultipleTurns) {\n try {\n // Call the tool and ensure the result is resolved if it's a Promise\n log.trace(`[operate] Calling tool - ${output.name}`);\n // Content will be set by extractContentFromResponse call later\n\n // Execute beforeEachTool hook if defined\n if (options.hooks?.beforeEachTool) {\n await resolveValue(\n options.hooks.beforeEachTool({\n toolName: output.name,\n args: output.arguments,\n }),\n );\n }\n\n let result;\n try {\n result = await toolkit.call({\n name: output.name,\n arguments: output.arguments,\n });\n\n // Execute afterEachTool hook if defined\n if (options.hooks?.afterEachTool) {\n await resolveValue(\n options.hooks.afterEachTool({\n result,\n toolName: output.name,\n args: output.arguments,\n }),\n );\n }\n } catch (error) {\n // Execute onToolError hook if defined\n if (options.hooks?.onToolError) {\n await resolveValue(\n options.hooks.onToolError({\n error: error as Error,\n toolName: output.name,\n args: output.arguments,\n }),\n );\n }\n throw error;\n }\n\n // Add model's function call and result\n if (Array.isArray(currentInput)) {\n currentInput.push(output);\n // Add function call result\n const functionCallOutput: LlmToolResult = {\n call_id: output.call_id,\n output: JSON.stringify(result),\n type: LlmMessageType.FunctionCallOutput,\n };\n currentInput.push(functionCallOutput);\n returnResponse.output.push(functionCallOutput);\n returnResponse.history.push(functionCallOutput);\n // Content will be set by extractContentFromResponse call later\n }\n } catch (error) {\n // TODO: but I do need to tell the model that something went wrong, right?\n const jaypieError = new BadGatewayError();\n const detail = [\n `Error executing function call ${output.name}.`,\n (error as Error).message,\n ].join(\"\\n\");\n returnResponse.error = {\n detail,\n status: jaypieError.status,\n title: ERROR.BAD_FUNCTION_CALL,\n };\n log.error(`Error executing function call ${output.name}`);\n log.var({ error });\n // We don't add error messages to allResponses here as we want to keep the original response objects\n }\n } else if (!toolkit) {\n log.warn(\n \"Model requested function call but no toolkit available\",\n );\n }\n }\n // Content processing is now handled by extractContentFromResponse function\n }\n }\n } catch (error) {\n // If there's an error processing the response, log it but don't fail\n // This helps with test mocks that might not have the expected structure\n log.warn(\"Error processing response for function calls\");\n log.var({ error });\n }\n\n // Set content using the shared extraction function\n returnResponse.content = extractContentFromResponse(\n currentResponse,\n options,\n );\n\n // If there's no function call or we can't take another turn, exit the loop\n if (!hasFunctionCall || !enableMultipleTurns) {\n returnResponse.status = LlmResponseStatus.Completed;\n return returnResponse;\n }\n\n // If we've reached the maximum number of turns, exit the loop\n if (currentTurn >= maxTurns) {\n const error = new TooManyRequestsError();\n const detail = `Model requested function call but exceeded ${maxTurns} turns`;\n log.warn(detail);\n returnResponse.status = LlmResponseStatus.Incomplete;\n returnResponse.error = {\n detail,\n status: error.status,\n title: error.title,\n };\n return returnResponse;\n }\n\n // Continue to next turn\n break;\n } catch (error: unknown) {\n // Check if we've reached the maximum number of retries\n if (retryCount >= maxRetries) {\n log.error(`OpenAI API call failed after ${maxRetries} retries`);\n log.var({ error });\n\n // Execute onUnrecoverableModelError hook if defined\n if (options.hooks?.onUnrecoverableModelError) {\n await resolveValue(\n options.hooks.onUnrecoverableModelError({\n input,\n options,\n providerRequest: requestOptions,\n error,\n }),\n );\n }\n\n throw new BadGatewayError();\n }\n\n // Check if the error is not retryable\n let isNotRetryable = false;\n for (const notRetryableError of NOT_RETRYABLE_ERRORS) {\n if (error instanceof notRetryableError) {\n isNotRetryable = true;\n break;\n }\n }\n\n if (isNotRetryable) {\n log.error(\"OpenAI API call failed with non-retryable error\");\n log.var({ error });\n\n // Execute onUnrecoverableModelError hook if defined\n if (options.hooks?.onUnrecoverableModelError) {\n await resolveValue(\n options.hooks.onUnrecoverableModelError({\n input,\n options,\n providerRequest: requestOptions,\n error,\n }),\n );\n }\n\n throw new BadGatewayError();\n }\n\n // Warn if this error is not in our known retryable errors\n let isUnknownError = true;\n for (const retryableError of RETRYABLE_ERRORS) {\n if (error instanceof retryableError) {\n isUnknownError = false;\n break;\n }\n }\n if (isUnknownError) {\n log.warn(\"OpenAI API returned unknown error\");\n log.var({ error });\n }\n\n // Log the error and retry\n log.warn(`OpenAI API call failed. Retrying in ${retryDelay}ms...`);\n\n // Execute onRetryableModelError hook if defined\n if (options.hooks?.onRetryableModelError) {\n await resolveValue(\n options.hooks.onRetryableModelError({\n input,\n options,\n providerRequest: requestOptions,\n error,\n }),\n );\n }\n\n // Wait before retrying\n await sleep(retryDelay);\n\n // Increase retry count and delay for next attempt (exponential backoff)\n retryCount++;\n retryDelay = Math.min(\n retryDelay * RETRY_BACKOFF_FACTOR,\n MAX_RETRY_DELAY_MS,\n );\n }\n }\n }\n\n // * All possible paths should return a response; getting here is an error\n // The main loop is `currentTurn < maxTurns` and `currentTurn >= maxTurns` within the loop returns\n log.warn(\"This should never happen\");\n returnResponse.status = LlmResponseStatus.Incomplete;\n\n // Always return the full LlmOperateResponse object for consistency\n return returnResponse;\n}\n","import { getEnvSecret } from \"@jaypie/aws\";\nimport {\n ConfigurationError,\n log as defaultLog,\n placeholders as replacePlaceholders,\n JAYPIE,\n} from \"@jaypie/core\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { OpenAI } from \"openai\";\nimport { zodResponseFormat } from \"openai/helpers/zod\";\nimport { z } from \"zod\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { naturalZodSchema } from \"../../util\";\n\n// Logger\nexport const getLogger = () => defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<OpenAI> {\n const logger = getLogger();\n const resolvedApiKey = apiKey || (await getEnvSecret(\"OPENAI_API_KEY\"));\n\n if (!resolvedApiKey) {\n throw new ConfigurationError(\n \"The application could not resolve the requested keys\",\n );\n }\n\n const client = new OpenAI({ apiKey: resolvedApiKey });\n logger.trace(\"Initialized OpenAI client\");\n return client;\n}\n\n// Message formatting\nexport interface ChatMessage {\n role: \"user\" | \"developer\";\n content: string;\n}\n\nexport function formatSystemMessage(\n systemPrompt: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.system === false\n ? systemPrompt\n : replacePlaceholders(systemPrompt, data);\n\n return {\n role: \"developer\" as const,\n content,\n };\n}\n\nexport function formatUserMessage(\n message: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.message === false\n ? message\n : replacePlaceholders(message, data);\n\n return {\n role: \"user\" as const,\n content,\n };\n}\n\nexport function prepareMessages(\n message: string,\n { system, data, placeholders }: LlmMessageOptions = {},\n): ChatMessage[] {\n const logger = getLogger();\n const messages: ChatMessage[] = [];\n\n if (system) {\n const systemMessage = formatSystemMessage(system, { data, placeholders });\n messages.push(systemMessage);\n logger.trace(`System message: ${systemMessage.content?.length} characters`);\n }\n\n const userMessage = formatUserMessage(message, { data, placeholders });\n messages.push(userMessage);\n logger.trace(`User message: ${userMessage.content?.length} characters`);\n\n return messages;\n}\n\n// Completion requests\nexport async function createStructuredCompletion(\n client: OpenAI,\n {\n messages,\n responseSchema,\n model,\n }: {\n messages: ChatMessage[];\n responseSchema: z.ZodType | NaturalSchema;\n model: string;\n },\n): Promise<JsonObject> {\n const logger = getLogger();\n logger.trace(\"Using structured output\");\n\n const zodSchema =\n responseSchema instanceof z.ZodType\n ? responseSchema\n : naturalZodSchema(responseSchema as NaturalSchema);\n\n const completion = await client.beta.chat.completions.parse({\n messages,\n model,\n response_format: zodResponseFormat(zodSchema, \"response\"),\n });\n\n logger.var({ assistantReply: completion.choices[0].message.parsed });\n return completion.choices[0].message.parsed;\n}\n\nexport async function createTextCompletion(\n client: OpenAI,\n {\n messages,\n model,\n }: {\n messages: ChatMessage[];\n model: string;\n },\n): Promise<string> {\n const logger = getLogger();\n logger.trace(\"Using text output (unstructured)\");\n\n const completion = await client.chat.completions.create({\n messages,\n model,\n });\n\n logger.trace(\n `Assistant reply: ${completion.choices[0]?.message?.content?.length} characters`,\n );\n\n return completion.choices[0]?.message?.content || \"\";\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { OpenAI } from \"openai\";\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n LlmHistoryItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { operate } from \"./operate.js\";\nimport {\n createStructuredCompletion,\n createTextCompletion,\n getLogger,\n initializeClient,\n prepareMessages,\n} from \"./utils.js\";\n\nexport class OpenAiProvider implements LlmProvider {\n private model: string;\n private _client?: OpenAI;\n private apiKey?: string;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = PROVIDER.OPENAI.MODEL.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<OpenAI> {\n if (this._client) {\n return this._client;\n }\n\n this._client = await initializeClient({ apiKey: this.apiKey });\n return this._client;\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const client = await this.getClient();\n const messages = prepareMessages(message, options || {});\n const modelToUse = options?.model || this.model;\n\n if (options?.response) {\n return createStructuredCompletion(client, {\n messages,\n responseSchema: options.response,\n model: modelToUse,\n });\n }\n\n return createTextCompletion(client, {\n messages,\n model: modelToUse,\n });\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const client = await this.getClient();\n options.model = options?.model || this.model;\n\n // Create a merged history including both the tracked history and any explicitly provided history\n const mergedOptions = { ...options };\n if (this.conversationHistory.length > 0) {\n // If options.history exists, merge with instance history, otherwise use instance history\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Call operate with the updated options\n const response = await operate(input, mergedOptions, { client });\n\n // Update conversation history with the new history from the response\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n}\n","import { getEnvSecret } from \"@jaypie/aws\";\nimport {\n ConfigurationError,\n log as defaultLog,\n placeholders as replacePlaceholders,\n JAYPIE,\n} from \"@jaypie/core\";\nimport Anthropic from \"@anthropic-ai/sdk\";\nimport { PROVIDER } from \"../../constants.js\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\n\n// Logger\nexport const getLogger = () => defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<Anthropic> {\n const logger = getLogger();\n const resolvedApiKey = apiKey || (await getEnvSecret(\"ANTHROPIC_API_KEY\"));\n\n if (!resolvedApiKey) {\n throw new ConfigurationError(\n \"The application could not resolve the required API key: ANTHROPIC_API_KEY\",\n );\n }\n\n const client = new Anthropic({ apiKey: resolvedApiKey });\n logger.trace(\"Initialized Anthropic client\");\n return client;\n}\n\n// Message formatting functions\nexport function formatSystemMessage(\n systemPrompt: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): string {\n return placeholders?.system === false\n ? systemPrompt\n : replacePlaceholders(systemPrompt, data);\n}\n\nexport function formatUserMessage(\n message: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): Anthropic.MessageParam {\n const content =\n placeholders?.message === false\n ? message\n : replacePlaceholders(message, data);\n\n return {\n role: PROVIDER.ANTHROPIC.ROLE.USER,\n content,\n };\n}\n\nexport function prepareMessages(\n message: string,\n { data, placeholders }: LlmMessageOptions = {},\n): Anthropic.MessageParam[] {\n const logger = getLogger();\n const messages: Anthropic.MessageParam[] = [];\n\n // Add user message (necessary for all requests)\n const userMessage = formatUserMessage(message, { data, placeholders });\n messages.push(userMessage);\n logger.trace(`User message: ${userMessage.content.length} characters`);\n\n return messages;\n}\n","import { LlmMessageRole } from \"../../types/LlmProvider.interface.js\";\nimport { PROVIDER } from \"../../constants.js\";\n\n// Maps Jaypie roles to Anthropic roles\nexport const ROLE_MAP: Record<LlmMessageRole, string> = {\n [LlmMessageRole.User]: PROVIDER.ANTHROPIC.ROLE.USER,\n [LlmMessageRole.System]: PROVIDER.ANTHROPIC.ROLE.SYSTEM,\n [LlmMessageRole.Assistant]: PROVIDER.ANTHROPIC.ROLE.ASSISTANT,\n [LlmMessageRole.Developer]: PROVIDER.ANTHROPIC.ROLE.SYSTEM,\n};\n","import { JsonObject } from \"@jaypie/types\";\nimport Anthropic from \"@anthropic-ai/sdk\";\nimport { PROVIDER } from \"../constants.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n LlmHistoryItem,\n} from \"../types/LlmProvider.interface.js\";\nimport { naturalZodSchema } from \"../util/index.js\";\nimport { z } from \"zod\";\nimport {\n getLogger,\n initializeClient,\n prepareMessages,\n formatSystemMessage,\n} from \"./anthropic/index.js\";\n\n// Main class implementation\nexport class AnthropicProvider implements LlmProvider {\n private model: string;\n private _client?: Anthropic;\n private apiKey?: string;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = PROVIDER.ANTHROPIC.MODEL.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<Anthropic> {\n if (this._client) {\n return this._client;\n }\n\n this._client = await initializeClient({ apiKey: this.apiKey });\n return this._client;\n }\n\n // Basic text completion\n async createTextCompletion(\n client: Anthropic,\n messages: Anthropic.MessageParam[],\n model: string,\n systemMessage?: string,\n ): Promise<string> {\n this.log.trace(\"Using text output (unstructured)\");\n\n const params: Anthropic.MessageCreateParams = {\n model,\n messages,\n max_tokens: PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT,\n };\n\n // Add system instruction if provided\n if (systemMessage) {\n params.system = systemMessage;\n this.log.trace(`System message: ${systemMessage.length} characters`);\n }\n\n const response = await client.messages.create(params);\n\n this.log.trace(\n `Assistant reply: ${response.content[0]?.text?.length || 0} characters`,\n );\n\n return response.content[0]?.text || \"\";\n }\n\n // Structured output completion\n async createStructuredCompletion(\n client: Anthropic,\n messages: Anthropic.MessageParam[],\n model: string,\n responseSchema: z.ZodType | JsonObject,\n systemMessage?: string,\n ): Promise<JsonObject> {\n this.log.trace(\"Using structured output\");\n\n // Get the JSON schema for the response\n const schema =\n responseSchema instanceof z.ZodType\n ? responseSchema\n : naturalZodSchema(responseSchema as JsonObject);\n\n // Set system message with JSON instructions\n const defaultSystemPrompt =\n \"You will be responding with structured JSON data. \" +\n \"Format your entire response as a valid JSON object with the following structure: \" +\n (responseSchema instanceof z.ZodType\n ? JSON.stringify(this.simplifyZodSchema(schema))\n : JSON.stringify(responseSchema));\n\n const systemPrompt = systemMessage || defaultSystemPrompt;\n\n try {\n // Use standard Anthropic API to get response\n const params: Anthropic.MessageCreateParams = {\n model,\n messages,\n max_tokens: PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT,\n system: systemPrompt,\n };\n\n const response = await client.messages.create(params);\n\n // Extract text from response\n const responseText = response.content[0]?.text || \"\";\n\n // Find JSON in response\n const jsonMatch =\n responseText.match(/```json\\s*([\\s\\S]*?)\\s*```/) ||\n responseText.match(/\\{[\\s\\S]*\\}/);\n\n if (jsonMatch) {\n try {\n // Parse the JSON response\n const jsonStr = jsonMatch[1] || jsonMatch[0];\n const result = JSON.parse(jsonStr);\n this.log.trace(\"Received structured response\", { result });\n return result;\n } catch {\n throw new Error(\n `Failed to parse JSON response from Anthropic: ${responseText}`,\n );\n }\n }\n\n // If we can't extract JSON\n throw new Error(\"Failed to parse structured response from Anthropic\");\n } catch (error: unknown) {\n this.log.error(\"Error creating structured completion\", { error });\n throw error;\n }\n }\n\n // Helper method to simplify Zod schema to a plain object for system prompt\n private simplifyZodSchema(schema: z.ZodType): Record<string, unknown> {\n try {\n // Type casting for internal Zod structure\n interface ZodTypeShape {\n _def?: {\n shape?: Record<string, unknown>;\n };\n }\n\n const zodSchema = schema as ZodTypeShape;\n\n if (typeof zodSchema._def?.shape === \"object\") {\n const result: Record<string, string> = {};\n Object.keys(zodSchema._def.shape || {}).forEach((key) => {\n result[key] = \"string\";\n });\n return result;\n }\n return { result: \"string\" };\n } catch (error: unknown) {\n this.log.error(`Error simplifying schema: ${error}`);\n return { result: \"string\" };\n }\n }\n\n // Main send method\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const client = await this.getClient();\n const messages = prepareMessages(message, options || {});\n const modelToUse = options?.model || this.model;\n\n // Process system message if provided\n let systemMessage: string | undefined;\n if (options?.system) {\n systemMessage = formatSystemMessage(options.system, {\n data: options.data,\n placeholders: options.placeholders,\n });\n }\n\n if (options?.response) {\n const schema =\n options.response instanceof z.ZodType\n ? options.response\n : naturalZodSchema(options.response);\n\n return this.createStructuredCompletion(\n client,\n messages,\n modelToUse,\n schema,\n systemMessage,\n );\n }\n\n return this.createTextCompletion(\n client,\n messages,\n modelToUse,\n systemMessage,\n );\n }\n\n // Placeholder for operate method - will be implemented in a future task\n // This will be properly implemented in the \"Tool Calling Implementation\" task\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n\n _options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n throw new Error(\n \"The operate method is not yet implemented for AnthropicProvider\",\n );\n }\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { NotImplementedError } from \"@jaypie/errors\";\nimport { DEFAULT, LlmProviderName, PROVIDER } from \"./constants.js\";\nimport {\n LlmProvider,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOptions,\n LlmOperateResponse,\n} from \"./types/LlmProvider.interface.js\";\nimport { OpenAiProvider } from \"./providers/openai/index.js\";\nimport { AnthropicProvider } from \"./providers/AnthropicProvider.class.js\";\n\nclass Llm implements LlmProvider {\n private _provider: LlmProviderName;\n private _llm: LlmProvider;\n private _options: LlmOptions;\n\n constructor(\n providerName: LlmProviderName = DEFAULT.PROVIDER.NAME,\n options: LlmOptions = {},\n ) {\n this._provider = providerName;\n this._options = options;\n this._llm = this.createProvider(providerName, options);\n }\n\n private createProvider(\n providerName: LlmProviderName,\n options: LlmOptions = {},\n ): LlmProvider {\n const { apiKey, model } = options;\n\n switch (providerName) {\n case PROVIDER.OPENAI.NAME:\n return new OpenAiProvider(model || PROVIDER.OPENAI.MODEL.DEFAULT, {\n apiKey,\n });\n case PROVIDER.ANTHROPIC.NAME:\n return new AnthropicProvider(\n model || PROVIDER.ANTHROPIC.MODEL.DEFAULT,\n { apiKey },\n );\n default:\n throw new Error(`Unsupported provider: ${providerName}`);\n }\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n return this._llm.send(message, options);\n }\n\n async operate(\n message: string,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n if (!this._llm.operate) {\n throw new NotImplementedError(\n `Provider ${this._provider} does not support operate method`,\n );\n }\n return this._llm.operate(message, options);\n }\n\n static async send(\n message: string,\n options?: LlmMessageOptions & {\n llm?: LlmProviderName;\n apiKey?: string;\n model?: string;\n },\n ): Promise<string | JsonObject> {\n const { llm, apiKey, model, ...messageOptions } = options || {};\n const instance = new Llm(llm, { apiKey, model });\n return instance.send(message, messageOptions);\n }\n\n static async operate(\n message: string,\n options?: LlmOperateOptions & {\n llm?: LlmProviderName;\n apiKey?: string;\n model?: string;\n },\n ): Promise<LlmOperateResponse> {\n const { llm, apiKey, model, ...operateOptions } = options || {};\n const instance = new Llm(llm, { apiKey, model });\n return instance.operate(message, operateOptions);\n }\n}\n\nexport default Llm;\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\nimport { random as randomUtil } from \"../util/random.js\";\n\nexport const random: LlmTool = {\n description:\n \"Generate a random number with optional distribution, precision, range, and seeding\",\n\n name: \"random\",\n parameters: {\n type: \"object\",\n properties: {\n min: {\n type: \"number\",\n description:\n \"Minimum value (inclusive). Default: 0. When used with mean/stddev, acts as a clamp on the normal distribution\",\n },\n max: {\n type: \"number\",\n description:\n \"Maximum value (inclusive). Default: 1. When used with mean/stddev, acts as a clamp on the normal distribution\",\n },\n mean: {\n type: \"number\",\n description:\n \"Mean value for normal distribution. When set with stddev, uses normal distribution (clamped by min/max if provided)\",\n },\n stddev: {\n type: \"number\",\n description:\n \"Standard deviation for normal distribution. When set with mean, uses normal distribution (clamped by min/max if provided)\",\n },\n integer: {\n type: \"boolean\",\n description: \"Whether to return an integer value. Default: false\",\n },\n seed: {\n type: \"string\",\n description:\n \"Seed string for consistent random generation. Default: undefined (uses default RNG)\",\n },\n precision: {\n type: \"number\",\n description:\n \"Number of decimal places for the result. Default: undefined (full precision)\",\n },\n currency: {\n type: \"boolean\",\n description:\n \"Whether to format as currency (2 decimal places). Default: false\",\n },\n },\n required: [],\n },\n type: \"function\",\n call: (options) => {\n const rng = randomUtil();\n return rng(options);\n },\n message: ({\n min,\n max,\n mean,\n stddev,\n integer,\n seed,\n precision,\n currency,\n } = {}) => {\n let description = \"Generating\";\n if (seed) {\n description += ` seeded`;\n } else {\n description += \" random\";\n }\n if (integer) {\n description += \" integer\";\n } else if (currency) {\n description += \" currency\";\n } else if (precision) {\n description += ` with precision \\`${precision}\\``;\n } else {\n description += \" number\";\n }\n if (min && max) {\n description += ` between \\`${min}\\` and \\`${max}\\``;\n }\n if (mean && stddev) {\n description += ` with normal distribution around \\`${mean}\\` with standard deviation \\`${stddev}\\``;\n }\n return description;\n },\n};\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\nimport { log, random, tryParseNumber } from \"../util\";\n\nexport const roll: LlmTool = {\n description: \"Roll one or more dice with a specified number of sides\",\n name: \"roll\",\n parameters: {\n type: \"object\",\n properties: {\n number: {\n type: \"number\",\n description: \"Number of dice to roll. Default: 1\",\n },\n sides: {\n type: \"number\",\n description: \"Number of sides on each die. Default: 6\",\n },\n },\n required: [\"number\", \"sides\"],\n },\n type: \"function\",\n call: ({ number = 1, sides = 6 } = {}): {\n rolls: number[];\n total: number;\n } => {\n const rng = random();\n const rolls: number[] = [];\n let total = 0;\n\n const parsedNumber = tryParseNumber(number, {\n defaultValue: 1,\n warnFunction: log.warn,\n }) as number;\n const parsedSides = tryParseNumber(sides, {\n defaultValue: 6,\n warnFunction: log.warn,\n }) as number;\n\n for (let i = 0; i < parsedNumber; i++) {\n const rollValue = rng({ min: 1, max: parsedSides, integer: true });\n rolls.push(rollValue);\n total += rollValue;\n }\n\n return { rolls, total };\n },\n message: ({ number = 1, sides = 6 } = {}) => {\n return `Rolling ${number} ${sides}-sided dice`;\n },\n};\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\n\nexport const time: LlmTool = {\n description:\n \"Returns the provided date as an ISO UTC string or the current time if no date provided.\",\n name: \"time\",\n parameters: {\n type: \"object\",\n properties: {\n date: {\n type: \"string\",\n description:\n \"Date string to convert to ISO UTC format. Default: current time\",\n },\n },\n required: [],\n },\n type: \"function\",\n call: ({ date } = {}) => {\n if (typeof date === \"number\" || typeof date === \"string\") {\n const parsedDate = new Date(date);\n if (isNaN(parsedDate.getTime())) {\n throw new Error(`Invalid date format: ${date}`);\n }\n return parsedDate.toISOString();\n }\n return new Date().toISOString();\n },\n message: ({ date } = {}) => {\n if (typeof date === \"number\" || typeof date === \"string\") {\n return `Converting date to ISO UTC format`;\n }\n return \"Checking current time\";\n },\n};\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\nimport { fetchWeatherApi } from \"openmeteo\";\nimport { JsonObject } from \"@jaypie/types\";\n\nexport const weather: LlmTool = {\n description: \"Get current weather and forecast data for a specific location\",\n name: \"weather\",\n parameters: {\n type: \"object\",\n properties: {\n latitude: {\n type: \"number\",\n description:\n \"Latitude of the location. Default: 42.051554533384866 (Evanston, IL)\",\n },\n location: {\n type: \"string\",\n description:\n \"Human-readable description of the location, not used for the API call. Default: Evanston, IL\",\n },\n longitude: {\n type: \"number\",\n description:\n \"Longitude of the location. Default: -87.6759911441785 (Evanston, IL)\",\n },\n timezone: {\n type: \"string\",\n description: \"Timezone for the results. Default: America/Chicago\",\n },\n past_days: {\n type: \"number\",\n description:\n \"Number of past days to include in the forecast. Default: 1\",\n },\n forecast_days: {\n type: \"number\",\n description: \"Number of forecast days to include. Default: 1\",\n },\n },\n required: [\"latitude\", \"location\", \"longitude\"],\n },\n type: \"function\",\n call: async ({\n latitude = 42.051554533384866,\n longitude = -87.6759911441785,\n timezone = \"America/Chicago\",\n past_days = 1,\n forecast_days = 1,\n } = {}): Promise<JsonObject> => {\n try {\n const params = {\n latitude,\n longitude,\n hourly: [\n \"temperature_2m\",\n \"precipitation_probability\",\n \"precipitation\",\n ],\n current: [\n \"temperature_2m\",\n \"is_day\",\n \"showers\",\n \"cloud_cover\",\n \"wind_speed_10m\",\n \"relative_humidity_2m\",\n \"precipitation\",\n \"snowfall\",\n \"rain\",\n \"apparent_temperature\",\n ],\n timezone,\n past_days,\n forecast_days,\n wind_speed_unit: \"mph\",\n temperature_unit: \"fahrenheit\",\n precipitation_unit: \"inch\",\n };\n\n const url = \"https://api.open-meteo.com/v1/forecast\";\n const responses = await fetchWeatherApi(url, params);\n\n // Helper function to form time ranges\n const range = (start: number, stop: number, step: number) =>\n Array.from(\n { length: (stop - start) / step },\n (_, i) => start + i * step,\n );\n\n // Process first location\n const response = responses[0];\n\n // Attributes for timezone and location\n const utcOffsetSeconds = response.utcOffsetSeconds();\n const timezoneAbbreviation = response.timezoneAbbreviation();\n\n const current = response.current()!;\n const hourly = response.hourly()!;\n\n // Create weather data object\n const weatherData = {\n location: {\n latitude: response.latitude(),\n longitude: response.longitude(),\n timezone: response.timezone(),\n timezoneAbbreviation,\n utcOffsetSeconds,\n },\n current: {\n time: new Date(\n (Number(current.time()) + utcOffsetSeconds) * 1000,\n ).toISOString(),\n temperature2m: current.variables(0)!.value(),\n isDay: current.variables(1)!.value(),\n showers: current.variables(2)!.value(),\n cloudCover: current.variables(3)!.value(),\n windSpeed10m: current.variables(4)!.value(),\n relativeHumidity2m: current.variables(5)!.value(),\n precipitation: current.variables(6)!.value(),\n snowfall: current.variables(7)!.value(),\n rain: current.variables(8)!.value(),\n apparentTemperature: current.variables(9)!.value(),\n },\n hourly: {\n time: range(\n Number(hourly.time()),\n Number(hourly.timeEnd()),\n hourly.interval(),\n ).map((t) => new Date((t + utcOffsetSeconds) * 1000).toISOString()),\n temperature2m: Array.from(hourly.variables(0)!.valuesArray()!),\n precipitationProbability: Array.from(\n hourly.variables(1)!.valuesArray()!,\n ),\n precipitation: Array.from(hourly.variables(2)!.valuesArray()!),\n },\n };\n\n return weatherData;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Weather API error: ${error.message}`);\n }\n throw new Error(\"Unknown error occurred while fetching weather data\");\n }\n },\n message: ({\n latitude = 42.051554533384866,\n longitude = -87.6759911441785,\n location = \"Evanston, IL\",\n } = {}) => {\n return `Getting weather for ${location} (${latitude}, ${longitude})`;\n },\n};\n","import { Toolkit } from \"./Toolkit.class.js\";\n\nimport { random } from \"./random.js\";\nimport { roll } from \"./roll.js\";\nimport { time } from \"./time.js\";\nimport { weather } from \"./weather.js\";\n\nexport const tools = [random, roll, time, weather];\n\nexport const toolkit = new Toolkit(tools);\n\nexport { Toolkit };\n"],"names":["log","jaypieLog","getLogger","defaultLog","random","initializeClient","ConfigurationError","formatSystemMessage","placeholders","replacePlaceholders","formatUserMessage","prepareMessages","randomUtil"],"mappings":";;;;;;;;;;AAAO,MAAM,QAAQ,GAAG;AACtB,IAAA,SAAS,EAAE;AACT,QAAA,KAAK,EAAE;AACL,YAAA,cAAc,EAAE,yBAAkC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AAE,CAAC,WAAW,EAAG,CAAC;AAC9D,oBAAA,wBAAwB,EAAE,KAAK,CAAC,IAAI,CAClC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAE,CAAC,WAAW,EAAG,CACpC;AACD,oBAAA,aAAa,EAAE,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAE,CAAC,WAAW,EAAG,CAAC;AAC/D,iBAAA;aACF;AAED,YAAA,OAAO,WAAW;;QAClB,OAAO,KAAK,EAAE;AACd,YAAA,IAAI,KAAK,YAAY,KAAK,EAAE;gBAC1B,MAAM,IAAI,KAAK,CAAC,CAAA,mBAAA,EAAsB,KAAK,CAAC,OAAO,CAAE,CAAA,CAAC;;AAExD,YAAA,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC;;KAExE;AACD,IAAA,OAAO,EAAE,CAAC,EACR,QAAQ,GAAG,kBAAkB,EAC7B,SAAS,GAAG,iBAAiB,EAC7B,QAAQ,GAAG,cAAc,GAC1B,GAAG,EAAE,KAAI;AACR,QAAA,OAAO,uBAAuB,QAAQ,CAAA,EAAA,EAAK,QAAQ,CAAK,EAAA,EAAA,SAAS,GAAG;KACrE;CACF;;AChJM,MAAM,KAAK,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO;MAEpC,OAAO,GAAG,IAAI,OAAO,CAAC,KAAK;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../src/constants.ts","../src/tools/Toolkit.class.ts","../src/types/LlmProvider.interface.ts","../src/util/formatOperateMessage.ts","../src/util/formatOperateInput.ts","../src/util/logger.ts","../src/util/maxTurnsFromOptions.ts","../src/util/naturalZodSchema.ts","../src/util/random.ts","../src/util/tryParseNumber.ts","../src/providers/openai/operate.ts","../src/providers/openai/utils.ts","../src/providers/openai/OpenAiProvider.class.ts","../src/providers/anthropic/operate.ts","../src/providers/anthropic/utils.ts","../src/providers/anthropic/types.ts","../src/providers/anthropic/AnthropicProvider.class.ts","../src/Llm.ts","../src/tools/random.ts","../src/tools/roll.ts","../src/tools/time.ts","../src/tools/weather.ts","../src/tools/index.ts"],"sourcesContent":["export const PROVIDER = {\n ANTHROPIC: {\n // https://docs.anthropic.com/en/docs/about-claude/models/overview\n MODEL: {\n // Jaypie Aliases\n DEFAULT: \"claude-opus-4-1\" as const,\n SMALL: \"claude-sonnet-4-0\" as const,\n TINY: \"claude-3-5-haiku-latest\" as const,\n LARGE: \"claude-opus-4-1\" as const,\n // Latests\n CLAUDE_OPUS_4: \"claude-opus-4-1\" as const,\n CLAUDE_SONNET_4: \"claude-sonnet-4-0\" as const,\n CLAUDE_3_HAIKU: \"claude-3-5-haiku-latest\" as const,\n CLAUDE_3_OPUS: \"claude-3-opus-latest\" as const,\n CLAUDE_3_SONNET: \"claude-3-7-sonnet-latest\" as const,\n // Specifics\n CLAUDE_OPUS_4_1: \"claude-opus-4-1\" as const,\n CLAUDE_OPUS_4_0: \"claude-opus-4-0\" as const,\n CLAUDE_SONNET_4_0: \"claude-sonnet-4-0\" as const,\n CLAUDE_3_7_SONNET: \"claude-3-7-sonnet-latest\t\" as const,\n CLAUDE_3_5_SONNET: \"claude-3-5-sonnet-latest\" as const,\n CLAUDE_3_5_HAIKU: \"claude-3-5-haiku-latest\" as const,\n // _Note: Claude reversed the order of model name and version in 4_\n // Backward compatibility\n CLAUDE_HAIKU_3: \"claude-3-5-haiku-latest\" as const,\n CLAUDE_OPUS_3: \"claude-3-opus-latest\" as const,\n CLAUDE_SONNET_3: \"claude-3-7-sonnet-latest\" as const,\n },\n NAME: \"anthropic\" as const,\n PROMPT: {\n AI: \"\\n\\nAssistant:\" as const,\n HUMAN: \"\\n\\nHuman:\" as const,\n },\n ROLE: {\n ASSISTANT: \"assistant\" as const,\n SYSTEM: \"system\" as const,\n USER: \"user\" as const,\n },\n MAX_TOKENS: {\n DEFAULT: 4096 as const,\n },\n TOOLS: {\n SCHEMA_VERSION: \"v2\" as const,\n },\n },\n OPENAI: {\n // https://platform.openai.com/docs/models\n MODEL: {\n // Jaypie Aliases\n DEFAULT: \"gpt-5\" as const,\n SMALL: \"gpt-5-mini\" as const,\n LARGE: \"gpt-5\" as const,\n TINY: \"gpt-5-nano\" as const,\n // OpenAI Official\n GPT_5: \"gpt-5\" as const,\n GPT_5_MINI: \"gpt-5-mini\" as const,\n GPT_5_NANO: \"gpt-5-nano\" as const,\n GPT_4_1: \"gpt-4.1\" as const,\n GPT_4_1_MINI: \"gpt-4.1-mini\" as const,\n GPT_4_1_NANO: \"gpt-4.1-nano\" as const,\n GPT_4: \"gpt-4\" as const,\n GPT_4_O_MINI: \"gpt-4o-mini\" as const,\n GPT_4_O: \"gpt-4o\" as const,\n GPT_4_5: \"gpt-4.5-preview\" as const,\n O1: \"o1\" as const,\n O1_MINI: \"o1-mini\" as const,\n O1_PRO: \"o1-pro\" as const,\n O3_MINI: \"o3-mini\" as const,\n O3_MINI_HIGH: \"o3-mini-high\" as const,\n O3: \"o3\" as const,\n O3_PRO: \"o3-pro\" as const,\n O4_MINI: \"o4-mini\" as const,\n },\n NAME: \"openai\" as const,\n },\n} as const;\n\nexport type LlmProviderName =\n | typeof PROVIDER.OPENAI.NAME\n | typeof PROVIDER.ANTHROPIC.NAME;\n\n// Last: Defaults\nexport const DEFAULT = {\n PROVIDER: PROVIDER.OPENAI,\n} as const;\n","import { JAYPIE, log as jaypieLog, resolveValue } from \"@jaypie/core\";\n\nimport { LlmTool } from \"../types/LlmTool.interface\";\n\nconst DEFAULT_TOOL_TYPE = \"function\";\n\nconst log = jaypieLog.lib({ lib: JAYPIE.LIB.LLM });\n\ntype LogFunction = (\n message: string,\n context: { name: string; args: any },\n) => void | Promise<void>;\n\nfunction logToolMessage(message: string, context: { name: string; args: any }) {\n log.trace.var({ [context.name]: message });\n}\n\nexport interface ToolkitOptions {\n explain?: boolean;\n log?: boolean | LogFunction;\n}\n\nexport class Toolkit {\n private readonly _tools: LlmTool[];\n private readonly _options: ToolkitOptions;\n private readonly explain: boolean;\n private readonly log: boolean | LogFunction;\n\n constructor(tools: LlmTool[], options?: ToolkitOptions) {\n this._tools = tools;\n this._options = options || {};\n this.explain = this._options.explain ? true : false;\n this.log = this._options.log !== undefined ? this._options.log : true;\n }\n\n get tools(): Omit<LlmTool, \"call\">[] {\n return this._tools.map((tool) => {\n const toolCopy: any = { ...tool };\n delete toolCopy.call;\n delete toolCopy.message;\n\n if (this.explain && toolCopy.parameters?.type === \"object\") {\n if (toolCopy.parameters?.properties) {\n if (!toolCopy.parameters.properties.__Explanation) {\n toolCopy.parameters.properties.__Explanation = {\n type: \"string\",\n description: `Clearly state why the tool is being called and what larger question it helps answer. For example, \"I am checking the location API because the user asked for nearby pizza and I need coordinates to proceed\"`,\n };\n }\n }\n }\n\n // Set default type if not provided\n if (!toolCopy.type) {\n toolCopy.type = DEFAULT_TOOL_TYPE;\n }\n\n return toolCopy;\n });\n }\n\n async call({ name, arguments: args }: { name: string; arguments: string }) {\n const tool = this._tools.find((t) => t.name === name);\n if (!tool) {\n throw new Error(`Tool '${name}' not found`);\n }\n\n let parsedArgs;\n try {\n parsedArgs = JSON.parse(args);\n if (this.explain) {\n delete parsedArgs.__Explanation;\n }\n } catch {\n parsedArgs = args;\n }\n\n if (this.log !== false) {\n try {\n const context: { name: string; args: any; explanation?: string } = {\n name,\n args: parsedArgs,\n };\n let message: string;\n\n if (this.explain) {\n context.explanation = parsedArgs.__Explanation;\n }\n\n if (tool.message) {\n if (typeof tool.message === \"string\") {\n log.trace(\"[Toolkit] Tool provided string message\");\n message = tool.message;\n } else if (typeof tool.message === \"function\") {\n log.trace(\"[Toolkit] Tool provided function message\");\n log.trace(\"[Toolkit] Resolving message result\");\n message = await resolveValue(tool.message(parsedArgs, { name }));\n } else {\n log.warn(\"[Toolkit] Tool provided unknown message type\");\n message = String(tool.message);\n }\n } else {\n log.trace(\"[Toolkit] Log tool call with default message\");\n message = `${tool.name}:${JSON.stringify(parsedArgs)}`;\n }\n\n if (typeof this.log === \"function\") {\n log.trace(\"[Toolkit] Log tool call with custom logger\");\n await resolveValue(this.log(message, context));\n } else {\n log.trace(\"[Toolkit] Log tool call with default logger\");\n logToolMessage(message, context);\n }\n } catch (error) {\n log.error(\"[Toolkit] Caught error during logToolCall\");\n log.var({ error });\n log.debug(\"[Toolkit] Continuing...\");\n }\n }\n\n return await resolveValue(tool.call(parsedArgs));\n }\n\n extend(\n tools: LlmTool[],\n options: {\n warn?: boolean;\n replace?: boolean;\n log?: boolean | LogFunction;\n explain?: boolean;\n } = {},\n ): this {\n for (const tool of tools) {\n const existingIndex = this._tools.findIndex((t) => t.name === tool.name);\n if (existingIndex !== -1) {\n if (options.replace === false) {\n continue;\n }\n if (options.warn !== false) {\n if (typeof this.log === \"function\") {\n this.log(\n `[Toolkit] Tool '${tool.name}' already exists, replacing with new tool`,\n { name: tool.name, args: {} },\n );\n } else if (this.log) {\n log.warn(\n `[Toolkit] Tool '${tool.name}' already exists, replacing with new tool`,\n );\n }\n }\n this._tools[existingIndex] = tool;\n } else {\n this._tools.push(tool);\n }\n }\n if (Object.prototype.hasOwnProperty.call(options, \"log\")) {\n (this as any).log = options.log;\n }\n if (Object.prototype.hasOwnProperty.call(options, \"explain\")) {\n (this as any).explain = options.explain;\n }\n return this;\n }\n}\n","import {\n AnyValue,\n JsonObject,\n JsonReturn,\n NaturalMap,\n NaturalSchema,\n} from \"@jaypie/types\";\nimport { z } from \"zod\";\nimport { LlmTool } from \"./LlmTool.interface.js\";\nimport { Toolkit } from \"../tools/Toolkit.class.js\";\n\n// Enums\n\nexport enum LlmMessageRole {\n Assistant = \"assistant\",\n Developer = \"developer\",\n System = \"system\",\n User = \"user\",\n}\n\nexport enum LlmMessageType {\n FunctionCall = \"function_call\",\n FunctionCallOutput = \"function_call_output\",\n InputFile = \"input_file\",\n InputImage = \"input_image\",\n InputText = \"input_text\",\n ItemReference = \"item_reference\",\n Message = \"message\",\n OutputText = \"output_text\",\n Refusal = \"refusal\",\n}\n\nexport enum LlmResponseStatus {\n Completed = \"completed\",\n Incomplete = \"incomplete\",\n InProgress = \"in_progress\",\n}\n\n// Errors\n\ninterface LlmError {\n detail?: string;\n status: number | string;\n title: string;\n}\n\n// Input\n\ninterface LlmInputContentFile {\n type: LlmMessageType.InputFile;\n file_data: File;\n file_id?: string;\n filename?: string;\n}\n\ninterface LlmInputContentImage {\n type: LlmMessageType.InputImage;\n detail: File;\n file_id?: string;\n image_url?: string;\n}\n\ninterface LlmInputContentText {\n type: LlmMessageType.InputText;\n text: string;\n}\n\ntype LlmInputContent =\n | LlmInputContentFile\n | LlmInputContentImage\n | LlmInputContentText;\n\n/**\n * Represents the \"Input message object\" in the \"input item list\"\n * from [OpenAI Responses API](https://platform.openai.com/docs/api-reference/responses/create)\n */\nexport interface LlmInputMessage {\n content: string | Array<LlmInputContent>;\n role: LlmMessageRole;\n type: LlmMessageType.Message;\n}\n\n// Output\nexport interface LlmOutputContentText {\n annotations?: AnyValue[];\n text: string;\n type: LlmMessageType.OutputText;\n}\n\ninterface LlmOutputRefusal {\n refusal: string;\n type: LlmMessageType.Refusal;\n}\n\ntype LlmOutputContent = LlmOutputContentText | LlmOutputRefusal;\n\n/**\n * Represents the \"Output message object\" in the \"input item list\"\n * from [OpenAI Responses API](https://platform.openai.com/docs/api-reference/responses/create)\n */\nexport interface LlmOutputMessage {\n content: string | Array<LlmOutputContent>;\n id?: string;\n role: LlmMessageRole.Assistant;\n status?: LlmResponseStatus;\n type?: LlmMessageType.Message;\n}\n\ntype LlmOutputItem = LlmToolCall | LlmToolResult | LlmOutputMessage;\n\ntype LlmOutput = LlmOutputItem[];\n\n// Tools\n\nexport interface LlmToolCall {\n arguments: string;\n call_id: string;\n id: string;\n name: string;\n type: LlmMessageType.FunctionCall;\n status: LlmResponseStatus;\n}\nexport interface LlmToolResult {\n call_id: string;\n output: string;\n status?: LlmResponseStatus;\n type: LlmMessageType.FunctionCallOutput;\n}\n\ninterface LlmItemReference {\n type: LlmMessageType.ItemReference;\n id: string;\n}\n\n// Options\n\nexport type LlmHistoryItem =\n | LlmInputMessage\n | LlmItemReference\n | LlmOutputItem\n | LlmToolResult;\n\nexport type LlmHistory = LlmHistoryItem[];\n\nexport interface LlmMessageOptions {\n data?: NaturalMap;\n model?: string;\n placeholders?: {\n message?: boolean;\n system?: boolean;\n };\n response?: NaturalSchema | z.ZodType;\n system?: string;\n}\n\nexport interface LlmOperateOptions {\n data?: NaturalMap;\n explain?: boolean;\n format?: JsonObject | NaturalSchema | z.ZodType;\n history?: LlmHistory;\n hooks?: {\n afterEachModelResponse?: ({\n input,\n options,\n providerRequest,\n providerResponse,\n content,\n usage,\n }: {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: any;\n providerResponse: any;\n content: string | JsonObject;\n usage: LlmUsage;\n }) => unknown | Promise<unknown>;\n afterEachTool?: ({\n result,\n toolName,\n args,\n }: {\n result: unknown;\n toolName: string;\n args: string;\n }) => unknown | Promise<unknown>;\n beforeEachModelRequest?: ({\n input,\n options,\n providerRequest,\n }: {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: any;\n }) => unknown | Promise<unknown>;\n beforeEachTool?: ({\n toolName,\n args,\n }: {\n toolName: string;\n args: string;\n }) => unknown | Promise<unknown>;\n onRetryableModelError?: ({\n input,\n options,\n providerRequest,\n error,\n }: {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: any;\n error: any;\n }) => unknown | Promise<unknown>;\n onToolError?: ({\n error,\n toolName,\n args,\n }: {\n error: Error;\n toolName: string;\n args: string;\n }) => unknown | Promise<unknown>;\n onUnrecoverableModelError?: ({\n input,\n options,\n providerRequest,\n error,\n }: {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: any;\n error: any;\n }) => unknown | Promise<unknown>;\n };\n instructions?: string;\n model?: string;\n placeholders?: {\n input?: boolean;\n instructions?: boolean;\n system?: boolean;\n };\n providerOptions?: JsonObject;\n system?: string;\n tools?: LlmTool[] | Toolkit;\n turns?: boolean | number;\n user?: string;\n}\n\nexport interface LlmOptions {\n apiKey?: string;\n model?: string;\n}\n\n// Responses\n\nexport interface LlmUsageItem {\n input: number;\n output: number;\n reasoning: number;\n total: number;\n provider?: string;\n model?: string;\n}\n\nexport type LlmUsage = LlmUsageItem[];\n\nexport interface LlmOperateResponse {\n content?: string | JsonObject;\n error?: LlmError;\n history: LlmHistory;\n model?: string;\n output: LlmOutput;\n provider?: string;\n responses: JsonReturn[];\n status: LlmResponseStatus;\n usage: LlmUsage;\n}\n\n// Main\n\nexport interface LlmProvider {\n operate?(\n input: string | LlmHistory | LlmInputMessage,\n options?: LlmOperateOptions,\n ): Promise<LlmOperateResponse>;\n send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject>;\n}\n","import { placeholders } from \"@jaypie/core\";\nimport {\n LlmInputMessage,\n LlmMessageRole,\n LlmMessageType,\n} from \"../types/LlmProvider.interface.js\";\nimport { NaturalMap } from \"@jaypie/types\";\n\n/**\n * Options for formatOperateMessage function\n */\nexport interface FormatOperateMessageOptions {\n /**\n * Data to use for placeholder substitution\n */\n data?: NaturalMap;\n\n /**\n * Role to use for the message\n */\n role?: LlmMessageRole;\n}\n\n/**\n * Converts a string to a standardized LlmInputMessage\n * @param input - String to format\n * @param options - Optional configuration\n * @param options.data - Data to use for placeholder substitution\n * @param options.role - Role to use for the message (defaults to User)\n * @returns LlmInputMessage\n */\nexport function formatOperateMessage(\n input: string,\n options?: FormatOperateMessageOptions,\n): LlmInputMessage {\n const content = options?.data ? placeholders(input, options.data) : input;\n\n return {\n content,\n role: options?.role || LlmMessageRole.User,\n type: LlmMessageType.Message,\n };\n}\n","import {\n LlmHistory,\n LlmInputMessage,\n LlmMessageRole,\n} from \"../types/LlmProvider.interface.js\";\nimport { NaturalMap } from \"@jaypie/types\";\nimport { formatOperateMessage } from \"./formatOperateMessage.js\";\n\n/**\n * Options for formatOperateInput function\n */\nexport interface FormatOperateInputOptions {\n /**\n * Data to use for placeholder substitution\n */\n data?: NaturalMap;\n\n /**\n * Role to use when converting a string to LlmInputMessage\n */\n role?: LlmMessageRole;\n}\n\n/**\n * Converts various input types to a standardized LlmHistory format\n * @param input - String, LlmInputMessage, or LlmHistory to format\n * @param options - Optional configuration\n * @param options.data - Data to use for placeholder substitution\n * @param options.role - Role to use when converting a string to LlmInputMessage (defaults to User)\n * @returns Standardized LlmHistory array\n */\nexport function formatOperateInput(\n input: string | LlmInputMessage | LlmHistory,\n options?: FormatOperateInputOptions,\n): LlmHistory {\n // If input is already LlmHistory, return it\n if (Array.isArray(input)) {\n return input;\n }\n\n // If input is a string, convert it to LlmInputMessage\n if (typeof input === \"string\") {\n return [formatOperateMessage(input, options)];\n }\n\n // If input is LlmInputMessage, apply placeholders if data is provided\n if (options?.data && typeof input.content === \"string\") {\n return [\n formatOperateMessage(input.content, {\n data: options.data,\n role: input.role || options?.role,\n }),\n ];\n }\n\n // Otherwise, just wrap the input in an array\n return [input];\n}\n","import { JAYPIE, log as defaultLog } from \"@jaypie/core\";\n\nexport const getLogger = () => defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\nexport const log = getLogger();\n","import { LlmOperateOptions } from \"../types/LlmProvider.interface.js\";\n\n// Turn policy constants\nexport const MAX_TURNS_ABSOLUTE_LIMIT = 72;\nexport const MAX_TURNS_DEFAULT_LIMIT = 12;\n\n/**\n * Determines the maximum number of turns based on the provided options\n *\n * @param options - The LLM operate options\n * @returns The maximum number of turns\n */\nexport function maxTurnsFromOptions(options: LlmOperateOptions): number {\n // Default to single turn (1) when turns are disabled\n\n // Handle the turns parameter\n if (options.turns === undefined) {\n // Default to default limit when undefined\n return MAX_TURNS_DEFAULT_LIMIT;\n } else if (options.turns === true) {\n // Explicitly set to true\n return MAX_TURNS_DEFAULT_LIMIT;\n } else if (typeof options.turns === \"number\") {\n if (options.turns > 0) {\n // Positive number - use that limit (capped at absolute limit)\n return Math.min(options.turns, MAX_TURNS_ABSOLUTE_LIMIT);\n } else if (options.turns < 0) {\n // Negative number - use default limit\n return MAX_TURNS_DEFAULT_LIMIT;\n }\n // If turns is 0, return 1 (disabled)\n return 1;\n }\n // All other values (false, null, etc.) will return 1 (disabled)\n return 1;\n}\n","import { z } from \"zod/v4\";\nimport { NaturalSchema } from \"@jaypie/types\";\n\nexport function naturalZodSchema(definition: NaturalSchema): z.ZodTypeAny {\n if (Array.isArray(definition)) {\n if (definition.length === 0) {\n // Handle empty array - accept any[]\n return z.array(z.any());\n } else if (definition.length === 1) {\n // Handle array types\n const itemType = definition[0];\n switch (itemType) {\n case String:\n return z.array(z.string());\n case Number:\n return z.array(z.number());\n case Boolean:\n return z.array(z.boolean());\n default:\n if (typeof itemType === \"object\") {\n // Handle array of objects\n return z.array(naturalZodSchema(itemType));\n }\n // Handle enum arrays\n return z.enum(definition as [string, ...string[]]);\n }\n } else {\n // Handle enum arrays\n return z.enum(definition as [string, ...string[]]);\n }\n } else if (definition && typeof definition === \"object\") {\n if (Object.keys(definition).length === 0) {\n // Handle empty object - accept any key-value pairs\n return z.record(z.string(), z.any());\n } else {\n // Handle object with properties\n const schemaShape: Record<string, z.ZodTypeAny> = {};\n for (const [key, value] of Object.entries(definition)) {\n schemaShape[key] = naturalZodSchema(value);\n }\n return z.object(schemaShape);\n }\n } else {\n switch (definition) {\n case String:\n return z.string();\n case Number:\n return z.number();\n case Boolean:\n return z.boolean();\n case Object:\n return z.record(z.string(), z.any());\n case Array:\n return z.array(z.any());\n default:\n throw new Error(`Unsupported type: ${definition}`);\n }\n }\n}\n","import RandomLib from \"random\";\nimport { ConfigurationError } from \"@jaypie/errors\";\n\n//\n// Types\n//\n\ninterface RandomOptions {\n min?: number;\n max?: number;\n mean?: number;\n stddev?: number;\n integer?: boolean;\n start?: number;\n seed?: string;\n precision?: number;\n currency?: boolean;\n}\n\ntype RandomFunction = {\n (options?: RandomOptions): number;\n};\n\n//\n// Constants\n//\n\nexport const DEFAULT_MIN = 0;\nexport const DEFAULT_MAX = 1;\n\n//\n// Helper Functions\n//\n\n/**\n * Clamps a number between optional minimum and maximum values\n * @param num - The number to clamp\n * @param min - Optional minimum value\n * @param max - Optional maximum value\n * @returns The clamped number\n */\nconst clamp = (num: number, min?: number, max?: number): number => {\n let result = num;\n if (typeof min === \"number\") result = Math.max(result, min);\n if (typeof max === \"number\") result = Math.min(result, max);\n return result;\n};\n\n/**\n * Validates that min is not greater than max\n * @param min - Optional minimum value\n * @param max - Optional maximum value\n * @throws {ConfigurationError} If min is greater than max\n */\nconst validateBounds = (\n min: number | undefined,\n max: number | undefined,\n): void => {\n if (typeof min === \"number\" && typeof max === \"number\" && min > max) {\n throw new ConfigurationError(\n `Invalid bounds: min (${min}) cannot be greater than max (${max})`,\n );\n }\n};\n\n//\n// Main\n//\n\n/**\n * Creates a random number generator with optional seeding\n *\n * @param defaultSeed - Seed string for the default RNG\n * @returns A function that generates random numbers based on provided options\n *\n * @example\n * const rng = random(\"default-seed\");\n *\n * // Generate a random float between 0 and 1\n * const basic = rng();\n *\n * // Generate an integer between 1 and 10\n * const integer = rng({ min: 1, max: 10, integer: true });\n *\n * // Generate from normal distribution\n * const normal = rng({ mean: 50, stddev: 10 });\n *\n * // Use consistent seeding\n * const seeded = rng({ seed: \"my-seed\" });\n */\nexport function random(defaultSeed?: string): RandomFunction {\n // Initialize default seeded RNG\n const defaultRng = RandomLib.clone(defaultSeed);\n\n // Store per-seed RNGs\n const seedMap = new Map<string, ReturnType<typeof RandomLib.clone>>();\n\n const rngFn = ({\n min,\n max: providedMax,\n mean,\n stddev,\n integer = false,\n start = 0,\n seed,\n precision,\n currency = false,\n }: RandomOptions = {}): number => {\n // Select the appropriate RNG based on seed\n const rng = seed\n ? seedMap.get(seed) ||\n (() => {\n const newRng = RandomLib.clone(seed);\n seedMap.set(seed, newRng);\n return newRng;\n })()\n : defaultRng;\n\n // If only min is set, set max to min*2, but keep track of whether max was provided\n let max = providedMax;\n if (typeof min === \"number\" && typeof max !== \"number\") {\n max = min * 2;\n }\n\n validateBounds(min, max);\n\n // Determine effective precision based on parameters\n const getEffectivePrecision = (): number | undefined => {\n if (integer) return 0;\n\n const precisions: number[] = [];\n if (typeof precision === \"number\" && precision >= 0) {\n precisions.push(precision);\n }\n if (currency) {\n precisions.push(2);\n }\n\n // Return the lowest precision if any are set, undefined otherwise\n return precisions.length > 0 ? Math.min(...precisions) : undefined;\n };\n\n // Helper function to apply precision\n const applyPrecision = (value: number): number => {\n const effectivePrecision = getEffectivePrecision();\n if (typeof effectivePrecision === \"number\") {\n const factor = Math.pow(10, effectivePrecision);\n return Math.round(value * factor) / factor;\n }\n return value;\n };\n\n // Use normal distribution if both mean and stddev are provided\n if (typeof mean === \"number\" && typeof stddev === \"number\") {\n const normalDist = rng.normal(mean, stddev);\n const value = normalDist();\n\n // Only clamp if min/max are defined\n const clampedValue = clamp(value, min, providedMax);\n\n // Switch to uniform distribution only if both bounds were explicitly provided and exceeded\n if (\n typeof min === \"number\" &&\n typeof providedMax === \"number\" &&\n clampedValue !== value\n ) {\n const baseValue = integer ? rng.int(min, max) : rng.float(min, max);\n return applyPrecision(start + baseValue);\n }\n\n return applyPrecision(\n start + (integer ? Math.round(clampedValue) : clampedValue),\n );\n }\n\n // For uniform distribution, use defaults if min/max are undefined\n const uniformMin = typeof min === \"number\" ? min : DEFAULT_MIN;\n const uniformMax = typeof max === \"number\" ? max : DEFAULT_MAX;\n\n const baseValue = integer\n ? rng.int(uniformMin, uniformMax)\n : rng.float(uniformMin, uniformMax);\n return applyPrecision(start + baseValue);\n };\n\n return rngFn;\n}\n","/**\n * Options for tryParseNumber function\n */\nexport interface TryParseNumberOptions {\n /**\n * Default value to return if parsing fails or results in NaN\n */\n defaultValue?: number;\n /**\n * Function to call with warning message if parsing fails or results in NaN\n */\n warnFunction?: (message: string) => void;\n}\n\n/**\n * Helper function to safely call a function that might throw\n * @param fn Function to call safely\n */\nfunction callSafely(fn: () => void): void {\n try {\n fn();\n } catch {\n // Silently catch any errors from the function\n }\n}\n\n/**\n * Attempts to parse a value as a number. Returns the original input if parsing fails or results in NaN.\n * @param input - The value to attempt to parse as a number\n * @param options - Optional configuration\n * @param options.defaultValue - Default value to return if parsing fails or results in NaN\n * @param options.warnFunction - Function to call with warning message if parsing fails or results in NaN\n * @returns The parsed number, defaultValue (if specified and parsing fails), or the original input\n */\nexport function tryParseNumber(\n input: unknown,\n options?: TryParseNumberOptions,\n): number | unknown {\n if (input === null || input === undefined) {\n return input;\n }\n\n try {\n const parsed = Number(input);\n\n if (Number.isNaN(parsed)) {\n if (options?.warnFunction) {\n const warningMessage = `Failed to parse \"${String(input)}\" as number`;\n callSafely(() => options.warnFunction!(warningMessage));\n }\n\n return typeof options?.defaultValue === \"number\"\n ? options.defaultValue\n : input;\n }\n\n return parsed;\n } catch (error: unknown) {\n if (options?.warnFunction) {\n let errorMessage = \"\";\n if (error instanceof Error) {\n errorMessage = error.message;\n }\n const warningMessage = `Error parsing \"${String(input)}\" as number${errorMessage ? \"; \" + errorMessage : \"\"}`;\n callSafely(() => options.warnFunction!(warningMessage));\n }\n\n return typeof options?.defaultValue === \"number\"\n ? options.defaultValue\n : input;\n }\n}\n","import { resolveValue, sleep, placeholders } from \"@jaypie/core\";\nimport { BadGatewayError, TooManyRequestsError } from \"@jaypie/errors\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport {\n APIConnectionError,\n APIConnectionTimeoutError,\n APIUserAbortError,\n AuthenticationError,\n BadRequestError,\n ConflictError,\n InternalServerError,\n NotFoundError,\n OpenAI,\n PermissionDeniedError,\n RateLimitError,\n UnprocessableEntityError,\n} from \"openai\";\nimport { zodResponseFormat } from \"openai/helpers/zod\";\nimport { z } from \"zod/v4\";\nimport { PROVIDER } from \"../../constants.js\";\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport { OpenAIRawResponse } from \"./types.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageType,\n LlmMessageRole,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmResponseStatus,\n LlmToolResult,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmTool } from \"../../types/LlmTool.interface.js\";\nimport {\n formatOperateInput,\n log,\n maxTurnsFromOptions,\n naturalZodSchema,\n} from \"../../util\";\n\n//\n//\n// Types\n//\n\n/**\n * OpenAI request options type that includes model and input properties\n */\nexport type OpenAiRequestOptions = Omit<LlmOperateOptions, \"tools\"> & {\n model: string;\n input: LlmInputMessage | LlmHistory;\n text?: unknown;\n tools?: Omit<LlmTool, \"call\">[];\n};\n\n//\n//\n// Constants\n//\n\nexport const MAX_RETRIES_ABSOLUTE_LIMIT = 72;\nexport const MAX_RETRIES_DEFAULT_LIMIT = 6;\n\n// Retry policy constants\nconst INITIAL_RETRY_DELAY_MS = 1000; // 1 second\nconst MAX_RETRY_DELAY_MS = 32000; // 32 seconds\nconst RETRY_BACKOFF_FACTOR = 2; // Exponential backoff multiplier\n\nconst RETRYABLE_ERRORS = [\n APIConnectionError,\n APIConnectionTimeoutError,\n InternalServerError,\n];\n\nconst NOT_RETRYABLE_ERRORS = [\n APIUserAbortError,\n AuthenticationError,\n BadRequestError,\n ConflictError,\n NotFoundError,\n PermissionDeniedError,\n RateLimitError,\n UnprocessableEntityError,\n];\n\nconst ERROR = {\n BAD_FUNCTION_CALL: \"Bad Function Call\",\n};\n\n//\n//\n// Helpers\n//\n\n/**\n * Creates content string for function calls\n */\nfunction createFunctionCallContent(output: any): string {\n return `${LlmMessageType.FunctionCall}:${output.name}${output.arguments}#${output.call_id}`;\n}\n\n/**\n * Extracts content from OpenAI response output array\n */\nfunction extractContentFromResponse(\n currentResponse: OpenAIRawResponse,\n options?: LlmOperateOptions,\n): any {\n if (!currentResponse.output || !Array.isArray(currentResponse.output)) {\n return \"\";\n }\n\n for (const output of currentResponse.output) {\n if (output.type === LlmMessageType.Message) {\n if (\n output.content?.[0] &&\n output.content[0].type === LlmMessageType.OutputText\n ) {\n const rawContent = output.content[0].text;\n\n // If format is provided, try to parse the content as JSON\n if (options?.format && typeof rawContent === \"string\") {\n try {\n const parsedContent = JSON.parse(rawContent);\n return parsedContent;\n } catch (error) {\n // If parsing fails, keep the original string content\n log.debug(\"Failed to parse formatted response as JSON\");\n log.var({ error });\n return rawContent;\n }\n }\n\n return rawContent;\n }\n }\n if (output.type === LlmMessageType.FunctionCall) {\n return createFunctionCallContent(output);\n }\n // Skip reasoning items when extracting content\n if (output.type === \"reasoning\") {\n continue;\n }\n }\n\n return \"\";\n}\n\n/**\n * Creates the request options for the OpenAI API call\n *\n * @param input - The formatted input messages\n * @param options - The LLM operation options\n * @returns The request options for the OpenAI API\n */\nexport function createRequestOptions(\n input: LlmInputMessage | LlmHistory,\n options: LlmOperateOptions = {},\n): OpenAiRequestOptions {\n const requestOptions: OpenAiRequestOptions = {\n model: options?.model || PROVIDER.OPENAI.MODEL.DEFAULT,\n input,\n };\n\n // Add user if provided\n if (options?.user) {\n requestOptions.user = options.user;\n }\n\n // Add any provider-specific options\n if (options?.providerOptions) {\n Object.assign(requestOptions, options.providerOptions);\n }\n\n // Handle instructions or system message\n if (options?.instructions) {\n // Apply placeholders to instructions if data is provided and placeholders.instructions is undefined or true\n requestOptions.instructions =\n options.data &&\n (options.placeholders?.instructions === undefined ||\n options.placeholders?.instructions)\n ? placeholders(options.instructions, options.data)\n : options.instructions;\n }\n\n // Handle developer message as system message\n // @ts-expect-error Testing invalid option\n if (options?.developer) {\n log.warn(\n \"Developer message provided but not supported. Using as system message.\",\n );\n // @ts-expect-error Testing invalid option\n requestOptions.system = options.developer;\n }\n\n // Handle structured output format\n if (options?.format) {\n // Check if format is a JsonObject with type \"json_schema\"\n if (\n typeof options.format === \"object\" &&\n options.format !== null &&\n !Array.isArray(options.format) &&\n (options.format as JsonObject).type === \"json_schema\"\n ) {\n // Direct pass-through for JsonObject with type \"json_schema\"\n requestOptions.text = {\n format: options.format,\n };\n } else {\n // Convert NaturalSchema to Zod schema if needed\n const zodSchema =\n options.format instanceof z.ZodType\n ? options.format\n : naturalZodSchema(options.format as NaturalSchema);\n\n const responseFormat = zodResponseFormat(zodSchema, \"response\");\n\n const jsonSchema = z.toJSONSchema(zodSchema);\n\n // Temporary hack because of OpenAI requires additional_properties to be false on all objects\n const checks = [jsonSchema];\n while (checks.length > 0) {\n const current = checks[0];\n if (current.type == \"object\") {\n current.additionalProperties = false;\n }\n Object.keys(current).forEach((key) => {\n if (typeof current[key] == \"object\") {\n checks.push(current[key]);\n }\n });\n checks.shift();\n }\n\n // Set up structured output format in the format expected by the test\n requestOptions.text = {\n format: {\n name: responseFormat.json_schema.name,\n schema: jsonSchema, // Replace this with responseFormat.json_schema.schema once OpenAI supports Zod v4\n strict: responseFormat.json_schema.strict,\n type: responseFormat.type,\n },\n };\n }\n }\n\n // Handle tools - either as LlmTool[] or Toolkit\n if (options.tools) {\n let toolkit: Toolkit | undefined;\n\n if (options.tools instanceof Toolkit) {\n // If toolkit is already provided, use it directly\n toolkit = options.tools;\n } else if (Array.isArray(options.tools) && options.tools.length > 0) {\n // If array of tools provided, create toolkit from them\n const explain = options?.explain ?? false;\n toolkit = new Toolkit(options.tools, { explain });\n }\n\n if (toolkit) {\n requestOptions.tools = toolkit.tools;\n }\n }\n\n return requestOptions;\n}\n\n//\n//\n// Main\n//\n\nexport async function operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n context: { client: OpenAI; maxRetries?: number } = {\n client: new OpenAI(),\n },\n): Promise<LlmOperateResponse> {\n //\n //\n // Setup\n //\n\n const openai = context.client;\n\n if (!context.maxRetries) {\n context.maxRetries = MAX_RETRIES_DEFAULT_LIMIT;\n }\n\n let retryCount = 0;\n let retryDelay = INITIAL_RETRY_DELAY_MS;\n const maxRetries = Math.min(context.maxRetries, MAX_RETRIES_ABSOLUTE_LIMIT);\n\n const returnResponse: LlmOperateResponse = {\n history: [],\n model: options?.model || PROVIDER.OPENAI.MODEL.DEFAULT,\n output: [],\n provider: PROVIDER.OPENAI.NAME,\n responses: [],\n status: LlmResponseStatus.InProgress,\n usage: [], // Initialize as empty array, will add entry for each response\n };\n\n // Convert string input to array format with placeholders if needed\n let currentInput: LlmHistory = formatOperateInput(input);\n if (\n options?.data &&\n (options.placeholders?.input === undefined || options.placeholders?.input)\n ) {\n currentInput = formatOperateInput(input, {\n data: options?.data,\n });\n }\n\n // If history is provided, merge it with currentInput\n if (options.history) {\n currentInput = [...options.history, ...currentInput];\n }\n\n // If system message is provided, add it to the beginning of the input\n if (options?.system) {\n const systemMessage =\n options.data && options.placeholders?.system !== false\n ? placeholders(options.system, options.data)\n : options.system;\n\n // Create system message\n const systemInputMessage: LlmInputMessage = {\n content: systemMessage,\n role: LlmMessageRole.System,\n type: LlmMessageType.Message,\n };\n\n // Check if history starts with an identical system message\n const firstMessage = currentInput[0];\n const isIdenticalSystemMessage =\n firstMessage?.type === LlmMessageType.Message &&\n firstMessage?.role === LlmMessageRole.System &&\n firstMessage?.content === systemMessage;\n\n // Only prepend if not identical\n if (!isIdenticalSystemMessage) {\n // Remove any existing system message from the beginning\n if (\n currentInput[0]?.type === LlmMessageType.Message &&\n currentInput[0]?.role === LlmMessageRole.System\n ) {\n currentInput = currentInput.slice(1);\n }\n currentInput = [systemInputMessage, ...currentInput];\n }\n }\n\n // Initialize history with currentInput\n returnResponse.history = [...currentInput];\n\n // Determine max turns from options\n const maxTurns = maxTurnsFromOptions(options);\n const enableMultipleTurns = maxTurns > 1;\n let currentTurn = 0;\n\n // Build request options outside the retry loop\n const requestOptions = createRequestOptions(currentInput, options);\n\n // OpenAI Multi-turn Loop\n while (currentTurn < maxTurns) {\n currentTurn++;\n retryCount = 0;\n retryDelay = INITIAL_RETRY_DELAY_MS;\n\n // OpenAI Retry Loop\n while (true) {\n try {\n // Log appropriate message based on turn number\n if (currentTurn > 1) {\n log.trace(`[operate] Calling OpenAI Responses API - ${currentTurn}`);\n } else {\n log.trace(\"[operate] Calling OpenAI Responses API\");\n }\n\n // Execute beforeEachModelRequest hook if defined\n if (options.hooks?.beforeEachModelRequest) {\n await resolveValue(\n options.hooks.beforeEachModelRequest({\n input,\n options,\n providerRequest: requestOptions,\n }),\n );\n }\n\n // Use type assertion to handle the OpenAI SDK response type\n const currentResponse = (await openai.responses.create(\n // @ts-expect-error error claims missing non-required id, status\n requestOptions,\n )) as unknown as OpenAIRawResponse;\n\n if (retryCount > 0) {\n log.debug(`OpenAI API call succeeded after ${retryCount} retries`);\n }\n // Add the response to the responses array\n returnResponse.responses.push(currentResponse);\n\n // Add a new usage entry for each response instead of accumulating\n if (currentResponse.usage) {\n // Create new usage item for this response\n returnResponse.usage.push({\n input: currentResponse.usage.input_tokens || 0,\n output: currentResponse.usage.output_tokens || 0,\n total: currentResponse.usage.total_tokens || 0,\n reasoning:\n currentResponse.usage.output_tokens_details?.reasoning_tokens ||\n 0,\n provider: PROVIDER.OPENAI.NAME,\n model: options?.model || PROVIDER.OPENAI.MODEL.DEFAULT,\n });\n }\n\n // Execute afterEachModelResponse hook immediately after usage processing\n if (options.hooks?.afterEachModelResponse) {\n const extractedContent = extractContentFromResponse(\n currentResponse,\n options,\n );\n await resolveValue(\n options.hooks.afterEachModelResponse({\n input,\n options,\n providerRequest: requestOptions,\n providerResponse: currentResponse,\n content: extractedContent || \"\",\n usage: returnResponse.usage,\n }),\n );\n }\n\n // Check if we need to process function calls for multi-turn conversations\n let hasFunctionCall = false;\n const pendingReasoningItems = []; // Track reasoning items that need to be paired\n\n try {\n if (currentResponse.output && Array.isArray(currentResponse.output)) {\n // New OpenAI API format with output array\n for (const output of currentResponse.output) {\n returnResponse.output.push(output);\n returnResponse.history.push(output);\n // Handle reasoning items (GPT-5)\n if (output.type === \"reasoning\") {\n // Store reasoning items to be added with their paired function calls\n pendingReasoningItems.push(output);\n continue;\n }\n if (output.type === LlmMessageType.FunctionCall) {\n hasFunctionCall = true;\n\n let toolkit: Toolkit | undefined;\n\n // Initialize toolkit for multi-turn function calling\n if (options.tools) {\n if (options.tools instanceof Toolkit) {\n // If toolkit is already provided, use it directly\n toolkit = options.tools;\n } else if (\n Array.isArray(options.tools) &&\n options.tools.length > 0\n ) {\n // If array of tools provided, create toolkit from them\n const explain = options?.explain ?? false;\n toolkit = new Toolkit(options.tools, { explain });\n }\n }\n\n if (toolkit && enableMultipleTurns) {\n try {\n // Call the tool and ensure the result is resolved if it's a Promise\n log.trace(`[operate] Calling tool - ${output.name}`);\n // Content will be set by extractContentFromResponse call later\n\n // Execute beforeEachTool hook if defined\n if (options.hooks?.beforeEachTool) {\n await resolveValue(\n options.hooks.beforeEachTool({\n toolName: output.name,\n args: output.arguments,\n }),\n );\n }\n\n let result;\n try {\n result = await toolkit.call({\n name: output.name,\n arguments: output.arguments,\n });\n\n // Execute afterEachTool hook if defined\n if (options.hooks?.afterEachTool) {\n await resolveValue(\n options.hooks.afterEachTool({\n result,\n toolName: output.name,\n args: output.arguments,\n }),\n );\n }\n } catch (error) {\n // Execute onToolError hook if defined\n if (options.hooks?.onToolError) {\n await resolveValue(\n options.hooks.onToolError({\n error: error as Error,\n toolName: output.name,\n args: output.arguments,\n }),\n );\n }\n throw error;\n }\n\n // Add model's function call and result\n if (Array.isArray(currentInput)) {\n // Add any pending reasoning items before the function call\n for (const reasoningItem of pendingReasoningItems) {\n currentInput.push(reasoningItem);\n }\n // Clear the pending reasoning items after adding them\n pendingReasoningItems.length = 0;\n\n // Add the function call\n currentInput.push(output);\n // Add function call result\n const functionCallOutput: LlmToolResult = {\n call_id: output.call_id,\n output: JSON.stringify(result),\n type: LlmMessageType.FunctionCallOutput,\n };\n currentInput.push(functionCallOutput);\n returnResponse.output.push(functionCallOutput);\n returnResponse.history.push(functionCallOutput);\n // Content will be set by extractContentFromResponse call later\n }\n } catch (error) {\n // TODO: but I do need to tell the model that something went wrong, right?\n const jaypieError = new BadGatewayError();\n const detail = [\n `Error executing function call ${output.name}.`,\n (error as Error).message,\n ].join(\"\\n\");\n returnResponse.error = {\n detail,\n status: jaypieError.status,\n title: ERROR.BAD_FUNCTION_CALL,\n };\n log.error(`Error executing function call ${output.name}`);\n log.var({ error });\n // We don't add error messages to allResponses here as we want to keep the original response objects\n }\n } else if (!toolkit) {\n log.warn(\n \"Model requested function call but no toolkit available\",\n );\n }\n }\n // Content processing is now handled by extractContentFromResponse function\n }\n }\n } catch (error) {\n // If there's an error processing the response, log it but don't fail\n // This helps with test mocks that might not have the expected structure\n log.warn(\"Error processing response for function calls\");\n log.var({ error });\n }\n\n // Set content using the shared extraction function\n returnResponse.content = extractContentFromResponse(\n currentResponse,\n options,\n );\n\n // If there's no function call or we can't take another turn, exit the loop\n if (!hasFunctionCall || !enableMultipleTurns) {\n returnResponse.status = LlmResponseStatus.Completed;\n return returnResponse;\n }\n\n // If we've reached the maximum number of turns, exit the loop\n if (currentTurn >= maxTurns) {\n const error = new TooManyRequestsError();\n const detail = `Model requested function call but exceeded ${maxTurns} turns`;\n log.warn(detail);\n returnResponse.status = LlmResponseStatus.Incomplete;\n returnResponse.error = {\n detail,\n status: error.status,\n title: error.title,\n };\n return returnResponse;\n }\n\n // Continue to next turn\n break;\n } catch (error: unknown) {\n // Check if we've reached the maximum number of retries\n if (retryCount >= maxRetries) {\n log.error(`OpenAI API call failed after ${maxRetries} retries`);\n log.var({ error });\n\n // Execute onUnrecoverableModelError hook if defined\n if (options.hooks?.onUnrecoverableModelError) {\n await resolveValue(\n options.hooks.onUnrecoverableModelError({\n input,\n options,\n providerRequest: requestOptions,\n error,\n }),\n );\n }\n\n throw new BadGatewayError();\n }\n\n // Check if the error is not retryable\n let isNotRetryable = false;\n for (const notRetryableError of NOT_RETRYABLE_ERRORS) {\n if (error instanceof notRetryableError) {\n isNotRetryable = true;\n break;\n }\n }\n\n if (isNotRetryable) {\n log.error(\"OpenAI API call failed with non-retryable error\");\n log.var({ error });\n\n // Execute onUnrecoverableModelError hook if defined\n if (options.hooks?.onUnrecoverableModelError) {\n await resolveValue(\n options.hooks.onUnrecoverableModelError({\n input,\n options,\n providerRequest: requestOptions,\n error,\n }),\n );\n }\n\n throw new BadGatewayError();\n }\n\n // Warn if this error is not in our known retryable errors\n let isUnknownError = true;\n for (const retryableError of RETRYABLE_ERRORS) {\n if (error instanceof retryableError) {\n isUnknownError = false;\n break;\n }\n }\n if (isUnknownError) {\n log.warn(\"OpenAI API returned unknown error\");\n log.var({ error });\n }\n\n // Log the error and retry\n log.warn(`OpenAI API call failed. Retrying in ${retryDelay}ms...`);\n\n // Execute onRetryableModelError hook if defined\n if (options.hooks?.onRetryableModelError) {\n await resolveValue(\n options.hooks.onRetryableModelError({\n input,\n options,\n providerRequest: requestOptions,\n error,\n }),\n );\n }\n\n // Wait before retrying\n await sleep(retryDelay);\n\n // Increase retry count and delay for next attempt (exponential backoff)\n retryCount++;\n retryDelay = Math.min(\n retryDelay * RETRY_BACKOFF_FACTOR,\n MAX_RETRY_DELAY_MS,\n );\n }\n }\n }\n\n // * All possible paths should return a response; getting here is an error\n // The main loop is `currentTurn < maxTurns` and `currentTurn >= maxTurns` within the loop returns\n log.warn(\"This should never happen\");\n returnResponse.status = LlmResponseStatus.Incomplete;\n\n // Always return the full LlmOperateResponse object for consistency\n return returnResponse;\n}\n","import { getEnvSecret } from \"@jaypie/aws\";\nimport {\n ConfigurationError,\n log as defaultLog,\n placeholders as replacePlaceholders,\n JAYPIE,\n} from \"@jaypie/core\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { OpenAI } from \"openai\";\nimport { zodResponseFormat } from \"openai/helpers/zod\";\nimport { z } from \"zod/v4\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { naturalZodSchema } from \"../../util\";\n\n// Logger\nexport const getLogger = () => defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<OpenAI> {\n const logger = getLogger();\n const resolvedApiKey = apiKey || (await getEnvSecret(\"OPENAI_API_KEY\"));\n\n if (!resolvedApiKey) {\n throw new ConfigurationError(\n \"The application could not resolve the requested keys\",\n );\n }\n\n const client = new OpenAI({ apiKey: resolvedApiKey });\n logger.trace(\"Initialized OpenAI client\");\n return client;\n}\n\n// Message formatting\nexport interface ChatMessage {\n role: \"user\" | \"developer\";\n content: string;\n}\n\nexport function formatSystemMessage(\n systemPrompt: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.system === false\n ? systemPrompt\n : replacePlaceholders(systemPrompt, data);\n\n return {\n role: \"developer\" as const,\n content,\n };\n}\n\nexport function formatUserMessage(\n message: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.message === false\n ? message\n : replacePlaceholders(message, data);\n\n return {\n role: \"user\" as const,\n content,\n };\n}\n\nexport function prepareMessages(\n message: string,\n { system, data, placeholders }: LlmMessageOptions = {},\n): ChatMessage[] {\n const logger = getLogger();\n const messages: ChatMessage[] = [];\n\n if (system) {\n const systemMessage = formatSystemMessage(system, { data, placeholders });\n messages.push(systemMessage);\n logger.trace(`System message: ${systemMessage.content?.length} characters`);\n }\n\n const userMessage = formatUserMessage(message, { data, placeholders });\n messages.push(userMessage);\n logger.trace(`User message: ${userMessage.content?.length} characters`);\n\n return messages;\n}\n\n// Completion requests\nexport async function createStructuredCompletion(\n client: OpenAI,\n {\n messages,\n responseSchema,\n model,\n }: {\n messages: ChatMessage[];\n responseSchema: z.ZodType | NaturalSchema;\n model: string;\n },\n): Promise<JsonObject> {\n const logger = getLogger();\n logger.trace(\"Using structured output\");\n\n const zodSchema =\n responseSchema instanceof z.ZodType\n ? responseSchema\n : naturalZodSchema(responseSchema as NaturalSchema);\n\n const responseFormat = zodResponseFormat(zodSchema, \"response\");\n\n const jsonSchema = z.toJSONSchema(zodSchema);\n\n // Temporary hack because OpenAI requires additional_properties to be false on all objects\n const checks = [jsonSchema];\n while (checks.length > 0) {\n const current = checks[0];\n if (current.type == \"object\") {\n current.additionalProperties = false;\n }\n Object.keys(current).forEach((key) => {\n if (typeof current[key] == \"object\") {\n checks.push(current[key]);\n }\n });\n checks.shift();\n }\n responseFormat.json_schema.schema = jsonSchema;\n\n const completion = await client.beta.chat.completions.parse({\n messages,\n model,\n response_format: responseFormat,\n });\n\n logger.var({ assistantReply: completion.choices[0].message.parsed });\n return completion.choices[0].message.parsed;\n}\n\nexport async function createTextCompletion(\n client: OpenAI,\n {\n messages,\n model,\n }: {\n messages: ChatMessage[];\n model: string;\n },\n): Promise<string> {\n const logger = getLogger();\n logger.trace(\"Using text output (unstructured)\");\n\n const completion = await client.chat.completions.create({\n messages,\n model,\n });\n\n logger.trace(\n `Assistant reply: ${completion.choices[0]?.message?.content?.length} characters`,\n );\n\n return completion.choices[0]?.message?.content || \"\";\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { OpenAI } from \"openai\";\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n LlmHistoryItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { operate } from \"./operate.js\";\nimport {\n createStructuredCompletion,\n createTextCompletion,\n getLogger,\n initializeClient,\n prepareMessages,\n} from \"./utils.js\";\n\nexport class OpenAiProvider implements LlmProvider {\n private model: string;\n private _client?: OpenAI;\n private apiKey?: string;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = PROVIDER.OPENAI.MODEL.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<OpenAI> {\n if (this._client) {\n return this._client;\n }\n\n this._client = await initializeClient({ apiKey: this.apiKey });\n return this._client;\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const client = await this.getClient();\n const messages = prepareMessages(message, options || {});\n const modelToUse = options?.model || this.model;\n\n if (options?.response) {\n return createStructuredCompletion(client, {\n messages,\n responseSchema: options.response,\n model: modelToUse,\n });\n }\n\n return createTextCompletion(client, {\n messages,\n model: modelToUse,\n });\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const client = await this.getClient();\n options.model = options?.model || this.model;\n\n // Create a merged history including both the tracked history and any explicitly provided history\n const mergedOptions = { ...options };\n if (this.conversationHistory.length > 0) {\n // If options.history exists, merge with instance history, otherwise use instance history\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Call operate with the updated options\n const response = await operate(input, mergedOptions, { client });\n\n // Update conversation history with the new history from the response\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n}\n","import { Anthropic } from \"@anthropic-ai/sdk\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageType,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmResponseStatus,\n LlmToolResult,\n LlmOutputMessage,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmTool } from \"../../types/LlmTool.interface.js\";\nimport {\n formatOperateInput,\n log,\n maxTurnsFromOptions,\n naturalZodSchema,\n} from \"../../util\";\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n JsonArray,\n JsonObject,\n JsonReturn,\n NaturalSchema,\n} from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\nimport ZSchema from \"z-schema\";\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport { placeholders } from \"@jaypie/core\";\nimport { TooManyRequestsError } from \"@jaypie/errors\";\n\n//\n//\n// Types\n//\n\n/**\n * OpenAI request options type that includes model and input properties\n */\nexport type AnthropicRequestOptions = Omit<LlmOperateOptions, \"tools\"> & {\n model: string;\n input: LlmInputMessage | LlmHistory;\n text?: unknown;\n tools?: Omit<LlmTool, \"call\">[];\n};\n\n// Handle placeholder logic\n// Convert string input to array format if needed\n// Apply placeholders to fields if data is provided and placeholders.* is undefined or true\nfunction handleInputAndPlaceholders(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions,\n) {\n let history: LlmHistory = formatOperateInput(input);\n let llmInstructions: string | undefined;\n let systemPrompt: string | undefined;\n\n if (\n options?.data &&\n (options.placeholders?.input === undefined || options.placeholders?.input)\n ) {\n history = formatOperateInput(input, {\n data: options?.data,\n });\n }\n\n if (options?.instructions) {\n llmInstructions =\n options.data && options.placeholders?.instructions !== false\n ? placeholders(options.instructions, options.data)\n : options.instructions;\n }\n\n if (options?.system) {\n systemPrompt =\n options.data && options.placeholders?.system !== false\n ? placeholders(options.system, options.data)\n : options.system;\n }\n\n return { history, systemPrompt, llmInstructions };\n}\n\nfunction updateUsage(\n usage: Anthropic.MessageCreateParamsNonStreaming.Usage,\n totalUsage: LlmUsageItem,\n) {\n totalUsage.input += usage.input_tokens;\n totalUsage.output += usage.output_tokens;\n totalUsage.reasoning += usage.prompt_tokens;\n totalUsage.total += usage.input_tokens + usage.output_tokens;\n}\n\nfunction handleMaxTurns(\n maxTurns: number,\n history: LlmHistory,\n inputMessages: Anthropic.MessageParam[],\n response: Anthropic.Message,\n totalUsage: LlmUsageItem,\n) {\n const error = new TooManyRequestsError();\n const detail = `Model requested function call but exceeded ${maxTurns} turns`;\n log.warn(detail);\n return {\n //model: model,\n //provider: PROVIDER.ANTHROPIC,\n error: {\n detail,\n status: error.status,\n title: error.title,\n },\n history,\n output: inputMessages.slice(-1) as LlmOutputMessage[],\n responses: response.content as unknown as JsonReturn[],\n status: LlmResponseStatus.Incomplete,\n usage: [totalUsage],\n };\n}\n\nfunction handleOutputSchema(\n format:\n | JsonObject\n | NaturalSchema\n | z.ZodType<any, z.ZodTypeDef, any>\n | undefined,\n) {\n let schema: JsonObject | undefined;\n if (format) {\n // Check if format is a JsonObject with type \"json_schema\"\n if (\n typeof format === \"object\" &&\n format !== null &&\n !Array.isArray(format) &&\n (format as JsonObject).type === \"json_schema\"\n ) {\n // Direct pass-through for JsonObject with type \"json_schema\"\n schema = structuredClone(format) as JsonObject;\n schema.type = \"object\"; // Validator does not recognise \"json_schema\" as a type\n } else {\n // Convert NaturalSchema to JSON schema through Zod\n const zodSchema =\n format instanceof z.ZodType\n ? format\n : naturalZodSchema(format as NaturalSchema);\n schema = z.toJSONSchema(zodSchema) as JsonObject;\n }\n\n if (schema.$schema) {\n delete schema.$schema; // Hack to fix issue with validator\n }\n\n return schema;\n }\n}\n\n// Register tools and process them to work with Anthropic\nfunction bundleTools(\n tools: LlmTool[] | Toolkit | undefined,\n explain: boolean | undefined,\n schema: JsonObject | undefined,\n) {\n let toolkit: Toolkit | undefined;\n let processedTools: Anthropic.Tool[] = [];\n\n if (tools instanceof Toolkit) {\n toolkit = tools;\n } else if (Array.isArray(tools)) {\n toolkit = new Toolkit(tools, { explain });\n }\n\n if (toolkit) {\n toolkit.tools.forEach((tool) => {\n processedTools.push({\n ...tool,\n input_schema: {\n ...tool.parameters,\n type: \"object\",\n },\n type: \"custom\",\n });\n delete (\n processedTools[processedTools.length - 1] as unknown as {\n parameters: unknown;\n }\n ).parameters;\n });\n }\n\n if (schema) {\n processedTools.push({\n name: \"structured_output\",\n description:\n \"Output a structured JSON object, \" +\n \"use this before your final response to give structured outputs to the user\",\n input_schema: schema as unknown as Anthropic.Messages.Tool.InputSchema,\n type: \"custom\",\n });\n }\n\n return { processedTools, toolkit };\n}\n\n// Handles individual tool calls. Returns true for break, false for continue.\nasync function callTool(\n inputMessages: Anthropic.MessageParam[],\n response: Anthropic.Message,\n hooks: LlmOperateOptions[\"hooks\"],\n toolkit: Toolkit | undefined,\n) {\n inputMessages.push({\n role: PROVIDER.ANTHROPIC.ROLE.ASSISTANT,\n content: response.content as Anthropic.TextBlockParam[],\n });\n\n // Get the tool use\n const toolUse = response.content[\n response.content.length - 1\n ] as Anthropic.ToolUseBlock;\n\n // If the tool use is structured output (magic tool), break\n if (toolUse.name === \"structured_output\") {\n return true;\n }\n\n if (hooks?.beforeEachTool) {\n await hooks.beforeEachTool({\n toolName: toolUse.name,\n args: JSON.stringify(toolUse.input),\n });\n }\n\n let result: unknown;\n try {\n result = await toolkit?.call({\n name: toolUse.name,\n arguments: JSON.stringify(toolUse.input),\n });\n } catch (error) {\n if (hooks?.onToolError) {\n await hooks.onToolError({\n error: error as Error,\n toolName: toolUse.name,\n args: JSON.stringify(toolUse.input),\n });\n }\n throw error;\n }\n\n if (hooks?.afterEachTool) {\n await hooks.afterEachTool({\n result,\n toolName: toolUse.name,\n args: JSON.stringify(toolUse.input),\n });\n }\n\n inputMessages.push({\n role: PROVIDER.ANTHROPIC.ROLE.USER,\n content: [\n {\n type: \"tool_result\",\n content: JSON.stringify(result),\n tool_use_id: toolUse.id,\n },\n ],\n });\n\n return false;\n}\n\n//\n//\n// Main\n//\n\nexport async function operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n context: { client: Anthropic; maxRetries?: number } = {\n client: new Anthropic(),\n },\n): Promise<LlmOperateResponse> {\n // Set model\n const model = options?.model || PROVIDER.ANTHROPIC.MODEL.DEFAULT;\n\n let schema = handleOutputSchema(options.format);\n\n let { processedTools, toolkit } = bundleTools(\n options.tools,\n options.explain,\n schema,\n );\n\n let { history, systemPrompt, llmInstructions } = handleInputAndPlaceholders(\n input,\n options,\n );\n\n // If history is provided, merge it with the input\n if (options.history) {\n history = [...options.history, ...history];\n }\n\n // Avoid Anthropic error by removing type property\n const inputMessages: Anthropic.MessageParam[] = structuredClone(history);\n inputMessages.forEach((message) => {\n delete message.type;\n });\n\n // Add instruction to the input message\n if (llmInstructions) {\n inputMessages[inputMessages.length - 1].content += \"\\n\\n\" + llmInstructions;\n }\n\n // Setup usage tracking\n let totalUsage: LlmUsageItem = {\n input: 0,\n output: 0,\n reasoning: 0,\n total: 0,\n };\n\n // Determine max turns from options\n const maxTurns = maxTurnsFromOptions(options);\n const enableMultipleTurns = maxTurns > 1;\n let currentTurn = 0;\n\n let response: Anthropic.Message;\n while (true) {\n // Loop for tool use\n response = await context.client.messages.create({\n model: model as Anthropic.MessageCreateParams[\"model\"],\n system: systemPrompt,\n messages: inputMessages,\n max_tokens: PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT,\n stream: false,\n tools: processedTools,\n tool_choice:\n processedTools.length > 0\n ? { type: schema ? \"any\" : \"auto\" }\n : undefined,\n ...options?.providerOptions,\n });\n\n // Update usage\n updateUsage(response.usage, totalUsage);\n\n // If the response is not a tool use, break\n if (response.stop_reason !== \"tool_use\") {\n break;\n }\n\n const breakLoop = await callTool(\n inputMessages,\n response,\n options.hooks,\n toolkit,\n );\n\n if (breakLoop) {\n break;\n }\n\n // Handle turn limit\n if (!enableMultipleTurns || currentTurn >= maxTurns) {\n return handleMaxTurns(\n maxTurns,\n history,\n inputMessages,\n response,\n totalUsage,\n );\n }\n\n currentTurn++;\n }\n\n let jsonResult: JsonObject | undefined;\n if (schema) {\n const validator = new ZSchema({});\n jsonResult = (\n response.content[response.content.length - 1] as Anthropic.ToolUseBlock\n ).input as JsonObject;\n\n if (!validator.validate(jsonResult, schema)) {\n throw new Error(\"Model returned invalid JSON\");\n }\n }\n\n history.push({\n content: schema\n ? JSON.stringify(jsonResult)\n : (response.content[0] as Anthropic.TextBlock).text,\n role: PROVIDER.ANTHROPIC.ROLE.ASSISTANT,\n type: LlmMessageType.Message,\n } as LlmOutputMessage);\n\n return {\n //model: model,\n //provider: PROVIDER.ANTHROPIC,\n content: schema\n ? jsonResult\n : (response.content[0] as Anthropic.TextBlock).text,\n responses: [response as unknown as JsonObject],\n output: history.slice(-1) as LlmOutputMessage[],\n history,\n status: LlmResponseStatus.Completed,\n usage: [totalUsage],\n };\n}\n","import { getEnvSecret } from \"@jaypie/aws\";\nimport {\n ConfigurationError,\n log as defaultLog,\n placeholders as replacePlaceholders,\n JAYPIE,\n log,\n} from \"@jaypie/core\";\nimport Anthropic from \"@anthropic-ai/sdk\";\nimport { PROVIDER } from \"../../constants.js\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { naturalZodSchema } from \"../../util/index.js\";\nimport { z } from \"zod/v4\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\n\n// Logger\nexport const getLogger = () => defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<Anthropic> {\n const logger = getLogger();\n const resolvedApiKey = apiKey || (await getEnvSecret(\"ANTHROPIC_API_KEY\"));\n\n if (!resolvedApiKey) {\n throw new ConfigurationError(\n \"The application could not resolve the required API key: ANTHROPIC_API_KEY\",\n );\n }\n\n const client = new Anthropic({ apiKey: resolvedApiKey });\n logger.trace(\"Initialized Anthropic client\");\n return client;\n}\n\n// Message formatting functions\nexport function formatSystemMessage(\n systemPrompt: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): string {\n return placeholders?.system === false\n ? systemPrompt\n : replacePlaceholders(systemPrompt, data);\n}\n\nexport function formatUserMessage(\n message: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): Anthropic.MessageParam {\n const content =\n placeholders?.message === false\n ? message\n : replacePlaceholders(message, data);\n\n return {\n role: PROVIDER.ANTHROPIC.ROLE.USER,\n content,\n };\n}\n\nexport function prepareMessages(\n message: string,\n { data, placeholders }: LlmMessageOptions = {},\n): Anthropic.MessageParam[] {\n const logger = getLogger();\n const messages: Anthropic.MessageParam[] = [];\n\n // Add user message (necessary for all requests)\n const userMessage = formatUserMessage(message, { data, placeholders });\n messages.push(userMessage);\n logger.trace(`User message: ${userMessage.content.length} characters`);\n\n return messages;\n}\n\n// Basic text completion\nexport async function createTextCompletion(\n client: Anthropic,\n messages: Anthropic.MessageParam[],\n model: string,\n systemMessage?: string,\n): Promise<string> {\n log.trace(\"Using text output (unstructured)\");\n\n const params: Anthropic.MessageCreateParams = {\n model,\n messages,\n max_tokens: PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT,\n };\n\n // Add system instruction if provided\n if (systemMessage) {\n params.system = systemMessage;\n log.trace(`System message: ${systemMessage.length} characters`);\n }\n\n const response = await client.messages.create(params);\n\n log.trace(\n `Assistant reply: ${response.content[0]?.text?.length || 0} characters`,\n );\n\n return response.content[0]?.text || \"\";\n}\n\n// Structured output completion\nexport async function createStructuredCompletion(\n client: Anthropic,\n messages: Anthropic.MessageParam[],\n model: string,\n responseSchema: z.ZodType | NaturalSchema,\n systemMessage?: string,\n): Promise<JsonObject> {\n log.trace(\"Using structured output\");\n\n // Get the JSON schema for the response\n const schema =\n responseSchema instanceof z.ZodType\n ? responseSchema\n : naturalZodSchema(responseSchema as NaturalSchema);\n\n // Set system message with JSON instructions\n const defaultSystemPrompt =\n \"You will be responding with structured JSON data. \" +\n \"Format your entire response as a valid JSON object with the following structure: \" +\n JSON.stringify(z.toJSONSchema(schema));\n\n const systemPrompt = systemMessage || defaultSystemPrompt;\n\n try {\n // Use standard Anthropic API to get response\n const params: Anthropic.MessageCreateParams = {\n model,\n messages,\n max_tokens: PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT,\n system: systemPrompt,\n };\n\n const response = await client.messages.create(params);\n\n // Extract text from response\n const responseText = response.content[0]?.text || \"\";\n\n // Find JSON in response\n const jsonMatch =\n responseText.match(/```json\\s*([\\s\\S]*?)\\s*```/) ||\n responseText.match(/\\{[\\s\\S]*\\}/);\n\n if (jsonMatch) {\n try {\n // Parse the JSON response\n const jsonStr = jsonMatch[1] || jsonMatch[0];\n const result = JSON.parse(jsonStr);\n if (!schema.parse(result)) {\n throw new Error(\n `JSON response from Anthropic does not match schema: ${responseText}`,\n );\n }\n log.trace(\"Received structured response\", { result });\n return result;\n } catch {\n throw new Error(\n `Failed to parse JSON response from Anthropic: ${responseText}`,\n );\n }\n }\n\n // If we can't extract JSON\n throw new Error(\"Failed to parse structured response from Anthropic\");\n } catch (error: unknown) {\n log.error(\"Error creating structured completion\", { error });\n throw error;\n }\n}\n","import { LlmMessageRole } from \"../../types/LlmProvider.interface.js\";\nimport { PROVIDER } from \"../../constants.js\";\n\n// Maps Jaypie roles to Anthropic roles\nexport const ROLE_MAP: Record<LlmMessageRole, string> = {\n [LlmMessageRole.User]: PROVIDER.ANTHROPIC.ROLE.USER,\n [LlmMessageRole.System]: PROVIDER.ANTHROPIC.ROLE.SYSTEM,\n [LlmMessageRole.Assistant]: PROVIDER.ANTHROPIC.ROLE.ASSISTANT,\n [LlmMessageRole.Developer]: PROVIDER.ANTHROPIC.ROLE.SYSTEM,\n};\n","import { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport Anthropic from \"@anthropic-ai/sdk\";\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n LlmHistoryItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { operate } from \"./operate.js\";\nimport {\n getLogger,\n initializeClient,\n prepareMessages,\n formatSystemMessage,\n createTextCompletion,\n createStructuredCompletion,\n} from \"./index.js\";\n\n// Main class implementation\nexport class AnthropicProvider implements LlmProvider {\n private model: string;\n private _client?: Anthropic;\n private apiKey?: string;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = PROVIDER.ANTHROPIC.MODEL.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<Anthropic> {\n if (this._client) {\n return this._client;\n }\n\n this._client = await initializeClient({ apiKey: this.apiKey });\n return this._client;\n }\n\n // Main send method\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const client = await this.getClient();\n const messages = prepareMessages(message, options || {});\n const modelToUse = options?.model || this.model;\n\n // Process system message if provided\n let systemMessage: string | undefined;\n if (options?.system) {\n systemMessage = formatSystemMessage(options.system, {\n data: options.data,\n placeholders: options.placeholders,\n });\n }\n\n if (options?.response) {\n return createStructuredCompletion(\n client,\n messages,\n modelToUse,\n options.response,\n systemMessage,\n );\n }\n\n return createTextCompletion(client, messages, modelToUse, systemMessage);\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const client = await this.getClient();\n options.model = options?.model || this.model;\n\n // Create a merged history including both the tracked history and any explicitly provided history\n const mergedOptions = { ...options };\n if (this.conversationHistory.length > 0) {\n // If options.history exists, merge with instance history, otherwise use instance history\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Call operate with the updated options\n const response = await operate(input, mergedOptions, { client });\n\n // Update conversation history with the new history from the response\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { NotImplementedError } from \"@jaypie/errors\";\nimport { DEFAULT, LlmProviderName, PROVIDER } from \"./constants.js\";\nimport {\n LlmProvider,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOptions,\n LlmOperateResponse,\n} from \"./types/LlmProvider.interface.js\";\nimport { OpenAiProvider } from \"./providers/openai/index.js\";\nimport { AnthropicProvider } from \"./providers/anthropic/AnthropicProvider.class.js\";\n\nclass Llm implements LlmProvider {\n private _provider: LlmProviderName;\n private _llm: LlmProvider;\n private _options: LlmOptions;\n\n constructor(\n providerName: LlmProviderName = DEFAULT.PROVIDER.NAME,\n options: LlmOptions = {},\n ) {\n this._provider = providerName;\n this._options = options;\n this._llm = this.createProvider(providerName, options);\n }\n\n private createProvider(\n providerName: LlmProviderName,\n options: LlmOptions = {},\n ): LlmProvider {\n const { apiKey, model } = options;\n\n switch (providerName) {\n case PROVIDER.OPENAI.NAME:\n return new OpenAiProvider(model || PROVIDER.OPENAI.MODEL.DEFAULT, {\n apiKey,\n });\n case PROVIDER.ANTHROPIC.NAME:\n return new AnthropicProvider(\n model || PROVIDER.ANTHROPIC.MODEL.DEFAULT,\n { apiKey },\n );\n default:\n throw new Error(`Unsupported provider: ${providerName}`);\n }\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n return this._llm.send(message, options);\n }\n\n async operate(\n message: string,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n if (!this._llm.operate) {\n throw new NotImplementedError(\n `Provider ${this._provider} does not support operate method`,\n );\n }\n return this._llm.operate(message, options);\n }\n\n static async send(\n message: string,\n options?: LlmMessageOptions & {\n llm?: LlmProviderName;\n apiKey?: string;\n model?: string;\n },\n ): Promise<string | JsonObject> {\n const { llm, apiKey, model, ...messageOptions } = options || {};\n const instance = new Llm(llm, { apiKey, model });\n return instance.send(message, messageOptions);\n }\n\n static async operate(\n message: string,\n options?: LlmOperateOptions & {\n llm?: LlmProviderName;\n apiKey?: string;\n model?: string;\n },\n ): Promise<LlmOperateResponse> {\n const { llm, apiKey, model, ...operateOptions } = options || {};\n const instance = new Llm(llm, { apiKey, model });\n return instance.operate(message, operateOptions);\n }\n}\n\nexport default Llm;\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\nimport { random as randomUtil } from \"../util/random.js\";\n\nexport const random: LlmTool = {\n description:\n \"Generate a random number with optional distribution, precision, range, and seeding\",\n\n name: \"random\",\n parameters: {\n type: \"object\",\n properties: {\n min: {\n type: \"number\",\n description:\n \"Minimum value (inclusive). Default: 0. When used with mean/stddev, acts as a clamp on the normal distribution\",\n },\n max: {\n type: \"number\",\n description:\n \"Maximum value (inclusive). Default: 1. When used with mean/stddev, acts as a clamp on the normal distribution\",\n },\n mean: {\n type: \"number\",\n description:\n \"Mean value for normal distribution. When set with stddev, uses normal distribution (clamped by min/max if provided)\",\n },\n stddev: {\n type: \"number\",\n description:\n \"Standard deviation for normal distribution. When set with mean, uses normal distribution (clamped by min/max if provided)\",\n },\n integer: {\n type: \"boolean\",\n description: \"Whether to return an integer value. Default: false\",\n },\n seed: {\n type: \"string\",\n description:\n \"Seed string for consistent random generation. Default: undefined (uses default RNG)\",\n },\n precision: {\n type: \"number\",\n description:\n \"Number of decimal places for the result. Default: undefined (full precision)\",\n },\n currency: {\n type: \"boolean\",\n description:\n \"Whether to format as currency (2 decimal places). Default: false\",\n },\n },\n required: [],\n },\n type: \"function\",\n call: (options) => {\n const rng = randomUtil();\n return rng(options);\n },\n message: ({\n min,\n max,\n mean,\n stddev,\n integer,\n seed,\n precision,\n currency,\n } = {}) => {\n let description = \"Generating\";\n if (seed) {\n description += ` seeded`;\n } else {\n description += \" random\";\n }\n if (integer) {\n description += \" integer\";\n } else if (currency) {\n description += \" currency\";\n } else if (precision) {\n description += ` with precision \\`${precision}\\``;\n } else {\n description += \" number\";\n }\n if (min && max) {\n description += ` between \\`${min}\\` and \\`${max}\\``;\n }\n if (mean && stddev) {\n description += ` with normal distribution around \\`${mean}\\` with standard deviation \\`${stddev}\\``;\n }\n return description;\n },\n};\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\nimport { log, random, tryParseNumber } from \"../util\";\n\nexport const roll: LlmTool = {\n description: \"Roll one or more dice with a specified number of sides\",\n name: \"roll\",\n parameters: {\n type: \"object\",\n properties: {\n number: {\n type: \"number\",\n description: \"Number of dice to roll. Default: 1\",\n },\n sides: {\n type: \"number\",\n description: \"Number of sides on each die. Default: 6\",\n },\n },\n required: [\"number\", \"sides\"],\n },\n type: \"function\",\n call: ({ number = 1, sides = 6 } = {}): {\n rolls: number[];\n total: number;\n } => {\n const rng = random();\n const rolls: number[] = [];\n let total = 0;\n\n const parsedNumber = tryParseNumber(number, {\n defaultValue: 1,\n warnFunction: log.warn,\n }) as number;\n const parsedSides = tryParseNumber(sides, {\n defaultValue: 6,\n warnFunction: log.warn,\n }) as number;\n\n for (let i = 0; i < parsedNumber; i++) {\n const rollValue = rng({ min: 1, max: parsedSides, integer: true });\n rolls.push(rollValue);\n total += rollValue;\n }\n\n return { rolls, total };\n },\n message: ({ number = 1, sides = 6 } = {}) => {\n return `Rolling ${number} ${sides}-sided dice`;\n },\n};\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\n\nexport const time: LlmTool = {\n description:\n \"Returns the provided date as an ISO UTC string or the current time if no date provided.\",\n name: \"time\",\n parameters: {\n type: \"object\",\n properties: {\n date: {\n type: \"string\",\n description:\n \"Date string to convert to ISO UTC format. Default: current time\",\n },\n },\n required: [],\n },\n type: \"function\",\n call: ({ date } = {}) => {\n if (typeof date === \"number\" || typeof date === \"string\") {\n const parsedDate = new Date(date);\n if (isNaN(parsedDate.getTime())) {\n throw new Error(`Invalid date format: ${date}`);\n }\n return parsedDate.toISOString();\n }\n return new Date().toISOString();\n },\n message: ({ date } = {}) => {\n if (typeof date === \"number\" || typeof date === \"string\") {\n return `Converting date to ISO UTC format`;\n }\n return \"Checking current time\";\n },\n};\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\nimport { fetchWeatherApi } from \"openmeteo\";\nimport { JsonObject } from \"@jaypie/types\";\n\nexport const weather: LlmTool = {\n description: \"Get current weather and forecast data for a specific location\",\n name: \"weather\",\n parameters: {\n type: \"object\",\n properties: {\n latitude: {\n type: \"number\",\n description:\n \"Latitude of the location. Default: 42.051554533384866 (Evanston, IL)\",\n },\n location: {\n type: \"string\",\n description:\n \"Human-readable description of the location, not used for the API call. Default: Evanston, IL\",\n },\n longitude: {\n type: \"number\",\n description:\n \"Longitude of the location. Default: -87.6759911441785 (Evanston, IL)\",\n },\n timezone: {\n type: \"string\",\n description: \"Timezone for the results. Default: America/Chicago\",\n },\n past_days: {\n type: \"number\",\n description:\n \"Number of past days to include in the forecast. Default: 1\",\n },\n forecast_days: {\n type: \"number\",\n description: \"Number of forecast days to include. Default: 1\",\n },\n },\n required: [\"latitude\", \"location\", \"longitude\"],\n },\n type: \"function\",\n call: async ({\n latitude = 42.051554533384866,\n longitude = -87.6759911441785,\n timezone = \"America/Chicago\",\n past_days = 1,\n forecast_days = 1,\n } = {}): Promise<JsonObject> => {\n try {\n const params = {\n latitude,\n longitude,\n hourly: [\n \"temperature_2m\",\n \"precipitation_probability\",\n \"precipitation\",\n ],\n current: [\n \"temperature_2m\",\n \"is_day\",\n \"showers\",\n \"cloud_cover\",\n \"wind_speed_10m\",\n \"relative_humidity_2m\",\n \"precipitation\",\n \"snowfall\",\n \"rain\",\n \"apparent_temperature\",\n ],\n timezone,\n past_days,\n forecast_days,\n wind_speed_unit: \"mph\",\n temperature_unit: \"fahrenheit\",\n precipitation_unit: \"inch\",\n };\n\n const url = \"https://api.open-meteo.com/v1/forecast\";\n const responses = await fetchWeatherApi(url, params);\n\n // Helper function to form time ranges\n const range = (start: number, stop: number, step: number) =>\n Array.from(\n { length: (stop - start) / step },\n (_, i) => start + i * step,\n );\n\n // Process first location\n const response = responses[0];\n\n // Attributes for timezone and location\n const utcOffsetSeconds = response.utcOffsetSeconds();\n const timezoneAbbreviation = response.timezoneAbbreviation();\n\n const current = response.current()!;\n const hourly = response.hourly()!;\n\n // Create weather data object\n const weatherData = {\n location: {\n latitude: response.latitude(),\n longitude: response.longitude(),\n timezone: response.timezone(),\n timezoneAbbreviation,\n utcOffsetSeconds,\n },\n current: {\n time: new Date(\n (Number(current.time()) + utcOffsetSeconds) * 1000,\n ).toISOString(),\n temperature2m: current.variables(0)!.value(),\n isDay: current.variables(1)!.value(),\n showers: current.variables(2)!.value(),\n cloudCover: current.variables(3)!.value(),\n windSpeed10m: current.variables(4)!.value(),\n relativeHumidity2m: current.variables(5)!.value(),\n precipitation: current.variables(6)!.value(),\n snowfall: current.variables(7)!.value(),\n rain: current.variables(8)!.value(),\n apparentTemperature: current.variables(9)!.value(),\n },\n hourly: {\n time: range(\n Number(hourly.time()),\n Number(hourly.timeEnd()),\n hourly.interval(),\n ).map((t) => new Date((t + utcOffsetSeconds) * 1000).toISOString()),\n temperature2m: Array.from(hourly.variables(0)!.valuesArray()!),\n precipitationProbability: Array.from(\n hourly.variables(1)!.valuesArray()!,\n ),\n precipitation: Array.from(hourly.variables(2)!.valuesArray()!),\n },\n };\n\n return weatherData;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Weather API error: ${error.message}`);\n }\n throw new Error(\"Unknown error occurred while fetching weather data\");\n }\n },\n message: ({\n latitude = 42.051554533384866,\n longitude = -87.6759911441785,\n location = \"Evanston, IL\",\n } = {}) => {\n return `Getting weather for ${location} (${latitude}, ${longitude})`;\n },\n};\n","import { Toolkit } from \"./Toolkit.class.js\";\nimport type { LlmTool } from \"../types/LlmTool.interface.js\";\n\nimport { random } from \"./random.js\";\nimport { roll } from \"./roll.js\";\nimport { time } from \"./time.js\";\nimport { weather } from \"./weather.js\";\n\nexport const tools = [random, roll, time, weather];\n\nexport class JaypieToolkit extends Toolkit {\n public readonly random: LlmTool;\n public readonly roll: LlmTool;\n public readonly time: LlmTool;\n public readonly weather: LlmTool;\n\n constructor(tools: LlmTool[], options?: any) {\n super(tools, options);\n this.random = random;\n this.roll = roll;\n this.time = time;\n this.weather = weather;\n }\n}\n\nexport const toolkit = new JaypieToolkit(tools);\n\nexport { Toolkit };\n"],"names":["log","jaypieLog","getLogger","defaultLog","random","operate","initializeClient","ConfigurationError","formatSystemMessage","placeholders","replacePlaceholders","formatUserMessage","prepareMessages","createStructuredCompletion","createTextCompletion","Anthropic","randomUtil"],"mappings":";;;;;;;;;;;AAAO,MAAM,QAAQ,GAAG;AACtB,IAAA,SAAS,EAAE;;AAET,QAAA,KAAK,EAAE;;AAEL,YAAA,OAAO,EAAE,iBAA0B;AACnC,YAAA,KAAK,EAAE,mBAA4B;AACnC,YAAA,IAAI,EAAE,yBAAkC;AACxC,YAAA,KAAK,EAAE,iBAA0B;;AAEjC,YAAA,aAAa,EAAE,iBAA0B;AACzC,YAAA,eAAe,EAAE,mBAA4B;AAC7C,YAAA,cAAc,EAAE,yBAAkC;AAClD,YAAA,aAAa,EAAE,sBAA+B;AAC9C,YAAA,eAAe,EAAE,0BAAmC;;AAEpD,YAAA,eAAe,EAAE,iBAA0B;AAC3C,YAAA,eAAe,EAAE,iBAA0B;AAC3C,YAAA,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