@jaypie/llm 1.1.6 → 1.1.7

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/util/naturalZodSchema.ts","../src/providers/openai/utils.ts","../src/tools/Toolkit.class.ts","../src/providers/openai/operate.ts","../src/providers/openai/OpenAiProvider.class.ts","../src/providers/AnthropicProvider.class.ts","../src/Llm.ts","../src/util/random.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 },\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 { z } from \"zod\";\nimport { NaturalSchema } from \"@jaypie/types\";\n\nexport default function naturalZodSchema(\n definition: NaturalSchema,\n): 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 { 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/naturalZodSchema.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<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 { LlmTool } from \"../types/LlmTool.interface\";\n\nconst DEFAULT_TOOL_TYPE = \"function\";\n\nexport interface ToolkitOptions {\n explain?: boolean;\n}\n\nexport class Toolkit {\n private readonly _tools: LlmTool[];\n private readonly _options: ToolkitOptions;\n private readonly explain: boolean;\n\n constructor(tools: LlmTool[], options?: ToolkitOptions) {\n this._tools = tools;\n this._options = options || {};\n this.explain = this._options.explain ? true : false;\n }\n\n get tools(): Omit<LlmTool, \"call\">[] {\n return this._tools.map((tool) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const toolCopy: any = { ...tool };\n delete toolCopy.call;\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:\n \"Explain the reasoning behind this function call. What is the expected result? Describe possible next steps and the conditions under which they should be taken.\",\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 const result = tool.call(parsedArgs);\n\n if (result instanceof Promise) {\n return await result;\n }\n\n return result;\n }\n}\n","import { sleep, placeholders } from \"@jaypie/core\";\nimport { BadGatewayError } 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 naturalZodSchema from \"../../util/naturalZodSchema.js\";\nimport { LlmOperateOptions } from \"../../types/LlmProvider.interface.js\";\nimport { getLogger } from \"./utils.js\";\nimport { PROVIDER } from \"../../constants.js\";\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport {\n OpenAIRawResponse,\n OpenAIResponse,\n OpenAIResponseTurn,\n} from \"./types.js\";\n\n// Constants\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\n// Turn policy constants\nexport const MAX_TURNS_ABSOLUTE_LIMIT = 72;\nexport const MAX_TURNS_DEFAULT_LIMIT = 12;\n\n//\n//\n// Helpers\n//\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\n//\n//\n// Main\n//\n\nexport async function operate(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: string | any[],\n options: LlmOperateOptions = {},\n context: { client: OpenAI; maxRetries?: number } = {\n client: new OpenAI(),\n },\n): Promise<OpenAIResponse> {\n const log = getLogger();\n const openai = context.client;\n\n // Validate\n if (!context.maxRetries) {\n context.maxRetries = MAX_RETRIES_DEFAULT_LIMIT;\n }\n const model = options?.model || PROVIDER.OPENAI.MODEL.DEFAULT;\n\n // Setup\n let retryCount = 0;\n let retryDelay = INITIAL_RETRY_DELAY_MS;\n const maxRetries = Math.min(context.maxRetries, MAX_RETRIES_ABSOLUTE_LIMIT);\n const allResponses: OpenAIResponseTurn[] = [];\n\n // Determine max turns from options\n const maxTurns = maxTurnsFromOptions(options);\n const enableMultipleTurns = maxTurns > 1;\n let currentTurn = 0;\n let currentInput = input;\n let toolkit: Toolkit | undefined;\n const explain = options?.explain ?? false;\n\n // Initialize toolkit if tools are provided\n if (options.tools?.length) {\n toolkit = new Toolkit(options.tools, { explain });\n }\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const requestOptions: /* OpenAI.Responses.InputItems */ any = {\n model,\n input:\n typeof currentInput === \"string\" &&\n options?.data &&\n (options.placeholders?.input === undefined ||\n options.placeholders?.input)\n ? placeholders(currentInput, options.data)\n : currentInput,\n };\n\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 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 } else if ((options as unknown as { system: string })?.system) {\n // Check for illegal system option, use it as instructions, and log a warning\n log.warn(\"[operate] Use 'instructions' instead of 'system'.\");\n // Apply placeholders to system 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(\n (options as unknown as { system: string }).system,\n options.data,\n )\n : (options as unknown as { system: string }).system;\n }\n\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 // Add tools if toolkit is initialized\n if (toolkit) {\n requestOptions.tools = toolkit.tools;\n }\n\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 log.var({ requestOptions });\n // Use type assertion to handle the OpenAI SDK response type\n const currentResponse = (await openai.responses.create(\n requestOptions,\n )) as unknown as OpenAIRawResponse;\n if (retryCount > 0) {\n log.debug(`OpenAI API call succeeded after ${retryCount} retries`);\n }\n // Add the entire response to allResponses\n allResponses.push(currentResponse as unknown as OpenAIResponseTurn);\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 if (output.type === \"function_call\") {\n hasFunctionCall = true;\n\n if (toolkit && enableMultipleTurns) {\n try {\n // Parse arguments for validation\n JSON.parse(output.arguments);\n\n // Call the tool and ensure the result is resolved if it's a Promise\n log.trace(`[operate] Calling tool - ${output.name}`);\n const result = await toolkit.call({\n name: output.name,\n arguments: output.arguments,\n });\n\n // Prepare for next turn by adding function call and result\n // Add the function call to the input for the next turn\n if (typeof currentInput === \"string\") {\n // Convert string input to array format for the first turn\n currentInput = [{ content: currentInput, role: \"user\" }];\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 currentInput.push({\n type: \"function_call_output\",\n call_id: output.call_id,\n output: JSON.stringify(result),\n });\n }\n } catch (error) {\n log.error(\n `Error executing function call ${output.name}:`,\n error,\n );\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 }\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 // If there's no function call or we can't take another turn, exit the loop\n if (!hasFunctionCall || !enableMultipleTurns) {\n return allResponses;\n }\n\n // If we've reached the maximum number of turns, exit the loop\n if (currentTurn >= maxTurns) {\n log.warn(\n `Model requested function call but exceeded ${maxTurns} turns`,\n );\n return allResponses;\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 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 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 // 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 // If we've reached the maximum number of turns, return all responses\n return allResponses;\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { OpenAI } from \"openai\";\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n LlmMessageOptions,\n LlmOperateOptions,\n LlmProvider,\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\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,\n options: LlmOperateOptions = {},\n ): Promise<unknown> {\n const client = await this.getClient();\n options.model = options?.model || this.model;\n\n return operate(input, options, { client });\n }\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { PROVIDER } from \"../constants.js\";\nimport { LlmProvider } from \"../types/LlmProvider.interface.js\";\n\nexport class AnthropicProvider implements LlmProvider {\n private model: string;\n private apiKey?: string;\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 async send(message: string): Promise<string | JsonObject> {\n // TODO: Implement Anthropic API call\n return `[anthropic ${this.model}] ${message}`;\n }\n}\n","import { JsonArray, 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} 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<JsonArray> {\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) as Promise<JsonArray>;\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<JsonArray> {\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 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 */\nconst 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//\n// Export\n//\n\nexport default random;\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\nimport 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};\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\nimport random from \"../util/random.js\";\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 const rng = random();\n const rolls: number[] = [];\n let total = 0;\n\n for (let i = 0; i < number; i++) {\n const rollValue = rng({ min: 1, max: sides, integer: true });\n rolls.push(rollValue);\n total += rollValue;\n }\n\n return { rolls, total };\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 (date) {\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};\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\nimport { fetchWeatherApi } from \"openmeteo\";\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 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 location. 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: [],\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 } = {}) => {\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};\n","import { random } from \"./random.js\";\nimport { roll } from \"./roll.js\";\nimport { time } from \"./time.js\";\nimport { weather } from \"./weather.js\";\n\nexport const toolkit = {\n random,\n roll,\n time,\n weather,\n};\n\nexport const tools = Object.values(toolkit);\n"],"names":["defaultLog","placeholders","replacePlaceholders","ConfigurationError","random","randomUtil"],"mappings":";;;;;;;;;AAAO,MAAM,QAAQ,GAAG;AACtB,IAAA,SAAS,EAAE;AACT,QAAA,KAAK,EAAE;AACL,YAAA,cAAc,EAAE,yBAAkC;AAClD,YAAA,aAAa,EAAE,sBAA+B;AAC9C,YAAA,eAAe,EAAE,0BAAmC;AACpD,YAAA,OAAO,EAAE,0BAAmC;AAC7C,SAAA;AACD,QAAA,IAAI,EAAE,WAAoB;AAC3B,KAAA;AACD,IAAA,MAAM,EAAE;AACN,QAAA,KAAK,EAAE;AACL,YAAA,OAAO,EAAE,QAAiB;AAC1B,YAAA,KAAK,EAAE,OAAgB;AACvB,YAAA,YAAY,EAAE,a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AE,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;CACF;;ACrIY,MAAA,OAAO,GAAG;IACrB,MAAM;IACN,IAAI;IACJ,IAAI;IACJ,OAAO;;AAGI,MAAA,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO;;;;"}
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/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 },\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 { LlmTool } from \"../types/LlmTool.interface\";\n\nconst DEFAULT_TOOL_TYPE = \"function\";\n\nexport interface ToolkitOptions {\n explain?: boolean;\n}\n\nexport class Toolkit {\n private readonly _tools: LlmTool[];\n private readonly _options: ToolkitOptions;\n private readonly explain: boolean;\n\n constructor(tools: LlmTool[], options?: ToolkitOptions) {\n this._tools = tools;\n this._options = options || {};\n this.explain = this._options.explain ? true : false;\n }\n\n get tools(): Omit<LlmTool, \"call\">[] {\n return this._tools.map((tool) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const toolCopy: any = { ...tool };\n delete toolCopy.call;\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:\n \"Explain the reasoning behind this function call. What is the expected result? Describe possible next steps and the conditions under which they should be taken.\",\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 const result = tool.call(parsedArgs);\n\n if (result instanceof Promise) {\n return await result;\n }\n\n return result;\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\";\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\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\nexport interface LlmOutputMessage {\n content: 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 instructions?: string;\n model?: string;\n placeholders?: {\n input?: boolean;\n instructions?: boolean;\n };\n providerOptions?: Record<string, AnyValue>;\n tools?: LlmTool[];\n turns?: boolean | number;\n user?: string;\n}\n\nexport interface LlmOptions {\n apiKey?: string;\n model?: string;\n}\n\n// Responses\n\ninterface LlmUsage {\n input: number;\n output: number;\n reasoning: number;\n total: number;\n}\n\nexport interface LlmOperateResponse {\n content?: string;\n error?: LlmError;\n history: LlmHistory;\n output: LlmOutput;\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 { 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 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 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 } else if ((options as unknown as { system: string })?.system) {\n // Check for illegal system option, use it as instructions, and log a warning\n log.warn(\"[operate] Use 'instructions' instead of 'system'.\");\n // Apply placeholders to system 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(\n (options as unknown as { system: string }).system,\n options.data,\n )\n : (options as unknown as { system: string }).system;\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 // Create toolkit and add tools if provided\n if (options.tools?.length) {\n const explain = options?.explain ?? false;\n const toolkit = new Toolkit(options.tools, { explain });\n requestOptions.tools = toolkit.tools;\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 output: [],\n responses: [],\n status: LlmResponseStatus.InProgress,\n usage: {\n input: 0,\n output: 0,\n reasoning: 0,\n total: 0,\n },\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 // Determine max turns from options\n const maxTurns = maxTurnsFromOptions(options);\n const enableMultipleTurns = maxTurns > 1;\n let currentTurn = 0;\n\n // If history is provided, merge it with currentInput\n if (options.history) {\n currentInput = [...options.history, ...currentInput];\n }\n // Initialize history with currentInput\n returnResponse.history = [...currentInput];\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 // 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 // Accumulate token usage from the current response\n if (currentResponse.usage) {\n returnResponse.usage.input += currentResponse.usage.input_tokens || 0;\n returnResponse.usage.output +=\n currentResponse.usage.output_tokens || 0;\n returnResponse.usage.total += currentResponse.usage.total_tokens || 0;\n if (currentResponse.usage.output_tokens_details?.reasoning_tokens) {\n returnResponse.usage.reasoning =\n (returnResponse.usage.reasoning || 0) +\n currentResponse.usage.output_tokens_details.reasoning_tokens;\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 const explain = options?.explain ?? false;\n\n // Initialize toolkit if tools are provided for multi-turn function calling\n if (options.tools?.length) {\n toolkit = new Toolkit(options.tools, { explain });\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 returnResponse.content = `${LlmMessageType.FunctionCall}:${output.name}${output.arguments}#${output.call_id}`;\n const result = await toolkit.call({\n name: output.name,\n arguments: output.arguments,\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 returnResponse.content = `${LlmMessageType.FunctionCallOutput}:${functionCallOutput.output}#${functionCallOutput.call_id}`;\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 if (output.type === LlmMessageType.Message) {\n if (\n output.content?.[0] &&\n output.content[0].type === LlmMessageType.OutputText\n ) {\n returnResponse.content = output.content[0].text;\n }\n }\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 // 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 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 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 // 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} 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: JsonObject[] = [];\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 // TODO: Create a merged history including both the tracked history and any explicitly provided history\n\n // Call operate with the updated options\n const response = await operate(input, options, { client });\n\n // TODO: Update conversation history with the input and response\n\n return response;\n }\n\n /**\n * Updates the conversation history with the latest input and response\n * @param input The formatted input messages\n * @param response The response from the model\n */\n private updateConversationHistory(\n input: JsonObject[],\n response: JsonObject[],\n ): void {\n // Add the input to history\n this.conversationHistory.push(...input);\n\n // Add the response to history if it exists and has content\n if (response && response.length > 0) {\n // Extract the last response item and add it to history\n const lastResponse = response[response.length - 1];\n if (lastResponse) {\n this.conversationHistory.push(lastResponse);\n }\n }\n }\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { PROVIDER } from \"../constants.js\";\nimport { LlmProvider } from \"../types/LlmProvider.interface.js\";\n\nexport class AnthropicProvider implements LlmProvider {\n private model: string;\n private apiKey?: string;\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 async send(message: string): Promise<string | JsonObject> {\n // TODO: Implement Anthropic API call\n return `[anthropic ${this.model}] ${message}`;\n }\n}\n","import { JsonArray, 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} 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<JsonArray> {\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) as Promise<JsonArray>;\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<JsonArray> {\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};\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};\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};\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 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 location. 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: [],\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};\n","import { random } from \"./random.js\";\nimport { roll } from \"./roll.js\";\nimport { time } from \"./time.js\";\nimport { weather } from \"./weather.js\";\n\nexport const toolkit = {\n random,\n roll,\n time,\n weather,\n};\n\nexport const tools = Object.values(toolkit);\n"],"names":["getLogger","defaultLog","random","ConfigurationError","placeholders","replacePlaceholders","randomUtil"],"mappings":";;;;;;;;;AAAO,MAAM,QAAQ,GAAG;AACtB,IAAA,SAAS,EAAE;AACT,QAAA,KAAK,EAAE;AACL,YAAA,cAAc,EAAE,yBAAkC;AAClD,YAAA,aAAa,EAAE,sBAA+B;AAC9C,YAAA,eAAe,EAAE,0BAAmC;AACpD,YAAA,OAAO,EAAE,0BAAmC;AAC7C,SAAA;AACD,QAAA,IAAI,EAAE,WAAoB;AAC3B,KAAA;AACD,IAAA,MAAM,EAAE;AACN,QAAA,KAAK,EAAE;AACL,YAAA,OAAO,EAAE,QAAiB;AAC1B,YAAA,KAAK,EAAE,OAAgB;AACvB,YAAA,YAAY,EAAE,aAAsB;AACpC,YAAA,OAAO,EAAE,QAAiB;AAC1B,YAAA,OAAO,EAAE,iBAA0B;AACnC,YAAA,EAAE,EAAE,IAAa;AACjB,YAAA,OAAO,EAAE,SAAkB;AAC3B,YAAA,MAAM,EAAE,QAAiB;AACzB,YAAA,OAAO,EAAE,SAAkB;AAC3B,YAAA,YAAY,EAAE,cAAuB;AACtC,SAAA;AACD,QAAA,IAAI,EAAE,QAAiB;AACxB,KAAA;CACO;AAMV;AACO,MAAM,OAAO,GAAG;IACrB,QAAQ,EAAE,QAAQ,CAAC,MAAM;CACjB;;;;;;;;AChCV,MAAM,iBAAiB,GAAG,UAAU;MAMvB,OAAO,CAAA;IAKlB,WAAY,CAAA,KAAgB,EAAE,OAAwB,EAAA;AACpD,QAAA,IAAI,CAAC,MAAM,GAAG,KAAK;AACnB,QAAA,IAAI,CAAC,QAAQ,GAAG,OAAO,IAAI,EAAE;AAC7B,QAAA,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,GAAG,IAAI,GAAG,KAAK;;AAGrD,IAAA,IAAI,KAAK,GAAA;QACP,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,KAAI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,CAAC,CAAC,WAAW,EAAE,CAAC;AACnE,oBAAA,aAAa,EAAE,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAE,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;CACF;;ACtIY,MAAA,OAAO,GAAG;IACrB,MAAM;IACN,IAAI;IACJ,IAAI;IACJ,OAAO;;AAGI,MAAA,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO;;;;"}
@@ -1,14 +1,21 @@
1
1
  import { JsonObject } from "@jaypie/types";
