import { JSONSchema, FromSchema } from 'json-schema-to-ts'; import { Narrow } from 'json-schema-to-ts/lib/types/type-utils'; type PrimitiveValue = bigint | boolean | null | number | string | symbol | undefined; type ObjectValue = PrimitiveValue | PlainObject | ObjectArray; interface PlainObject { [key: string]: ObjectValue; } interface ObjectArray extends Array { } interface Serializable { serialize?(): Record; deserialize?(): void; } type IChatMessageRole = "system" | "model" | "assistant" | "user" | "function" | "function_call"; interface IChatMessageContentDetailed { type: string; text?: string; image_url?: { url: string; }; } interface IChatMessageBase { role: IChatMessageRole; content: string | null | IChatMessageContentDetailed[]; } interface IChatUserMessage extends IChatMessageBase { role: Extract; content: string | IChatMessageContentDetailed[]; name?: string; } interface IChatFunctionMessage extends IChatMessageBase { id?: string; role: Extract; content: string; name: string; } interface IChatAssistantMessage extends IChatMessageBase { role: Extract; content: string; function_call?: undefined; } interface IChatFunctionCallMessage extends IChatMessageBase { role: Extract; content: null; function_call: { name: string; arguments: string; id?: string; }; } interface IChatSystemMessage extends IChatMessageBase { role: Extract; content: string; } interface IChatMessagesPlaceholder { role: "placeholder"; content: string; } type IPromptMessages = (IChatSystemMessage | IChatMessagesPlaceholder)[]; type IPromptChatMessages = (IChatUserMessage | IChatAssistantMessage | IChatFunctionCallMessage | IChatSystemMessage | IChatMessagesPlaceholder | IChatFunctionMessage)[]; type IChatMessage = IChatUserMessage | IChatAssistantMessage | IChatFunctionCallMessage | IChatSystemMessage | IChatFunctionMessage; type IChatMessages = IChatMessage[]; type OpenAIChatModelName = "gpt-3.5-turbo" | "gpt-3.5-turbo-0613" | "gpt-3.5-turbo-16k" | "gpt-4-0613" | "gpt-4" | "gpt-4o" | "gpt-4o-mini" | "gpt-4-0613" | "gpt-4-32k-0613" | `gpt-4${string}` | `gpt-3.5-turbo-${string}`; type OpenAIConversationModelName = "davinci" | "text-curie-001" | "text-babbage-001" | "text-ada-001"; type OpenAIEmbeddingModelName = "text-embedding-ada-002"; type OpenAIModelName = OpenAIChatModelName | OpenAIConversationModelName | OpenAIEmbeddingModelName; /** * BaseParser is an abstract class for parsing text and enforcing JSON schema on the parsed data. */ declare abstract class BaseParser { name: string; target: "text" | "function_call"; /** * Create a new BaseParser. * @param name - The name of the parser. * @param target - Whether the parser consumes text or function-call output. */ constructor(name: string, target?: "text" | "function_call"); /** * Parse the given text and return the parsed data. * @abstract * @param text - The text to parse. * @param [attributes] - Optional attributes to use during parsing. * @returns The parsed data. */ abstract parse(text: TInput, attributes?: Record): T; } declare abstract class BaseParserWithJson : Record, TInput = string> extends BaseParser { schema: S; validateSchema: boolean; constructor(name: string, options: ParserSchemaOptions); } /** * v3 parser contract: * Category: pass-through * Mode: string pass-through * * Accepts any string and returns it exactly. * Throws LlmExeError(parser.parse_failed) for non-string input. * Executor output normalization owns OutputResult handling before parser * invocation. * */ declare class StringParser extends BaseParser { constructor(); parse(text: string, _attributes?: Record): string; } type BooleanParserMatch = "exact" | "extract"; interface BooleanParserOptions { match?: BooleanParserMatch; } /** * v3 parser contract: * Category: strict * Mode: exact * * Accepts only documented boolean literals after trim/lowercase. * Returns true/false only when input is recognized. Pass match: "extract" to * extract one documented boolean literal from surrounding text. * Throws LlmExeError(parser.parse_failed) for empty or unrecognized input. * Invalid input types throw LlmExeError(parser.invalid_input). * Error context does not include input content unless LLM_EXE_DEBUG is enabled. * */ declare class BooleanParser extends BaseParser { private match; constructor(options?: BooleanParserOptions); private getInputErrorContext; parse(text: string, _attributes?: Record): boolean; } type NumberParserMatch = "exact" | "extract"; interface NumberParserOptions { match?: NumberParserMatch; } /** * v3 parser contract: * Category: extractor * Mode: numeric token extraction * * Extracts one documented numeric token from text. Pass match: "exact" to * require the input to consist of exactly one numeric token (after trim) with * no surrounding prose. * * Throws LlmExeError(parser.parse_failed) for empty input, no numeric token, * multiple numeric tokens, invalid conversion. Invalid input type throws * LlmExeError(parser.invalid_input). */ declare class NumberParser extends BaseParser { private match; constructor(options?: NumberParserOptions); parse(text: string, _attributes?: Record): number; } type JsonParserInput = string | Record | unknown[]; type JsonParserOutput = S extends JSONSchema ? FromSchema : Record; declare class JsonParser extends BaseParserWithJson, JsonParserInput> { private shouldValidateSchema; private match; constructor(options?: JsonParserOptions); /** * v3 parser contract: * Category: strict * Mode: exact * * Parses strict JSON object/array output by default. Pass match: "extract" * to extract one JSON object or array from surrounding text. Invalid JSON, * empty input, JSON primitives, and non-plain runtime objects throw typed parser errors. * Schema validation is on by default when a schema is provided unless * validateSchema: false is explicitly set. * */ parse(text: JsonParserInput, _attributes?: Record): JsonParserOutput; } declare class ListToJsonParser extends BaseParserWithJson { private keyTransform; private shouldValidateSchema; constructor(options?: ListToJsonParserOptions); /** * v3 parser contract: * Category: converter * Mode: line-oriented format conversion * * Uses the shared list boundary. Parses normalized lines as key/value pairs * split at the first colon. Duplicate keys throw because object output would * overwrite data. * */ parse(text: string): ParserOutput>; } interface ListToKeyValueParserOptions { keyTransform?: "preserve" | "camelCase"; } declare class ListToKeyValueParser extends BaseParser> { private keyTransform; constructor(options?: ListToKeyValueParserOptions); /** * v3 parser contract: * Category: converter * Mode: line-oriented collector * * Uses the shared list boundary. Parses normalized lines as key/value pairs * split at the first colon. Preserves duplicate keys because output is an * ordered array. Keys are returned as written by default; pass * keyTransform: "camelCase" to match listToJson's key normalization. * */ parse(text: string, _attributes?: Record): { key: string; value: string; }[]; } /** * CustomParser class, extending the BaseParser class. * @template O The type of the parsed value (output) * @extends {BaseParser} * * v3 parser contract: * Category: pass-through extension point * Mode: user-defined * * Calls the user parser function with text and the per-call ExecutionContext. * Returns the user parser result exactly. * Does not wrap user parser errors. * * When invoked through an executor, `context` includes the resolved trace ID, * stable executor metadata, current execution metadata, and the attributes * extension bag. When parse() is called directly without a context, callers * may pass any shape they want; the type widens to allow that. */ declare class CustomParser extends BaseParser { parserFn: (text: string, context: ExecutionContext) => O; constructor(name: string, parserFn: (text: string, context: ExecutionContext) => O); parse(text: string, context?: ExecutionContext): O; } /** * v3 parser contract: * Category: converter * Mode: line-oriented collection conversion * * Uses the shared list boundary. Returns normalized item text exactly. * Throws for empty input, invalid input type, mixed marked/unmarked lines, or * a single unmarked prose line. * */ declare class ListToArrayParser extends BaseParser { constructor(); parse(text: string, _attributes?: Record): string[]; } /** * v3 parser contract: * Category: pass-through transformation * Mode: template replacement * * Accepts a string template and optional attributes object. * Returns the helper replacement result. * Throws LlmExeError(parser.parse_failed) for invalid input type, * invalid attributes, or template helper failures. * */ declare class ReplaceStringTemplateParser extends BaseParser { constructor(); parse(text: string, attributes?: Record): string; } /** * v3 parser contract: * Category: strict * Mode: singular fenced block * * Accepts input containing exactly one complete fenced markdown code block. * Returns that block with exact code content and language string. * Throws LlmExeError(parser.parse_failed) for empty input, no block, multiple * blocks, malformed fences, or invalid input type. * */ declare class MarkdownCodeBlockParser extends BaseParser<{ language: string; code: string; }> { constructor(); parse(input: string, _attributes?: Record): { code: string; language: string; }; } /** * v3 parser contract: * Category: collector * Mode: markdown fenced block collection * * Accepts text containing zero or more complete fenced code blocks. * Returns all complete blocks in source order. * Returns [] when no complete block exists. * Throws LlmExeError(parser.parse_failed) for invalid input type or malformed * fence structure. Does not unwrap stringified JSON. * */ declare class MarkdownCodeBlocksParser extends BaseParser<{ language: string; code: string; }[]> { constructor(); parse(input: string, _attributes?: Record): { code: string; language: string; }[]; } type StringExtractMatch = "exact" | "word" | "substring"; interface StringExtractParserOptions { enum: E; ignoreCase?: boolean; match?: StringExtractMatch; } declare class StringExtractParser extends BaseParser { private enum; private ignoreCase; private match; constructor(options?: StringExtractParserOptions); /** * v3 parser contract: * Category: extractor * Mode: configured value extraction * * Returns the single configured enum value found in input. Matching is * word-bounded by default; pass match: "exact" to require exact input or * match: "substring" for legacy contains() behavior. Case-insensitive by * default. * */ parse(text: string, _attributes?: Record): E[number]; private findMatches; private matchExact; private matchSubstring; private matchWord; } /** * Labeled-tuple union for `createParser` arguments. Each branch enumerates * exactly what's valid for one parser type. TypeScript validates the whole * argument tuple against this union, which produces useful error messages * (e.g. "Source has 1 element(s) but target requires 2" when stringExtract * is called without options) instead of overload-resolution mystery. */ type CreateParserArgs = [type: "string", options?: never] | [type: "boolean", options?: BooleanParserOptions] | [type: "listToArray", options?: never] | [type: "markdownCodeBlock", options?: never] | [type: "markdownCodeBlocks", options?: never] | [type: "replaceStringTemplate", options?: never] | [type: "number", options?: NumberParserOptions] | [type: "listToKeyValue", options?: ListToKeyValueParserOptions] | [type: "json", options?: JsonParserOptions] | [ type: "listToJson", options?: ListToJsonParserOptions ] | [ type: "stringExtract", options: StringExtractParserOptions ]; /** * Maps a concrete argument tuple back to the parser instance type, preserving * schema inference for json/listToJson and enum literal narrowing for * stringExtract. */ type CreateParserReturn = A extends readonly ["string", ...unknown[]] ? StringParser : A extends readonly ["boolean", ...unknown[]] ? BooleanParser : A extends readonly ["number", ...unknown[]] ? NumberParser : A extends readonly ["listToArray", ...unknown[]] ? ListToArrayParser : A extends readonly ["listToKeyValue", ...unknown[]] ? ListToKeyValueParser : A extends readonly ["markdownCodeBlock", ...unknown[]] ? MarkdownCodeBlockParser : A extends readonly ["markdownCodeBlocks", ...unknown[]] ? MarkdownCodeBlocksParser : A extends readonly ["replaceStringTemplate", ...unknown[]] ? ReplaceStringTemplateParser : A extends readonly ["json"] | readonly ["json", undefined] ? JsonParser : A extends readonly ["json", JsonParserOptions] ? JsonParser : A extends readonly ["listToJson"] | readonly ["listToJson", undefined] ? ListToJsonParser : A extends readonly [ "listToJson", ListToJsonParserOptions ] ? ListToJsonParser : A extends readonly [ "stringExtract", StringExtractParserOptions ] ? StringExtractParser : never; declare function createParser(...args: A): CreateParserReturn; declare function createCustomParser(name: string, parserFn: (text: string, context: ExecutionContext) => O): CustomParser>; interface LlmNativeFunctionParserOptions> { parser: T; } declare class LlmFunctionParser> extends BaseParser | OutputResultContent[], OutputResult | string> { parser: T; constructor(options: LlmNativeFunctionParserOptions); parse(text: OutputResult, _options?: Record): ParserOutput | OutputResultContent[]; } /** * @deprecated Use `LlmFunctionParser` instead. */ declare class LlmNativeFunctionParser> extends BaseParser | { name: any; arguments: any; }, OutputResult | string> { parser: T; constructor(options: LlmNativeFunctionParserOptions); parse(text: OutputResult, _options?: Record): ParserOutput | { name: string; arguments: any; }; } /** * @deprecated Use `LlmExecutorWithFunctions` instead. */ declare const OpenAiFunctionParser: typeof LlmNativeFunctionParser; declare function replaceTemplateString(templateString?: string, substitutions?: Record, configuration?: PromptTemplateOptions): string; declare function replaceTemplateStringAsync(templateString?: string, substitutions?: Record, configuration?: PromptTemplateOptions): Promise; /** * BasePrompt should be extended. */ declare abstract class BasePrompt> { readonly type: PromptType; messages: IPromptMessages | IPromptChatMessages; partials: PromptPartial[]; helpers: PromptHelper[]; validateInput: ValidateInputMode; replaceTemplateString: typeof replaceTemplateString; replaceTemplateStringAsync: typeof replaceTemplateStringAsync; filters: { pre: ((prompt: string) => string)[]; post: ((prompt: string) => string)[]; }; /** * constructor description * @param initialPromptMessage An initial message to add to the prompt. */ constructor(initialPromptMessage?: string, options?: PromptOptions); /** * addToPrompt description * @param content The message content * @param role The role of the user. Defaults to system for base text prompt. * @return instance of BasePrompt. */ addToPrompt(content: string, role?: string): BasePrompt; /** * addSystemMessage description * @param content The message content * @return returns BasePrompt so it can be chained. */ addSystemMessage(content: string): this; /** * registerPartial description * @param partialOrPartials Additional partials that can be made available to the template parser. * @return BasePrompt so it can be chained. */ registerPartial(partialOrPartials: PromptPartial | PromptPartial[]): this; /** * registerHelpers description * @param helperOrHelpers Additional helper functions that can be made available to the template parser. * @return BasePrompt so it can be chained. */ registerHelpers(helperOrHelpers: PromptHelper | PromptHelper[]): this; /** * Returns the Handlebars-bearing strings that should be validated, along * with a location label used for error context. Subclasses with structured * message content (e.g. ChatPrompt) should override. */ protected getTemplateContents(): { content: string; location: string; }[]; protected preflightValidate(values: I): void; /** * format description * @param values The message content * @param separator The separator between messages. defaults to "\n\n" * @return returns messages formatted with template replacement */ format(values: I, separator?: string): string | IChatMessages; /** * format description * @param values The message content * @param separator The separator between messages. defaults to "\n\n" * @return returns messages formatted with template replacement */ formatAsync(values: I, separator?: string): Promise; runPromptFilter(prompt: string, filters: ((prompt: string, values: I) => string)[], values: I): string; getReplacements(values: I): Omit & { input: any; _input: any; }; /** * Validates that `input` provides every variable referenced by this prompt's * templates, and that every identifiable helper call is registered. * * @breaking v3: previously returned `this.messages.length > 0` with no * `input` parameter. For the old behavior, read `prompt.messages.length > 0` * directly. * * @throws LlmExeError with code `"prompt.missing_template_variable"` listing * all missing variables and helpers. */ validate(input: I): void; } /** * `TextPrompt` provides a standard text-based prompt. * The text prompt can be used with models such as davinci. * @extends BasePrompt */ declare class TextPrompt> extends BasePrompt { constructor(base?: string, options?: PromptOptions); } interface ChatPrompt> extends BasePrompt { messages: IPromptChatMessages; } /** * `ChatPrompt` provides a conversation-style prompt enabling various roles. * The chat prompt can be used with models such as gpt-3.5.turbo and gpt-4+. * @extends BasePrompt */ declare class ChatPrompt> extends BasePrompt { /** * @property type - Prompt type (chat) */ readonly type: ChatPromptType; /** * @property parseUserTemplates - Whether or not to allow parsing * user messages with the template engine. Defaults to true. * Set `allowUnsafeUserTemplate: false` in options to disable. */ private parseUserTemplates; /** * new `ChatPrompt` * @param initialSystemPromptMessage (optional) An initial system message to add to the new prompt. * @param options (optional) Options to pass in when creating the prompt. */ constructor(initialSystemPromptMessage?: string, options?: ChatPromptOptions); /** * addToPrompt Adds a message to the prompt based on role. * @param content The message content. * @param role The role of the chat user. Must be one of: assistant, system, user. * @param name (optional) The name of the user. Only accepted if role is `user`. * @return instance of ChatPrompt. */ addToPrompt(content: string, role: Extract, name?: undefined): ChatPrompt; addToPrompt(content: string, role: Extract, name?: undefined): ChatPrompt; addToPrompt(content: string, role: Extract, name?: string): ChatPrompt; addToPrompt(content: string, role: Extract, name: string): ChatPrompt; addToPrompt(content: string, role: Extract, name: string): ChatPrompt; /** * addUserMessage Helper to add a user message to the prompt. * @param content The message content. * @param name (optional) The name of the user. * @return instance of ChatPrompt. */ addUserMessage(content: string | IChatMessageContentDetailed[], name?: string): ChatPrompt; /** * addAssistantMessage Helper to add an assistant message to the prompt. * @param content The message content. * @return ChatPrompt so it can be chained. */ addAssistantMessage(content: string): ChatPrompt; /** * addFunctionMessage Helper to add a function message to the prompt. * @param content The message content. * @return ChatPrompt so it can be chained. */ addFunctionMessage(content: string, name: string, id?: string): ChatPrompt; /** * addFunctionCallMessage Helper to add a function_call message to the prompt. * @param content The message content. * @return ChatPrompt so it can be chained. */ addFunctionCallMessage(function_call?: { name: string; arguments: string; id?: string; }): this; /** * addFromHistory Adds multiple messages at one time. * @param history History of chat messages. * @return ChatPrompt so it can be chained. */ addFromHistory(history: IChatMessages): ChatPrompt; /** * addPlaceholder description * @param content The message content * @return returns ChatPrompt so it can be chained. */ addChatHistoryPlaceholder(key: keyof I, options?: { assistant?: string; user?: string; }): ChatPrompt; /** * addTokenPlaceholder description * @param content The message content * @return returns ChatPrompt so it can be chained. */ addMessagePlaceholder(content: string, role?: IChatMessageRole, name?: string): this; private _format_placeholderDialogueHistory; /** * format formats the stored prompt based on input values. * Uses template engine. * Output is intended for LLM. * @param values input values. * @return formatted prompt. */ format(values: I): IChatMessages; /** * format formats the stored prompt based on input values. * Uses template engine. * Output is intended for LLM. * @param values input values. * @return formatted prompt. */ formatAsync(values: I): Promise; } type TextPromptType = "text"; type ChatPromptType = "chat"; type PromptType = TextPromptType | ChatPromptType; type PromptHelper = { name: string; handler: (args: any) => any; }; type PromptPartial = { name: string; template: string; }; type ValidateInputMode = false | "strict" | "warn"; interface PromptTemplateOptions { partials?: PromptPartial[]; helpers?: PromptHelper[]; } interface PromptOptions extends PromptTemplateOptions { preFilters?: ((prompt: string) => string)[]; postFilters?: ((prompt: string) => string)[]; replaceTemplateString?: (...args: any[]) => string; /** * Controls whether `format()` preflights input against the variables * referenced by the prompt's templates. See `validate(input)`. * * - `false` (default): no preflight; rendering proceeds. * - `"strict"`: throw `LlmExeError("prompt.missing_template_variable")` before rendering. * - `"warn"`: emit a Node warning via `process.emitWarning` and continue rendering. */ validateInput?: ValidateInputMode; } interface ChatPromptOptions extends PromptOptions { allowUnsafeUserTemplate?: boolean; } /** * `createPrompt` Creates a new instance of a prompt. * * @param type Define whether using chat or string prompt * @param initialPromptMessage (optional) A message to use for an initial system message. */ declare function createPrompt>(type: Extract, initialPromptMessage?: string, options?: PromptOptions): TextPrompt; declare function createPrompt>(type: Extract, initialPromptMessage?: string, options?: ChatPromptOptions): ChatPrompt; declare function createPrompt>(type?: PromptType, initialPromptMessage?: string, options?: PromptOptions | ChatPromptOptions): TextPrompt; /** * `createChatPrompt` Creates a new instance of a chat prompt. * * @param initialSystemPromptMessage (optional) A message to use for an initial system message. */ declare function createChatPrompt>(initialSystemPromptMessage?: string, options?: ChatPromptOptions): ChatPrompt; /** * BaseExecutor * @template I - Input type. * @template O - Output type. * @template H - Hooks type. */ declare abstract class BaseExecutor { /** * @property id - internal id of the executor */ readonly id: string; /** * @property type - type of executor */ type: string; /** * @property created - timestamp date created */ readonly created: number; /** * @property name - name of executor */ name: string; /** * @property executions - */ executions: number; traceId: string | null; /** * @property hooks - hooks to be ran during execution */ hooks: any; readonly allowedHooks: any[]; /** * @property maxHooksPerEvent - Maximum number of hooks allowed per event */ readonly maxHooksPerEvent: number; constructor(name: string, type: string, options?: CoreExecutorExecuteOptions); abstract handler(input: I, _options?: any, _context?: ExecutionContext): Promise; /** * Build a per-call execution context snapshot. Captures the current * execution metadata so the snapshot reflects state at the time it was * taken (e.g. `handlerInput` becomes available after `getHandlerInput`). */ protected snapshotContext(execution: ExecutorExecutionMetadata): ExecutionContext; /** * * Used to filter the input of the handler. * * Throws a `TypeError` if `_input` is `null` or `undefined`. The declared * input type is `I extends PlainObject`; omitting input or passing an * explicit `null` is a contract violation with no valid coercion, so we * surface it loudly rather than silently wrapping it. * * Non-object inputs (strings, numbers, arrays) are intentionally coerced * to `{ input: value }` via {@link ensureInputIsObject}. This preserves the * convenience pattern used by tool/function callables, which forward raw * string arguments into an executor. * * @param _input * @returns original input formatted for handler */ getHandlerInput(_input: I, _metadata: ExecutorExecutionMetadata, _options?: any): Promise; /** * * Used to filter the output of the handler * @param _input * @returns output O */ getHandlerOutput(out: any, _metadata: ExecutorExecutionMetadata, _options?: any, _context?: ExecutionContext): O; /** * * execute - Runs the executor * @param _input * @returns handler output */ execute(_input: I, _options?: any): Promise; private collectHookErrors; metadata(): Record; getMetadata(metadata?: Record): ExecutorMetadata; runHook(hook: keyof H, _metadata: ExecutorExecutionMetadata): HookErrorRecord[]; setHooks(hooks?: CoreExecutorHookInput): this; removeHook(eventName: keyof H, fn: ListenerFunction): this; on(eventName: keyof H, fn: ListenerFunction): this; off(eventName: keyof H, fn: ListenerFunction): this; once(eventName: keyof H, fn: ListenerFunction): this; withTraceId(traceId: string): this; getTraceId(): string | null; /** * Clear all hooks for a specific event or all events * Useful for preventing memory leaks in long-running processes * @param eventName - The event name to clear hooks for */ clearHooks(eventName?: keyof H): this; /** * Get the count of hooks for monitoring memory usage * @param eventName - Optional event name to get count for * @returns Hook count for specific event or all events */ getHookCount(eventName?: keyof H): number | Record; } /** * Core Function Executor */ declare class CoreExecutor extends BaseExecutor { _handler: (input: I) => Promise | any; constructor(fn: CoreExecutorInput, options?: CoreExecutorExecuteOptions); handler(_input: I): Promise; } declare abstract class BaseStateItem implements Serializable { protected key: string; protected value: T; protected initialValue: T; constructor(key: string, initialValue: T); setValue(value: T): void; getKey(): string; getValue(): T; resetValue(): void; serializeValue(): { [x: string]: T; }; serialize(): { class: string; name: string; value: any; }; } declare class DefaultStateItem extends BaseStateItem { constructor(name: string, defaultValue: any); } declare class Dialogue extends BaseStateItem { name: string; constructor(name: string); setUserMessage(content: string | IChatMessageContentDetailed[], name?: string): this; setAssistantMessage(content: string | OutputResultsText): this; setSystemMessage(content: string): this; setToolMessage(content: string, name: string, id?: string): this; setFunctionMessage(content: string, name: string, id?: string): this; /** * Set */ setToolCallMessage(input: { name: string; arguments: string; id?: string; }): this; setFunctionCallMessage(input: { name: string; arguments: string; id?: string; } | { function_call: { name: string; arguments: string; id?: string; }; }): this; setMessageTurn(userMessage: string, assistantMessage: string, systemMessage?: string): this; /** * Aliases using `add*` naming to match ChatPrompt's API. * These delegate to the corresponding `set*` methods. */ addUserMessage(content: string | IChatMessageContentDetailed[], name?: string): this; addAssistantMessage(content: string | OutputResultsText): this; addSystemMessage(content: string): this; addToolMessage(content: string, name: string, id?: string): this; addToolCallMessage(input: { name: string; arguments: string; id?: string; }): this; addFunctionMessage(content: string, name: string, id?: string): this; addFunctionCallMessage(input: { name: string; arguments: string; id?: string; } | { function_call: { name: string; arguments: string; id?: string; }; }): this; addMessageTurn(userMessage: string, assistantMessage: string, systemMessage?: string): this; addHistory(messages: IChatMessages): this; setHistory(messages: IChatMessages): this; getHistory(): IChatMessages; serialize(): { class: string; name: string; value: IChatMessage[]; }; /** * Add LLM output to dialogue history in the order it was returned * * @param output - The LLM output result from llm.call() * @returns this for chaining */ addFromOutput(output: OutputResult | BaseLlCall): this; } declare abstract class BaseState { dialogues: { [key in string]: Dialogue; }; attributes: Record; context: Record>; constructor(); createDialogue(name?: string): Dialogue; useDialogue(name?: string): Dialogue; getDialogue(name?: string): Dialogue; createContextItem>(item: T): T; getContext(key: string): BaseStateItem; getContextValue(key: string): T; setAttribute(key: string, value: any): void; deleteAttribute(key: string): void; clearAttributes(): void; serialize(): { dialogues: any; context: any; attributes: any; }; abstract saveState(): Promise; } declare class DefaultState extends BaseState { constructor(); saveState(): Promise; } declare function createState(): DefaultState; declare function createDialogue(name: string): Dialogue; declare function createStateItem(name: string, defaultValue: T): DefaultStateItem; /** * Core Executor With LLM */ declare class LlmExecutor, Prompt extends BasePrompt>, Parser extends BaseParser, State extends BaseState> extends BaseExecutor, ParserOutput, LlmExecutorHooks> { llm: Llm; prompt: Prompt | undefined; promptFn: any; parser: StringParser | Parser; constructor(llmConfiguration: ExecutorWithLlmOptions, options?: CoreExecutorExecuteOptions); /** * Runs the executor against the configured LLM and prompt. * * `null` and `undefined` are rejected with a `TypeError`: the declared * input type requires an object, and silently coercing missing input hides a * clear contract violation. Use `{}` for prompts that declare no template * variables. See issue #410. */ execute(_input: PromptInput, _options?: LlmExecutorExecuteOptions): Promise>; handler(_input: PromptInput, _options?: LlmExecutorExecuteOptions, _context?: ExecutionContext, ParserOutput>): Promise; getHandlerInput(_input: PromptInput): Promise; getHandlerOutput(out: BaseLlCall, _metadata: ExecutorExecutionMetadata, ParserOutput>, _options?: LlmExecutorExecuteOptions, _context?: ExecutionContext, ParserOutput>): ParserOutput; metadata(): { llm: Record; }; getTraceId(): string | null; } /** * Core Executor With LLM */ declare class LlmExecutorWithFunctions>, Parser extends BaseParser, State extends BaseState = BaseState> extends LlmExecutor, State> { constructor(llmConfiguration: ExecutorWithLlmOptions, options?: CoreExecutorExecuteOptions); execute(_input: PromptInput, _options: LlmExecutorWithFunctionsOptions): Promise>; } /** * @deprecated Use `LlmExecutorWithFunctions` instead. */ declare class LlmExecutorOpenAiFunctions>, Parser extends BaseParser, State extends BaseState = BaseState> extends LlmExecutor, State> { constructor(llmConfiguration: ExecutorWithLlmOptions, options?: CoreExecutorExecuteOptions); execute(_input: PromptInput, _options: LlmExecutorWithFunctionsOptions): Promise | { name: string; arguments: any; }>; } /** * Function to create a core executor. * @template I - Input type. * @template O - Output type. * @param handler - The handler function. * @returns - A new CoreExecutor instance. */ declare function createCoreExecutor(handler: (input: I) => Promise | O, options?: CoreExecutorExecuteOptions): CoreExecutor; /** * Function to create a core executor with Llm. * @template Llm - Llm type. * @template Prompt - Prompt type. * @template Parser - Parser type. * @template State - State type. * @param options - Options for BaseExecutorV3. * @returns - A new LlmExecutor instance. */ declare function createLlmExecutor, Prompt extends BasePrompt, Parser extends BaseParser, State extends BaseState>(llmConfiguration: ExecutorWithLlmOptions, options?: CoreExecutorExecuteOptions): LlmExecutor; declare function createLlmFunctionExecutor>, Parser extends BaseParser, State extends BaseState>(llmConfiguration: ExecutorWithLlmOptions, options?: CoreExecutorExecuteOptions): LlmExecutorWithFunctions; declare const hookOnComplete = "onComplete"; declare const hookOnError = "onError"; declare const hookOnSuccess = "onSuccess"; type ListenerFunction = (...args: any[]) => void; type ParserOutput