2
- import { LlmMessageOptions, LlmOperateOptions, LlmProvider } from "../../types/LlmProvider.interface.js";
2
+ import { LlmHistory, LlmInputMessage, LlmMessageOptions, LlmOperateOptions, LlmOperateResponse, LlmProvider } from "../../types/LlmProvider.interface.js";
3
3
  export declare class OpenAiProvider implements LlmProvider {
4
4
  private model;
5
5
  private _client?;
6
6
  private apiKey?;
7
7
  private log;
8
+ private conversationHistory;
8
9
  constructor(model?: string, { apiKey }?: {
9
10
  apiKey?: string;
10
11
  });
11
12
  private getClient;
12
13
  send(message: string, options?: LlmMessageOptions): Promise<string | JsonObject>;
13
- operate(input: string, options?: LlmOperateOptions): Promise<unknown>;
14
+ operate(input: string | LlmHistory | LlmInputMessage, options?: LlmOperateOptions): Promise<LlmOperateResponse>;
15
+ /**
16
+ * Updates the conversation history with the latest input and response
17
+ * @param input The formatted input messages
18
+ * @param response The response from the model
19
+ */
20
+ private updateConversationHistory;
14
21
  }
@@ -1,12 +1,26 @@
1
1
  import { OpenAI } from "openai";
2
- import { LlmOperateOptions } from "../../types/LlmProvider.interface.js";
3
- import { OpenAIResponse } from "./types.js";
2
+ import { LlmHistory, LlmInputMessage, LlmOperateOptions, LlmOperateResponse } from "../../types/LlmProvider.interface.js";
3
+ import { LlmTool } from "../../types/LlmTool.interface.js";
4
+ /**
5
+ * OpenAI request options type that includes model and input properties
6
+ */
7
+ export type OpenAiRequestOptions = Omit<LlmOperateOptions, "tools"> & {
8
+ model: string;
9
+ input: LlmInputMessage | LlmHistory;
10
+ text?: unknown;
11
+ tools?: Omit<LlmTool, "call">[];
12
+ };
4
13
  export declare const MAX_RETRIES_ABSOLUTE_LIMIT = 72;
5
14
  export declare const MAX_RETRIES_DEFAULT_LIMIT = 6;
6
- export declare const MAX_TURNS_ABSOLUTE_LIMIT = 72;
7
- export declare const MAX_TURNS_DEFAULT_LIMIT = 12;
8
- export declare function maxTurnsFromOptions(options: LlmOperateOptions): number;
9
- export declare function operate(input: string | any[], options?: LlmOperateOptions, context?: {
15
+ /**
16
+ * Creates the request options for the OpenAI API call
17
+ *
18
+ * @param input - The formatted input messages
19
+ * @param options - The LLM operation options
20
+ * @returns The request options for the OpenAI API
21
+ */
22
+ export declare function createRequestOptions(input: LlmInputMessage | LlmHistory, options?: LlmOperateOptions): OpenAiRequestOptions;
23
+ export declare function operate(input: string | LlmHistory | LlmInputMessage, options?: LlmOperateOptions, context?: {
10
24
  client: OpenAI;
11
25
  maxRetries?: number;
12
- }): Promise<OpenAIResponse>;
26
+ }): Promise<LlmOperateResponse>;
@@ -1,3 +1,4 @@
1
+ import { JsonValue } from "@jaypie/types";
1
2
  /**
2
3
  * Type definitions for OpenAI API responses
3
4
  */