= P extends BaseParser ? T : never; type PromptInput

= P extends BasePrompt ? T : never; interface ExecutorWithLlmOptions { name?: string; llm: Llm; prompt: Prompt | ((values: PromptInput) => Prompt); parser?: Parser; state?: State; __mock_response_key__?: string; } interface CoreExecutorInput { name?: string; handler: (input: I) => Promise | O; getHandlerInput?(input: I): Promise; getHandlerOutput?(out: any): O; } type FunctionOrExecutor = ((input: I) => Promise | O) | BaseExecutor; interface ExecutorMetadata { id: string; type: string; name: string; created: number; executions: number; metadata?: Record; } interface HookErrorRecord { hook: string; error: unknown; errorMessage: string; errorCategory?: string; errorCode?: string; errorContext?: unknown; errorCause?: unknown; } interface ExecutorExecutionMetadata { start: null | number; end: null | number; input: I; handlerInput?: any; handlerOutput?: any; output?: O; errorMessage?: string; error?: Error; errorCategory?: string; errorCode?: string; errorContext?: unknown; errorCause?: unknown; hookErrors?: HookErrorRecord[]; metadata?: null | ExecutorMetadata; } interface ExecutorContext> extends ExecutorExecutionMetadata { metadata: ExecutorMetadata; attributes: A; } /** * Per-call execution context. Built by `BaseExecutor.execute()` and threaded * through `handler()`, `llm.call()`, parsers, and warnings. Provides a single * place to read the resolved trace ID, stable executor identity, and the * mutable execution state for the current run. */ interface ExecutionContext> { traceId?: string; executor: ExecutorMetadata; execution: ExecutorExecutionMetadata; attributes: A; } interface BaseExecutorHooks { [hookOnError]: ListenerFunction[]; [hookOnSuccess]: ListenerFunction[]; [hookOnComplete]: ListenerFunction[]; } interface LlmExecutorHooks extends BaseExecutorHooks { } type CoreExecutorHookInput = { [key in keyof H]?: ListenerFunction | ListenerFunction[]; }; interface CoreExecutorExecuteOptions { hooks?: CoreExecutorHookInput; } interface CallableExecutorCore { name: string; description: string; parameters?: Record; } interface LlmExecutorExecuteOptions { functions?: CallableExecutorCore[]; functionCall?: any; jsonSchema?: Record; } type GenericFunctionCall = "auto" | "none" | "any" | { name: string; }; interface LlmExecutorWithFunctionsOptions extends LlmExecutorExecuteOptions { functions?: CallableExecutorCore[]; functionCall?: T; functionCallStrictInput?: boolean; jsonSchema?: Record; } interface ParserSchemaOptions { schema?: S; validateSchema?: boolean; } type JsonParserMatch = "exact" | "extract"; interface JsonParserOptions extends ParserSchemaOptions { match?: JsonParserMatch; } interface ListToJsonParserOptions extends ParserSchemaOptions { keyTransform?: "camelCase" | "preserve"; } /** * Internal Formats */ interface OutputResultsBase { type: "text" | "function_use"; text?: string; } interface OutputResultsText extends OutputResultsBase { type: "text"; text: string; } interface OutputResultsFunction extends OutputResultsBase { type: "function_use"; name: string; input: Record; functionId: string; } type OutputResultContent = OutputResultsText | OutputResultsFunction; interface OutputResult { id: string; name?: string; created: number; stopReason: string; content: OutputResultContent[]; options?: OutputResultContent[][]; usage: { input_tokens: number; output_tokens: number; total_tokens: number; }; } interface EmbeddingOutputResult { id: string; model?: string; created: number; embedding: number[][]; usage: { input_tokens: number; output_tokens: number; total_tokens: number; }; } interface BaseLlmOptions { traceId?: null | string; timeout?: number; maxDelay?: number; numOfAttempts?: number; jitter?: "none" | "full"; promptType?: PromptType; endpoint?: string; headers?: Record; } interface GenericEmbeddingOptions extends BaseLlmOptions { model?: string; dimensions?: number; } interface OpenAiEmbeddingOptions extends GenericEmbeddingOptions { model?: string; openAiApiKey?: string; baseUrl?: string; } interface AmazonEmbeddingOptions extends GenericEmbeddingOptions { model: string; awsRegion?: string; awsSecretKey?: string; awsAccessKey?: string; } interface CohereBedrockEmbeddingOptions extends AmazonEmbeddingOptions { inputType?: "search_document" | "search_query" | "classification" | "clustering"; truncate?: "NONE" | "START" | "END" | "LEFT" | "RIGHT"; } interface GenericLLm extends BaseLlmOptions { model?: string; system?: string; prompt?: string | { role: string; content: string; }[]; temperature?: number; topP?: number; stream?: boolean; streamOptions?: Record; maxTokens?: number; stopSequences?: string[]; effort?: "minimal" | "low" | "medium" | "high"; } interface OpenAiRequest extends GenericLLm { model: string; frequencyPenalty?: number; logitBias?: Record | null; responseFormat?: Record; openAiApiKey?: string; useJson?: boolean; } interface XAiRequest extends GenericLLm { model: string; frequencyPenalty?: number; logitBias?: Record | null; responseFormat?: Record; xAiApiKey?: string; useJson?: boolean; } interface AmazonBedrockRequest extends GenericLLm { model: string; awsRegion?: string; awsSecretKey?: string; awsAccessKey?: string; } interface AnthropicRequest extends GenericLLm { model: string; anthropicApiKey?: string; topK?: number; metadata?: { user_id?: string; }; serviceTier?: "auto" | "standard_only"; } interface GeminiRequest extends GenericLLm { model: string; geminiApiKey?: string; } interface DeepseekRequest extends GenericLLm { model: string; responseFormat?: Record; deepseekApiKey?: string; useJson?: boolean; } type AllEmbedding = { "openai.embedding.v1": { input: OpenAiEmbeddingOptions; }; "amazon.embedding.v1": { input: AmazonEmbeddingOptions; }; "amazon:cohere.embedding.v1": { input: CohereBedrockEmbeddingOptions; }; }; type AllLlm = { "openai.chat.v1": { input: OpenAiRequest; }; "openai.chat-mock.v1": { input: OpenAiRequest; }; "anthropic.chat.v1": { input: AnthropicRequest; }; "amazon:anthropic.chat.v1": { input: AnthropicRequest & AmazonBedrockRequest; }; "amazon:meta.chat.v1": { input: AmazonBedrockRequest; }; "xai.chat.v1": { input: XAiRequest; }; "ollama.chat.v1": { input: GenericLLm; }; "google.chat.v1": { input: GeminiRequest; }; "deepseek.chat.v1": { input: DeepseekRequest; }; }; type AllUseLlmOptions = AllLlm & { "openai.gpt-5.2": { input: Omit; }; "openai.gpt-5-mini": { input: Omit; }; "openai.gpt-5-nano": { input: Omit; }; "openai.gpt-4.1": { input: Omit; }; "openai.gpt-4.1-mini": { input: Omit; }; "openai.gpt-4.1-nano": { input: Omit; }; "openai.o3": { input: Omit; }; "openai.gpt-4": { input: Omit; }; "openai.gpt-4o": { input: Omit; }; "openai.gpt-4o-mini": { input: Omit; }; "openai.o4-mini": { input: Omit; }; "anthropic.claude-opus-4-8": { input: Omit; }; "anthropic.claude-opus-4-7": { input: Omit; }; "anthropic.claude-sonnet-4-6": { input: Omit; }; "anthropic.claude-opus-4-5": { input: Omit; }; "anthropic.claude-haiku-4-5": { input: Omit; }; "anthropic.claude-sonnet-4-5": { input: Omit; }; "anthropic.claude-opus-4-6": { input: Omit; }; "anthropic.claude-opus-4-1": { input: Omit; }; "anthropic.claude-sonnet-4-0": { input: Omit; }; "anthropic.claude-opus-4-0": { input: Omit; }; "anthropic.claude-sonnet-4": { input: Omit; }; "anthropic.claude-opus-4": { input: Omit; }; "anthropic.claude-3-7-sonnet": { input: Omit; }; "anthropic.claude-3-5-sonnet": { input: Omit; }; "anthropic.claude-3-5-haiku": { input: Omit; }; "anthropic.claude-3-opus": { input: Omit; }; "google.gemini-2.5-flash": { input: Omit; }; "google.gemini-2.5-flash-lite": { input: Omit; }; "google.gemini-2.5-pro": { input: Omit; }; "google.gemini-3.1-flash-lite": { input: Omit; }; "google.gemini-3.5-flash": { input: Omit; }; "google.gemini-2.0-flash": { input: Omit; }; "google.gemini-2.0-flash-lite": { input: Omit; }; "google.gemini-1.5-pro": { input: Omit; }; "xai.grok-2": { input: Omit; }; "xai.grok-3": { input: Omit; }; "xai.grok-3-mini": { input: Omit; }; "xai.grok-4": { input: Omit; }; "xai.grok-4-fast": { input: Omit; }; "xai.grok-4-1-fast": { input: Omit; }; "xai.grok-4.3": { input: Omit; }; "xai.grok-4.20": { input: Omit; }; "xai.grok-4.20-reasoning": { input: Omit; }; "ollama.deepseek-r1": { input: GenericLLm; }; "ollama.llama3.3": { input: GenericLLm; }; "ollama.llama3.2": { input: GenericLLm; }; "ollama.llama3.1": { input: GenericLLm; }; "ollama.qwq": { input: GenericLLm; }; "ollama.gemma3": { input: GenericLLm; }; "ollama.mistral": { input: GenericLLm; }; "ollama.qwen2.5": { input: GenericLLm; }; "ollama.qwen3": { input: GenericLLm; }; "ollama.qwen3.5": { input: GenericLLm; }; "ollama.gemma4": { input: GenericLLm; }; "ollama.gpt-oss": { input: GenericLLm; }; "deepseek.chat": { input: DeepseekRequest; }; "deepseek.v4-flash": { input: Omit; }; "deepseek.v4-pro": { input: Omit; }; }; type LlmProviderKey = keyof AllLlm; type EmbeddingProviderKey = keyof AllEmbedding; type UseLlmKey = keyof AllUseLlmOptions; interface BaseLlCall { getResultContent: () => OutputResultContent[]; getResultText: () => string; getResult: () => OutputResult; } interface BaseRequest<_T extends Record> { call: (...args: any[]) => Promise<_T>; getTraceId: () => string | null; withTraceId: (traceId: string) => void; getMetadata: () => Record; } interface BaseLlm<_T extends BaseLlCall = BaseLlCall> extends BaseRequest<_T> { } type LlmProvider = "openai.chat" | "openai.embedding" | "google.embedding" | "openai.chat-mock" | "anthropic.chat" | "amazon:anthropic.chat" | "amazon:meta.chat" | "amazon:nova.chat" | "amazon.embedding" | "amazon:cohere.embedding" | "xai.chat" | "google.chat" | "ollama.chat" | "deepseek.chat"; interface Config { /** * Unique identifier for this configuration (e.g., "openai.chat.v1", "anthropic.claude-3-opus") * Used to reference this config when calling useLlm() */ key: Pk; /** * The provider type this config is for (e.g., "openai.chat", "anthropic.chat") * Used internally for provider-specific logic */ provider: LlmProvider; /** * HTTP method for the API request (typically "POST" for LLM providers) */ method: "POST" | "PUT" | "GET"; /** * API endpoint URL template. Supports template variables using {{variable}} syntax * Variables are replaced with values from the state object * @example "https://api.openai.com/v1/chat/completions" * @example "https://bedrock-runtime.{{awsRegion}}.amazonaws.com/model/{{model}}/invoke" */ endpoint: string; /** * HTTP headers template as a JSON string. Supports template variables using {{variable}} syntax * @example '{"Authorization":"Bearer {{openAiApiKey}}", "Content-Type": "application/json"}' * // TODO: make this also accept object and function */ headers: string; options: { [key in string]: { /** * Default value for this parameter if not provided by the user * Can be a static value or a function that returns the value * @example 4096 * @example () => process.env.OPENAI_API_KEY */ default?: any; /** * Whether this parameter is required * [true, "error message"] - Required with custom error * [true] - Required with default error message * @example [true, "maxTokens is required for Anthropic"] */ required?: [boolean, string] | [boolean]; }; }; mapBody: { [key in string]: { /** * The target field name in the provider's request body. * Supports dot notation for nested fields (e.g., "response_format.type") */ key: string; /** * Default value to use if the source field is not provided */ default?: any; /** * Transform function to convert the value before mapping to the request body * @param value - The input value from the user's state * @param state - The complete user state object containing all parameters * @param config - The current Config object (for access to options, etc.) * @returns The transformed value to be included in the request body */ transform?: (value: any, state: Record, config: Record) => any; }; }; /** * Maps executor-level options (jsonSchema, functions, functionCall) to provider-specific request formats * @optional - Only needed if provider supports these features */ mapOptions?: { /** * Transform JSON schema into provider-specific format * @param schema - The JSON schema object * @param options - Executor options (e.g., functionCallStrictInput) * @param currentInput - Current accumulated input state (for merging) * @param config - The full config object * @returns Provider-specific request body additions */ jsonSchema?: (schema: any, options: any, currentInput?: Record, config?: Config) => Record; /** * Transform function call mode into provider-specific format * @param call - Function call mode ("auto", "any", "none", or specific function) * @param options - Executor options * @param currentInput - Current accumulated input state (for merging) * @param config - The full config object * @returns Provider-specific request body additions */ functionCall?: (call: any, options?: any, currentInput?: Record, config?: Config) => Record; /** * Transform function definitions into provider-specific format * @param functions - Array of function definitions * @param options - Executor options (e.g., functionCallStrictInput) * @param currentInput - Current accumulated input state (for merging) * @param config - The full config object * @returns Provider-specific request body additions */ functions?: (functions: any[], options?: any, currentInput?: Record, config?: Config) => Record; }; /** * Optional response transformer for chat/LLM configs. The LLM call path * (`llm.call.ts`) defaults to `OutputDefault` when this is omitted. * Embedding configs do not use this — their flow dispatches via * `getEmbeddingOutputParser` instead. */ transformResponse?: (result: any, _config?: Config, headers?: Record) => OutputResult; /** * Marks this config as deprecated. When set, useLlm() will emit a one-time * deprecation warning to inform users about upcoming model shutdowns. */ deprecated?: { shorthand: string; message: string; }; } type JsonSafe = string | number | boolean | null | JsonSafe[] | { [key: string]: JsonSafe; }; type ErrorCategory = "unknown" | "configuration" | "llm" | "embedding" | "prompt" | "parser" | "executor" | "callable" | "state" | "request" | "auth" | "template" | "internal"; type BaseErrorContext = { operation?: string; provider?: string; model?: string; key?: string; input?: unknown; output?: unknown; response?: unknown; status?: number; url?: string; parser?: string; promptType?: string; functionName?: string; hook?: string; expected?: unknown; received?: unknown; resolution?: string; docsPath?: string; docsUrl?: string; }; type ConfigurationProviderContext = BaseErrorContext & { provider?: string; availableProviders?: string[]; }; type MissingConfigurationContext = BaseErrorContext & { provider?: string; key?: string; option?: string; envVar?: string; }; type InvalidHeadersContext = BaseErrorContext & { provider?: string; key?: string; headerTemplate?: string; replacedHeadersExcerpt?: string; }; type ParserInvalidTypeContext = BaseErrorContext & { parser?: unknown; availableParsers?: string[]; }; type ParserSchemaValidationContext = BaseErrorContext & { parser?: string; schemaErrors?: unknown; outputExcerpt?: string; }; type ParserParseFailedContext = BaseErrorContext & { parser?: string; reason?: string; inputExcerpt?: string; inputExcerptTruncated?: boolean; inputLength?: number; matchCount?: number; match?: string; outputExcerpt?: string; }; type PromptInputContext = BaseErrorContext & { promptType?: string; }; type PromptMessagesContext = BaseErrorContext & { provider?: string; }; type PromptMissingTemplateVariableContext = BaseErrorContext & { promptType?: string; missingVariables: string[]; missingHelpers: string[]; }; type NormalizedProviderError = { message?: string; providerType?: string; providerCode?: string; status?: number; statusText?: string; retryable?: boolean; retryAfterMs?: number; }; type ProviderErrorContext = BaseErrorContext & { provider?: string; model?: string; status?: number; statusText?: string; url?: string; providerError?: NormalizedProviderError; providerErrorBody?: unknown; providerErrorRaw?: string; responseHeaders?: Record; }; type ProviderResponseContext = BaseErrorContext & { provider?: string; model?: string; responseExcerpt?: string; lineNumber?: number; lineExcerpt?: string; lineCount?: number; availableProviders?: string[]; }; type EmbeddingDimensionsContext = BaseErrorContext & { provider?: string; model?: string; dimensions?: number; }; type ExecutorErrorContext = BaseErrorContext & { executorName?: string; executorType?: string; traceId?: string; }; type ExecutorHookContext = ExecutorErrorContext & { hook?: string; hookCount?: number; maxHooksPerEvent?: number; }; type CallableErrorContext = BaseErrorContext & { functionName?: string; availableFunctions?: string[]; }; type TemplateHelperContext = BaseErrorContext & { helper?: string; }; type StateErrorContext = BaseErrorContext & { module?: string; }; type AwsAuthContext = BaseErrorContext & { url?: string; regionName?: string; }; type RequestErrorContext = BaseErrorContext & { url?: string; status?: number; statusText?: string; providerError?: NormalizedProviderError; providerErrorBody?: unknown; providerErrorRaw?: string; responseHeaders?: Record; }; type InternalErrorContext = BaseErrorContext & { invariant?: string; }; type ErrorContextByCode = { "configuration.missing_provider": ConfigurationProviderContext; "configuration.invalid_provider": ConfigurationProviderContext; "configuration.missing_env": MissingConfigurationContext; "configuration.missing_option": MissingConfigurationContext; "configuration.invalid_headers": InvalidHeadersContext; "parser.invalid_type": ParserInvalidTypeContext; "parser.invalid_input": ParserParseFailedContext; "parser.parse_failed": ParserParseFailedContext; "parser.schema_validation_failed": ParserSchemaValidationContext; "prompt.missing_input": PromptInputContext; "prompt.invalid_messages": PromptMessagesContext; "prompt.missing_template_variable": PromptMissingTemplateVariableContext; "llm.provider_http_error": ProviderErrorContext; "llm.provider_rate_limited": ProviderErrorContext; "llm.provider_auth_failed": ProviderErrorContext; "llm.provider_invalid_request": ProviderErrorContext; "llm.provider_unavailable": ProviderErrorContext; "llm.invalid_response_shape": ProviderResponseContext; "llm.invalid_jsonl_response": ProviderResponseContext; "embedding.provider_http_error": ProviderErrorContext; "embedding.provider_rate_limited": ProviderErrorContext; "embedding.provider_auth_failed": ProviderErrorContext; "embedding.provider_invalid_request": ProviderErrorContext; "embedding.provider_unavailable": ProviderErrorContext; "embedding.missing_provider": ConfigurationProviderContext; "embedding.invalid_provider": ConfigurationProviderContext; "embedding.unsupported_dimensions": EmbeddingDimensionsContext; "embedding.invalid_response_shape": ProviderResponseContext; "executor.missing_prompt": ExecutorErrorContext; "executor.hook_limit_reached": ExecutorHookContext; "executor.hook_failed": ExecutorHookContext; "callable.invalid_handler": CallableErrorContext; "callable.handler_not_found": CallableErrorContext; "callable.validation_failed": CallableErrorContext; "template.invalid_helper_arguments": TemplateHelperContext; "state.invalid_arguments": StateErrorContext; "auth.aws_signing_input_missing": AwsAuthContext; "request.invalid_url": RequestErrorContext; "request.http_error": RequestErrorContext; "internal.invariant_failed": InternalErrorContext; "unknown.unclassified": Record; }; type ErrorCodes = keyof ErrorContextByCode; type CategoryFor = C extends `${infer Category}.${string}` ? Category & ErrorCategory : never; type SerializableCause = { name?: string; message?: string; category?: string; code?: string; context?: unknown; cause?: unknown; } | JsonSafe; type LlmExeErrorOptions = { code: C; context?: ErrorContextByCode[C]; cause?: unknown; }; type LlmExeErrorJson = { name: "LlmExeError"; message: string; category: CategoryFor; code: C; context?: ErrorContextByCode[C]; cause?: SerializableCause; truncated?: boolean; }; declare function enforceResultAttributes(input: any): { result: O; attributes: Record; }; /** * Represents the input for a CallableExecutor. * @interface CallableExecutorInput * @property name - The name of the callable function. * @property key - The key for the callable function. Defaults to the name if not provided. * @property description - A description of the callable function. * @property input - The input for the callable function. * @property visibilityHandler - An optional visibility handler for the callable function. * @property handler - An optional handler for the callable function. */ interface CallableExecutorInput extends CallableExecutorCore { name: string; description: string; key?: string; parameters?: Record; input: string; attributes?: Record; visibilityHandler?(input: I, context: any, attributes?: Record): boolean; handler?: FunctionOrExecutor; validateInput?(input: I, ...args: any[]): ReturnType> | Promise>>; } /** * Represents a CallableExecutor. * @interface CallableExecutor * @property name - The name of the callable core function. * @property key - The key for the callable core function. * @property description - A description of the callable core function. * @property input - The input for the callable core function. * @property visibilityHandler - The visibility handler for the callable core function. * @property - The handler for the callable core function. */ interface CallableExecutor extends CallableExecutorCore { key: string; attributes: Record; parameters: Record; input: string; _handler: BaseExecutor; visibilityHandler(input: any, attributes?: Record): boolean; _visibilityHandler?(input: any, context: any, attributes?: Record): boolean; validateInput(input: I): Promise>>; _validateInput?(input: I, context: any): ReturnType> | Promise>>; } /** * A class representing a CallableExecutor. * @class CallableExecutor */ declare class CallableExecutor { name: string; key: string; description: string; input: string; attributes: Record; parameters: Record; _handler: BaseExecutor; _validateInput?(input: I, context: any): ReturnType> | Promise>>; _visibilityHandler?(input: any, context: any, attributes?: Record): boolean; constructor(options: CallableExecutorInput); execute(input: I): Promise<{ result: O; attributes: any; }>; } declare abstract class UseExecutorsBase { handlers: CallableExecutor[]; constructor(handlers: CallableExecutor[]); hasFunction(name: string): boolean; getFunction(name: string): CallableExecutor | undefined; getFunctions(): CallableExecutor[]; getVisibleFunctions(_input: any, _attributes?: any): CallableExecutor[]; callFunction(name: string, input: string): Promise<{ result: any; attributes: any; }>; validateFunctionInput(name: string, input: string): Promise<{ result: boolean; attributes: any; }>; } /** * Creates a new CallableExecutor instance. * @function createCallableExecutor * @param options - The input options for the callable core function. * @returns A new CallableExecutor instance. */ declare function createCallableExecutor(options: CallableExecutorInput): CallableExecutor; declare class UseExecutors extends UseExecutorsBase { constructor(handlers: CallableExecutor[]); } declare function useExecutors(executors: [ ...(CallableExecutor | CallableExecutorInput)[] ]): UseExecutors; declare function assert(condition: any, message?: string | Error | undefined): asserts condition; declare function defineSchema(obj: Narrow): Narrow; declare const LLM_EXE_ERROR_SYMBOL: unique symbol; declare class LlmExeError extends Error { readonly name: "LlmExeError"; readonly isLlmExeError: true; readonly [LLM_EXE_ERROR_SYMBOL]: true; readonly category: CategoryFor; readonly code: C; readonly context?: ErrorContextByCode[C]; constructor(message: string, options: LlmExeErrorOptions); toJSON(): LlmExeErrorJson; } declare function isLlmExeError(error: unknown, code?: C | readonly C[]): error is LlmExeError; declare function importPartials(_partials: { [key in string]: string; }): PromptPartial[]; declare function importHelpers(_helpers: { [key in string]: (...args: any[]) => any; }): PromptHelper[]; declare function filterObjectOnSchema(schema: any, doc: any, detach?: any, property?: string): any; declare const asyncCallWithTimeout: (asyncPromise: Promise, timeLimit?: number) => Promise; declare function guessProviderFromModel(payload: { model: string; }): "openai" | "xai" | "bedrock:anthropic" | "anthropic"; declare const maybeStringifyJSON: (objOrMaybeString: any) => string; declare const maybeParseJSON: (objOrMaybeJSON: any) => Expected; declare function isObjectStringified(maybeObject: string): boolean; declare function registerHelpers(helpers: any[]): void; declare function registerPartials(partials: any[]): void; declare const index_LLM_EXE_ERROR_SYMBOL: typeof LLM_EXE_ERROR_SYMBOL; type index_LlmExeError = LlmExeError; declare const index_LlmExeError: typeof LlmExeError; declare const index_assert: typeof assert; declare const index_asyncCallWithTimeout: typeof asyncCallWithTimeout; declare const index_defineSchema: typeof defineSchema; declare const index_filterObjectOnSchema: typeof filterObjectOnSchema; declare const index_guessProviderFromModel: typeof guessProviderFromModel; declare const index_importHelpers: typeof importHelpers; declare const index_importPartials: typeof importPartials; declare const index_isLlmExeError: typeof isLlmExeError; declare const index_isObjectStringified: typeof isObjectStringified; declare const index_maybeParseJSON: typeof maybeParseJSON; declare const index_maybeStringifyJSON: typeof maybeStringifyJSON; declare const index_registerHelpers: typeof registerHelpers; declare const index_registerPartials: typeof registerPartials; declare const index_replaceTemplateString: typeof replaceTemplateString; declare const index_replaceTemplateStringAsync: typeof replaceTemplateStringAsync; declare namespace index { export { index_LLM_EXE_ERROR_SYMBOL as LLM_EXE_ERROR_SYMBOL, index_LlmExeError as LlmExeError, index_assert as assert, index_asyncCallWithTimeout as asyncCallWithTimeout, index_defineSchema as defineSchema, index_filterObjectOnSchema as filterObjectOnSchema, index_guessProviderFromModel as guessProviderFromModel, index_importHelpers as importHelpers, index_importPartials as importPartials, index_isLlmExeError as isLlmExeError, index_isObjectStringified as isObjectStringified, index_maybeParseJSON as maybeParseJSON, index_maybeStringifyJSON as maybeStringifyJSON, index_registerHelpers as registerHelpers, index_registerPartials as registerPartials, index_replaceTemplateString as replaceTemplateString, index_replaceTemplateStringAsync as replaceTemplateStringAsync }; } declare function isOutputResult(obj: any): obj is OutputResult; declare function isOutputResultContentText(obj: any): obj is OutputResultsText; /** * Does a llm response have a tool/function call? */ declare function isFunctionCall(result: any): result is OutputResultsFunction; declare function isToolCall(result: any): result is OutputResultsFunction; /** * Is it a tool/function Call */ declare function hasFunctionCall(results: any): boolean; declare function hasToolCall(results: any): boolean; declare function isUserMessage(message: IChatMessage): message is IChatUserMessage; declare function isAssistantMessage(message: IChatMessage): message is IChatAssistantMessage; declare function isSystemMessage(message: IChatMessage): message is IChatSystemMessage; declare const guards_hasFunctionCall: typeof hasFunctionCall; declare const guards_hasToolCall: typeof hasToolCall; declare const guards_isAssistantMessage: typeof isAssistantMessage; declare const guards_isFunctionCall: typeof isFunctionCall; declare const guards_isOutputResult: typeof isOutputResult; declare const guards_isOutputResultContentText: typeof isOutputResultContentText; declare const guards_isSystemMessage: typeof isSystemMessage; declare const guards_isToolCall: typeof isToolCall; declare const guards_isUserMessage: typeof isUserMessage; declare namespace guards { export { guards_hasFunctionCall as hasFunctionCall, guards_hasToolCall as hasToolCall, guards_isAssistantMessage as isAssistantMessage, guards_isFunctionCall as isFunctionCall, guards_isOutputResult as isOutputResult, guards_isOutputResultContentText as isOutputResultContentText, guards_isSystemMessage as isSystemMessage, guards_isToolCall as isToolCall, guards_isUserMessage as isUserMessage }; } declare const configs: { "deepseek.chat.v1": Config; "deepseek.chat": Config; "deepseek.v4-flash": Config; "deepseek.v4-pro": Config; "google.gemini-2.0-flash": Config; "google.gemini-2.0-flash-lite": Config; "google.gemini-1.5-pro": Config; "google.gemini-2.5-pro": Config; "google.gemini-2.5-flash-lite": Config; "google.gemini-2.5-flash": Config; "google.chat.v1": Config; "google.gemini-3.1-flash-lite": Config; "google.gemini-3.5-flash": Config; "ollama.chat.v1": Config; "ollama.deepseek-r1": Config; "ollama.llama3.3": Config; "ollama.llama3.2": Config; "ollama.llama3.1": Config; "ollama.qwq": Config; "ollama.gemma3": Config; "ollama.mistral": Config; "ollama.qwen2.5": Config; "ollama.qwen3": Config; "ollama.qwen3.5": Config; "ollama.gemma4": Config; "ollama.gpt-oss": Config; "xai.chat.v1": Config; "xai.grok-2": Config; "xai.grok-3": Config; "xai.grok-3-mini": Config; "xai.grok-4": Config; "xai.grok-4-fast": Config; "xai.grok-4-1-fast": Config; "xai.grok-4.3": Config; "xai.grok-4.20": Config; "xai.grok-4.20-reasoning": Config; "amazon:anthropic.chat.v1": Config; "amazon:meta.chat.v1": Config; "anthropic.claude-3-opus": Config; "anthropic.claude-3-5-haiku": Config; "anthropic.claude-3-5-sonnet": Config; "anthropic.claude-3-7-sonnet": Config; "anthropic.claude-opus-4": Config; "anthropic.claude-sonnet-4": Config; "anthropic.claude-opus-4-1": Config; "anthropic.claude-opus-4-6": Config; "anthropic.chat.v1": Config; "anthropic.claude-opus-4-8": Config; "anthropic.claude-opus-4-7": Config; "anthropic.claude-sonnet-4-6": Config; "anthropic.claude-opus-4-5": Config; "anthropic.claude-haiku-4-5": Config; "anthropic.claude-sonnet-4-5": Config; "openai.o4-mini": Config; "openai.chat.v1": Config; "openai.chat-mock.v1": Config; "openai.gpt-5.2": Config; "openai.gpt-5-mini": Config; "openai.gpt-5-nano": Config; "openai.gpt-4.1": Config; "openai.gpt-4.1-mini": Config; "openai.gpt-4.1-nano": Config; "openai.o3": Config; "openai.gpt-4": Config; "openai.gpt-4o": Config; "openai.gpt-4o-mini": Config; }; declare function useLlm(provider: T, options?: AllUseLlmOptions[T]["input"]): BaseLlm; declare function useLlmConfiguration(config: Config): (options?: AllUseLlmOptions[T]["input"]) => { call: (messages: string | IChatMessages, options?: LlmExecutorWithFunctionsOptions, context?: ExecutionContext) => Promise<{ getResultContent: (index?: number) => OutputResultContent[]; getResultText: (index?: number) => string; getResult: () => OutputResult; }>; getTraceId: () => string | null; withTraceId: (id: string) => void; getMetadata: () => { traceId: string | null; timeout: number; jitter: "none" | "full"; maxDelay: number; numOfAttempts: number; metrics: any; } & { [x: string]: any; }; }; declare function createOpenAiCompatibleConfiguration(overrides: { key: string; provider: string; endpoint: string; apiKeyMapping: [string, string]; isReasoningModel?: (model: string) => boolean; transformResponse?: any; }): Config; declare function createEmbedding(provider: T, options: AllEmbedding[T]["input"]): { call: (messages: string | string[], options?: LlmExecutorWithFunctionsOptions, context?: ExecutionContext) => Promise<{ getEmbedding: (index?: number) => number[]; getResult: () => EmbeddingOutputResult; }>; getTraceId: () => string | null; withTraceId: (id: string) => void; getMetadata: () => { traceId: string | null; timeout: number; jitter: "none" | "full"; maxDelay: number; numOfAttempts: number; metrics: any; } & { [x: string]: any; }; }; export { BaseExecutor, type BaseLlm, BaseParser, BasePrompt, BaseStateItem, type BooleanParserMatch, type BooleanParserOptions, ChatPrompt, CustomParser, DefaultState, DefaultStateItem, type EmbeddingProviderKey, type ErrorCategory, type ErrorCodes, type ErrorContextByCode, type ExecutionContext, type ExecutorContext, type ExecutorExecutionMetadata, type HookErrorRecord, type IChatMessages, type JsonParserMatch, type JsonParserOptions, LLM_EXE_ERROR_SYMBOL, LlmExeError, LlmExecutorOpenAiFunctions, LlmExecutorWithFunctions, LlmNativeFunctionParser, type LlmProvider, type LlmProviderKey, type NormalizedProviderError, type NumberParserMatch, type NumberParserOptions, type OpenAIModelName, OpenAiFunctionParser, type ProviderErrorContext, type StringExtractMatch, type StringExtractParserOptions, TextPrompt, type UseLlmKey, createCallableExecutor, createChatPrompt, createCoreExecutor, createCustomParser, createDialogue, createEmbedding, createLlmExecutor, createLlmFunctionExecutor, createOpenAiCompatibleConfiguration, createParser, createPrompt, createState, createStateItem, defineSchema, guards, isLlmExeError, registerHelpers, registerPartials, useExecutors, useLlm, useLlmConfiguration, index as utils };