@@ -36,6 +37,20 @@ export interface OpenAIFunctionCallOutput {
36
37
  * Union type for all possible response items
37
38
  */
38
39
  export type OpenAIResponseItem = OpenAIFunctionCall | OpenAIMessage | OpenAIFunctionCallOutput;
40
+ /**
41
+ * Represents token usage information in the OpenAI response
42
+ */
43
+ export interface OpenAIUsage extends Record<string, JsonValue> {
44
+ input_tokens: number;
45
+ input_tokens_details?: {
46
+ cached_tokens: number;
47
+ };
48
+ output_tokens: number;
49
+ output_tokens_details?: {
50
+ reasoning_tokens: number;
51
+ };
52
+ total_tokens: number;
53
+ }
39
54
  /**
40
55
  * Raw response from the OpenAI API
41
56
  */
@@ -49,7 +64,11 @@ export interface OpenAIRawResponse {
49
64
  error?: any | null;
50
65
  status?: string | any;
51
66
  _request_id?: string | null;
52
- [key: string]: unknown;
67
+ usage?: OpenAIUsage;
68
+ meta?: {
69
+ [key: string]: JsonValue;
70
+ };
71
+ [key: string]: JsonValue;
53
72
  }
54
73
  /**
55
74
  * Represents a single turn in a multi-turn conversation
@@ -64,7 +83,7 @@ export interface OpenAIResponseTurn {
64
83
  error?: any | null;
65
84
  status?: string;
66
85
  _request_id?: string | null;
67
- [key: string]: unknown;
86
+ [key: string]: JsonValue;
68
87
  }
69
88
  /**
70
89
  * Represents the complete response from the OpenAI API,
@@ -1,8 +1,96 @@
1
- import { JsonObject, NaturalSchema } from "@jaypie/types";
1
+ import { AnyValue, JsonObject, JsonReturn, NaturalMap, NaturalSchema } from "@jaypie/types";
2
2
  import { z } from "zod";
3
3
  import { LlmTool } from "./LlmTool.interface.js";
4
+ export declare enum LlmMessageRole {
5
+ Assistant = "assistant",
6
+ Developer = "developer",
7
+ System = "system",
8
+ User = "user"
9
+ }
10
+ export declare enum LlmMessageType {
11
+ FunctionCall = "function_call",
12
+ FunctionCallOutput = "function_call_output",
13
+ InputFile = "input_file",
14
+ InputImage = "input_image",
15
+ InputText = "input_text",
16
+ ItemReference = "item_reference",
17
+ Message = "message",
18
+ OutputText = "output_text",
19
+ Refusal = "refusal"
20
+ }
21
+ export declare enum LlmResponseStatus {
22
+ Completed = "completed",
23
+ Incomplete = "incomplete",
24
+ InProgress = "in_progress"
25
+ }
26
+ interface LlmError {
27
+ detail?: string;
28
+ status: number | string;
29
+ title: string;
30
+ }
31
+ interface LlmInputContentFile {
32
+ type: LlmMessageType.InputFile;
33
+ file_data: File;
34
+ file_id?: string;
35
+ filename?: string;
36
+ }
37
+ interface LlmInputContentImage {
38
+ type: LlmMessageType.InputImage;
39
+ detail: File;
40
+ file_id?: string;
41
+ image_url?: string;
42
+ }
43
+ interface LlmInputContentText {
44
+ type: LlmMessageType.InputText;
45
+ text: string;
46
+ }
47
+ type LlmInputContent = LlmInputContentFile | LlmInputContentImage | LlmInputContentText;
48
+ export interface LlmInputMessage {
49
+ content: string | Array<LlmInputContent>;
50
+ role: LlmMessageRole;
51
+ type: LlmMessageType.Message;
52
+ }
53
+ export interface LlmOutputContentText {
54
+ annotations?: AnyValue[];
55
+ text: string;
56
+ type: LlmMessageType.OutputText;
57
+ }
58
+ interface LlmOutputRefusal {
59
+ refusal: string;
60
+ type: LlmMessageType.Refusal;
61
+ }
62
+ type LlmOutputContent = LlmOutputContentText | LlmOutputRefusal;
63
+ export interface LlmOutputMessage {
64
+ content: Array<LlmOutputContent>;
65
+ id?: string;
66
+ role: LlmMessageRole.Assistant;
67
+ status: LlmResponseStatus;
68
+ type: LlmMessageType.Message;
69
+ }
70
+ type LlmOutputItem = LlmToolCall | LlmToolResult | LlmOutputMessage;
71
+ type LlmOutput = LlmOutputItem[];
72
+ export interface LlmToolCall {
73
+ arguments: string;
74
+ call_id: string;
75
+ id: string;
76
+ name: string;
77
+ type: LlmMessageType.FunctionCall;
78
+ status: LlmResponseStatus;
79
+ }
80
+ export interface LlmToolResult {
81
+ call_id: string;
82
+ output: string;
83
+ status?: LlmResponseStatus;
84
+ type: LlmMessageType.FunctionCallOutput;
85
+ }
86
+ interface LlmItemReference {
87
+ type: LlmMessageType.ItemReference;
88
+ id: string;
89
+ }
90
+ export type LlmHistoryItem = LlmInputMessage | LlmItemReference | LlmOutputItem | LlmToolResult;
91
+ export type LlmHistory = LlmHistoryItem[];
4
92
  export interface LlmMessageOptions {
5
- data?: Record<string, string>;
93
+ data?: NaturalMap;
6
94
  model?: string;
7
95
  placeholders?: {
8
96
  message?: boolean;
@@ -12,16 +100,17 @@ export interface LlmMessageOptions {
12
100
  system?: string;
13
101
  }
14
102
  export interface LlmOperateOptions {
15
- data?: Record<string, string>;
103
+ data?: NaturalMap;
16
104
  explain?: boolean;
17
105
  format?: JsonObject | NaturalSchema | z.ZodType;
106
+ history?: LlmHistory;
18
107
  instructions?: string;
19
108
  model?: string;
20
109
  placeholders?: {
21
110
  input?: boolean;
22
111
  instructions?: boolean;
23
112
  };
24
- providerOptions?: Record<string, unknown>;
113
+ providerOptions?: Record<string, AnyValue>;
25
114
  tools?: LlmTool[];
26
115
  turns?: boolean | number;
27
116
  user?: string;
@@ -30,7 +119,23 @@ export interface LlmOptions {
30
119
  apiKey?: string;
31
120
  model?: string;
32
121
  }
122
+ interface LlmUsage {
123
+ input: number;
124
+ output: number;
125
+ reasoning: number;
126
+ total: number;
127
+ }
128
+ export interface LlmOperateResponse {
129
+ content?: string;
130
+ error?: LlmError;
131
+ history: LlmHistory;
132
+ output: LlmOutput;
133
+ responses: JsonReturn[];
134
+ status: LlmResponseStatus;
135
+ usage: LlmUsage;
136
+ }
33
137
  export interface LlmProvider {
34
- operate?(input: string, options?: LlmOperateOptions): Promise<unknown>;
138
+ operate?(input: string | LlmHistory | LlmInputMessage, options?: LlmOperateOptions): Promise<LlmOperateResponse>;
35
139
  send(message: string, options?: LlmMessageOptions): Promise<string | JsonObject>;
36
140
  }
141
+ export {};