import { Span, Histogram, Counter, Gauge, Meter, Tracer, Context } from '@opentelemetry/api'; interface RetryConfig { maxRetries: number; initialDelayMs: number; maxDelayMs: number; backoffFactor: number; retryableStatusCodes: number[]; } interface RequestValidation { validateRequest?: (request: unknown) => boolean | Promise; } interface ResponseValidation { validateResponse?: (response: unknown) => boolean | Promise; } interface AxAPI { name?: string; headers?: Record; put?: boolean; localCall?: (data: TRequest, stream?: boolean) => Promise>; } interface AxAPIConfig extends AxAPI, RequestValidation, ResponseValidation { url?: string | URL; stream?: boolean; debug?: boolean; fetch?: typeof fetch; span?: Span; timeout?: number; retry?: Partial; abortSignal?: AbortSignal; corsProxy?: string; } declare class AxAIServiceError extends Error { readonly url: string; readonly requestBody: unknown; readonly responseBody: unknown; readonly timestamp: string; readonly errorId: string; readonly context: Record; constructor(message: string, url: string, requestBody: unknown, responseBody: unknown, context?: Record); toString(): string; } declare class AxAIServiceStatusError extends AxAIServiceError { readonly status: number; readonly statusText: string; constructor(status: number, statusText: string, url: string, requestBody: unknown, responseBody: unknown, context?: Record); } declare class AxAIServiceNetworkError extends AxAIServiceError { readonly originalError: Error; constructor(originalError: Error, url: string, requestBody: unknown, responseBody: unknown, context?: Record); } declare class AxAIServiceResponseError extends AxAIServiceError { constructor(message: string, url: string, requestBody?: unknown, context?: Record); } declare class AxAIServiceStreamTerminatedError extends AxAIServiceError { readonly lastChunk?: unknown | undefined; constructor(url: string, requestBody?: unknown, lastChunk?: unknown | undefined, context?: Record); } declare class AxAIServiceTimeoutError extends AxAIServiceError { constructor(url: string, timeoutMs: number, requestBody?: unknown, context?: Record); } declare class AxAIServiceAbortedError extends AxAIServiceError { constructor(url: string, reason?: string, requestBody?: unknown, context?: Record); } declare class AxAIServiceAuthenticationError extends AxAIServiceError { constructor(url: string, requestBody: unknown, responseBody: unknown, context?: Record); } declare class AxAIRefusalError extends Error { readonly refusalMessage: string; readonly model?: string | undefined; readonly requestId?: string | undefined; readonly timestamp: string; readonly errorId: string; constructor(refusalMessage: string, model?: string | undefined, requestId?: string | undefined); toString(): string; } /** * Error thrown when an AI provider doesn't support a required media type. * * This error is thrown during content processing when a provider cannot handle * a specific media type and no suitable fallback mechanism is available or configured. * * @example * ```typescript * try { * await textOnlyProvider.chat(imageRequest); * } catch (error) { * if (error instanceof AxMediaNotSupportedError) { * console.log(`${error.mediaType} not supported by ${error.provider}`); * if (error.fallbackAvailable) { * console.log('Consider using content processing services'); * } * } * } * ``` */ declare class AxMediaNotSupportedError extends Error { readonly mediaType: string; readonly provider: string; readonly fallbackAvailable: boolean; /** ISO timestamp when the error occurred */ readonly timestamp: string; /** Unique identifier for this error instance */ readonly errorId: string; /** * Creates a new media not supported error. * * @param mediaType - The type of media that is not supported (e.g., 'Images', 'Audio') * @param provider - The name of the AI provider that doesn't support the media type * @param fallbackAvailable - Whether fallback processing options are available */ constructor(mediaType: string, provider: string, fallbackAvailable?: boolean); toString(): string; } /** * Error thrown when content processing/transformation fails. * * This error wraps underlying failures from content processing services like * image-to-text, audio transcription, file text extraction, or URL content fetching. * It provides context about what type of content was being processed and at which step. * * @example * ```typescript * try { * await axProcessContentForProvider(content, provider, { * imageToText: imageService.analyze * }); * } catch (error) { * if (error instanceof AxContentProcessingError) { * console.log(`Failed processing ${error.contentType} during ${error.processingStep}`); * console.log('Original error:', error.originalError.message); * } * } * ``` */ declare class AxContentProcessingError extends Error { readonly originalError: Error; readonly contentType: string; readonly processingStep: string; /** ISO timestamp when the error occurred */ readonly timestamp: string; /** Unique identifier for this error instance */ readonly errorId: string; /** * Creates a new content processing error. * * @param originalError - The underlying error that caused the processing failure * @param contentType - The type of content being processed (e.g., 'image', 'audio', 'file') * @param processingStep - The specific processing step that failed (e.g., 'vision analysis', 'transcription') */ constructor(originalError: Error, contentType: string, processingStep: string); toString(): string; } type AxMemoryData = { tags?: string[]; role: AxChatRequest['chatPrompt'][number]['role']; updatable?: boolean; chat: { index: number; value: Omit; }[]; }[]; interface AxAIMemory { addRequest(result: AxChatRequest['chatPrompt'], sessionId?: string): void; addResponse(results: Readonly, sessionId?: string): void; updateResult(results: Readonly & { delta?: string; }, sessionId?: string): void; addFunctionResults(results: Readonly, sessionId?: string): void; history(index: number, sessionId?: string): AxChatRequest['chatPrompt']; reset(sessionId?: string): void; getLast(sessionId?: string): AxMemoryData[number] | undefined; addTag(name: string, sessionId?: string): void; rewindToTag(name: string, sessionId?: string): AxMemoryData; removeByTag(name: string, sessionId?: string): AxMemoryData; } interface AxFieldType { readonly type: 'string' | 'number' | 'boolean' | 'json' | 'image' | 'audio' | 'file' | 'url' | 'date' | 'datetime' | 'class' | 'code'; readonly isArray?: boolean; readonly options?: readonly string[]; readonly description?: string; readonly isOptional?: boolean; readonly isInternal?: boolean; } declare class AxSignatureBuilder<_TInput extends Record = {}, _TOutput extends Record = {}> { private inputFields; private outputFields; private desc?; /** * Add an input field to the signature * @param name - Field name * @param fieldInfo - Field type created with f.string(), f.number(), etc. * @param prepend - If true, adds field to the beginning of input fields */ input | AxFluentFieldType>(name: K, fieldInfo: T, prepend?: boolean): AxSignatureBuilder, _TOutput>; /** * Add an output field to the signature * @param name - Field name * @param fieldInfo - Field type created with f.string(), f.number(), etc. * @param prepend - If true, adds field to the beginning of output fields */ output | AxFluentFieldType>(name: K, fieldInfo: T, prepend?: boolean): AxSignatureBuilder<_TInput, AddFieldToShape<_TOutput, K, T>>; /** * Set the description for the signature * @param description - Description text */ description(description: string): AxSignatureBuilder<_TInput, _TOutput>; /** * Build the final AxSignature instance */ build(): AxSignature<_TInput, _TOutput>; } declare class AxFluentFieldType implements AxFieldType { readonly type: TType; readonly isArray: TIsArray; readonly options?: TOptions; readonly description?: string; readonly isOptional: TIsOptional; readonly isInternal: TIsInternal; constructor(fieldType: { type: TType; isArray: TIsArray; options?: TOptions; description?: string; isOptional: TIsOptional; isInternal: TIsInternal; }); optional(): AxFluentFieldType; array(): AxFluentFieldType; internal(): AxFluentFieldType; } declare const f: (() => AxSignatureBuilder) & { string: (desc?: string) => AxFluentFieldType<"string", false, undefined, false, false>; number: (desc?: string) => AxFluentFieldType<"number", false, undefined, false, false>; boolean: (desc?: string) => AxFluentFieldType<"boolean", false, undefined, false, false>; json: (desc?: string) => AxFluentFieldType<"json", false, undefined, false, false>; datetime: (desc?: string) => AxFluentFieldType<"datetime", false, undefined, false, false>; date: (desc?: string) => AxFluentFieldType<"date", false, undefined, false, false>; class: (options: TOptions, desc?: string) => AxFluentFieldType<"class", false, TOptions, false, false>; image: (desc?: string) => AxFluentFieldType<"image", false, undefined, false, false>; audio: (desc?: string) => AxFluentFieldType<"audio", false, undefined, false, false>; file: (desc?: string) => AxFluentFieldType<"file", false, undefined, false, false>; url: (desc?: string) => AxFluentFieldType<"url", false, undefined, false, false>; code: (language?: string, desc?: string) => AxFluentFieldType<"code", false, undefined, false, false>; }; interface AxField { name: string; title?: string; description?: string; type?: { name: 'string' | 'number' | 'boolean' | 'json' | 'image' | 'audio' | 'file' | 'url' | 'date' | 'datetime' | 'class' | 'code'; isArray?: boolean; options?: string[]; }; isOptional?: boolean; isInternal?: boolean; } type AxIField = Omit & { title: string; }; type InferFieldValueType = T extends AxFieldType | AxFluentFieldType ? T['type'] extends 'string' ? T['isArray'] extends true ? string[] : string : T['type'] extends 'number' ? T['isArray'] extends true ? number[] : number : T['type'] extends 'boolean' ? T['isArray'] extends true ? boolean[] : boolean : T['type'] extends 'json' ? T['isArray'] extends true ? any[] : any : T['type'] extends 'date' ? T['isArray'] extends true ? Date[] : Date : T['type'] extends 'datetime' ? T['isArray'] extends true ? Date[] : Date : T['type'] extends 'image' ? T['isArray'] extends true ? { mimeType: string; data: string; }[] : { mimeType: string; data: string; } : T['type'] extends 'audio' ? T['isArray'] extends true ? { format?: 'wav'; data: string; }[] : { format?: 'wav'; data: string; } : T['type'] extends 'file' ? T['isArray'] extends true ? ({ mimeType: string; data: string; } | { mimeType: string; fileUri: string; })[] : { mimeType: string; data: string; } | { mimeType: string; fileUri: string; } : T['type'] extends 'url' ? T['isArray'] extends true ? string[] : string : T['type'] extends 'code' ? T['isArray'] extends true ? string[] : string : T['type'] extends 'class' ? T['options'] extends readonly (infer U)[] ? T['isArray'] extends true ? U[] : U : T['isArray'] extends true ? string[] : string : any : any; interface AxFluentFieldInfo { readonly type: TType; readonly isArray?: TIsArray; readonly options?: TOptions; readonly description?: string; readonly isOptional?: TIsOptional; readonly isInternal?: boolean; } type InferFluentType | AxFluentFieldType> = T['type'] extends 'string' ? T['isArray'] extends true ? string[] : string : T['type'] extends 'number' ? T['isArray'] extends true ? number[] : number : T['type'] extends 'boolean' ? T['isArray'] extends true ? boolean[] : boolean : T['type'] extends 'json' ? T['isArray'] extends true ? any[] : any : T['type'] extends 'date' ? T['isArray'] extends true ? Date[] : Date : T['type'] extends 'datetime' ? T['isArray'] extends true ? Date[] : Date : T['type'] extends 'image' ? T['isArray'] extends true ? { mimeType: string; data: string; }[] : { mimeType: string; data: string; } : T['type'] extends 'audio' ? T['isArray'] extends true ? { format?: 'wav'; data: string; }[] : { format?: 'wav'; data: string; } : T['type'] extends 'file' ? T['isArray'] extends true ? ({ mimeType: string; data: string; } | { mimeType: string; fileUri: string; })[] : { mimeType: string; data: string; } | { mimeType: string; fileUri: string; } : T['type'] extends 'url' ? T['isArray'] extends true ? string[] : string : T['type'] extends 'code' ? T['isArray'] extends true ? string[] : string : T['type'] extends 'class' ? T['options'] extends readonly (infer U)[] ? T['isArray'] extends true ? U[] : U : T['isArray'] extends true ? string[] : string : any; type _IsInternal = T extends { readonly isInternal: true; } ? true : false; type _IsOptional = T extends { readonly isOptional: true; } ? true : false; type AddFieldToShape, K extends string, T extends AxFluentFieldInfo | AxFluentFieldType> = _IsInternal extends true ? S : _IsOptional extends true ? S & { readonly [P in K]?: InferFluentType; } : S & { readonly [P in K]: InferFluentType; }; interface AxSignatureConfig { description?: string; inputs: readonly AxField[]; outputs: readonly AxField[]; } declare class AxSignature<_TInput extends Record = Record, _TOutput extends Record = Record> { private description?; private inputFields; private outputFields; private sigHash; private sigString; private validatedAtHash?; /** * @deprecated Use `AxSignature.create()` for better type safety instead of the constructor. * This constructor will be removed in v15.0.0. * * Migration timeline: * - v13.0.24+: Deprecation warnings (current) * - v14.0.0: Runtime console warnings * - v15.0.0: Complete removal * * @example * ```typescript * // Instead of: new AxSignature('userInput:string -> responseText:string') * // Use: AxSignature.create('userInput:string -> responseText:string') * ``` */ constructor(signature?: Readonly); /** * Static factory method for type inference. * Creates a typed AxSignature instance from a signature string. */ static create(signature: T): AxSignature['inputs'], ParseSignature['outputs']>; private parseParsedField; private parseField; setDescription: (desc: string) => void; addInputField: (field: Readonly) => void; addOutputField: (field: Readonly) => void; setInputFields: (fields: readonly AxField[]) => void; setOutputFields: (fields: readonly AxField[]) => void; getInputFields: () => Readonly; getOutputFields: () => Readonly; getDescription: () => string | undefined; appendInputField: (name: K, fieldType: T) => AxSignature<_TInput & Record>, _TOutput>; prependInputField: (name: K, fieldType: T) => AxSignature> & _TInput, _TOutput>; appendOutputField: (name: K, fieldType: T) => AxSignature<_TInput, _TOutput & Record>>; prependOutputField: (name: K, fieldType: T) => AxSignature<_TInput, Record> & _TOutput>; private invalidateValidationCache; private toTitle; toJSONSchema: () => AxFunctionJSONSchema; private updateHashLight; private updateHash; private validateSignatureConsistency; validate: () => boolean; hash: () => string; toString: () => string; toJSON: () => { id: string; description: string | undefined; inputFields: AxIField[]; outputFields: AxIField[]; }; } interface AxAssertion> { fn(values: T): Promise | boolean | string | undefined; message?: string; } interface AxStreamingAssertion { fieldName: string; fn(content: string, done?: boolean): boolean | string | undefined; message?: string; } declare class AxAssertionError extends Error { constructor({ message, }: Readonly<{ message: string; }>); getFixingInstructions: () => { name: string; title: string; description: string; }[]; toString(): string; } declare class AxMemory implements AxAIMemory { private memories; private defaultMemory; constructor(); private getMemory; addRequest(value: AxChatRequest['chatPrompt'], sessionId?: string): void; addResponse(results: Readonly, sessionId?: string): void; addFunctionResults(results: Readonly, sessionId?: string): void; updateResult(result: Readonly, sessionId?: string): void; addTag(name: string, sessionId?: string): void; rewindToTag(name: string, sessionId?: string): AxMemoryData; removeByTag(name: string, sessionId?: string): AxMemoryData; history(index: number, sessionId?: string): ({ role: "system"; content: string; cache?: boolean; } | { role: "user"; name?: string; content: string | ({ type: "text"; text: string; cache?: boolean; } | { type: "image"; mimeType: string; image: string; details?: "high" | "low" | "auto"; cache?: boolean; optimize?: "quality" | "size" | "auto"; altText?: string; } | { type: "audio"; data: string; format?: "wav" | "mp3" | "ogg"; cache?: boolean; transcription?: string; duration?: number; } | { type: "file"; data: string; filename?: string; mimeType: string; cache?: boolean; extractedText?: string; } | { type: "file"; fileUri: string; filename?: string; mimeType: string; cache?: boolean; extractedText?: string; } | { type: "url"; url: string; cache?: boolean; cachedContent?: string; title?: string; description?: string; })[]; } | { role: "assistant"; content?: string; name?: string; functionCalls?: { id: string; type: "function"; function: { name: string; params?: string | object; }; }[]; cache?: boolean; } | { role: "function"; result: string; isError?: boolean; functionId: string; cache?: boolean; })[]; getLast(sessionId?: string): { tags?: string[]; role: AxChatRequest["chatPrompt"][number]["role"]; updatable?: boolean; chat: { index: number; value: Omit; }[]; } | undefined; reset(sessionId?: string): void; } declare class AxStopFunctionCallException extends Error { readonly calls: ReadonlyArray<{ func: Readonly; args: unknown; result: unknown; }>; constructor(calls: ReadonlyArray<{ func: Readonly; args: unknown; result: unknown; }>); } declare class AxFunctionError extends Error { private fields; constructor(fields: { field: string; message: string; }[]); getFields: () => { field: string; message: string; }[]; toString(): string; } type AxChatResponseFunctionCall = { id: string; name: string; args: string; }; declare class AxFunctionProcessor { private funcList; constructor(funcList: Readonly); private executeFunction; executeWithDetails: (func: Readonly, options?: Readonly & { traceId?: string; stopFunctionNames?: readonly string[]; }>) => Promise<{ formatted: string; rawResult: unknown; parsedArgs: unknown; }>; execute: (func: Readonly, options?: Readonly & { traceId?: string; stopFunctionNames?: readonly string[]; }>) => Promise; } type AxInputFunctionType = (AxFunction | { toFunction: () => AxFunction | AxFunction[]; })[]; type AxOptimizerLoggerData = { name: 'OptimizationStart'; value: { optimizerType: string; config: Record; exampleCount: number; validationCount: number; }; } | { name: 'RoundProgress'; value: { round: number; totalRounds: number; currentScore: number; bestScore: number; configuration: Record; }; } | { name: 'EarlyStopping'; value: { reason: string; finalScore: number; round: number; }; } | { name: 'OptimizationComplete'; value: { optimizerType?: string; bestScore: number; bestConfiguration: Record; totalCalls?: number; successRate?: string; explanation?: string; recommendations?: string[]; performanceAssessment?: string; stats: AxOptimizationStats; }; } | { name: 'ConfigurationProposal'; value: { type: 'instructions' | 'demos' | 'general'; proposals: string[] | Record[]; count: number; }; } | { name: 'BootstrappedDemos'; value: { count: number; demos: unknown[]; }; } | { name: 'BestConfigFound'; value: { config: Record; score: number; }; }; type AxOptimizerLoggerFunction = (data: AxOptimizerLoggerData) => void; interface AxOptimizerMetricsConfig { enabled: boolean; enabledCategories: ('optimization' | 'convergence' | 'resource_usage' | 'teacher_student' | 'checkpointing' | 'pareto')[]; maxLabelLength: number; samplingRate: number; } declare const axDefaultOptimizerMetricsConfig: AxOptimizerMetricsConfig; interface AxOptimizerMetricsInstruments { optimizationLatencyHistogram?: Histogram; optimizationRequestsCounter?: Counter; optimizationErrorsCounter?: Counter; convergenceRoundsHistogram?: Histogram; convergenceScoreGauge?: Gauge; convergenceImprovementGauge?: Gauge; stagnationRoundsGauge?: Gauge; earlyStoppingCounter?: Counter; tokenUsageCounter?: Counter; costUsageCounter?: Counter; memoryUsageGauge?: Gauge; optimizationDurationHistogram?: Histogram; teacherStudentUsageCounter?: Counter; teacherStudentLatencyHistogram?: Histogram; teacherStudentScoreImprovementGauge?: Gauge; checkpointSaveCounter?: Counter; checkpointLoadCounter?: Counter; checkpointSaveLatencyHistogram?: Histogram; checkpointLoadLatencyHistogram?: Histogram; paretoOptimizationsCounter?: Counter; paretoFrontSizeHistogram?: Histogram; paretoHypervolumeGauge?: Gauge; paretoSolutionsGeneratedHistogram?: Histogram; programInputFieldsGauge?: Gauge; programOutputFieldsGauge?: Gauge; examplesCountGauge?: Gauge; validationSetSizeGauge?: Gauge; evaluationLatencyHistogram?: Histogram; demoGenerationLatencyHistogram?: Histogram; metricComputationLatencyHistogram?: Histogram; optimizerTypeGauge?: Gauge; targetScoreGauge?: Gauge; maxRoundsGauge?: Gauge; } declare const axUpdateOptimizerMetricsConfig: (config: Readonly>) => void; declare const axGetOptimizerMetricsConfig: () => AxOptimizerMetricsConfig; interface AxOptimizerResult { demos?: AxProgramDemos[]; stats: AxOptimizationStats; bestScore: number; finalConfiguration?: Record; scoreHistory?: number[]; configurationHistory?: Record[]; } interface AxOptimizedProgram { bestScore: number; stats: AxOptimizationStats; instruction?: string; demos?: AxProgramDemos[]; examples?: AxExample[]; modelConfig?: { temperature?: number; maxTokens?: number; topP?: number; topK?: number; frequencyPenalty?: number; presencePenalty?: number; stop?: string | string[]; [key: string]: unknown; }; optimizerType: string; optimizationTime: number; totalRounds: number; converged: boolean; scoreHistory?: number[]; configurationHistory?: Record[]; applyTo(program: AxGen): void; } declare class AxOptimizedProgramImpl implements AxOptimizedProgram { readonly bestScore: number; readonly stats: AxOptimizationStats; readonly instruction?: string; readonly demos?: AxProgramDemos[]; readonly examples?: AxExample[]; readonly modelConfig?: { temperature?: number; maxTokens?: number; topP?: number; topK?: number; frequencyPenalty?: number; presencePenalty?: number; stop?: string | string[]; [key: string]: unknown; }; readonly optimizerType: string; readonly optimizationTime: number; readonly totalRounds: number; readonly converged: boolean; readonly scoreHistory?: number[]; readonly configurationHistory?: Record[]; constructor(config: { bestScore: number; stats: AxOptimizationStats; instruction?: string; demos?: AxProgramDemos[]; examples?: AxExample[]; modelConfig?: AxOptimizedProgram['modelConfig']; optimizerType: string; optimizationTime: number; totalRounds: number; converged: boolean; scoreHistory?: number[]; configurationHistory?: Record[]; }); applyTo(program: AxGen): void; } interface AxParetoResult extends AxOptimizerResult { paretoFront: ReadonlyArray<{ demos: readonly AxProgramDemos[]; scores: Readonly>; configuration: Readonly>; dominatedSolutions: number; }>; hypervolume?: number; paretoFrontSize: number; convergenceMetrics?: Record; } interface AxOptimizer { /** * Optimize a program using the provided metric function * @param program The program to optimize * @param examples Training examples (typed based on the program) - will be auto-split into train/validation * @param metricFn Evaluation metric function to assess program performance * @param options Optional configuration options * @returns Optimization result containing demos, stats, and configuration */ compile(program: Readonly>, examples: readonly AxTypedExample[], metricFn: AxMetricFn, options?: AxCompileOptions): Promise>; /** * Optimize a program with real-time streaming updates * @param program The program to optimize * @param examples Training examples * @param metricFn Evaluation metric function * @param options Optional configuration options * @returns Async iterator yielding optimization progress */ compileStream?(program: Readonly>, examples: readonly AxTypedExample[], metricFn: AxMetricFn, options?: AxCompileOptions): AsyncIterableIterator; /** * Multi-objective optimization using Pareto frontier * @param program The program to optimize * @param examples Training examples * @param metricFn Multi-objective metric function * @param options Optional configuration options * @returns Pareto optimization result */ compilePareto?(program: Readonly>, examples: readonly AxTypedExample[], metricFn: AxMultiMetricFn, options?: AxCompileOptions): Promise>; /** * Get current optimization statistics * @returns Current optimization statistics */ getStats(): AxOptimizationStats; /** * Cancel ongoing optimization gracefully * @returns Promise that resolves when cancellation is complete */ cancel?(): Promise; /** * Reset optimizer state for reuse with different programs */ reset?(): void; /** * Get optimizer-specific configuration * @returns Current optimizer configuration */ getConfiguration?(): Record; /** * Update optimizer configuration * @param config New configuration to merge with existing */ updateConfiguration?(config: Readonly>): void; /** * Validate that the optimizer can handle the given program * @param program Program to validate * @returns Validation result with any issues found */ validateProgram?(program: Readonly>): { isValid: boolean; issues: string[]; suggestions: string[]; }; } interface AxBootstrapOptimizerOptions { maxRounds?: number; maxExamples?: number; maxDemos?: number; batchSize?: number; earlyStoppingPatience?: number; teacherAI?: AxAIService; costMonitoring?: boolean; maxTokensPerGeneration?: number; verboseMode?: boolean; debugMode?: boolean; adaptiveBatching?: boolean; dynamicTemperature?: boolean; qualityThreshold?: number; diversityWeight?: number; } interface AxMiPROOptimizerOptions { numCandidates?: number; initTemperature?: number; maxBootstrappedDemos?: number; maxLabeledDemos?: number; numTrials?: number; minibatch?: boolean; minibatchSize?: number; minibatchFullEvalSteps?: number; programAwareProposer?: boolean; dataAwareProposer?: boolean; viewDataBatchSize?: number; tipAwareProposer?: boolean; fewshotAwareProposer?: boolean; verbose?: boolean; earlyStoppingTrials?: number; minImprovementThreshold?: number; bayesianOptimization?: boolean; acquisitionFunction?: 'expected_improvement' | 'upper_confidence_bound' | 'probability_improvement'; explorationWeight?: number; sampleCount?: number; } declare class AxDefaultCostTracker implements AxCostTracker { private tokenUsage; private totalTokens; private readonly costPerModel; private readonly maxCost?; private readonly maxTokens?; constructor(options?: AxCostTrackerOptions); trackTokens(count: number, model: string): void; getCurrentCost(): number; getTokenUsage(): Record; getTotalTokens(): number; isLimitReached(): boolean; reset(): void; } /** * Abstract base class for optimizers that provides common functionality * and standardized handling of AxOptimizerArgs */ declare abstract class AxBaseOptimizer implements AxOptimizer { protected readonly studentAI: AxAIService; protected readonly teacherAI?: AxAIService; protected readonly targetScore?: number; protected readonly minSuccessRate?: number; protected readonly onProgress?: (progress: Readonly) => void; protected readonly onEarlyStop?: (reason: string, stats: Readonly) => void; protected readonly costTracker?: AxCostTracker; protected readonly seed?: number; protected readonly checkpointSave?: AxCheckpointSaveFn; protected readonly checkpointLoad?: AxCheckpointLoadFn; protected readonly checkpointInterval?: number; protected readonly resumeFromCheckpoint?: string; protected readonly logger?: AxLoggerFunction; protected readonly verbose?: boolean; protected readonly debugOptimizer: boolean; protected readonly optimizerLogger?: AxOptimizerLoggerFunction; protected currentRound: number; private scoreHistory; private configurationHistory; protected stats: AxOptimizationStats; protected readonly metricsInstruments?: AxOptimizerMetricsInstruments; private resultExplainer?; constructor(args: Readonly); /** * Initialize the result explanation generator * FIXME: Disabled due to circular dependency with ax() function */ private initializeResultExplainer; /** * Initialize the optimization statistics structure */ protected initializeStats(): AxOptimizationStats; /** * Set up reproducible random seed if provided */ protected setupRandomSeed(): void; /** * Check if optimization should stop early due to cost limits */ protected checkCostLimits(): boolean; /** * Check if target score has been reached */ protected checkTargetScore(currentScore: number): boolean; /** * Update resource usage statistics */ protected updateResourceUsage(startTime: number, tokensUsed?: number): void; /** * Trigger early stopping with appropriate callbacks */ protected triggerEarlyStopping(reason: string, bestScoreRound: number): void; /** * Validate that examples meet minimum requirements for optimization * @param examples Examples to validate * @param requireSplit Whether this optimizer requires train/validation split (default: true) * @throws Error if examples don't meet minimum requirements */ protected validateExamples(examples: readonly AxTypedExample[], requireSplit?: boolean): void; /** * Get the AI service to use for a specific task, preferring teacher when available * @param preferTeacher Whether to prefer teacher AI over student AI * @param options Optional compile options that may override teacher AI * @returns The appropriate AI service to use */ protected getAIService(preferTeacher?: boolean, options?: AxCompileOptions): AxAIService; /** * Check if teacher AI is available (including overrides) * @param options Optional compile options that may override teacher AI * @returns True if teacher AI is configured or overridden */ protected hasTeacherAI(options?: AxCompileOptions): boolean; /** * Get teacher AI if available, otherwise return student AI * @param options Optional compile options that may override teacher AI * @returns Teacher AI if available, otherwise student AI */ protected getTeacherOrStudentAI(options?: AxCompileOptions): AxAIService; /** * Execute a task with teacher AI if available, otherwise use student AI * @param task Function that takes an AI service and returns a promise * @param preferTeacher Whether to prefer teacher AI (default: true) * @param options Optional compile options that may override teacher AI * @returns Result of the task execution */ protected executeWithTeacher(task: (ai: AxAIService) => Promise, preferTeacher?: boolean, options?: AxCompileOptions): Promise; /** * Abstract method that must be implemented by concrete optimizers */ abstract compile(program: Readonly>, examples: readonly AxTypedExample[], metricFn: AxMetricFn, options?: AxCompileOptions): Promise>; /** * Optimize a program with real-time streaming updates * @param program The program to optimize * @param examples Training examples * @param metricFn Evaluation metric function * @param options Optional configuration options * @returns Async iterator yielding optimization progress */ compileStream(program: Readonly>, examples: readonly AxTypedExample[], metricFn: AxMetricFn, options?: AxCompileOptions): AsyncIterableIterator; /** * Multi-objective optimization using Pareto frontier * Default implementation that leverages the single-objective compile method * @param program The program to optimize * @param examples Training examples * @param metricFn Multi-objective metric function that returns multiple scores * @param options Optional configuration options * @returns Pareto optimization result with frontier of non-dominated solutions */ compilePareto(program: Readonly>, examples: readonly AxTypedExample[], metricFn: AxMultiMetricFn, options?: AxCompileOptions): Promise>; /** * Generate solutions using different weighted combinations of objectives */ private generateWeightedSolutions; /** * Generate solutions using constraint-based optimization */ private generateConstraintSolutions; /** * Generate different weight combinations for objectives */ private generateWeightCombinations; /** * Evaluate a single-objective result with multi-objective metrics */ private evaluateWithMultiObjective; /** * Find the Pareto frontier from a set of solutions */ private findParetoFrontier; /** * Check if solution A dominates solution B * A dominates B if A is better or equal in all objectives and strictly better in at least one */ private dominates; /** * Calculate hypervolume of the Pareto frontier * Simplified implementation using reference point at origin */ private calculateHypervolume; /** * Save current optimization state to checkpoint */ protected saveCheckpoint(optimizerType: string, optimizerConfig: Record, bestScore: number, bestConfiguration?: Record, optimizerState?: Record, options?: AxCompileOptions): Promise; /** * Load optimization state from checkpoint */ protected loadCheckpoint(checkpointId: string, options?: AxCompileOptions): Promise; /** * Restore optimizer state from checkpoint */ protected restoreFromCheckpoint(checkpoint: Readonly): void; /** * Check if checkpoint should be saved */ protected shouldSaveCheckpoint(round: number, options?: AxCompileOptions): boolean; /** * Update optimization progress and handle checkpointing */ protected updateOptimizationProgress(round: number, score: number, configuration: Record, optimizerType: string, optimizerConfig: Record, bestScore: number, bestConfiguration?: Record, optimizerState?: Record, options?: AxCompileOptions): Promise; /** * Save final checkpoint on completion */ protected saveFinalCheckpoint(optimizerType: string, optimizerConfig: Record, bestScore: number, bestConfiguration?: Record, optimizerState?: Record, options?: AxCompileOptions): Promise; /** * Get the logger function with fallback hierarchy: * 1. Explicit logger passed to optimizer * 2. Logger from student AI service * 3. undefined if verbose is false */ protected getLogger(options?: AxCompileOptions): AxLoggerFunction | undefined; /** * Check if logging is enabled based on verbose settings */ protected isLoggingEnabled(options?: AxCompileOptions): boolean; /** * Record optimization start metrics */ protected recordOptimizationStart(optimizerType: string, programSignature?: string): void; /** * Record optimization completion metrics */ protected recordOptimizationComplete(duration: number, success: boolean, optimizerType: string, programSignature?: string): void; /** * Record convergence metrics */ protected recordConvergenceMetrics(rounds: number, currentScore: number, improvement: number, stagnationRounds: number, optimizerType: string): void; /** * Record early stopping metrics */ protected recordEarlyStoppingMetrics(reason: string, optimizerType: string): void; /** * Record teacher-student interaction metrics */ protected recordTeacherStudentMetrics(latency: number, scoreImprovement: number, optimizerType: string): void; /** * Record checkpoint metrics */ protected recordCheckpointMetrics(operation: 'save' | 'load', latency: number, success: boolean, optimizerType: string): void; /** * Record Pareto optimization metrics */ protected recordParetoMetrics(frontSize: number, solutionsGenerated: number, optimizerType: string, hypervolume?: number): void; /** * Record performance metrics */ protected recordPerformanceMetrics(metricType: 'evaluation' | 'demo_generation' | 'metric_computation', duration: number, optimizerType: string): void; protected isOptimizerLoggingEnabled(options?: AxCompileOptions): boolean; protected getOptimizerLogger(options?: AxCompileOptions): AxOptimizerLoggerFunction | undefined; getStats(): AxOptimizationStats; protected explainOptimizationResults(bestScore: number, bestConfiguration?: Record, _options?: AxCompileOptions): Promise<{ humanExplanation: string; recommendations: string[]; performanceAssessment: string; } | undefined>; /** * Log human-readable optimization completion message */ protected logOptimizationComplete(optimizerType: string, bestScore: number, bestConfiguration?: Record, options?: AxCompileOptions, explanation?: { humanExplanation: string; recommendations: string[]; performanceAssessment: string; }): Promise; reset(): void; } declare class AxProgram implements AxUsable, AxTunable { protected signature: AxSignature; protected sigHash: string; protected examples?: OUT[]; protected examplesOptions?: AxSetExamplesOptions; protected demos?: OUT[]; protected trace?: OUT; protected usage: AxProgramUsage[]; protected traceLabel?: string; private key; private children; constructor(signature: ConstructorParameters[0], options?: Readonly); getSignature(): AxSignature; setSignature(signature: ConstructorParameters[0]): void; setDescription(description: string): void; private updateSignatureHash; register(prog: Readonly & AxUsable>): void; setId(id: string): void; setParentId(parentId: string): void; setExamples(examples: Readonly>, options?: Readonly): void; private _setExamples; getTraces(): AxProgramTrace[]; getUsage(): AxProgramUsage[]; resetUsage(): void; setDemos(demos: readonly AxProgramDemos[]): void; /** * Apply optimized configuration to this program * @param optimizedProgram The optimized program configuration to apply */ applyOptimization(optimizedProgram: AxOptimizedProgram): void; } type AxGenerateResult = OUT & { thought?: string; }; interface AxResponseHandlerArgs { ai: Readonly; model?: string; res: T; mem: AxAIMemory; sessionId?: string; traceId?: string; functions: Readonly; strictMode?: boolean; span?: Span; logger: AxLoggerFunction; } interface AxStreamingEvent { event: 'delta' | 'done' | 'error'; data: { contentDelta?: string; partialValues?: Partial; error?: string; functions?: AxChatResponseFunctionCall[]; }; } declare class AxGen extends AxProgram implements AxProgrammable { private promptTemplate; private asserts; private streamingAsserts; private options?; private functions; private fieldProcessors; private streamingFieldProcessors; private excludeContentFromTrace; private thoughtFieldName; private signatureToolCallingManager?; constructor(signature: NonNullable[0]> | AxSignature, options?: Readonly>); private getSignatureName; private getMetricsInstruments; updateMeter(meter?: Meter): void; private createStates; addAssert: (fn: AxAssertion["fn"], message?: string) => void; addStreamingAssert: (fieldName: keyof OUT, fn: AxStreamingAssertion["fn"], message?: string) => void; private addFieldProcessorInternal; addStreamingFieldProcessor: (fieldName: keyof OUT, fn: (value: string, context?: { values?: OUT; sessionId?: string; done?: boolean; }) => unknown | Promise) => void; addFieldProcessor: (fieldName: keyof OUT, fn: (value: OUT[keyof OUT], context?: { values?: OUT; sessionId?: string; done?: boolean; }) => unknown | Promise) => void; private forwardSendRequest; private forwardCore; private _forward2; _forward1(ai: Readonly, values: IN | AxMessage[], options: Readonly>): AxGenStreamingOut; forward>(ai: T, values: IN | AxMessage[], options?: Readonly>): Promise; streamingForward>(ai: T, values: IN | AxMessage[], options?: Readonly>): AxGenStreamingOut; setExamples(examples: Readonly>, options?: Readonly): void; private isDebug; private getLogger; } type AxGenerateErrorDetails = { model?: string; maxTokens?: number; streaming: boolean; signature: { input: Readonly; output: Readonly; description?: string; }; }; type ErrorOptions = { cause?: Error; }; declare class AxGenerateError extends Error { readonly details: AxGenerateErrorDetails; constructor(message: string, details: Readonly, options?: ErrorOptions); } type Writeable = { -readonly [P in keyof T]: T[P]; }; interface AxPromptTemplateOptions { functions?: Readonly; thoughtFieldName?: string; cacheSystemPrompt?: boolean; } type AxChatRequestChatPrompt = Writeable; type ChatRequestUserMessage = Exclude['content'], string>; type AxFieldTemplateFn = (field: Readonly, value: Readonly) => ChatRequestUserMessage; declare class AxPromptTemplate { private sig; private fieldTemplates?; private task; private readonly thoughtFieldName; private readonly functions?; private readonly cacheSystemPrompt?; constructor(sig: Readonly, options?: Readonly, fieldTemplates?: Record); private renderSingleValueUserContent; render: (values: T | ReadonlyArray>, // Allow T or array of AxMessages { examples, demos, }: Readonly<{ skipSystemPrompt?: boolean; examples?: Record[]; demos?: Record[]; }>) => Extract[]; renderExtraFields: (extraFields: readonly AxIField[]) => ({ type: "text"; text: string; cache?: boolean; } | { type: "image"; mimeType: string; image: string; details?: "high" | "low" | "auto"; cache?: boolean; optimize?: "quality" | "size" | "auto"; altText?: string; } | { type: "audio"; data: string; format?: "wav" | "mp3" | "ogg"; cache?: boolean; transcription?: string; duration?: number; } | { type: "file"; data: string; filename?: string; mimeType: string; cache?: boolean; extractedText?: string; } | { type: "file"; fileUri: string; filename?: string; mimeType: string; cache?: boolean; extractedText?: string; } | { type: "url"; url: string; cache?: boolean; cachedContent?: string; title?: string; description?: string; })[]; private renderExamples; private renderDemos; private renderInputFields; private renderInField; private defaultRenderInField; } /** * A map of string type names to their corresponding TypeScript types. * Maps signature type strings to actual TypeScript types for type inference. */ interface TypeMap { string: string; number: number; boolean: boolean; json: any; date: Date; datetime: Date; image: { mimeType: string; data: string; }; audio: { format?: 'wav'; data: string; }; file: { mimeType: string; data: string; } | { mimeType: string; fileUri: string; }; url: string; code: string; } type ParseClassOptions = S extends `${infer First},${infer Rest}` ? Trim | ParseClassOptions> : S extends `${infer First}|${infer Rest}` ? Trim | ParseClassOptions> : S extends `${infer First} | ${infer Rest}` ? Trim | ParseClassOptions> : S extends `${infer First}, ${infer Rest}` ? Trim | ParseClassOptions> : Trim; type ResolveType = T extends keyof TypeMap ? TypeMap[T] : T extends `${infer BaseType}[]` ? BaseType extends keyof TypeMap ? TypeMap[BaseType][] : any[] : T extends `class[]|${infer Options}` ? ParseClassOptions[] : T extends `class|${infer Options}` ? ParseClassOptions : T extends 'class' ? string : any; type Trim = S extends ` ${infer T}` ? Trim : S extends `\n${infer T}` ? Trim : S extends `\t${infer T}` ? Trim : S extends `\r${infer T}` ? Trim : S extends `${infer U} ` ? Trim : S extends `${infer U}\n` ? Trim : S extends `${infer U}\t` ? Trim : S extends `${infer U}\r` ? Trim : S; type ParseField = S extends `${infer Name}?!` ? { name: Trim; optional: true; internal: true; } : S extends `${infer Name}!?` ? { name: Trim; optional: true; internal: true; } : S extends `${infer Name}?` ? { name: Trim; optional: true; internal: false; } : S extends `${infer Name}!` ? { name: Trim; optional: false; internal: true; } : { name: Trim; optional: false; internal: false; }; type ExtractType = S extends `class[] "${infer Options}" "${infer _Desc}"` ? `class[]|${Options}` : S extends `class[] "${infer Options}"` ? `class[]|${Options}` : S extends `class "${infer Options}" "${infer _Desc}"` ? `class|${Options}` : S extends `class "${infer Options}"` ? `class|${Options}` : S extends `${infer Type}[] "${infer _Desc}"` ? `${Type}[]` : S extends `${infer Type}[]` ? `${Type}[]` : S extends `${infer Type} "${infer _Desc}"` ? Type : S; type ParseNameAndType = S extends `${infer Name}:${infer TypePart}` ? ParseField & { type: Trim>>; } : S extends `${infer Name} "${infer _Description}"` ? ParseField & { type: 'string'; } : ParseField & { type: 'string'; }; /** * Advanced field splitting that respects quotes using a state machine approach. * * This type-level parser solves the core problem of parsing comma-separated fields * when commas can appear both as field separators AND inside quoted strings. * * PROBLEM EXAMPLE: * Input: 'sourceType:class "class1, class2, class3", relevantContext:string, sources:string' * * Simple comma splitting would incorrectly produce: * ['sourceType:class "class1', ' class2', ' class3"', ' relevantContext:string', ' sources:string'] * * This parser correctly produces: * ['sourceType:class "class1, class2, class3"', 'relevantContext:string', 'sources:string'] * * ALGORITHM: * 1. Process each character in the input string one by one * 2. Track whether we're currently inside or outside quotes * 3. When encountering a quote ("), toggle the quote state * 4. When encountering a comma (,): * - If inside quotes: treat as literal character, add to current field * - If outside quotes: treat as field separator, complete current field and start new one * 5. For all other characters: add to current field being built * * STATE PARAMETERS: * @param S - The remaining string to process * @param Current - The current field being built character by character * @param InQuote - Boolean state tracking if we're inside quotes * @param Result - Accumulator array of completed fields */ type SplitFieldsRespectingQuotes = S extends `${infer Char}${infer Rest}` ? Char extends '"' ? SplitFieldsRespectingQuotes : Char extends ',' ? InQuote extends true ? SplitFieldsRespectingQuotes : Rest extends ` ${infer RestTrimmed}` ? SplitFieldsRespectingQuotes : SplitFieldsRespectingQuotes : SplitFieldsRespectingQuotes : Current extends '' ? Result : [...Result, Current]; /** * Convert string array to parsed field objects. * * Takes the array of field strings produced by SplitFieldsRespectingQuotes * and converts each string into a structured field object with name, type, and optional properties. * * EXAMPLE: * Input: ['sourceType:class "class1, class2, class3"', 'relevantContext:string', 'sources:string'] * Output: [ * { name: 'sourceType', type: 'class|class1, class2, class3', optional: false }, * { name: 'relevantContext', type: 'string', optional: false }, * { name: 'sources', type: 'string', optional: false } * ] */ type StringArrayToFields = T extends readonly [ infer First, ...infer Rest ] ? First extends string ? Rest extends readonly string[] ? [ParseNameAndType>, ...StringArrayToFields] : [ParseNameAndType>] : [] : []; /** * Main field parser using the quote-aware splitter. * * This is the entry point for parsing a field list string into typed field objects. * It combines the quote-aware splitting with field object conversion to produce * the final tuple that BuildObject can use for type inference. * * FLOW: * 1. SplitFieldsRespectingQuotes: 'field1, field2' -> ['field1', 'field2'] * 2. StringArrayToFields: ['field1', 'field2'] -> [FieldObj1, FieldObj2] * 3. BuildObject: [FieldObj1, FieldObj2] -> { field1: Type1, field2: Type2 } */ type ParseFields = StringArrayToFields>; /** * Builds a TypeScript object type from a readonly tuple of field definitions, * supporting both required and optional fields. */ type BuildObject = { -readonly [K in T[number] as K['internal'] extends true ? never : K['optional'] extends false ? K['name'] : never]: ResolveType; } & { -readonly [K in T[number] as K['internal'] extends true ? never : K['optional'] extends true ? K['name'] : never]?: ResolveType; }; type StripSignatureDescription = S extends `"${infer _Desc}" ${infer Rest}` ? Trim : S; /** * The main signature parser that handles the complete parsing pipeline. * * This is the top-level type that users interact with. It takes a signature string * and produces TypeScript types for both inputs and outputs with proper type inference. * * SIGNATURE FORMAT: * "[description] inputField1:type1, inputField2:type2 -> outputField1:type1, outputField2:type2" * * EXAMPLES: * Simple: 'userQuery:string -> response:string' * Complex: 'searchQuery:string -> sourceType:class "class1, class2, class3", context:string' * With description: '"Analyze text" text:string -> sentiment:class "positive, negative", confidence:number' * * PROCESSING STEPS: * 1. StripSignatureDescription: Remove optional description at start * 2. Split on " -> " to separate inputs from outputs * 3. ParseFields: Use quote-aware parsing for both input and output field lists * 4. BuildObject: Convert field tuples to TypeScript object types * * RESULT TYPE: * { * inputs: { [fieldName]: FieldType }, * outputs: { [fieldName]: FieldType } * } * * Where FieldType is inferred from the signature (string, number, 'option1'|'option2', etc.) */ type ParseSignature = StripSignatureDescription> extends `${infer Inputs} -> ${infer Outputs}` ? { inputs: BuildObject>>; outputs: BuildObject>>; } : { inputs: Record; outputs: Record; }; type AxFieldValue = string | string[] | number | boolean | object | null | undefined | { mimeType: string; data: string; } | { mimeType: string; data: string; }[] | { format?: 'wav'; data: string; } | { format?: 'wav'; data: string; }[]; type AxGenIn = { [key: string]: AxFieldValue; }; type AxGenOut = { [key: string]: AxFieldValue; }; /** * @deprecated AxMessage will be updated to a new design within this major version. * The current structure will be replaced in v15.0.0. * * Migration timeline: * - v14.0.0+: Deprecation warnings (current) * - v14.x: New message design introduced alongside existing * - v15.0.0: Complete replacement with new design */ type AxMessage = { role: 'user'; values: IN; } | { role: 'assistant'; values: IN; }; type AxProgramTrace = { trace: OUT & Partial; programId: string; }; type AxProgramDemos = { traces: (OUT & Partial)[]; programId: string; }; type AxProgramExamples = AxProgramDemos | AxProgramDemos['traces']; type AxResultPickerFunctionFieldResults = { type: 'fields'; results: readonly { index: number; sample: Partial; }[]; }; type AxResultPickerFunctionFunctionResults = { type: 'function'; results: readonly { index: number; functionName: string; functionId: string; args: string | object; result: string; isError?: boolean; }[]; }; type AxResultPickerFunction = (data: AxResultPickerFunctionFieldResults | AxResultPickerFunctionFunctionResults) => number | Promise; type AxProgramForwardOptions = AxAIServiceOptions & { maxRetries?: number; maxSteps?: number; mem?: AxAIMemory; ai?: AxAIService; modelConfig?: AxModelConfig; model?: MODEL; sampleCount?: number; resultPicker?: AxResultPickerFunction; functions?: AxInputFunctionType; functionCall?: AxChatRequest['functionCall']; stopFunction?: string | string[]; functionResultFormatter?: (result: unknown) => string; fastFail?: boolean; showThoughts?: boolean; functionCallMode?: 'auto' | 'native' | 'prompt'; cacheSystemPrompt?: boolean; disableMemoryCleanup?: boolean; traceLabel?: string; description?: string; thoughtFieldName?: string; promptTemplate?: typeof AxPromptTemplate; asserts?: AxAssertion[]; streamingAsserts?: AxStreamingAssertion[]; excludeContentFromTrace?: boolean; strictMode?: boolean; }; type AxAIServiceActionOptions = AxAIServiceOptions & { ai?: Readonly>; functionResultFormatter?: (result: unknown) => string; }; type AxProgramStreamingForwardOptions = Omit, 'stream'>; type AxAIServiceModelType>> = T extends Readonly> ? TModel extends unknown ? TModelKey : TModel | TModelKey : never; type AxProgramForwardOptionsWithModels>> = AxProgramForwardOptions>; type AxProgramStreamingForwardOptionsWithModels>> = AxProgramStreamingForwardOptions>; type AxGenDeltaOut = { version: number; index: number; delta: Partial; }; type AxGenStreamingOut = AsyncGenerator, void, unknown>; type AxSetExamplesOptions = {}; interface AxForwardable { forward(ai: Readonly, values: IN | AxMessage[], options?: Readonly>): Promise; streamingForward(ai: Readonly, values: IN | AxMessage[], options?: Readonly>): AxGenStreamingOut; } interface AxTunable { setExamples: (examples: Readonly>, options?: Readonly) => void; setId: (id: string) => void; setParentId: (parentId: string) => void; getTraces: () => AxProgramTrace[]; setDemos: (demos: readonly AxProgramDemos[]) => void; applyOptimization: (optimizedProgram: AxOptimizedProgram) => void; } interface AxUsable { getUsage: () => AxProgramUsage[]; resetUsage: () => void; } interface AxProgrammable extends AxForwardable, AxTunable, AxUsable { getSignature: () => AxSignature; } type AxProgramUsage = AxChatResponse['modelUsage'] & { ai: string; model: string; }; interface AxProgramOptions { description?: string; traceLabel?: string; } type AxExamples = T extends AxSignature ? OUT & Partial : T extends AxSignatureBuilder ? OUT2 & Partial : T extends AxGen ? OUT4 & Partial : T extends string ? ParseSignature extends { inputs: infer IN3; outputs: infer OUT3; } ? OUT3 & Partial : never : never; type AxGenInput = T extends AxGen ? IN : T extends AxSignature ? IN2 : T extends AxSignatureBuilder ? IN3 : T extends string ? ParseSignature extends { inputs: infer IN4; outputs: any; } ? IN4 : never : never; type AxGenOutput = T extends AxGen ? OUT : T extends AxSignature ? OUT2 : T extends AxSignatureBuilder ? OUT3 : T extends string ? ParseSignature extends { inputs: any; outputs: infer OUT4; } ? OUT4 : never : never; interface AxAIFeatures { functions: boolean; streaming: boolean; functionCot?: boolean; hasThinkingBudget?: boolean; hasShowThoughts?: boolean; /** Enhanced media capability specifications */ media: { /** Image processing capabilities */ images: { /** Whether the provider supports image inputs */ supported: boolean; /** Supported image MIME types (e.g., ['image/jpeg', 'image/png']) */ formats: string[]; /** Maximum image size in bytes */ maxSize?: number; /** Supported detail/quality levels for image processing */ detailLevels?: ('high' | 'low' | 'auto')[]; }; /** Audio processing capabilities */ audio: { /** Whether the provider supports audio inputs */ supported: boolean; /** Supported audio formats (e.g., ['wav', 'mp3']) */ formats: string[]; /** Maximum audio duration in seconds */ maxDuration?: number; }; /** File processing capabilities */ files: { /** Whether the provider supports file inputs */ supported: boolean; /** Supported file MIME types (e.g., ['application/pdf', 'text/plain']) */ formats: string[]; /** Maximum file size in bytes */ maxSize?: number; /** How files are uploaded to the provider */ uploadMethod: 'inline' | 'upload' | 'cloud' | 'none'; }; /** URL and web content capabilities */ urls: { /** Whether the provider supports URL inputs */ supported: boolean; /** Whether the provider can perform web searches */ webSearch: boolean; /** Whether the provider can fetch web page content */ contextFetching: boolean; }; }; /** Content caching capabilities */ caching: { /** Whether the provider supports content caching */ supported: boolean; /** Types of caching available */ types: ('ephemeral' | 'persistent')[]; }; /** Whether the provider supports thinking/reasoning modes */ thinking: boolean; /** Whether the provider supports multi-turn conversations */ multiTurn: boolean; } interface AxBaseAIArgs { name: string; apiURL?: string; headers: () => Promise>; modelInfo: Readonly; defaults: Readonly<{ model: TModel; embedModel?: TEmbedModel; }>; options?: Readonly; supportFor: AxAIFeatures | ((model: TModel) => AxAIFeatures); models?: AxAIInputModelList; } declare const axBaseAIDefaultConfig: () => AxModelConfig; declare const axBaseAIDefaultCreativeConfig: () => AxModelConfig; declare class AxBaseAI implements AxAIService { #private; private readonly aiImpl; private rt?; private fetch?; private tracer?; private meter?; private timeout?; private excludeContentFromTrace?; private models?; private abortSignal?; private logger; private corsProxy?; private modelInfo; private modelUsage?; private embedModelUsage?; private defaults; private lastUsedModelConfig?; private lastUsedChatModel?; private lastUsedEmbedModel?; protected apiURL?: string; protected name: string; protected id: string; protected headers: () => Promise>; protected supportFor: AxAIFeatures | ((model: TModel) => AxAIFeatures); private metrics; constructor(aiImpl: Readonly>, { name, apiURL, headers, modelInfo, defaults, options, supportFor, models, }: Readonly>); private getMetricsInstruments; setName(name: string): void; getId(): string; setAPIURL(apiURL: string): void; setHeaders(headers: () => Promise>): void; get debug(): boolean; setOptions(options: Readonly): void; getOptions(): Readonly; getLogger(): AxLoggerFunction; getModelList(): ({ readonly key: TModelKey; readonly description: string; readonly model: string; readonly embedModel?: undefined; } | { readonly key: TModelKey; readonly description: string; readonly embedModel: string; readonly model?: undefined; })[]; getName(): string; getFeatures(model?: TModel): AxAIFeatures; getLastUsedChatModel(): TModel | undefined; getLastUsedEmbedModel(): TEmbedModel | undefined; getLastUsedModelConfig(): AxModelConfig | undefined; private calculatePercentile; private updateLatencyMetrics; private updateErrorMetrics; private recordTokenUsage; private calculateRequestSize; private calculateResponseSize; private detectMultimodalContent; private calculatePromptLength; private calculateContextWindowUsage; private estimateCost; private estimateCostByName; private recordFunctionCallMetrics; private recordTimeoutMetric; private recordAbortMetric; private recordChatMetrics; private recordEmbedMetrics; getMetrics(): AxAIServiceMetrics; chat(req: Readonly>, options?: Readonly): Promise>; private _chat1; private cleanupFunctionSchema; private _chat2; embed(req: Readonly>, options?: Readonly): Promise; private _embed1; private _embed2; private buildHeaders; private getModelByKey; private getModel; private getEmbedModel; } type AxAIInputModelList = (AxAIModelListBase & { isInternal?: boolean; /** Optional per-model config applied when this key is used (callers still override) */ modelConfig?: Omit; /** Optional per-model options applied when this key is used (callers still override) */ thinkingTokenBudget?: AxAIServiceOptions['thinkingTokenBudget']; showThoughts?: AxAIServiceOptions['showThoughts']; stream?: AxAIServiceOptions['stream']; debug?: AxAIServiceOptions['debug']; useExpensiveModel?: AxAIServiceOptions['useExpensiveModel']; } & ({ model: TModel; } | { embedModel: TEmbedModel; }))[]; type AxAIModelListBase = { key: TModelKey; description: string; }; type AxAIModelList = (AxAIModelListBase & ({ model: string; } | { embedModel: string; }))[]; type AxModelInfo = { name: string; currency?: string; characterIsToken?: boolean; promptTokenCostPer1M?: number; completionTokenCostPer1M?: number; aliases?: string[]; supported?: { thinkingBudget?: boolean; showThoughts?: boolean; }; notSupported?: { temperature?: boolean; topP?: boolean; }; maxTokens?: number; isExpensive?: boolean; contextWindow?: number; }; type AxTokenUsage = { promptTokens: number; completionTokens: number; totalTokens: number; thoughtsTokens?: number; reasoningTokens?: number; cacheCreationTokens?: number; cacheReadTokens?: number; serviceTier?: 'standard' | 'priority' | 'batch'; }; type AxModelConfig = { maxTokens?: number; temperature?: number; topP?: number; topK?: number; presencePenalty?: number; frequencyPenalty?: number; stopSequences?: string[]; endSequences?: string[]; stream?: boolean; n?: number; }; type AxFunctionHandler = (args?: any, extra?: Readonly<{ sessionId?: string; traceId?: string; debug?: boolean; ai?: AxAIService; }>) => unknown; type AxFunctionJSONSchema = { type: string; properties?: Record; required?: string[]; items?: AxFunctionJSONSchema; }; type AxFunction = { name: string; description: string; parameters?: AxFunctionJSONSchema; func: AxFunctionHandler; }; type AxFunctionResult = Extract & { index: number; }; type AxChatResponseResult = { index: number; content?: string; thought?: string; /** Provider-agnostic thinking block with encryption flag */ thoughtBlock?: { data: string; encrypted: boolean; signature?: string; }; name?: string; id?: string; functionCalls?: { id: string; type: 'function'; function: { name: string; params?: string | object; }; }[]; citations?: AxCitation[]; finishReason?: 'stop' | 'length' | 'function_call' | 'content_filter' | 'error'; logprobs?: { content?: { token: string; logprob: number; topLogprobs?: { token: string; logprob: number; }[]; }[]; }; }; type AxCitation = { url: string; title?: string; description?: string; license?: string; publicationDate?: string; snippet?: string; }; type AxModelUsage = { ai: string; model: string; tokens?: AxTokenUsage; citations?: AxCitation[]; }; type AxChatResponse = { sessionId?: string; remoteId?: string; results: readonly AxChatResponseResult[]; modelUsage?: AxModelUsage; }; type AxEmbedResponse = { remoteId?: string; sessionId?: string; embeddings: readonly (readonly number[])[]; modelUsage?: AxModelUsage; }; type AxModelInfoWithProvider = AxModelInfo & { provider: string; }; type AxChatRequest = { chatPrompt: ({ role: 'system'; content: string; cache?: boolean; } | { role: 'user'; name?: string; content: string | ({ type: 'text'; text: string; cache?: boolean; } | { type: 'image'; mimeType: string; image: string; details?: 'high' | 'low' | 'auto'; cache?: boolean; /** Optimization preference for image processing */ optimize?: 'quality' | 'size' | 'auto'; /** Fallback text description when images aren't supported */ altText?: string; } | { type: 'audio'; data: string; format?: 'wav' | 'mp3' | 'ogg'; cache?: boolean; /** Pre-transcribed text content for fallback */ transcription?: string; /** Duration of audio in seconds */ duration?: number; } | { /** File content type with inline data */ type: 'file'; /** File data as base64 */ data: string; /** Original filename */ filename?: string; /** MIME type of the file */ mimeType: string; cache?: boolean; /** Pre-extracted text content for fallback */ extractedText?: string; } | { /** File content type with cloud storage URI */ type: 'file'; /** File URI (e.g., gs:// URL) */ fileUri: string; /** Original filename */ filename?: string; /** MIME type of the file */ mimeType: string; cache?: boolean; /** Pre-extracted text content for fallback */ extractedText?: string; } | { /** URL/Link content type */ type: 'url'; /** The URL to fetch content from */ url: string; cache?: boolean; /** Pre-fetched content for providers without web access */ cachedContent?: string; /** Page title for context */ title?: string; /** Page description for context */ description?: string; })[]; } | { role: 'assistant'; content?: string; name?: string; functionCalls?: { id: string; type: 'function'; function: { name: string; params?: string | object; }; }[]; cache?: boolean; } | { role: 'function'; result: string; isError?: boolean; functionId: string; cache?: boolean; })[]; /** Provider capability preferences and requirements */ capabilities?: { /** Whether the request requires image support */ requiresImages?: boolean; /** Whether the request requires audio support */ requiresAudio?: boolean; /** Whether the request requires file support */ requiresFiles?: boolean; /** Whether the request requires web search capabilities */ requiresWebSearch?: boolean; /** How to handle unsupported content types */ fallbackBehavior?: 'error' | 'degrade' | 'skip'; }; /** Content processing preferences and hints */ processing?: { /** Whether to apply image compression */ imageCompression?: boolean; /** Whether to apply audio transcription */ audioTranscription?: boolean; /** Whether to extract text from files */ fileTextExtraction?: boolean; /** Whether to fetch content from URLs */ urlContentFetching?: boolean; }; functions?: Readonly<{ name: string; description: string; parameters?: AxFunctionJSONSchema; }>[]; functionCall?: 'none' | 'auto' | 'required' | { type: 'function'; function: { name: string; }; }; modelConfig?: AxModelConfig; model?: TModel; }; interface AxAIServiceMetrics { latency: { chat: { mean: number; p95: number; p99: number; samples: number[]; }; embed: { mean: number; p95: number; p99: number; samples: number[]; }; }; errors: { chat: { count: number; rate: number; total: number; }; embed: { count: number; rate: number; total: number; }; }; } type AxInternalChatRequest = Omit & Required, 'model'>>; type AxEmbedRequest = { texts?: readonly string[]; embedModel?: TEmbedModel; }; type AxInternalEmbedRequest = Omit & Required, 'embedModel'>>; type AxRateLimiterFunction = (reqFunc: () => Promise>, info: Readonly<{ modelUsage?: AxModelUsage; }>) => Promise>; type AxLoggerData = { name: 'ChatRequestChatPrompt'; step: number; value: AxChatRequest['chatPrompt']; } | { name: 'FunctionResults'; value: AxFunctionResult[]; } | { name: 'ChatResponseResults'; value: AxChatResponseResult[]; } | { name: 'ChatResponseStreamingResult'; index: number; value: AxChatResponseResult & { delta?: string; }; } | { name: 'ChatResponseStreamingDoneResult'; index: number; value: AxChatResponseResult; } | { name: 'FunctionError'; index: number; fixingInstructions: string; error: unknown; } | { name: 'ValidationError'; index: number; fixingInstructions: string; error: unknown; } | { name: 'AssertionError'; index: number; fixingInstructions: string; error: unknown; } | { name: 'RefusalError'; index: number; error: unknown; } | { name: 'ResultPickerUsed'; sampleCount: number; selectedIndex: number; latency: number; } | { name: 'Notification'; id: string; value: string; } | { name: 'EmbedRequest'; embedModel: string; value: readonly string[]; } | { name: 'EmbedResponse'; totalEmbeddings: number; value: { length: number; sample: number[]; truncated: boolean; }[]; } | { name: 'ChatResponseUsage'; value: AxModelUsage; } | { name: 'ChatResponseCitations'; value: AxCitation[]; }; type AxLoggerFunction = (message: AxLoggerData) => void; type AxAIServiceOptions = { debug?: boolean; rateLimiter?: AxRateLimiterFunction; fetch?: typeof fetch; tracer?: Tracer; meter?: Meter; timeout?: number; excludeContentFromTrace?: boolean; abortSignal?: AbortSignal; logger?: AxLoggerFunction; sessionId?: string; debugHideSystemPrompt?: boolean; traceContext?: Context; stream?: boolean; functionCallMode?: 'auto' | 'native' | 'prompt'; thinkingTokenBudget?: 'minimal' | 'low' | 'medium' | 'high' | 'highest' | 'none'; showThoughts?: boolean; useExpensiveModel?: 'yes'; stepIndex?: number; corsProxy?: string; }; interface AxAIService { getId(): string; getName(): string; getFeatures(model?: TModel): AxAIFeatures; getModelList(): AxAIModelList | undefined; getMetrics(): AxAIServiceMetrics; getLogger(): AxLoggerFunction; getLastUsedChatModel(): TModel | undefined; getLastUsedEmbedModel(): TEmbedModel | undefined; getLastUsedModelConfig(): AxModelConfig | undefined; chat(req: Readonly>, options?: Readonly): Promise>; embed(req: Readonly>, options?: Readonly): Promise; setOptions(options: Readonly): void; getOptions(): Readonly; } interface AxAIServiceImpl { createChatReq(req: Readonly>, config?: Readonly): Promise<[AxAPI, TChatRequest]> | [AxAPI, TChatRequest]; createChatResp(resp: Readonly): AxChatResponse; createChatStreamResp?(resp: Readonly, state: object): AxChatResponse; createEmbedReq?(req: Readonly>): Promise<[AxAPI, TEmbedRequest]> | [AxAPI, TEmbedRequest]; createEmbedResp?(resp: Readonly): AxEmbedResponse; getModelConfig(): AxModelConfig; getTokenUsage(): AxTokenUsage | undefined; } interface AxGEPAEvaluationBatch { outputs: Out[]; scores: number[]; trajectories?: Traj[] | null; } interface AxGEPAAdapter { evaluate(batch: readonly Datum[], candidate: Readonly>, captureTraces?: boolean): Promise> | AxGEPAEvaluationBatch; make_reflective_dataset(candidate: Readonly>, evalBatch: Readonly>, componentsToUpdate: readonly string[]): Record; propose_new_texts?: (candidate: Readonly>, reflectiveDataset: Readonly>, componentsToUpdate: readonly string[]) => Promise> | Record; } type AxExample = Record; type AxTypedExample = IN & { [key: string]: AxFieldValue; }; type AxMetricFn = (arg0: Readonly<{ prediction: T; example: AxExample; }>) => number | Promise; type AxMetricFnArgs = Parameters[0]; type AxMultiMetricFn = (arg0: Readonly<{ prediction: T; example: AxExample; }>) => Record | Promise>; interface AxOptimizationProgress { round: number; totalRounds: number; currentScore: number; bestScore: number; tokensUsed: number; timeElapsed: number; successfulExamples: number; totalExamples: number; currentConfiguration?: Record; bestConfiguration?: Record; convergenceInfo?: { improvement: number; stagnationRounds: number; isConverging: boolean; }; } interface AxCostTracker { trackTokens(count: number, model: string): void; getCurrentCost(): number; getTokenUsage(): Record; getTotalTokens(): number; isLimitReached(): boolean; reset(): void; } interface AxCostTrackerOptions { costPerModel?: Record; maxCost?: number; maxTokens?: number; } interface AxOptimizationCheckpoint { version: string; timestamp: number; optimizerType: string; optimizerConfig: Record; currentRound: number; totalRounds: number; bestScore: number; bestConfiguration?: Record; scoreHistory: number[]; configurationHistory: Record[]; stats: AxOptimizationStats; optimizerState: Record; examples: readonly AxExample[]; } type AxCheckpointSaveFn = (checkpoint: Readonly) => Promise; type AxCheckpointLoadFn = (checkpointId: string) => Promise; interface AxOptimizationStats { totalCalls: number; successfulDemos: number; estimatedTokenUsage: number; earlyStopped: boolean; earlyStopping?: { bestScoreRound: number; patienceExhausted: boolean; reason: string; }; bestScore: number; bestConfiguration?: Record; resourceUsage: { totalTokens: number; totalTime: number; avgLatencyPerEval: number; peakMemoryUsage?: number; costByModel: Record; }; convergenceInfo: { converged: boolean; finalImprovement: number; stagnationRounds: number; convergenceThreshold: number; }; evaluationBreakdown?: { trainingScore: number; validationScore: number; crossValidationScores?: number[]; standardDeviation?: number; }; } type AxOptimizerArgs = { studentAI: AxAIService; teacherAI?: AxAIService; optimizerEndpoint?: string; optimizerTimeout?: number; optimizerRetries?: number; numCandidates?: number; initTemperature?: number; maxBootstrappedDemos?: number; maxLabeledDemos?: number; numTrials?: number; minibatch?: boolean; minibatchSize?: number; minibatchFullEvalSteps?: number; programAwareProposer?: boolean; dataAwareProposer?: boolean; viewDataBatchSize?: number; tipAwareProposer?: boolean; fewshotAwareProposer?: boolean; earlyStoppingTrials?: number; minImprovementThreshold?: number; bayesianOptimization?: boolean; acquisitionFunction?: 'expected_improvement' | 'upper_confidence_bound' | 'probability_improvement'; explorationWeight?: number; sampleCount?: number; resultPicker?: AxResultPickerFunction; optimizeTopP?: boolean; minSuccessRate?: number; targetScore?: number; onProgress?: (progress: Readonly) => void; onEarlyStop?: (reason: string, stats: Readonly) => void; costTracker?: AxCostTracker; checkpointSave?: AxCheckpointSaveFn; checkpointLoad?: AxCheckpointLoadFn; checkpointInterval?: number; resumeFromCheckpoint?: string; logger?: AxLoggerFunction; verbose?: boolean; seed?: number; debugOptimizer?: boolean; optimizerLogger?: (data: AxOptimizerLoggerData) => void; }; interface AxCompileOptions { maxIterations?: number; earlyStoppingPatience?: number; verbose?: boolean; maxDemos?: number; auto?: 'light' | 'medium' | 'heavy'; overrideTargetScore?: number; overrideCostTracker?: AxCostTracker; overrideTeacherAI?: AxAIService; overrideOnProgress?: (progress: Readonly) => void; overrideOnEarlyStop?: (reason: string, stats: Readonly) => void; overrideCheckpointSave?: AxCheckpointSaveFn; overrideCheckpointLoad?: AxCheckpointLoadFn; overrideCheckpointInterval?: number; saveCheckpointOnComplete?: boolean; gepaAdapter?: AxGEPAAdapter; validationExamples?: readonly AxTypedExample[]; feedbackExamples?: readonly AxTypedExample[]; feedbackFn?: (args: Readonly<{ prediction: unknown; example: AxExample; }>) => string | string[] | undefined; skipPerfectScore?: boolean; perfectScore?: number; maxMetricCalls?: number; } /** * Individual playbook bullet with metadata used for incremental updates. * Mirrors the structure described in the ACE paper (Section 3.1). */ interface AxACEBullet extends Record { id: string; section: string; content: string; helpfulCount: number; harmfulCount: number; createdAt: string; updatedAt: string; tags?: string[]; metadata?: Record; } /** * Aggregated ACE playbook structure grouped by sections. */ interface AxACEPlaybook { version: number; sections: Record; stats: { bulletCount: number; helpfulCount: number; harmfulCount: number; tokenEstimate: number; }; updatedAt: string; description?: string; } /** * Generator output format (Appendix B of the paper) distilled to core fields. */ interface AxACEGeneratorOutput extends Record { reasoning: string; answer: unknown; bulletIds: string[]; trajectory?: string; metadata?: Record; } /** * Reflection payload, mapping to the Reflector JSON schema in the paper. */ interface AxACEReflectionOutput extends Record { reasoning: string; errorIdentification: string; rootCauseAnalysis: string; correctApproach: string; keyInsight: string; bulletTags: { id: string; tag: 'helpful' | 'harmful' | 'neutral'; }[]; metadata?: Record; } /** * Curator operations emitted as deltas (Section 3.1). */ type AxACECuratorOperationType = 'ADD' | 'UPDATE' | 'REMOVE'; interface AxACECuratorOperation { type: AxACECuratorOperationType; section: string; bulletId?: string; content?: string; metadata?: Record; } interface AxACECuratorOutput extends Record { reasoning: string; operations: AxACECuratorOperation[]; metadata?: Record; } /** * Runtime feedback captured after each generator rollout for online updates. */ interface AxACEFeedbackEvent { example: AxExample; prediction: unknown; score: number; generatorOutput: AxACEGeneratorOutput; reflection?: AxACEReflectionOutput; curator?: AxACECuratorOutput; timestamp: string; } /** * Configuration options specific to ACE inside Ax. */ interface AxACEOptions { /** * Maximum number of epochs for offline adaptation. */ maxEpochs?: number; /** * Maximum reflector refinement rounds (paper uses up to 5). */ maxReflectorRounds?: number; /** * Maximum bullets allowed in any section before triggering pruning. */ maxSectionSize?: number; /** * Optional similarity threshold used by the semantic deduper. */ similarityThreshold?: number; /** * Whether to automatically create sections when curator emits new ones. */ allowDynamicSections?: boolean; /** * Initial playbook supplied by the caller. */ initialPlaybook?: AxACEPlaybook; } /** * Serialized artifact saved after optimization for future reuse. */ interface AxACEOptimizationArtifact { playbook: AxACEPlaybook; feedback: AxACEFeedbackEvent[]; history: { epoch: number; exampleIndex: number; operations: AxACECuratorOperation[]; }[]; } interface AxACECompileOptions extends AxCompileOptions { aceOptions?: AxACEOptions; } interface AxACEResult extends AxOptimizerResult { optimizedProgram?: AxACEOptimizedProgram; playbook: AxACEPlaybook; artifact: AxACEOptimizationArtifact; } /** * Optimized program artifact that persists ACE playbook updates. */ declare class AxACEOptimizedProgram extends AxOptimizedProgramImpl { readonly playbook: AxACEPlaybook; readonly artifact: AxACEOptimizationArtifact; private readonly baseInstruction?; constructor(config: { baseInstruction?: string; playbook: AxACEPlaybook; artifact: AxACEOptimizationArtifact; bestScore: number; stats: AxOptimizationStats; optimizerType: string; optimizationTime: number; totalRounds: number; converged: boolean; instruction?: string; demos?: AxOptimizedProgram['demos']; examples?: AxExample[]; modelConfig?: AxOptimizedProgram['modelConfig']; scoreHistory?: number[]; configurationHistory?: Record[]; }); applyTo(program: AxGen): void; } /** * AxACE implements the Agentic Context Engineering loop (Generator → Reflector → Curator). * The implementation mirrors the paper's architecture while integrating with the Ax optimizer * ergonomics (unified optimized program artifacts, metrics, and checkpointing). */ declare class AxACE extends AxBaseOptimizer { private readonly aceConfig; private playbook; private generatorHistory; private deltaHistory; private reflectorProgram?; private curatorProgram?; constructor(args: Readonly, options?: Readonly); reset(): void; configureAuto(level: 'light' | 'medium' | 'heavy'): void; compile(program: Readonly>, examples: readonly AxTypedExample[], metricFn: AxMetricFn, options?: AxACECompileOptions): Promise>; /** * Apply ACE updates after each online inference. Mirrors the online adaptation * flow described in the paper; can be called by user-land code between queries. */ applyOnlineUpdate(args: Readonly<{ example: AxExample; prediction: unknown; feedback?: string; }>): Promise; private composeInstruction; private extractProgramInstruction; private createGeneratorOutput; private resolveCuratorOperationTargets; private locateBullet; private locateFallbackBullet; private collectProtectedBulletIds; private normalizeCuratorOperations; private inferOperationsFromReflection; private runReflectionRounds; private runReflector; private runCurator; private getOrCreateReflectorProgram; private getOrCreateCuratorProgram; } declare enum AxAIAnthropicModel { Claude41Opus = "claude-opus-4-1-20250805", Claude4Opus = "claude-opus-4-20250514", Claude4Sonnet = "claude-sonnet-4-20250514", Claude45Sonnet = "claude-sonnet-4-5-20250929", Claude45Haiku = "claude-haiku-4-5", Claude37Sonnet = "claude-3-7-sonnet-latest", Claude35Sonnet = "claude-3-5-sonnet-latest", Claude35Haiku = "claude-3-5-haiku-latest", Claude3Opus = "claude-3-opus-latest", Claude3Sonnet = "claude-3-sonnet-20240229", Claude3Haiku = "claude-3-haiku-20240307", Claude21 = "claude-2.1", ClaudeInstant12 = "claude-instant-1.2" } declare enum AxAIAnthropicVertexModel { Claude37Sonnet = "claude-3-7-sonnet", Claude35Haiku = "claude-3-5-haiku", Claude35Sonnet = "claude-3-5-sonnet", Claude35SonnetV2 = "claude-3-5-sonnet-v2", Claude3Haiku = "claude-3-haiku", Claude3Opus = "claude-3-opus" } type AxAIAnthropicThinkingConfig = { type: 'enabled'; budget_tokens: number; /** Optional: numeric budget hint used in config normalization */ thinkingTokenBudget?: number; /** Optional: include provider thinking content in outputs */ includeThoughts?: boolean; }; type AxAIAnthropicThinkingTokenBudgetLevels = { minimal?: number; low?: number; medium?: number; high?: number; highest?: number; }; type AxAIAnthropicFunctionTool = { name: string; description: string; input_schema?: object; } & AxAIAnthropicChatRequestCacheParam; type AxAIAnthropicWebSearchTool = { type: 'web_search_20250305'; name: string; max_uses?: number; allowed_domains?: string[]; blocked_domains?: string[]; user_location?: { type: 'approximate'; city?: string; region?: string; country?: string; timezone?: string; }; }; type AxAIAnthropicRequestTool = AxAIAnthropicFunctionTool | AxAIAnthropicWebSearchTool; type AxAIAnthropicConfig = AxModelConfig & { model: AxAIAnthropicModel | AxAIAnthropicVertexModel; thinking?: AxAIAnthropicThinkingConfig; thinkingTokenBudgetLevels?: AxAIAnthropicThinkingTokenBudgetLevels; tools?: ReadonlyArray; }; type AxAIAnthropicChatRequestCacheParam = { cache_control?: { type: 'ephemeral'; }; }; type AxAIAnthropicChatRequest = { model?: string; anthropic_version?: string; messages: ({ role: 'user'; content: string | (({ type: 'text'; text: string; } & AxAIAnthropicChatRequestCacheParam) | ({ type: 'image'; source: { type: 'base64'; media_type: string; data: string; }; } & AxAIAnthropicChatRequestCacheParam) | { type: 'tool_result'; is_error?: boolean; tool_use_id: string; content: string | (({ type: 'text'; text: string; } & AxAIAnthropicChatRequestCacheParam) | ({ type: 'image'; source: { type: 'base64'; media_type: string; data: string; }; } & AxAIAnthropicChatRequestCacheParam))[]; })[]; } | { role: 'assistant'; content: string | ({ type: 'text'; text: string; } | { type: 'tool_use'; id: string; name: string; input: object; } | { type: 'thinking'; thinking: string; signature?: string; } | { type: 'redacted_thinking'; data: string; signature?: string; })[]; })[]; tools?: AxAIAnthropicRequestTool[]; tool_choice?: { type: 'auto' | 'any'; } | { type: 'tool'; name?: string; }; max_tokens?: number; stop_sequences?: string[]; stream?: boolean; system?: string | ({ type: 'text'; text: string; } & AxAIAnthropicChatRequestCacheParam)[]; temperature?: number; top_p?: number; top_k?: number; thinking?: AxAIAnthropicThinkingConfig; metadata?: { user_id: string; }; }; type AxAIAnthropicChatResponse = { id: string; type: 'message'; role: 'assistant'; content: ({ type: 'text'; text: string; } | { id: string; name: string; type: 'tool_use'; input?: string; } | { type: 'thinking'; thinking: string; signature?: string; } | { type: 'redacted_thinking'; thinking?: string; data?: string; signature?: string; })[]; model: string; stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use'; stop_sequence?: string; usage: { input_tokens: number; output_tokens: number; cache_creation_input_tokens?: number; cache_read_input_tokens?: number; }; }; type AxAIAnthropicChatError = { type: 'error'; error: { type: 'authentication_error'; message: string; }; }; interface AxAIAnthropicMessageStartEvent { type: 'message_start'; message: { id: string; type: 'message'; role: 'assistant'; content: []; model: string; stop_reason: null | string; stop_sequence: null | string; usage: { input_tokens: number; output_tokens: number; }; }; } interface AxAIAnthropicContentBlockStartEvent { index: number; type: 'content_block_start'; content_block: { type: 'text'; text: string; } | { type: 'tool_use'; id: string; name: string; input: object; } | { type: 'server_tool_use'; id: string; name: string; input: object; } | { type: 'web_search_tool_result'; tool_use_id: string; content: unknown[]; } | { type: 'thinking'; thinking: string; }; } interface AxAIAnthropicContentBlockDeltaEvent { index: number; type: 'content_block_delta'; delta: { type: 'text_delta'; text: string; } | { type: 'input_json_delta'; partial_json: string; } | { type: 'thinking_delta'; thinking: string; } | { type: 'signature_delta'; signature: string; }; } interface AxAIAnthropicContentBlockStopEvent { type: 'content_block_stop'; index: number; } interface AxAIAnthropicMessageDeltaEvent { type: 'message_delta'; delta: { stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | null; stop_sequence: string | null; }; usage: { output_tokens: number; }; } interface AxAIAnthropicMessageStopEvent { type: 'message_stop'; } interface AxAIAnthropicPingEvent { type: 'ping'; } interface AxAIAnthropicErrorEvent { type: 'error'; error: { type: 'overloaded_error'; message: string; }; } type AxAIAnthropicChatResponseDelta = AxAIAnthropicMessageStartEvent | AxAIAnthropicContentBlockStartEvent | AxAIAnthropicContentBlockDeltaEvent | AxAIAnthropicContentBlockStopEvent | AxAIAnthropicMessageDeltaEvent | AxAIAnthropicMessageStopEvent | AxAIAnthropicPingEvent | AxAIAnthropicErrorEvent; declare const axAIAnthropicDefaultConfig: () => AxAIAnthropicConfig; declare const axAIAnthropicVertexDefaultConfig: () => AxAIAnthropicConfig; type ExtractModelKeys$1 = T extends readonly { key: infer K; }[] ? K : never; interface AxAIAnthropicArgs { name: 'anthropic'; apiKey?: string | (() => Promise); projectId?: string; region?: string; config?: Readonly>; options?: Readonly; models?: AxAIInputModelList; } declare class AxAIAnthropic extends AxBaseAI { static create>(options: T): T extends { models: infer M; } ? AxAIAnthropic> : AxAIAnthropic; constructor({ apiKey, projectId, region, config, options, models, }: Readonly, 'name'>>); } declare enum AxAIOpenAIModel { GPT4 = "gpt-4", GPT41 = "gpt-4.1", GPT41Mini = "gpt-4.1-mini", GPT41Nano = "gpt-4.1-nano", GPT4O = "gpt-4o", GPT4OMini = "gpt-4o-mini", GPT4ChatGPT4O = "chatgpt-4o-latest", GPT4Turbo = "gpt-4-turbo", GPT35Turbo = "gpt-3.5-turbo", GPT35TurboInstruct = "gpt-3.5-turbo-instruct", GPT35TextDavinci002 = "text-davinci-002", GPT3TextBabbage002 = "text-babbage-002", GPT3TextAda001 = "text-ada-001", GPT5 = "gpt-5", GPT5Nano = "gpt-5-nano", GPT5Mini = "gpt-5-mini", GPT5Chat = "gpt-5-chat", O1 = "o1", O1Mini = "o1-mini", O3 = "o3", O3Mini = "o3-mini", O4Mini = "o4-mini" } declare enum AxAIOpenAIEmbedModel { TextEmbeddingAda002 = "text-embedding-ada-002", TextEmbedding3Small = "text-embedding-3-small", TextEmbedding3Large = "text-embedding-3-large" } type AxAIOpenAIUrlCitation = { url: string; title?: string; description?: string; }; type AxAIOpenAIAnnotation = { type: 'url_citation'; url_citation: AxAIOpenAIUrlCitation; }; type AxAIOpenAIConfig = Omit & { model: TModel; embedModel?: TEmbedModel; user?: string; responseFormat?: 'json_object'; bestOf?: number; logitBias?: Map; suffix?: string | null; stop?: string[]; logprobs?: number; echo?: boolean; dimensions?: number; reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high'; store?: boolean; serviceTier?: 'auto' | 'default' | 'flex'; webSearchOptions?: { searchContextSize?: 'low' | 'medium' | 'high'; userLocation?: { approximate: { type: 'approximate'; city?: string; country?: string; region?: string; timezone?: string; }; } | null; }; }; type AxAIOpenAILogprob = { tokens: string[]; token_logprobs: number[]; top_logprobs: Map; text_offset: number[]; }; type AxAIOpenAIUsage = { prompt_tokens: number; completion_tokens: number; total_tokens: number; }; interface AxAIOpenAIResponseDelta { id: string; object: string; created: number; model: string; choices: { index: number; delta: T; finish_reason: 'stop' | 'length' | 'content_filter' | 'tool_calls'; }[]; usage?: AxAIOpenAIUsage; system_fingerprint: string; } type AxAIOpenAIChatRequest = { model: TModel; reasoning_effort?: 'minimal' | 'low' | 'medium' | 'high'; store?: boolean; messages: ({ role: 'system'; content: string; } | { role: 'user'; content: string | ({ type: string; text: string; } | { type: 'image_url'; image_url: { url: string; details?: 'high' | 'low' | 'auto'; }; } | { type: 'input_audio'; input_audio: { data: string; format?: 'wav'; }; } | { type: 'file'; file: { file_data: string; filename: string; }; })[]; name?: string; } | { role: 'assistant'; content: string | { type: string; text: string; }; name?: string; } | { role: 'assistant'; content?: string | { type: string; text: string; }; name?: string; tool_calls: { type: 'function'; function: { name: string; arguments?: string; }; }[]; } | { role: 'tool'; content: string; tool_call_id: string; })[]; tools?: { type: 'function'; function: { name: string; description: string; parameters?: object; }; }[]; tool_choice?: 'none' | 'auto' | 'required' | { type: 'function'; function: { name: string; }; }; response_format?: { type: string; }; max_completion_tokens?: number; temperature?: number; top_p?: number; n?: number; stream?: boolean; stop?: readonly string[]; presence_penalty?: number; frequency_penalty?: number; logit_bias?: Map; user?: string; organization?: string; web_search_options?: { search_context_size?: 'low' | 'medium' | 'high'; user_location?: { approximate: { type: 'approximate'; city?: string; country?: string; region?: string; timezone?: string; }; } | null; }; }; type AxAIOpenAIChatResponse = { id: string; object: 'chat.completion'; created: number; model: string; choices: { index: number; message: { role: string; content: string | null; refusal: string | null; reasoning_content?: string; annotations?: AxAIOpenAIAnnotation[]; tool_calls?: { id: string; type: 'function'; function: { name: string; arguments: string; }; }[]; }; finish_reason: 'stop' | 'length' | 'content_filter' | 'tool_calls'; }[]; usage?: AxAIOpenAIUsage; error?: { message: string; type: string; param: string; code: number; }; system_fingerprint: string; }; type AxAIOpenAIChatResponseDelta = AxAIOpenAIResponseDelta<{ content: string | null; refusal?: string | null; reasoning_content?: string; role?: string; annotations?: AxAIOpenAIAnnotation[]; tool_calls?: (NonNullable[0] & { index: number; })[]; }>; type AxAIOpenAIEmbedRequest = { input: readonly string[]; model: TEmbedModel; dimensions?: number; user?: string; }; type AxAIOpenAIEmbedResponse = { model: string; data: { embedding: readonly number[]; index: number; }[]; usage: AxAIOpenAIUsage; }; declare const axAIOpenAIDefaultConfig: () => AxAIOpenAIConfig; declare const axAIOpenAIBestConfig: () => AxAIOpenAIConfig; declare const axAIOpenAICreativeConfig: () => AxAIOpenAIConfig; declare const axAIOpenAIFastConfig: () => AxAIOpenAIConfig; interface AxAIOpenAIArgs = AxAIOpenAIChatRequest> extends Omit, 'config' | 'supportFor' | 'modelInfo'> { name: TName; modelInfo?: AxModelInfo[]; config?: Partial['config']>; } type ChatReqUpdater> = (req: Readonly) => TChatReq; interface AxAIOpenAIBaseArgs> { apiKey: string; apiURL?: string; config: Readonly>; options?: Readonly; modelInfo: Readonly; models?: AxAIInputModelList; chatReqUpdater?: ChatReqUpdater; supportFor: AxAIFeatures | ((model: TModel) => AxAIFeatures); } declare class AxAIOpenAIBase = AxAIOpenAIChatRequest> extends AxBaseAI, AxAIOpenAIEmbedRequest, AxAIOpenAIChatResponse, AxAIOpenAIChatResponseDelta, AxAIOpenAIEmbedResponse, TModelKey> { constructor({ apiKey, config, options, apiURL, modelInfo, models, chatReqUpdater, supportFor, }: Readonly, 'name'>>); } declare class AxAIOpenAI extends AxAIOpenAIBase { constructor({ apiKey, apiURL, config, options, models, modelInfo, }: Readonly, 'name'>>); } declare const axAIAzureOpenAIDefaultConfig: () => AxAIOpenAIConfig; declare const axAIAzureOpenAICreativeConfig: () => AxAIOpenAIConfig; declare const axAIAzureOpenAIFastConfig: () => AxAIOpenAIConfig; declare const axAIAzureOpenAIBestConfig: () => AxAIOpenAIConfig; type AxAIAzureOpenAIConfig = AxAIOpenAIConfig; type AxAIAzureOpenAIArgs = AxAIOpenAIArgs<'azure-openai', AxAIOpenAIModel, AxAIOpenAIEmbedModel, TModelKey> & { resourceName: string; deploymentName: string; version?: string; }; declare class AxAIAzureOpenAI extends AxAIOpenAIBase { constructor({ apiKey, resourceName, deploymentName, version, config, options, models, modelInfo, }: Readonly, 'name'>>); } /** * Cohere: Models for text generation */ declare enum AxAICohereModel { CommandRPlus = "command-r-plus", CommandR = "command-r", Command = "command", CommandLight = "command-light" } /** * Cohere: Models for use in embeddings */ declare enum AxAICohereEmbedModel { EmbedEnglishV30 = "embed-english-v3.0", EmbedEnglishLightV30 = "embed-english-light-v3.0", EmbedMultiLingualV30 = "embed-multilingual-v3.0", EmbedMultiLingualLightV30 = "embed-multilingual-light-v3.0" } /** * Cohere: Model options for text generation */ type AxAICohereConfig = AxModelConfig & { model: AxAICohereModel; embedModel?: AxAICohereEmbedModel; }; type AxAICohereChatResponseToolCalls = { name: string; parameters?: object; }[]; type AxAICohereChatRequestToolResults = { call: AxAICohereChatResponseToolCalls[0]; outputs: object[]; }[]; type AxAICohereChatRequest = { message?: string; preamble?: string; chat_history: ({ role: 'CHATBOT'; message: string; tool_calls?: AxAICohereChatResponseToolCalls; } | { role: 'SYSTEM'; message: string; } | { role: 'USER'; message: string; } | { role: 'TOOL'; message?: string; tool_results: AxAICohereChatRequestToolResults; })[]; model: AxAICohereModel; max_tokens?: number; temperature?: number; k?: number; p?: number; frequency_penalty?: number; presence_penalty?: number; end_sequences?: readonly string[]; stop_sequences?: string[]; tools?: { name: string; description: string; parameter_definitions: Record; }[]; tool_results?: AxAICohereChatRequestToolResults; }; type AxAICohereChatResponse = { response_id: string; meta: { billed_units: { input_tokens: number; output_tokens: number; }; }; generation_id: string; text: string; finish_reason: 'COMPLETE' | 'ERROR' | 'ERROR_TOXIC' | 'ERROR_LIMIT' | 'USER_CANCEL' | 'MAX_TOKENS'; tool_calls: AxAICohereChatResponseToolCalls; }; type AxAICohereChatResponseDelta = AxAICohereChatResponse & { event_type: 'stream-start' | 'text-generation' | 'tool-calls-generation' | 'stream-end'; }; type AxAICohereEmbedRequest = { texts: readonly string[]; model: AxAICohereEmbedModel; truncate: string; }; type AxAICohereEmbedResponse = { id: string; texts: string[]; model: AxAICohereEmbedModel; embeddings: number[][]; }; /** * Creates the default configuration for Cohere AI service * @returns A deep clone of the default Cohere configuration with CommandRPlus model and EmbedEnglishV30 embed model */ declare const axAICohereDefaultConfig: () => AxAICohereConfig; /** * Creates a creative configuration for Cohere AI service with more flexible parameters * @returns A deep clone of the creative Cohere configuration with CommandR model and EmbedEnglishV30 embed model */ declare const axAICohereCreativeConfig: () => AxAICohereConfig; /** * Configuration arguments for initializing the Cohere AI service * @template TModelKey - The type of model keys supported */ interface AxAICohereArgs { name: 'cohere'; apiKey: string; config?: Readonly>; options?: Readonly; models?: AxAIInputModelList; } /** * Main Cohere AI service class that extends the base AI implementation * @template TModelKey - The type of model keys supported */ declare class AxAICohere extends AxBaseAI { /** * Creates a new instance of AxAICohere * @param args - Configuration arguments including API key, config, options, and models */ constructor({ apiKey, config, options, models, }: Readonly, 'name'>>); } /** * DeepSeek: Models for text generation */ declare enum AxAIDeepSeekModel { DeepSeekChat = "deepseek-chat", DeepSeekCoder = "deepseek-coder", DeepSeekReasoner = "deepseek-reasoner" } /** * Configuration type for DeepSeek AI models */ type DeepSeekConfig = AxAIOpenAIConfig; /** * Creates the default configuration for DeepSeek AI with the chat model * @returns Default DeepSeek configuration with chat model settings */ declare const axAIDeepSeekDefaultConfig: () => DeepSeekConfig; /** * Creates a configuration optimized for code generation tasks using DeepSeek Coder * @returns DeepSeek configuration with creative settings for coding tasks */ declare const axAIDeepSeekCodeConfig: () => DeepSeekConfig; /** * Arguments type for initializing DeepSeek AI instances * @template TModelKey - The model key type for type safety */ type AxAIDeepSeekArgs = AxAIOpenAIArgs<'deepseek', AxAIDeepSeekModel, undefined, TModelKey>; /** * DeepSeek AI client implementation extending OpenAI base functionality * Provides access to DeepSeek's language models through OpenAI-compatible API * @template TModelKey - The model key type for type safety */ declare class AxAIDeepSeek extends AxAIOpenAIBase { /** * Creates a new DeepSeek AI client instance * @param args - Configuration arguments for the DeepSeek client * @param args.apiKey - DeepSeek API key for authentication * @param args.config - Optional configuration overrides * @param args.options - Optional client options * @param args.models - Optional model definitions * @param args.modelInfo - Optional additional model information * @throws {Error} When API key is not provided or empty */ constructor({ apiKey, config, options, models, modelInfo, }: Readonly, 'name'>>); } declare enum AxAIGoogleGeminiModel { Gemini25Pro = "gemini-2.5-pro", Gemini25Flash = "gemini-2.5-flash", Gemini25FlashLite = "gemini-2.5-flash-lite", Gemini20Flash = "gemini-2.0-flash", Gemini20FlashLite = "gemini-2.0-flash-lite", Gemini1Pro = "gemini-1.0-pro", Gemini15Flash = "gemini-1.5-flash", Gemini15Flash002 = "gemini-1.5-flash-002", Gemini15Flash8B = "gemini-1.5-flash-8b", Gemini15Pro = "gemini-1.5-pro", GeminiFlashLatest = "gemini-flash-latest", GeminiFlashLiteLatest = "gemini-flash-lite-latest", GeminiProLatest = "gemini-pro-latest" } declare enum AxAIGoogleGeminiEmbedModel { GeminiEmbedding = "gemini-embedding-exp", TextEmbeddingLarge = "text-embedding-large-exp-03-07", TextEmbedding004 = "text-embedding-004", TextEmbedding005 = "text-embedding-005" } declare enum AxAIGoogleGeminiSafetyCategory { HarmCategoryHarassment = "HARM_CATEGORY_HARASSMENT", HarmCategoryHateSpeech = "HARM_CATEGORY_HATE_SPEECH", HarmCategorySexuallyExplicit = "HARM_CATEGORY_SEXUALLY_EXPLICIT", HarmCategoryDangerousContent = "HARM_CATEGORY_DANGEROUS_CONTENT" } declare enum AxAIGoogleGeminiSafetyThreshold { BlockNone = "BLOCK_NONE", BlockOnlyHigh = "BLOCK_ONLY_HIGH", BlockMediumAndAbove = "BLOCK_MEDIUM_AND_ABOVE", BlockLowAndAbove = "BLOCK_LOW_AND_ABOVE", BlockDefault = "HARM_BLOCK_THRESHOLD_UNSPECIFIED" } declare enum AxAIGoogleGeminiEmbedTypes { SemanticSimilarity = "SEMANTIC_SIMILARITY", Classification = "CLASSIFICATION", Clustering = "CLUSTERING", RetrievalDocument = "RETRIEVAL_DOCUMENT", RetrievalQuery = "RETRIEVAL_QUERY", QuestionAnswering = "QUESTION_ANSWERING", FactVerification = "FACT_VERIFICATION", CodeRetrievalQuery = "CODE_RETRIEVAL_QUERY" } type AxAIGoogleGeminiContent = { role: 'user' | 'model'; parts: AxAIGoogleGeminiContentPart[]; }; type AxAIGoogleGeminiContentPart = { thought?: boolean; metadata?: { videoMetadata: object; }; } & ({ text: string; } | { inlineData: { mimeType: string; data: string; }; } | { functionCall: { name: string; args: object; }; } | { functionResponse: { name: string; response: object; }; } | { fileData: { mimeType: string; fileUri: string; }; } | { executableCode: object; } | { codeExecutionResult: object; }); type AxAIGoogleGeminiToolFunctionDeclaration = { name: string; description?: string; parameters?: object; }; type AxAIGoogleGeminiToolGoogleSearchRetrieval = { dynamic_retrieval_config: { mode?: 'MODE_DYNAMIC'; dynamic_threshold?: number; }; }; type AxAIGoogleGeminiToolGoogleMaps = { enableWidget?: boolean; }; type AxAIGoogleGeminiTool = { function_declarations?: AxAIGoogleGeminiToolFunctionDeclaration[]; code_execution?: object; google_search_retrieval?: AxAIGoogleGeminiToolGoogleSearchRetrieval; google_search?: object; url_context?: object; google_maps?: AxAIGoogleGeminiToolGoogleMaps; }; type AxAIGoogleGeminiToolConfig = { function_calling_config: { mode: 'ANY' | 'NONE' | 'AUTO'; allowed_function_names?: string[]; }; retrievalConfig?: AxAIGoogleGeminiRetrievalConfig; }; type AxAIGoogleGeminiGenerationConfig = { temperature?: number; topP?: number; topK?: number; frequencyPenalty?: number; candidateCount?: number; maxOutputTokens?: number; stopSequences?: readonly string[]; responseMimeType?: string; thinkingConfig?: { thinkingBudget?: number; includeThoughts?: boolean; }; }; type AxAIGoogleGeminiRetrievalConfig = { latLng?: { latitude: number; longitude: number; }; }; type AxAIGoogleGeminiSafetySettings = { category: AxAIGoogleGeminiSafetyCategory; threshold: AxAIGoogleGeminiSafetyThreshold; }[]; type AxAIGoogleGeminiChatRequest = { contents: AxAIGoogleGeminiContent[]; tools?: AxAIGoogleGeminiTool[]; toolConfig?: AxAIGoogleGeminiToolConfig; systemInstruction?: AxAIGoogleGeminiContent; generationConfig: AxAIGoogleGeminiGenerationConfig; safetySettings?: AxAIGoogleGeminiSafetySettings; }; type AxAIGoogleGeminiChatResponse = { candidates: { content: AxAIGoogleGeminiContent; finishReason: 'STOP' | 'MAX_TOKENS' | 'SAFETY' | 'RECITATION' | 'OTHER' | 'BLOCKLIST' | 'PROHIBITED_CONTENT' | 'SPII' | 'MALFORMED_FUNCTION_CALL' | 'UNEXPECTED_TOOL_CALL' | 'FINISH_REASON_UNSPECIFIED'; citationMetadata: { citations: { startIndex: number; endIndex: number; uri: string; title: string; license: string; publicationDate: { year: number; month: number; day: number; }; }[]; }; groundingMetadata?: { groundingChunks?: { maps?: { title?: string; uri?: string; }; }[]; googleMapsWidgetContextToken?: string; }; }[]; usageMetadata: { promptTokenCount: number; candidatesTokenCount: number; totalTokenCount: number; thoughtsTokenCount: number; }; }; type AxAIGoogleGeminiChatResponseDelta = AxAIGoogleGeminiChatResponse; type AxAIGoogleGeminiThinkingConfig = { thinkingTokenBudget?: number; includeThoughts?: boolean; }; type AxAIGoogleGeminiThinkingTokenBudgetLevels = { minimal?: number; low?: number; medium?: number; high?: number; highest?: number; }; /** * AxAIGoogleGeminiConfig: Configuration options for Google Gemini API */ type AxAIGoogleGeminiConfig = AxModelConfig & { model: AxAIGoogleGeminiModel; embedModel?: AxAIGoogleGeminiEmbedModel; safetySettings?: AxAIGoogleGeminiSafetySettings; embedType?: AxAIGoogleGeminiEmbedTypes; dimensions?: number; autoTruncate?: boolean; thinking?: AxAIGoogleGeminiThinkingConfig; thinkingTokenBudgetLevels?: AxAIGoogleGeminiThinkingTokenBudgetLevels; urlContext?: string; }; /** * AxAIGoogleGeminiEmbedRequest: Structure for making an embedding request to the Google Gemini API. */ type AxAIGoogleGeminiBatchEmbedRequest = { requests: { model: string; content: { parts: { text: string; }[]; }; }[]; }; /** * AxAIGoogleGeminiEmbedResponse: Structure for handling responses from the Google Gemini API embedding requests. */ type AxAIGoogleGeminiBatchEmbedResponse = { embeddings: { values: number[]; }[]; }; /** * AxAIGoogleVertexBatchEmbedRequest: Structure for making an embedding request to the Google Vertex API. */ type AxAIGoogleVertexBatchEmbedRequest = { instances: { content: string; task_type?: AxAIGoogleGeminiEmbedTypes; }[]; parameters: { autoTruncate?: boolean; outputDimensionality?: number; }; }; /** * AxAIGoogleVertexBatchEmbedResponse: Structure for handling responses from the Google Vertex API embedding requests. */ type AxAIGoogleVertexBatchEmbedResponse = { predictions: { embeddings: { values: number[]; }; }[]; }; /** * AxAIGoogleGemini: Default Model options for text generation */ declare const axAIGoogleGeminiDefaultConfig: () => AxAIGoogleGeminiConfig; declare const axAIGoogleGeminiDefaultCreativeConfig: () => AxAIGoogleGeminiConfig; interface AxAIGoogleGeminiOptionsTools { codeExecution?: boolean; googleSearchRetrieval?: { mode?: 'MODE_DYNAMIC'; dynamicThreshold?: number; }; googleSearch?: boolean; urlContext?: boolean; googleMaps?: AxAIGoogleGeminiToolGoogleMaps; retrievalConfig?: AxAIGoogleGeminiRetrievalConfig; } interface AxAIGoogleGeminiArgs { name: 'google-gemini'; apiKey?: string | (() => Promise); projectId?: string; region?: string; endpointId?: string; config?: Readonly>; options?: Readonly; models?: AxAIInputModelList; modelInfo?: AxModelInfo[]; } type ExtractModelKeys = T extends readonly { key: infer K; }[] ? K : never; declare class AxAIGoogleGemini extends AxBaseAI { static create>(options: T): T extends { models: infer M; } ? AxAIGoogleGemini> : AxAIGoogleGemini; constructor({ apiKey, projectId, region, endpointId, config, options, models, modelInfo, }: Readonly, 'name'>>); } declare enum AxAIGroqModel { Llama3_8B = "llama3-8b-8192", Llama33_70B = "llama-3.3-70b-versatile", Mixtral_8x7B = "mixtral-8x7b-32768", Gemma2_9B = "gemma2-9b-it" } type AxAIGroqArgs = AxAIOpenAIArgs<'groq', AxAIGroqModel, undefined, TModelKey> & { options?: Readonly & { tokensPerMinute?: number; }; modelInfo?: AxModelInfo[]; }; declare class AxAIGroq extends AxAIOpenAIBase { constructor({ apiKey, config, options, models, modelInfo, }: Readonly, 'name'>>); setOptions: (options: Readonly) => void; private newRateLimiter; } declare enum AxAIHuggingFaceModel { MetaLlama270BChatHF = "meta-llama/Llama-2-70b-chat-hf" } type AxAIHuggingFaceConfig = AxModelConfig & { model: AxAIHuggingFaceModel; returnFullText?: boolean; doSample?: boolean; maxTime?: number; useCache?: boolean; waitForModel?: boolean; }; type AxAIHuggingFaceRequest = { model: AxAIHuggingFaceModel; inputs: string; parameters: { max_new_tokens?: number; repetition_penalty?: number; temperature?: number; top_p?: number; top_k?: number; return_full_text?: boolean; num_return_sequences?: number; do_sample?: boolean; max_time?: number; }; options?: { use_cache?: boolean; wait_for_model?: boolean; }; }; type AxAIHuggingFaceResponse = { generated_text: string; }; declare const axAIHuggingFaceDefaultConfig: () => AxAIHuggingFaceConfig; declare const axAIHuggingFaceCreativeConfig: () => AxAIHuggingFaceConfig; interface AxAIHuggingFaceArgs { name: 'huggingface'; apiKey: string; config?: Readonly>; options?: Readonly; models?: AxAIInputModelList; } declare class AxAIHuggingFace extends AxBaseAI { constructor({ apiKey, config, options, models, }: Readonly, 'name'>>); } declare enum AxAIMistralModel { Mistral7B = "open-mistral-7b", Mistral8x7B = "open-mixtral-8x7b", MistralSmall = "mistral-small-latest", MistralNemo = "mistral-nemo-latest", MistralLarge = "mistral-large-latest", Codestral = "codestral-latest", OpenCodestralMamba = "open-codestral-mamba", OpenMistralNemo = "open-mistral-nemo-latest" } declare enum AxAIMistralEmbedModels { MistralEmbed = "mistral-embed" } type AxAIMistralConfig = AxAIOpenAIConfig; declare const axAIMistralDefaultConfig: () => AxAIMistralConfig; declare const axAIMistralBestConfig: () => AxAIMistralConfig; type AxAIMistralChatRequest = Omit, 'max_completion_tokens' | 'stream_options' | 'messages'> & { max_tokens?: number; messages: ({ role: 'system'; content: string; } | { role: 'user'; content: string | ({ type: 'text'; text: string; } | { type: 'image_url'; image_url: string; })[]; name?: string; } | { role: 'assistant'; content: string; name?: string; tool_calls?: { type: 'function'; function: { name: string; arguments?: string; }; }[]; } | { role: 'tool'; content: string; tool_call_id: string; })[]; }; type AxAIMistralArgs = AxAIOpenAIArgs<'mistral', AxAIMistralModel, AxAIMistralEmbedModels, TModelKey> & { options?: Readonly & { tokensPerMinute?: number; }; modelInfo?: AxModelInfo[]; }; declare class AxAIMistral extends AxAIOpenAIBase { constructor({ apiKey, config, options, models, modelInfo, }: Readonly, 'name'>>); private updateMessages; } /** * Configuration type for Ollama AI service */ type AxAIOllamaAIConfig = AxAIOpenAIConfig; /** * Creates default configuration for Ollama AI service * @returns Default configuration object with nous-hermes2 model and all-minilm embed model */ declare const axAIOllamaDefaultConfig: () => AxAIOllamaAIConfig; /** * Creates default creative configuration for Ollama AI service * @returns Creative configuration object with nous-hermes2 model and all-minilm embed model */ declare const axAIOllamaDefaultCreativeConfig: () => AxAIOllamaAIConfig; /** * Arguments type for initializing Ollama AI service * @template TModelKey - Type for model key */ type AxAIOllamaArgs = AxAIOpenAIArgs<'ollama', string, string, TModelKey> & { model?: string; embedModel?: string; url?: string; }; /** * Ollama AI service implementation that extends OpenAI base functionality * Provides access to locally hosted Ollama models with OpenAI-compatible API * @template TModelKey - Type for model key */ declare class AxAIOllama extends AxAIOpenAIBase { /** * Creates a new Ollama AI service instance * @param args - Configuration arguments for the Ollama service * @param args.apiKey - API key for authentication (defaults to 'not-set') * @param args.url - Base URL for the Ollama API (defaults to 'http://localhost:11434/v1') * @param args.config - Additional configuration options * @param args.options - Service options * @param args.models - Available models configuration */ constructor({ apiKey, url, config, options, models, }: Readonly, 'name'>>); } declare enum AxAIOpenAIResponsesModel { GPT4 = "gpt-4", GPT41 = "gpt-4.1", GPT41Mini = "gpt-4.1-mini", GPT41Nano = "gpt-4.1-nano", GPT4O = "gpt-4o", GPT4OMini = "gpt-4o-mini", GPT4ChatGPT4O = "chatgpt-4o-latest", GPT4Turbo = "gpt-4-turbo", GPT35Turbo = "gpt-3.5-turbo", GPT35TurboInstruct = "gpt-3.5-turbo-instruct", GPT35TextDavinci002 = "text-davinci-002", GPT3TextBabbage002 = "text-babbage-002", GPT3TextAda001 = "text-ada-001", GPT5 = "gpt-5", GPT5Nano = "gpt-5-nano", GPT5Mini = "gpt-5-mini", GPT5Chat = "gpt-5-chat", O1Pro = "o1-pro", O1 = "o1", O1Mini = "o1-mini", O3Pro = "o3-pro", O3 = "o3", O3Mini = "o3-mini", O4Mini = "o4-mini" } interface AxAIOpenAIResponsesInputTextContentPart { readonly type: 'input_text'; text: string; } interface AxAIOpenAIResponsesInputImageUrlContentPart { readonly type: 'input_image'; readonly image_url: { readonly url: string; readonly details?: 'low' | 'high' | 'auto'; }; } interface AxAIOpenAIResponsesInputAudioContentPart { readonly type: 'input_audio'; readonly input_audio: { readonly data: string; readonly format?: string; }; } type AxAIOpenAIResponsesInputContentPart = AxAIOpenAIResponsesInputTextContentPart | AxAIOpenAIResponsesInputImageUrlContentPart | AxAIOpenAIResponsesInputAudioContentPart | AxAIOpenAIResponsesOutputTextContentPart; interface AxAIOpenAIResponsesInputMessageItem { readonly type: 'message'; readonly role: 'system' | 'user' | 'assistant' | 'developer'; readonly content: string | ReadonlyArray; readonly name?: string; } interface AxAIOpenAIResponsesInputFunctionCallItem { readonly type: 'function_call'; readonly id?: string; readonly call_id: string; readonly name: string; readonly arguments: string; } interface AxAIOpenAIResponsesInputFunctionCallOutputItem { readonly type: 'function_call_output'; readonly id?: string; readonly call_id: string; readonly output: string; } type AxAIOpenAIResponsesInputItem = string | AxAIOpenAIResponsesInputMessageItem | AxAIOpenAIResponsesInputFunctionCallItem | AxAIOpenAIResponsesInputFunctionCallOutputItem; interface AxAIOpenAIResponsesDefineFunctionTool { readonly type: 'function'; readonly name: string; readonly description?: string; readonly parameters: object; readonly strict?: boolean; } type AxAIOpenAIResponsesToolDefinition = AxAIOpenAIResponsesDefineFunctionTool; type AxAIOpenAIResponsesToolChoice = 'none' | 'auto' | 'required' | { readonly type: 'function'; readonly name: string; } | { readonly type: 'file_search'; }; interface AxAIOpenAIResponsesRequest { readonly input: string | ReadonlyArray; readonly model: TModel; readonly background?: boolean | null; readonly include?: ReadonlyArray<'file_search_call.results' | 'message.input_image.image_url' | 'computer_call_output.output.image_url' | 'reasoning.encrypted_content' | 'code_interpreter_call.outputs'> | null; readonly instructions?: string | null; readonly max_output_tokens?: number | null; readonly metadata?: Readonly> | null; readonly parallel_tool_calls?: boolean | null; readonly previous_response_id?: string | null; readonly reasoning?: { readonly effort?: 'minimal' | 'low' | 'medium' | 'high' | null; readonly summary?: 'auto' | 'concise' | 'detailed' | null; } | null; readonly service_tier?: 'auto' | 'default' | 'flex' | null; readonly store?: boolean | null; readonly stream?: boolean | null; readonly temperature?: number | null; readonly text?: { readonly format?: { readonly type: 'text'; } | { readonly type: 'json_object'; } | { readonly type: 'json_schema'; readonly json_schema?: object; } | null; } | null; readonly tool_choice?: AxAIOpenAIResponsesToolChoice | null; readonly tools?: ReadonlyArray | null; readonly top_p?: number | null; readonly truncation?: 'auto' | 'disabled' | null; readonly user?: string | null; readonly seed?: number | null; } interface AxAIOpenAIResponsesOutputMessageItem { type: 'message'; id: string; role: 'assistant'; content: ReadonlyArray; status: 'in_progress' | 'completed' | 'incomplete'; } interface AxAIOpenAIResponsesFunctionCallItem { type: 'function_call'; id: string; call_id: string; name: string; arguments: string; status?: 'in_progress' | 'completed' | 'incomplete' | 'searching' | 'failed'; } interface AxAIOpenAIResponsesReasoningItem { readonly type: 'reasoning'; readonly id: string; readonly summary: ReadonlyArray<{ type: 'summary_text'; text: string; }>; readonly encrypted_content?: string | null; readonly status?: 'in_progress' | 'completed' | 'incomplete'; } interface AxAIOpenAIResponsesOutputTextContentPart { readonly type: 'output_text'; readonly text: string; readonly annotations?: ReadonlyArray; } interface AxAIOpenAIResponsesOutputRefusalContentPart { readonly type: 'refusal'; readonly refusal: string; } interface AxAIOpenAIResponsesReasoningSummaryPart { readonly type: 'summary_text'; readonly text: string; } type AxAIOpenAIResponsesOutputItem = AxAIOpenAIResponsesOutputMessageItem | AxAIOpenAIResponsesFunctionCallItem | AxAIOpenAIResponsesReasoningItem | AxAIOpenAIResponsesFileSearchToolCall | AxAIOpenAIResponsesWebSearchToolCall | AxAIOpenAIResponsesComputerToolCall | AxAIOpenAIResponsesCodeInterpreterToolCall | AxAIOpenAIResponsesImageGenerationToolCall | AxAIOpenAIResponsesLocalShellToolCall | AxAIOpenAIResponsesMCPToolCall; interface AxAIOpenAIResponsesResponse { readonly id: string; readonly object: string; readonly created: number; readonly model: string; readonly output: ReadonlyArray; readonly usage?: { readonly prompt_tokens: number; readonly completion_tokens?: number; readonly output_tokens?: number; readonly total_tokens: number; } | null; } interface AxAIOpenAIResponsesStreamEventBase { readonly type: string; readonly sequence_number: number; } interface AxAIOpenAIResponsesResponseCreatedEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.created'; readonly response: Readonly; } interface AxAIOpenAIResponsesResponseInProgressEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.in_progress'; readonly response: Readonly; } interface AxAIOpenAIResponsesResponseCompletedEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.completed'; readonly response: Readonly; } interface AxAIOpenAIResponsesResponseFailedEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.failed'; readonly response: Readonly; } interface AxAIOpenAIResponsesResponseIncompleteEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.incomplete'; readonly response: Readonly; } interface AxAIOpenAIResponsesResponseQueuedEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.queued'; readonly response: Readonly; } interface AxAIOpenAIResponsesOutputItemAddedEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.output_item.added'; readonly output_index: number; readonly item: Readonly; } interface AxAIOpenAIResponsesOutputItemDoneEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.output_item.done'; readonly output_index: number; readonly item: Readonly; } interface AxAIOpenAIResponsesContentPartAddedEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.content_part.added'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly part: Readonly; } interface AxAIOpenAIResponsesContentPartDoneEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.content_part.done'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly part: Readonly; } interface AxAIOpenAIResponsesOutputTextDeltaEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.output_text.delta'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly delta: string; } interface AxAIOpenAIResponsesOutputTextDoneEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.output_text.done'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly text: string; } interface AxAIOpenAIResponsesRefusalDeltaEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.refusal.delta'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly delta: string; } interface AxAIOpenAIResponsesRefusalDoneEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.refusal.done'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly refusal: string; } interface AxAIOpenAIResponsesFunctionCallArgumentsDeltaEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.function_call_arguments.delta'; readonly item_id: string; readonly output_index: number; readonly delta: string; } interface AxAIOpenAIResponsesFunctionCallArgumentsDoneEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.function_call_arguments.done'; readonly item_id: string; readonly output_index: number; readonly arguments: string; } interface AxAIOpenAIResponsesFileSearchCallInProgressEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.file_search_call.in_progress'; readonly item_id: string; readonly output_index: number; } interface AxAIOpenAIResponsesFileSearchCallSearchingEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.file_search_call.searching'; readonly item_id: string; readonly output_index: number; } interface AxAIOpenAIResponsesFileSearchCallCompletedEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.file_search_call.completed'; readonly item_id: string; readonly output_index: number; } interface AxAIOpenAIResponsesWebSearchCallInProgressEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.web_search_call.in_progress'; readonly item_id: string; readonly output_index: number; } interface AxAIOpenAIResponsesWebSearchCallSearchingEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.web_search_call.searching'; readonly item_id: string; readonly output_index: number; } interface AxAIOpenAIResponsesWebSearchCallCompletedEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.web_search_call.completed'; readonly item_id: string; readonly output_index: number; } interface AxAIOpenAIResponsesReasoningDeltaEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.reasoning.delta'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly delta: object; } interface AxAIOpenAIResponsesReasoningDoneEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.reasoning.done'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly text: string; } interface AxAIOpenAIResponsesReasoningSummaryPartAddedEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.reasoning_summary_part.added'; readonly item_id: string; readonly output_index: number; readonly summary_index: number; readonly part: Readonly; } interface AxAIOpenAIResponsesReasoningSummaryPartDoneEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.reasoning_summary_part.done'; readonly item_id: string; readonly output_index: number; readonly summary_index: number; readonly part: Readonly; } interface AxAIOpenAIResponsesReasoningSummaryTextDeltaEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.reasoning_summary_text.delta'; readonly item_id: string; readonly output_index: number; readonly summary_index: number; readonly delta: string; } interface AxAIOpenAIResponsesReasoningSummaryTextDoneEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.reasoning_summary_text.done'; readonly item_id: string; readonly output_index: number; readonly summary_index: number; readonly text: string; } interface AxAIOpenAIResponsesReasoningSummaryDeltaEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.reasoning_summary.delta'; readonly item_id: string; readonly output_index: number; readonly summary_index: number; readonly delta: object; } interface AxAIOpenAIResponsesReasoningSummaryDoneEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.reasoning_summary.done'; readonly item_id: string; readonly output_index: number; readonly summary_index: number; readonly text: string; } interface AxAIOpenAIResponsesImageGenerationCallInProgressEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.image_generation_call.in_progress'; readonly item_id: string; readonly output_index: number; } interface AxAIOpenAIResponsesImageGenerationCallGeneratingEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.image_generation_call.generating'; readonly item_id: string; readonly output_index: number; } interface AxAIOpenAIResponsesImageGenerationCallCompletedEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.image_generation_call.completed'; readonly item_id: string; readonly output_index: number; } interface AxAIOpenAIResponsesImageGenerationCallPartialImageEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.image_generation_call.partial_image'; readonly item_id: string; readonly output_index: number; readonly partial_image_index: number; readonly partial_image_b64: string; } interface AxAIOpenAIResponsesMCPCallInProgressEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.mcp_call.in_progress'; readonly item_id: string; readonly output_index: number; } interface AxAIOpenAIResponsesMCPCallArgumentsDeltaEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.mcp_call.arguments.delta'; readonly item_id: string; readonly output_index: number; readonly delta: object; } interface AxAIOpenAIResponsesMCPCallArgumentsDoneEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.mcp_call.arguments.done'; readonly item_id: string; readonly output_index: number; readonly arguments: object; } interface AxAIOpenAIResponsesMCPCallCompletedEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.mcp_call.completed'; } interface AxAIOpenAIResponsesMCPCallFailedEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.mcp_call.failed'; } interface AxAIOpenAIResponsesMCPListToolsInProgressEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.mcp_list_tools.in_progress'; } interface AxAIOpenAIResponsesMCPListToolsCompletedEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.mcp_list_tools.completed'; } interface AxAIOpenAIResponsesMCPListToolsFailedEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.mcp_list_tools.failed'; } interface AxAIOpenAIResponsesOutputTextAnnotationAddedEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'response.output_text_annotation.added'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly annotation_index: number; readonly annotation: object; } interface AxAIOpenAIResponsesErrorEvent extends AxAIOpenAIResponsesStreamEventBase { readonly type: 'error'; readonly code: string | null; readonly message: string; readonly param: string | null; } type AxAIOpenAIResponsesStreamEvent = AxAIOpenAIResponsesResponseCreatedEvent | AxAIOpenAIResponsesResponseInProgressEvent | AxAIOpenAIResponsesResponseCompletedEvent | AxAIOpenAIResponsesResponseFailedEvent | AxAIOpenAIResponsesResponseIncompleteEvent | AxAIOpenAIResponsesResponseQueuedEvent | AxAIOpenAIResponsesOutputItemAddedEvent | AxAIOpenAIResponsesOutputItemDoneEvent | AxAIOpenAIResponsesContentPartAddedEvent | AxAIOpenAIResponsesContentPartDoneEvent | AxAIOpenAIResponsesOutputTextDeltaEvent | AxAIOpenAIResponsesOutputTextDoneEvent | AxAIOpenAIResponsesRefusalDeltaEvent | AxAIOpenAIResponsesRefusalDoneEvent | AxAIOpenAIResponsesFunctionCallArgumentsDeltaEvent | AxAIOpenAIResponsesFunctionCallArgumentsDoneEvent | AxAIOpenAIResponsesFileSearchCallInProgressEvent | AxAIOpenAIResponsesFileSearchCallSearchingEvent | AxAIOpenAIResponsesFileSearchCallCompletedEvent | AxAIOpenAIResponsesWebSearchCallInProgressEvent | AxAIOpenAIResponsesWebSearchCallSearchingEvent | AxAIOpenAIResponsesWebSearchCallCompletedEvent | AxAIOpenAIResponsesReasoningDeltaEvent | AxAIOpenAIResponsesReasoningDoneEvent | AxAIOpenAIResponsesReasoningSummaryPartAddedEvent | AxAIOpenAIResponsesReasoningSummaryPartDoneEvent | AxAIOpenAIResponsesReasoningSummaryTextDeltaEvent | AxAIOpenAIResponsesReasoningSummaryTextDoneEvent | AxAIOpenAIResponsesReasoningSummaryDeltaEvent | AxAIOpenAIResponsesReasoningSummaryDoneEvent | AxAIOpenAIResponsesImageGenerationCallInProgressEvent | AxAIOpenAIResponsesImageGenerationCallGeneratingEvent | AxAIOpenAIResponsesImageGenerationCallCompletedEvent | AxAIOpenAIResponsesImageGenerationCallPartialImageEvent | AxAIOpenAIResponsesMCPCallInProgressEvent | AxAIOpenAIResponsesMCPCallArgumentsDeltaEvent | AxAIOpenAIResponsesMCPCallArgumentsDoneEvent | AxAIOpenAIResponsesMCPCallCompletedEvent | AxAIOpenAIResponsesMCPCallFailedEvent | AxAIOpenAIResponsesMCPListToolsInProgressEvent | AxAIOpenAIResponsesMCPListToolsCompletedEvent | AxAIOpenAIResponsesMCPListToolsFailedEvent | AxAIOpenAIResponsesOutputTextAnnotationAddedEvent | AxAIOpenAIResponsesErrorEvent; interface AxAIOpenAIResponsesResponseDelta { readonly id?: string; readonly model?: string; readonly event?: string; readonly delta?: { readonly content?: string; readonly arguments?: string; }; readonly item_index?: number; readonly item?: Partial>; readonly response?: Readonly; readonly usage?: { readonly prompt_tokens: number; readonly completion_tokens: number; readonly total_tokens: number; } | null; } type ResponsesReqUpdater> = (req: Readonly) => Readonly; type AxAIOpenAIResponsesConfig = Omit & { model: TModel; embedModel?: TEmbedModel; user?: string; bestOf?: number; logitBias?: Map; suffix?: string | null; stop?: string[]; logprobs?: number; echo?: boolean; dimensions?: number; reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high'; reasoningSummary?: 'auto' | 'concise' | 'detailed'; store?: boolean; systemPrompt?: string; parallelToolCalls?: boolean; seed?: number; responseFormat?: 'text' | 'json_object' | 'json_schema'; serviceTier?: 'auto' | 'default' | 'flex'; }; interface AxAIOpenAIResponsesToolCallBase { id: string; type: string; status?: string; } interface AxAIOpenAIResponsesFileSearchToolCall extends AxAIOpenAIResponsesToolCallBase { type: 'file_search_call'; queries: string[]; results?: { file_id: string; filename: string; score: number; text: string; attributes?: Record; }[]; } interface AxAIOpenAIResponsesWebSearchToolCall extends AxAIOpenAIResponsesToolCallBase { type: 'web_search_call'; queries: string[]; } interface AxAIOpenAIResponsesComputerToolCall extends AxAIOpenAIResponsesToolCallBase { type: 'computer_call'; action: object; } interface AxAIOpenAIResponsesCodeInterpreterToolCall extends AxAIOpenAIResponsesToolCallBase { type: 'code_interpreter_call'; code: string; results?: unknown[]; } interface AxAIOpenAIResponsesImageGenerationToolCall extends AxAIOpenAIResponsesToolCallBase { type: 'image_generation_call'; result?: string; } interface AxAIOpenAIResponsesLocalShellToolCall extends AxAIOpenAIResponsesToolCallBase { type: 'local_shell_call'; action: object; } interface AxAIOpenAIResponsesMCPToolCall extends AxAIOpenAIResponsesToolCallBase { type: 'mcp_call'; name: string; args: string; server_label: string; output?: string; error?: string; } type AxAIOpenAIResponsesToolCall = AxAIOpenAIResponsesFunctionCallItem | AxAIOpenAIResponsesFileSearchToolCall | AxAIOpenAIResponsesWebSearchToolCall | AxAIOpenAIResponsesComputerToolCall | AxAIOpenAIResponsesCodeInterpreterToolCall | AxAIOpenAIResponsesImageGenerationToolCall | AxAIOpenAIResponsesLocalShellToolCall | AxAIOpenAIResponsesMCPToolCall; declare const axAIOpenAIResponsesDefaultConfig: () => AxAIOpenAIResponsesConfig; declare const axAIOpenAIResponsesBestConfig: () => AxAIOpenAIResponsesConfig; declare const axAIOpenAIResponsesCreativeConfig: () => AxAIOpenAIResponsesConfig; interface AxAIOpenAIResponsesBaseArgs> { apiKey: string; config: AxAIOpenAIResponsesConfig; options?: { streamingUsage?: boolean; } & AxAIServiceOptions; apiURL?: string; modelInfo?: ReadonlyArray; models?: AxAIInputModelList; responsesReqUpdater?: (req: Readonly) => Readonly; supportFor?: AxAIFeatures | ((model: TModel) => AxAIFeatures); } /** * Base class for OpenAI AI services using the /v1/responses API endpoint */ declare class AxAIOpenAIResponsesBase> extends AxBaseAI, AxAIOpenAIEmbedRequest, AxAIOpenAIResponsesResponse, AxAIOpenAIResponsesResponseDelta, AxAIOpenAIEmbedResponse, TModelKey> { constructor({ apiKey, config, options, apiURL, modelInfo, models, responsesReqUpdater, supportFor, }: Readonly>); } /** * Ready-to-use implementation of the OpenAI Responses API client * This class uses OpenAI's /v1/responses API endpoint which supports text, image, and audio inputs */ interface AxAIOpenAIResponsesArgs = AxAIOpenAIResponsesRequest> extends Omit, 'config' | 'supportFor' | 'modelInfo'> { name: TName; modelInfo?: AxModelInfo[]; config?: Partial['config']>; } declare class AxAIOpenAIResponses extends AxAIOpenAIResponsesBase> { constructor({ apiKey, config, options, models, modelInfo, }: Readonly, 'name'>>); } type DreamsRouterConfig = AxAIOpenAIConfig; declare const axAIDreamsRouterDefaultConfig: () => DreamsRouterConfig; type AxAIDreamsRouterArgs = Omit, 'apiKey'> & { referer?: string; title?: string; options?: Readonly; }; declare class AxAIDreamsRouter extends AxAIOpenAIBase { constructor({ config, options, models, modelInfo, referer, title, }: Readonly, 'name'>>); } type OpenRouterConfig = AxAIOpenAIConfig; declare const axAIOpenRouterDefaultConfig: () => OpenRouterConfig; type AxAIOpenRouterArgs = AxAIOpenAIArgs<'openrouter', string, unknown, TModelKey> & { referer?: string; title?: string; options?: Readonly; }; declare class AxAIOpenRouter extends AxAIOpenAIBase { constructor({ apiKey, config, options, models, modelInfo, referer, title, }: Readonly, 'name'>>); } declare enum AxAIRekaModel { RekaCore = "reka-core", RekaFlash = "reka-flash", RekaEdge = "reka-edge" } type AxAIRekaConfig = Omit & { model: AxAIRekaModel; stop?: readonly string[]; useSearchEngine?: boolean; }; type AxAIRekaUsage = { input_tokens: number; output_tokens: number; }; type AxAIRekaChatRequest = { model: string; messages: ({ role: 'user'; content: string | { type: 'text'; text: string; }[]; } | { role: 'assistant'; content: string | { type: 'text'; text: string; }[]; })[]; usage?: AxAIRekaUsage; response_format?: { type: string; }; max_tokens?: number; temperature?: number; top_p?: number; top_k?: number; stream?: boolean; stop?: readonly string[]; presence_penalty?: number; frequency_penalty?: number; use_search_engine?: boolean; }; type AxAIRekaChatResponse = { id: string; model: string; responses: { message: { content: string | { type: 'text'; text: string; }; }; finish_reason: 'stop' | 'length' | 'context'; }[]; usage?: AxAIRekaUsage; }; type AxAIRekaChatResponseDelta = { id: string; model: string; responses: { chunk: AxAIRekaChatResponse['responses'][0]['message']; finish_reason: AxAIRekaChatResponse['responses'][0]['finish_reason']; }[]; usage?: AxAIRekaUsage; }; declare const axAIRekaDefaultConfig: () => AxAIRekaConfig; declare const axAIRekaBestConfig: () => AxAIRekaConfig; declare const axAIRekaCreativeConfig: () => AxAIRekaConfig; declare const axAIRekaFastConfig: () => AxAIRekaConfig; interface AxAIRekaArgs { name: 'reka'; apiKey: string; apiURL?: string; config?: Readonly>; options?: Readonly; modelInfo?: Readonly; models?: AxAIInputModelList; } declare class AxAIReka extends AxBaseAI { constructor({ apiKey, config, options, apiURL, modelInfo, models, }: Readonly, 'name'>>); } type TogetherAIConfig = AxAIOpenAIConfig; declare const axAITogetherDefaultConfig: () => TogetherAIConfig; type AxAITogetherArgs = AxAIOpenAIArgs<'together', string, unknown, TModelKey>; declare class AxAITogether extends AxAIOpenAIBase { constructor({ apiKey, config, options, models, modelInfo, }: Readonly, 'name'>>); } /** * WebLLM: Models for text generation * Based on WebLLM's supported models */ declare enum AxAIWebLLMModel { Llama31_8B_Instruct = "Llama-3.1-8B-Instruct-q4f32_1-MLC", Llama31_70B_Instruct = "Llama-3.1-70B-Instruct-q4f16_1-MLC", Llama32_1B_Instruct = "Llama-3.2-1B-Instruct-q4f32_1-MLC", Llama32_3B_Instruct = "Llama-3.2-3B-Instruct-q4f32_1-MLC", Mistral7B_Instruct = "Mistral-7B-Instruct-v0.3-q4f32_1-MLC", Phi35_Mini_Instruct = "Phi-3.5-mini-instruct-q4f32_1-MLC", Gemma2_2B_Instruct = "gemma-2-2b-it-q4f32_1-MLC", Gemma2_9B_Instruct = "gemma-2-9b-it-q4f32_1-MLC", Qwen2_5_0_5B_Instruct = "Qwen2.5-0.5B-Instruct-q4f32_1-MLC", Qwen2_5_1_5B_Instruct = "Qwen2.5-1.5B-Instruct-q4f32_1-MLC", Qwen2_5_3B_Instruct = "Qwen2.5-3B-Instruct-q4f32_1-MLC", Qwen2_5_7B_Instruct = "Qwen2.5-7B-Instruct-q4f32_1-MLC" } /** * WebLLM: Model options for text generation */ type AxAIWebLLMConfig = AxModelConfig & { model: AxAIWebLLMModel; logitBias?: Record; logProbs?: boolean; topLogprobs?: number; }; /** * WebLLM: Chat request structure * Based on OpenAI-compatible API from WebLLM */ type AxAIWebLLMChatRequest = { model: AxAIWebLLMModel; messages: Array<{ role: 'system' | 'user' | 'assistant' | 'function'; content?: string; name?: string; function_call?: { name: string; arguments: string; }; }>; temperature?: number; top_p?: number; max_tokens?: number; stream?: boolean; stop?: string | string[]; presence_penalty?: number; frequency_penalty?: number; logit_bias?: Record; logprobs?: boolean; top_logprobs?: number; n?: number; tools?: Array<{ type: 'function'; function: { name: string; description: string; parameters: object; }; }>; tool_choice?: 'none' | 'auto' | { type: 'function'; function: { name: string; }; }; }; /** * WebLLM: Chat response structure */ type AxAIWebLLMChatResponse = { id: string; object: 'chat.completion'; created: number; model: AxAIWebLLMModel; choices: Array<{ index: number; message: { role: 'assistant'; content?: string; tool_calls?: Array<{ id: string; type: 'function'; function: { name: string; arguments: string; }; }>; }; finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter'; logprobs?: { content: Array<{ token: string; logprob: number; bytes: number[]; top_logprobs: Array<{ token: string; logprob: number; bytes: number[]; }>; }>; }; }>; usage: { prompt_tokens: number; completion_tokens: number; total_tokens: number; }; }; /** * WebLLM: Streaming chat response structure */ type AxAIWebLLMChatResponseDelta = { id: string; object: 'chat.completion.chunk'; created: number; model: AxAIWebLLMModel; choices: Array<{ index: number; delta: { role?: 'assistant'; content?: string; tool_calls?: Array<{ index: number; id?: string; type?: 'function'; function?: { name?: string; arguments?: string; }; }>; }; finish_reason?: 'stop' | 'length' | 'tool_calls' | 'content_filter'; logprobs?: { content: Array<{ token: string; logprob: number; bytes: number[]; top_logprobs: Array<{ token: string; logprob: number; bytes: number[]; }>; }>; }; }>; usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number; }; }; /** * WebLLM doesn't support embeddings natively * This is a placeholder for consistency with the framework */ type AxAIWebLLMEmbedModel = never; type AxAIWebLLMEmbedRequest = never; type AxAIWebLLMEmbedResponse = never; declare const axAIWebLLMDefaultConfig: () => AxAIWebLLMConfig; declare const axAIWebLLMCreativeConfig: () => AxAIWebLLMConfig; interface AxAIWebLLMArgs { name: 'webllm'; engine: any; config?: Readonly>; options?: Readonly; models?: AxAIInputModelList; } declare class AxAIWebLLM extends AxBaseAI { constructor({ engine, config, options, models, }: Readonly, 'name'>>); } declare enum AxAIGrokModel { Grok3 = "grok-3", Grok3Mini = "grok-3-mini", Grok3Fast = "grok-3-fast", Grok3MiniFast = "grok-3-mini-fast" } declare enum AxAIGrokEmbedModels { GrokEmbedSmall = "grok-embed-small" } declare const axAIGrokDefaultConfig: () => AxAIOpenAIConfig; declare const axAIGrokBestConfig: () => AxAIOpenAIConfig; interface AxAIGrokSearchSource { type: 'web' | 'x' | 'news' | 'rss'; country?: string; excludedWebsites?: string[]; allowedWebsites?: string[]; safeSearch?: boolean; xHandles?: string[]; links?: string[]; } interface AxAIGrokOptionsTools { searchParameters?: { mode?: 'auto' | 'on' | 'off'; returnCitations?: boolean; fromDate?: string; toDate?: string; maxSearchResults?: number; sources?: AxAIGrokSearchSource[]; }; } type AxAIGrokChatRequest = AxAIOpenAIChatRequest & { search_parameters?: { mode?: 'auto' | 'on' | 'off'; return_citations?: boolean; from_date?: string; to_date?: string; max_search_results?: number; sources?: AxAIGrokSearchSource[]; }; }; type AxAIGrokArgs = AxAIOpenAIArgs<'grok', AxAIGrokModel, AxAIGrokEmbedModels, TModelKey, AxAIGrokChatRequest> & { options?: Readonly & { tokensPerMinute?: number; }; modelInfo?: AxModelInfo[]; }; declare class AxAIGrok extends AxAIOpenAIBase { constructor({ apiKey, config, options, models, modelInfo, }: Readonly, 'name'>>); } type AxAIArgs = AxAIOpenAIArgs<'openai', AxAIOpenAIModel, AxAIOpenAIEmbedModel, TModelKey> | AxAIOpenAIResponsesArgs<'openai-responses', AxAIOpenAIResponsesModel, AxAIOpenAIEmbedModel, TModelKey> | AxAIAzureOpenAIArgs | AxAITogetherArgs | AxAIDreamsRouterArgs | AxAIOpenRouterArgs | AxAIAnthropicArgs | AxAIGroqArgs | AxAIGoogleGeminiArgs | AxAICohereArgs | AxAIHuggingFaceArgs | AxAIMistralArgs | AxAIDeepSeekArgs | AxAIOllamaArgs | AxAIRekaArgs | AxAIGrokArgs | AxAIWebLLMArgs; type AxAIModels = AxAIOpenAIModel | AxAIAnthropicModel | AxAIGroqModel | AxAIGoogleGeminiModel | AxAICohereModel | AxAIHuggingFaceModel | AxAIMistralModel | AxAIDeepSeekModel | AxAIGrokModel | AxAIWebLLMModel; type AxAIEmbedModels = AxAIOpenAIEmbedModel | AxAIGoogleGeminiEmbedModel | AxAICohereEmbedModel; type ExtractModelKeysAndValues = T extends readonly { key: infer K; model: infer M; }[] ? K | M : never; type InferTModelKey = T extends { models: infer M; } ? ExtractModelKeysAndValues : string; /** * Factory function for creating AxAI instances with type safety. * This is the recommended way to create AxAI instances instead of using the constructor. * * @param options - Configuration options for the AI service * @returns A properly typed AxAI instance * * @example * ```typescript * const ai = ai({ * name: 'openai', * apiKey: process.env.OPENAI_APIKEY! * }); * ``` */ declare function ai>(options: T): AxAI>; declare class AxAI implements AxAIService { private ai; static create>(options: T): AxAI>; /** * @deprecated Use `AxAI.create()` or `ai()` function instead for better type safety. * This constructor will be removed in v15.0.0. * * Migration timeline: * - v13.0.24+: Deprecation warnings (current) * - v14.0.0: Runtime console warnings * - v15.0.0: Complete removal * * @example * ```typescript * // Instead of: new AxAI({ name: 'openai', apiKey: '...' }) * // Use: AxAI.create({ name: 'openai', apiKey: '...' }) * // Or: ai({ name: 'openai', apiKey: '...' }) * ``` */ constructor(options: Readonly>); getName(): string; getId(): string; getFeatures(model?: string): AxAIFeatures; getModelList(): AxAIModelList | undefined; getLastUsedChatModel(): any; getLastUsedEmbedModel(): any; getLastUsedModelConfig(): AxModelConfig | undefined; getMetrics(): AxAIServiceMetrics; chat(req: Readonly>, options?: Readonly): Promise>; embed(req: Readonly>, options?: Readonly): Promise; setOptions(options: Readonly): void; getOptions(): Readonly; getLogger(): AxLoggerFunction; } /** * Interface for agents that can be used as child agents. * Provides methods to get the agent's function definition and features. */ interface AxAgentic extends AxProgrammable { getFunction(): AxFunction; getFeatures(): AxAgentFeatures; } type AxAgentOptions = Omit, 'functions'> & { disableSmartModelRouting?: boolean; /** List of field names that should not be automatically passed from parent to child agents */ excludeFieldsFromPassthrough?: string[]; debug?: boolean; }; interface AxAgentFeatures { /** Whether this agent can use smart model routing (requires an AI service) */ canConfigureSmartModelRouting: boolean; /** List of fields that this agent excludes from parent->child value passing */ excludeFieldsFromPassthrough: string[]; } /** * An AI agent that can process inputs using an AI service and coordinate with child agents. * Supports features like smart model routing and automatic input field passing to child agents. * * @deprecated Use the `agent()` factory function instead of instantiating this class directly. * The factory function provides better type inference and cleaner syntax. * This class will be removed in v15.0.0. * * Migration timeline: * - v13.0.24+: Deprecation warnings (current) * - v14.0.0: Runtime console warnings * - v15.0.0: Complete removal * * @example * // Old (deprecated): * const myAgent = new AxAgent({ * name: 'myAgent', * description: 'An agent that does something', * signature: 'userInput:string -> responseText:string' * }); * * // New (recommended): * const myAgent = agent('userInput:string -> responseText:string', { * name: 'myAgent', * description: 'An agent that does something' * }); */ declare class AxAgent implements AxAgentic { private ai?; private program; private functions?; private agents?; private disableSmartModelRouting?; private excludeFieldsFromPassthrough; private debug?; private options?; private name; private func; constructor({ ai, name, description, definition, signature, agents, functions, }: Readonly<{ ai?: Readonly; name: string; description: string; definition?: string; signature: NonNullable[0]>; agents?: AxAgentic[]; functions?: AxInputFunctionType; }>, options?: Readonly); /** * Creates a new AxAgent instance with type-safe signature parsing. * This is the recommended way to create agents with string-based signatures. * * @param signature - The signature string defining input/output fields * @param config - Agent configuration including name, description, etc. * @returns A new AxAgent instance with inferred types * * @example * ```typescript * const agent = AxAgent.create( * 'userInput:string "User question" -> responseText:string "Agent response"', * { * name: 'helpfulAgent', * description: 'An agent that provides helpful responses to user questions', * definition: 'You are a helpful assistant that provides clear, accurate responses to user questions.', * ai: llm * } * ); * ``` */ static create(signature: T, config: AxAgentConfig['inputs'], ParseSignature['outputs']>): AxAgent['inputs'], ParseSignature['outputs']>; setExamples(examples: Readonly>, options?: Readonly): void; setId(id: string): void; setParentId(parentId: string): void; getTraces(): AxProgramTrace[]; setDemos(demos: readonly AxProgramDemos[]): void; getUsage(): (AxModelUsage & { ai: string; model: string; })[]; resetUsage(): void; getFunction(): AxFunction; getFeatures(): AxAgentFeatures; /** * Initializes the agent's execution context, processing child agents and their functions. */ private init; forward>(parentAi: T, values: IN | AxMessage[], options?: Readonly>): Promise; streamingForward>(parentAi: T, values: IN | AxMessage[], options?: Readonly>): AxGenStreamingOut; /** * Updates the agent's description. * This updates both the stored description and the function's description. * * @param description - New description for the agent (must be at least 20 characters) * @throws Error if description is too short */ setDescription(description: string): void; setDefinition(definition: string): void; getSignature(): AxSignature; setSignature(signature: NonNullable[0]>): void; applyOptimization(optimizedProgram: any): void; private getDebug; } /** * Configuration options for creating an agent using the agent() factory function. */ interface AxAgentConfig extends AxAgentOptions { ai?: AxAIService; name: string; description: string; definition?: string; agents?: AxAgentic[]; functions?: AxInputFunctionType; } /** * Creates a strongly-typed AI agent from a signature. * This is the recommended way to create agents, providing better type inference and cleaner syntax. * Supports both string signatures and AxSignature objects. * * @param signature - The input/output signature as a string or AxSignature object * @param config - Configuration options for the agent * @returns A typed agent instance * * @example * ```typescript * // Using string signature * const myAgent = agent('userInput:string -> responseText:string', { * name: 'myAgent', * description: 'An agent that processes user input and returns a response', * definition: 'You are a helpful assistant that responds to user queries...' * }); * * // Using AxSignature object * const sig = s('userInput:string -> responseText:string'); * const myAgent2 = agent(sig, { * name: 'myAgent2', * description: 'Same agent but using AxSignature object' * }); * * // With child agents * const parentAgent = agent('taskDescription:string -> completedTask:string', { * name: 'parentAgent', * description: 'Coordinates child agents to complete tasks', * agents: [childAgent1, childAgent2] * }); * * // Type-safe usage * const result = await myAgent.forward(ai, { userInput: 'Hello!' }); * console.log(result.responseText); // TypeScript knows this exists * ``` */ declare function agent(signature: T, config: AxAgentConfig['inputs'], ParseSignature['outputs']>): AxAgent['inputs'], ParseSignature['outputs']>; declare function agent, TOutput extends Record>(signature: AxSignature, config: AxAgentConfig): AxAgent; interface AxApacheTikaArgs { url?: string | URL; fetch?: typeof fetch; } interface AxApacheTikaConvertOptions { format?: 'text' | 'html'; } declare class AxApacheTika { private tikaUrl; private fetch?; constructor(args?: Readonly); private _convert; convert(files: Readonly, options?: Readonly<{ batchSize?: number; format?: 'html' | 'text'; }>): Promise; } type ExtractServiceModelKeys$1 = T extends AxAIService ? K : never; type ExtractAllModelKeys$1 = T extends readonly [ infer First, ...infer Rest ] ? ExtractServiceModelKeys$1 | ExtractAllModelKeys$1 : never; /** * Options for the balancer. */ type AxBalancerOptions = { comparator?: (a: AxAIService, b: AxAIService) => number; debug?: boolean; initialBackoffMs?: number; maxBackoffMs?: number; maxRetries?: number; }; /** * Balancer that rotates through services. */ declare class AxBalancer[] = readonly AxAIService[], TModelKey = ExtractAllModelKeys$1> implements AxAIService { private services; private currentServiceIndex; private currentService; private debug; private initialBackoffMs; private maxBackoffMs; private maxRetries; private serviceFailures; constructor(services: TServices, options?: AxBalancerOptions); /** * Static factory method for type-safe balancer creation with automatic model key inference. */ static create[]>(services: TServices, options?: AxBalancerOptions>): AxBalancer>; getLastUsedChatModel(): unknown; getLastUsedEmbedModel(): unknown; getLastUsedModelConfig(): AxModelConfig | undefined; /** * Service comparator that respects the input order of services. */ static inputOrderComparator: () => number; /** * Service comparator that sorts services by cost. */ static metricComparator: (a: AxAIService, b: AxAIService) => number; getModelList(): AxAIModelList | undefined; private getNextService; private reset; getName(): string; getId(): string; getFeatures(model?: string): AxAIFeatures; getMetrics(): AxAIServiceMetrics; private canRetryService; private handleFailure; private handleSuccess; chat(req: Readonly>, options?: Readonly): Promise>; embed(req: Readonly>, options?: Readonly): Promise; setOptions(options: Readonly): void; getOptions(): Readonly; getLogger(): AxLoggerFunction; } type AxDBUpsertRequest = { id: string; text?: string; values?: readonly number[]; metadata?: Record; table: string; namespace?: string; }; type AxDBUpsertResponse = { ids: string[]; }; type AxDBQueryRequest = { id?: string; text?: string; values?: readonly number[]; table: string; columns?: string[]; limit?: number; namespace?: string; }; type AxDBQueryResponse = { matches: { id: string; score: number; metadata?: Record; table?: string; }[]; }; interface AxDBService extends AxDBQueryService { upsert(req: Readonly, update?: boolean): Promise; batchUpsert(batchReq: Readonly, update?: boolean): Promise; } interface AxDBQueryService { query(req: Readonly): Promise; } interface AxDBBaseArgs { fetch?: typeof fetch; tracer?: Tracer; } interface AxDBBaseOpOptions { span?: Span; } declare class AxDBBase implements AxDBService { protected name: string; protected fetch?: typeof fetch; private tracer?; _upsert?: (req: Readonly, update?: boolean, options?: Readonly) => Promise; _batchUpsert?: (batchReq: Readonly, update?: boolean, options?: Readonly) => Promise; _query?: (req: Readonly, options?: Readonly) => Promise; constructor({ name, fetch, tracer, }: Readonly); upsert(req: Readonly, update?: boolean): Promise; batchUpsert(req: Readonly, update?: boolean): Promise; query(req: Readonly): Promise; } type AxDBCloudflareOpOptions = AxDBBaseOpOptions; interface AxDBCloudflareArgs extends AxDBBaseArgs { name: 'cloudflare'; apiKey: string; accountId: string; fetch?: typeof fetch; } /** * Cloudflare: DB Service */ declare class AxDBCloudflare extends AxDBBase { private apiKey; private accountId; constructor({ apiKey, accountId, fetch, tracer, }: Readonly>); _upsert: (req: Readonly, _update?: boolean, options?: Readonly) => Promise; batchUpsert: (batchReq: Readonly, update?: boolean, options?: Readonly) => Promise; query: (req: Readonly, options?: Readonly) => Promise; } type AxDBMemoryOpOptions = AxDBBaseOpOptions; interface AxDBMemoryArgs extends AxDBBaseArgs { name: 'memory'; } type AxDBState = Record>; /** * MemoryDB: DB Service */ declare class AxDBMemory extends AxDBBase { private state; constructor({ tracer }?: Readonly>); _upsert: (req: Readonly, _update?: boolean, _options?: Readonly) => Promise; _batchUpsert: (batchReq: Readonly, update?: boolean, _options?: Readonly) => Promise; _query: (req: Readonly, _options?: Readonly) => Promise; getDB: () => AxDBState; setDB: (state: AxDBState) => void; clearDB: () => void; } type AxDBPineconeOpOptions = AxDBBaseOpOptions; interface AxDBPineconeArgs extends AxDBBaseArgs { name: 'pinecone'; apiKey: string; host: string; fetch?: typeof fetch; } /** * Pinecone: DB Service */ declare class AxDBPinecone extends AxDBBase { private apiKey; private apiURL; constructor({ apiKey, host, fetch, tracer, }: Readonly>); _upsert: (req: Readonly, update?: boolean, options?: Readonly) => Promise; _batchUpsert: (batchReq: Readonly, _update?: boolean, options?: Readonly) => Promise; query: (req: Readonly, options?: Readonly) => Promise; } type AxDBWeaviateOpOptions = AxDBBaseOpOptions; interface AxDBWeaviateArgs extends AxDBBaseArgs { name: 'weaviate'; apiKey: string; host: string; fetch?: typeof fetch; } /** * Weaviate: DB Service */ declare class AxDBWeaviate extends AxDBBase { private apiKey; private apiURL; constructor({ apiKey, host, fetch, tracer, }: Readonly>); _upsert: (req: Readonly, update?: boolean, options?: Readonly) => Promise; _batchUpsert: (batchReq: Readonly, update?: boolean, options?: Readonly) => Promise; _query: (req: Readonly, options?: Readonly) => Promise; } type AxDBArgs = AxDBCloudflareArgs | AxDBPineconeArgs | AxDBWeaviateArgs | AxDBMemoryArgs; declare class AxDB implements AxDBService { private db; constructor(args: Readonly); upsert(req: Readonly, update?: boolean): Promise; batchUpsert(batchReq: Readonly, update?: boolean): Promise; query(req: Readonly): Promise; } type AxRewriteIn = { query: string; }; type AxRewriteOut = { rewrittenQuery: string; }; type AxRerankerIn = { query: string; items: string[]; }; type AxRerankerOut = { rankedItems: string[]; }; interface AxDBLoaderOptions { chunker?: (text: string) => string[]; rewriter?: AxGen; reranker?: AxGen; } interface AxDBManagerArgs { ai: AxAIService; db: AxDBService; config?: AxDBLoaderOptions; } interface AxDBMatch { score: number; text: string; } declare class AxDBManager { private ai; private db; private chunker; private rewriter?; private reranker?; constructor({ ai, db, config }: Readonly); private defaultChunker; insert: (text: Readonly, options?: Readonly<{ batchSize?: number; maxWordsPerChunk?: number; minWordsPerChunk?: number; abortSignal?: AbortSignal; }>) => Promise; query: (query: Readonly, { topPercent, abortSignal, }?: Readonly<{ topPercent?: number; abortSignal?: AbortSignal; }> | undefined) => Promise; } interface AxDockerContainer { Id: string; Names: string[]; Image: string; ImageID: string; Command: string; Created: number; State: { Status: string; Running: boolean; Paused: boolean; Restarting: boolean; OOMKilled: boolean; Dead: boolean; Pid: number; ExitCode: number; Error: string; StartedAt: Date; FinishedAt: Date; }; Status: string; Ports: Array<{ IP: string; PrivatePort: number; PublicPort: number; Type: string; }>; Labels: { [key: string]: string; }; SizeRw: number; SizeRootFs: number; HostConfig: { NetworkMode: string; }; NetworkSettings: { Networks: { [key: string]: { IPAddress: string; IPPrefixLen: number; Gateway: string; MacAddress: string; }; }; }; Mounts: Array<{ Type: string; Source: string; Destination: string; Mode: string; RW: boolean; Propagation: string; }>; } declare class AxDockerSession { private readonly apiUrl; private containerId; constructor(apiUrl?: string); pullImage(imageName: string): Promise; createContainer({ imageName, volumes, doNotPullImage, tag, }: Readonly<{ imageName: string; volumes?: Array<{ hostPath: string; containerPath: string; }>; doNotPullImage?: boolean; tag?: string; }>): Promise<{ Id: string; }>; findOrCreateContainer({ imageName, volumes, doNotPullImage, tag, }: Readonly<{ imageName: string; volumes?: Array<{ hostPath: string; containerPath: string; }>; doNotPullImage?: boolean; tag: string; }>): Promise<{ Id: string; isNew: boolean; }>; startContainer(): Promise; connectToContainer(containerId: string): Promise; stopContainers({ tag, remove, timeout, }: Readonly<{ tag?: string; remove?: boolean; timeout?: number; }>): Promise>; listContainers(all?: boolean): Promise; getContainerLogs(): Promise; executeCommand(command: string): Promise; private getContainerInfo; private waitForContainerToBeRunning; private fetchDockerAPI; toFunction(): AxFunction; } type AxFlowState = Record; interface AxFlowNodeDefinition { inputs: Record; outputs: Record; } type AxFlowStepFunction = (state: AxFlowState, context: Readonly<{ mainAi: AxAIService; mainOptions?: AxProgramForwardOptions; }>) => Promise | AxFlowState; interface AxFlowDynamicContext> { ai?: T; options?: AxProgramForwardOptions>[number]['key']>; } type GetGenIn> = T extends AxProgrammable ? IN : never; type GetGenOut> = T extends AxProgrammable ? OUT : never; type InferAxGen = AxGen['inputs'], ParseSignature['outputs']>; type NodeResultKey = `${TNodeName}Result`; type AddNodeResult = TState & { [K in NodeResultKey]: TNodeOut; }; /** * Interface for flows that can be tuned, executed, and used in compositions. * Provides methods for building and executing complex AI workflows. */ interface AxFlowable extends AxProgrammable { } type AxFlowTypedParallelBranch>, TState extends AxFlowState> = (subFlow: AxFlowTypedSubContext) => AxFlowTypedSubContext; interface AxFlowTypedSubContext>, TState extends AxFlowState> { execute>(nodeName: TNodeName, mapping: (state: TState) => GetGenIn, dynamicContext?: AxFlowDynamicContext): AxFlowTypedSubContext>>; map(transform: (state: TState) => TNewState): AxFlowTypedSubContext; executeSteps(initialState: TState, context: Readonly<{ mainAi: AxAIService; mainOptions?: AxProgramForwardOptions; }>): Promise; } type AxFlowParallelBranch = (subFlow: AxFlowSubContext) => AxFlowSubContext; interface AxFlowSubContext { execute>(nodeName: string, mapping: (state: AxFlowState) => Record, dynamicContext?: AxFlowDynamicContext): this; map(transform: (state: AxFlowState) => AxFlowState): this; executeSteps>(initialState: AxFlowState, context: Readonly<{ mainAi: TAI; mainOptions?: AxProgramForwardOptions>[number]['key']>; }>): Promise; } interface AxFlowBranchContext { predicate: (state: AxFlowState) => unknown; branches: Map; currentBranchValue?: unknown; } interface AxFlowExecutionStep { type: 'execute' | 'map' | 'merge' | 'parallel-map' | 'parallel' | 'derive'; nodeName?: string; dependencies: string[]; produces: string[]; stepFunction: AxFlowStepFunction; stepIndex: number; } interface AxFlowParallelGroup { level: number; steps: AxFlowExecutionStep[]; } interface AxFlowAutoParallelConfig { enabled: boolean; batchSize?: number; } /** * Data types for different AxFlow logging events */ interface AxFlowLoggerData { name: string; timestamp: number; [key: string]: unknown; } interface AxFlowStartData extends AxFlowLoggerData { name: 'FlowStart'; inputFields: string[]; totalSteps: number; parallelGroups: number; maxParallelism: number; autoParallelEnabled: boolean; } interface AxFlowStepStartData extends AxFlowLoggerData { name: 'StepStart'; stepIndex: number; stepType: 'execute' | 'map' | 'merge' | 'parallel-map' | 'parallel' | 'derive' | 'branch' | 'feedback' | 'while' | 'other'; nodeName?: string; dependencies: string[]; produces: string[]; state: AxFlowState; } interface AxFlowStepCompleteData extends AxFlowLoggerData { name: 'StepComplete'; stepIndex: number; stepType: 'execute' | 'map' | 'merge' | 'parallel-map' | 'parallel' | 'derive' | 'branch' | 'feedback' | 'while' | 'other'; nodeName?: string; executionTime: number; state: AxFlowState; newFields?: string[]; result?: any; } interface AxFlowParallelGroupStartData extends AxFlowLoggerData { name: 'ParallelGroupStart'; groupLevel: number; stepsCount: number; stepTypes: string[]; } interface AxFlowParallelGroupCompleteData extends AxFlowLoggerData { name: 'ParallelGroupComplete'; groupLevel: number; stepsCount: number; executionTime: number; } interface AxFlowBranchEvaluationData extends AxFlowLoggerData { name: 'BranchEvaluation'; branchValue: unknown; hasMatchingBranch: boolean; branchStepsCount: number; } interface AxFlowCompleteData extends AxFlowLoggerData { name: 'FlowComplete'; totalExecutionTime: number; finalState: AxFlowState; outputFields: string[]; stepsExecuted: number; } interface AxFlowErrorData extends AxFlowLoggerData { name: 'FlowError'; error: string; stepIndex?: number; stepType?: string; nodeName?: string; state?: AxFlowState; } type AxFlowLogData = AxFlowStartData | AxFlowStepStartData | AxFlowStepCompleteData | AxFlowParallelGroupStartData | AxFlowParallelGroupCompleteData | AxFlowBranchEvaluationData | AxFlowCompleteData | AxFlowErrorData; /** * Function type for AxFlow logging */ type AxFlowLoggerFunction = (data: AxFlowLogData) => void; /** * Factory function to create a colorized AxFlow logger */ declare const axCreateFlowColorLogger: (output?: (message: string) => void) => AxFlowLoggerFunction; /** * Factory function to create a text-only AxFlow logger (no colors) */ declare const axCreateFlowTextLogger: (output?: (message: string) => void) => AxFlowLoggerFunction; /** * Default AxFlow logger with colors */ declare const axDefaultFlowLogger: AxFlowLoggerFunction; /** * AxFlow - A fluent, chainable API for building and orchestrating complex, stateful AI programs. * * Now with advanced type-safe chaining where each method call evolves the type information, * providing compile-time type safety and superior IntelliSense. * * @example * ``` * const flow = new AxFlow<{ topic: string }, { finalAnswer: string }>() * .node('summarizer', 'text:string -> summary:string') * .node('critic', 'summary:string -> critique:string') * .execute('summarizer', state => ({ text: `About ${state.topic}` })) // state is { topic: string } * .execute('critic', state => ({ summary: state.summarizerResult.summary })) // state evolves! * .map(state => ({ finalAnswer: state.criticResult.critique })) // fully typed! * * const result = await flow.forward(ai, { topic: "AI safety" }) * ``` */ declare class AxFlow, OUT, TNodes extends Record> = Record, // Node registry for type tracking TState extends AxFlowState = IN> implements AxFlowable { private static _ctorWarned; private readonly nodes; private readonly flowDefinition; private readonly nodeGenerators; private readonly loopStack; private readonly stepLabels; private branchContext; private readonly autoParallelConfig; private readonly executionPlanner; private program?; private nodeUsage; private nodeTraces; private readonly flowLogger?; private readonly timingLogger?; private readonly defaultAIOptions?; /** * Converts a string to camelCase for valid field names */ private toCamelCase; /** * Executes a list of steps with comprehensive logging */ private executeStepsWithLogging; /** * Determines the type of a step function for logging purposes */ private getStepType; /** * Gets metadata about a step for logging purposes */ private getStepMetadata; /** * Extracts node name from step function source code */ private extractNodeNameFromSource; /** * Infers the signature of the flow based on the execution plan and node definitions. * This is the core method that determines what input/output fields the flow should have * based on the nodes and operations defined in the flow. * * The inference process follows these steps: * 1. If no nodes are defined, return a default signature * 2. Analyze the execution plan to find all produced and consumed fields * 3. Determine input fields (consumed but not produced by any step) * 4. Determine output fields with special handling for final map/merge operations * 5. If no clear pattern is found, create a comprehensive signature from all nodes * * Special handling for final operations: * - Map operations: Use the fields produced by the map transformation * - Merge operations: Use fields from the merged branches or merge result * - Conditional merges: Analyze what fields the branches actually produce * * @returns AxSignature - The inferred signature for this flow */ private inferSignatureFromFlow; constructor(options?: { autoParallel?: boolean; batchSize?: number; logger?: AxFlowLoggerFunction; debug?: boolean; tracer?: Tracer; meter?: Meter; }); /** * Static factory method to create a new AxFlow instance with proper type safety * @param options - Optional configuration for the flow * @returns New AxFlow instance with type-safe defaults */ static create = Record, OUT = {}, TNodes extends Record> = Record, TState extends AxFlowState = IN>(options?: { autoParallel?: boolean; batchSize?: number; logger?: AxFlowLoggerFunction; debug?: boolean; }): AxFlow; /** * Initializes the program field every time something is added to the graph */ private ensureProgram; setExamples(examples: Readonly>, options?: Readonly): void; setId(id: string): void; setParentId(parentId: string): void; getTraces(): AxProgramTrace[]; setDemos(demos: readonly AxProgramDemos[]): void; getUsage(): AxProgramUsage[]; resetUsage(): void; /** * Resets trace tracking for the flow. * This is called automatically on each forward/streamingForward call. */ resetTraces(): void; /** * Gets a detailed usage report broken down by node name. * This provides visibility into which nodes are consuming the most tokens. * * @returns Object mapping node names to their usage statistics */ getUsageReport(): Record; /** * Expose node programs for system-level operations (optimization, inspection) */ getNodePrograms(): ReadonlyArray<{ name: string; program: AxProgrammable; }>; /** * Attempt to set instruction on a node if supported (AxGen. * setInstruction is optional; returns true if applied) */ setNodeInstruction(name: string, instruction: string): boolean; /** * Bulk-apply instructions to nodes; ignores names that don’t exist or nodes without instruction setter */ setAllNodeInstructions(map: Readonly>): void; /** * Gets a detailed trace report broken down by node name. * This provides visibility into the execution traces for each node. * * @returns Object mapping node names to their trace data */ getTracesReport(): Record[]>; streamingForward>(ai: T, values: IN | AxMessage[], options?: Readonly>): AxGenStreamingOut; /** * Executes the flow with the given AI service and input values. * * This is the main execution method that orchestrates the entire flow execution. * It handles several complex aspects: * * 1. **Dynamic Signature Inference**: If the flow was created with a default signature * but has nodes defined, it will infer the actual signature from the flow structure. * * 2. **Execution Mode Selection**: Chooses between optimized parallel execution * (when auto-parallel is enabled) or sequential execution based on configuration. * * 3. **State Management**: Maintains the evolving state object as it flows through * each step, accumulating results and transformations. * * 4. **Performance Optimization**: Uses the execution planner to identify * independent operations that can run in parallel, reducing total execution time. * * Execution Flow: * - Initialize state with input values * - Infer signature if needed (based on nodes and current signature) * - Choose execution strategy (parallel vs sequential) * - Execute all steps while maintaining state consistency * - Return final state cast to expected output type * * @param ai - The AI service to use as the default for all steps * @param values - The input values for the flow * @param options - Optional forward options to use as defaults (includes autoParallel override) * @returns Promise that resolves to the final output */ forward>(ai: T, values: IN | AxMessage[], options?: Readonly & { autoParallel?: boolean; }>): Promise; /** * Declares a reusable computational node using a signature string. * Returns a new AxFlow type that tracks this node in the TNodes registry. * * @param name - The name of the node * @param signature - Signature string in the same format as AxSignature * @returns New AxFlow instance with updated TNodes type * * @example * ``` * flow.node('summarizer', 'text:string -> summary:string') * flow.node('analyzer', 'text:string -> analysis:string, confidence:number', { debug: true }) * ``` */ node(name: TName, signature: TSig): AxFlow; }, // Add new node to registry TState>; /** * Declares a reusable computational node using an AxSignature instance. * This allows using pre-configured signatures in the flow. * * @param name - The name of the node * @param signature - AxSignature instance to use for this node * @returns New AxFlow instance with updated TNodes type * * @example * ``` * const sig = s('text:string -> summary:string') * flow.node('summarizer', sig, { temperature: 0.1 }) * ``` */ node(name: TName, signature: AxSignature): AxFlow; }, // Add new node to registry TState>; /** * Declares a reusable computational node using a class that extends AxProgram. * This allows using custom program classes in the flow. * * @param name - The name of the node * @param programClass - Class that extends AxProgram to use for this node * @returns New AxFlow instance with updated TNodes type * * @example * ``` * class CustomProgram extends AxProgram<{ input: string }, { output: string }> { * async forward(ai, values) { return { output: values.input.toUpperCase() } } * } * flow.node('custom', CustomProgram) * ``` */ node AxProgrammable>(name: TName, programClass: TProgram): AxFlow; }, // Add new node to registry with exact type TState>; /** * Declares a reusable computational node using an AxProgrammable instance. * This allows using pre-configured AxGen instances or other programmable objects in the flow. * * @param name - The name of the node * @param programInstance - The AxProgrammable instance to use for this node * @returns New AxFlow instance with updated TNodes type */ node>(name: TName, programInstance: TProgram): AxFlow; /** * Short alias for node() - supports signature strings, AxSignature instances, AxGen instances, and program classes */ n(name: TName, signature: TSig): AxFlow; }, TState>; n(name: TName, signature: AxSignature): AxFlow; }, TState>; n AxProgrammable>(name: TName, programClass: TProgram): AxFlow; }, TState>; n>(name: TName, programInstance: TProgram): AxFlow; /** * Applies a synchronous transformation to the state object. * Returns a new AxFlow type with the evolved state. * * @param transform - Function that takes the current state and returns a new state * @returns New AxFlow instance with updated TState type * * @example * ``` * flow.map(state => ({ ...state, processedText: state.text.toLowerCase() })) * ``` */ map(transform: (_state: TState) => TNewState): AxFlow; /** * Applies an asynchronous transformation to the state object. * Returns a new AxFlow type with the evolved state. * * @param transform - Async function that takes the current state and returns a promise of new state * @returns New AxFlow instance with updated TState type * * @example * ``` * flow.map(async state => ({ * ...state, * apiResult: await fetchDataFromAPI(state.query) * })) * ``` */ map(transform: (_state: TState) => Promise): AxFlow; /** * Applies a transformation to the state object with optional parallel execution. * When parallel is enabled, the transform function should prepare data for parallel processing. * The actual parallel processing happens with the array of transforms provided. * * @param transforms - Array of transformation functions to apply in parallel * @param options - Options including parallel execution configuration * @returns New AxFlow instance with updated TState type * * @example * ``` * // Parallel map with multiple transforms * flow.map([ * state => ({ ...state, result1: processA(state.data) }), * state => ({ ...state, result2: processB(state.data) }), * state => ({ ...state, result3: processC(state.data) }) * ], { parallel: true }) * ``` */ map(transforms: Array<(_state: TState) => TNewState>, options: { parallel: true; }): AxFlow; /** * Applies async transformations to the state object with optional parallel execution. * When parallel is enabled, all async transforms are executed concurrently. * * @param transforms - Array of async transformation functions to apply in parallel * @param options - Options including parallel execution configuration * @returns New AxFlow instance with updated TState type * * @example * ``` * // Parallel async map with multiple transforms * flow.map([ * async state => ({ ...state, result1: await apiCall1(state.data) }), * async state => ({ ...state, result2: await apiCall2(state.data) }), * async state => ({ ...state, result3: await apiCall3(state.data) }) * ], { parallel: true }) * ``` */ map(transforms: Array<(_state: TState) => Promise>, options: { parallel: true; }): AxFlow; map(transform: (_state: TState) => TNewState | Promise, options?: { parallel?: boolean; }): AxFlow; /** * Short alias for map() - supports parallel option and async functions */ m(transform: (_state: TState) => TNewState): AxFlow; m(transform: (_state: TState) => Promise): AxFlow; m(transforms: Array<(_state: TState) => TNewState>, options: { parallel: true; }): AxFlow; m(transforms: Array<(_state: TState) => Promise>, options: { parallel: true; }): AxFlow; /** * Terminal transformation that sets the final output type of the flow. * Use this as the last transformation to get proper type inference for the flow result. * * @param transform - Function that transforms the current state to the final output * @returns A new flow with the output type set to the transform result * * @example * ```typescript * const flow = flow<{ input: string }>() * .map(state => ({ ...state, processed: true })) * .returns(state => ({ * result: state.processed ? "done" : "pending" * })) // TypeScript now knows the output is { result: string } * ``` */ returns>(transform: (_state: TState) => TNewOut): AxFlow; /** * Short alias for returns() - r() is to returns() as m() is to map() * * @param transform - Function that transforms the current state to the final output * @returns A new flow with the output type set to the transform result */ r>(transform: (_state: TState) => TNewOut): AxFlow; /** * Labels a step for later reference (useful for feedback loops). * * @param label - The label to assign to the current step position * @returns this (for chaining, no type change) * * @example * ```typescript * flow.label('retry-point') * .execute('queryGen', ...) * ``` */ label(label: string): this; /** * Short alias for label() */ l(label: string): this; /** * Executes a previously defined node with full type safety. * The node name must exist in TNodes, and the mapping function is typed based on the node's signature. * * @param nodeName - The name of the node to execute (must exist in TNodes) * @param mapping - Typed function that takes the current state and returns the input for the node * @param dynamicContext - Optional object to override the AI service or options for this specific step * @returns New AxFlow instance with TState augmented with the node's result * * @example * ```typescript * flow.execute('summarizer', state => ({ text: state.originalText }), { ai: cheapAI }) * ``` */ execute>(nodeName: TNodeName, mapping: (_state: TState) => GetGenIn, dynamicContext?: AxFlowDynamicContext): AxFlow>>; /** * Apply optimized configuration to this flow and all node programs. */ applyOptimization(optimizedProgram: AxOptimizedProgram): void; /** * Short alias for execute() */ e>(nodeName: TNodeName, mapping: (_state: TState) => GetGenIn, dynamicContext?: AxFlowDynamicContext): AxFlow>>; /** * Starts a conditional branch based on a predicate function. * * @param predicate - Function that takes state and returns a value to branch on * @returns this (for chaining) * * @example * ```typescript * flow.branch(state => state.qualityResult.needsMoreInfo) * .when(true) * .execute('queryGen', ...) * .when(false) * .execute('answer', ...) * .merge() * ``` */ branch(predicate: (_state: TState) => unknown): this; /** * Short alias for branch() */ b(predicate: (_state: TState) => unknown): this; /** * Defines a branch case for the current branch context. * * @param value - The value to match against the branch predicate result * @returns this (for chaining) */ when(value: unknown): this; /** * Short alias for when() */ w(value: unknown): this; /** * Merges the results of conditional branches into a single execution path. * * This method is called after defining conditional branches with branch() and when() methods. * It creates a merge point where the flow continues with the results from whichever * branch was executed based on the branch condition. * * How conditional merging works: * 1. The branch predicate is evaluated against the current state * 2. The matching branch's steps are executed sequentially * 3. If no branch matches, the state is returned unchanged * 4. The merged result becomes the new state for subsequent steps * * Type safety note: * The TMergedState generic allows for type-level tracking of what fields * will be available after the merge, though runtime behavior depends on * which branch actually executes. * * @returns AxFlow with updated state type reflecting the merged result * * @example * ```typescript * flow * .branch(state => state.complexity > 0.5) * .when(true) * .execute('complexProcessor', state => ({ input: state.text })) * .when(false) * .execute('simpleProcessor', state => ({ input: state.text })) * .merge() // Combines results from either branch * ``` */ merge(): AxFlow; /** * Short alias for merge() */ mg(): AxFlow; /** * Executes multiple operations in parallel and provides a merge method for combining results. * * This method enables true parallel execution of independent operations, which is particularly * useful for operations like: * - Multiple document retrievals * - Parallel processing of different data sources * - Independent LLM calls that can run simultaneously * * How parallel execution works: * 1. Each branch function receives a sub-context for defining operations * 2. All branches are executed simultaneously using Promise.all() * 3. Results are stored in _parallelResults for the merge operation * 4. The merge function combines the results into a single field * * Performance benefits: * - Reduces total execution time for independent operations * - Maximizes throughput for I/O-bound operations (like LLM calls) * - Maintains type safety through the merge operation * * @param branches - Array of functions that define parallel operations * @returns Object with merge method for combining results * * @example * ```typescript * flow.parallel([ * subFlow => subFlow.execute('retrieve1', state => ({ query: state.query1 })), * subFlow => subFlow.execute('retrieve2', state => ({ query: state.query2 })), * subFlow => subFlow.execute('retrieve3', state => ({ query: state.query3 })) * ]).merge('documents', (docs1, docs2, docs3) => [...docs1, ...docs2, ...docs3]) * ``` */ parallel(branches: (AxFlowParallelBranch | AxFlowTypedParallelBranch)[]): { merge(resultKey: TResultKey, mergeFunction: (..._results: unknown[]) => T): AxFlow; }; /** * Short alias for parallel() */ p(branches: (AxFlowParallelBranch | AxFlowTypedParallelBranch)[]): { merge(resultKey: TResultKey, mergeFunction: (..._results: unknown[]) => T): AxFlow; }; /** * Creates a feedback loop that jumps back to a labeled step if a condition is met. * * @param condition - Function that returns true to trigger the feedback loop * @param targetLabel - The label to jump back to * @param maxIterations - Maximum number of iterations to prevent infinite loops (default: 10) * @returns this (for chaining) * * @example * ```typescript * flow.label('retry-point') * .execute('answer', ...) * .execute('qualityCheck', ...) * .feedback(state => state.qualityCheckResult.confidence < 0.7, 'retry-point') * ``` */ feedback(condition: (_state: TState) => boolean, targetLabel: string, maxIterations?: number): this; /** * Short alias for feedback() */ fb(condition: (_state: TState) => boolean, targetLabel: string, maxIterations?: number): this; /** * Marks the beginning of a loop block. * * @param condition - Function that takes the current state and returns a boolean * @param maxIterations - Maximum number of iterations to prevent infinite loops (default: 100) * @returns this (for chaining) * * @example * ```typescript * flow.while(state => state.iterations < 3, 10) * .map(state => ({ ...state, iterations: (state.iterations || 0) + 1 })) * .endWhile() * ``` */ while(condition: (state: TState) => boolean, maxIterations?: number): this; /** * Short alias for while() */ wh(condition: (_state: TState) => boolean, maxIterations?: number): this; /** * Marks the end of a loop block. * * @returns this (for chaining) */ endWhile(): this; /** * Short alias for endWhile() */ end(): this; /** * Derives a new field from an existing field by applying a transform function. * * If the input field contains an array, the transform function is applied to each * array element in parallel with batch size control. If the input field contains * a scalar value, the transform function is applied directly. * * @param outputFieldName - Name of the field to store the result * @param inputFieldName - Name of the existing field to transform * @param transformFn - Function to apply to each element (for arrays) or the value directly (for scalars) * @param options - Options including batch size for parallel processing * @returns this (for chaining) * * @example * ```typescript * // Parallel processing of array items * flow.derive('processedItems', 'items', (item, index) => processItem(item), { batchSize: 5 }) * * // Direct transformation of scalar value * flow.derive('upperText', 'text', (text) => text.toUpperCase()) * ``` */ derive(outputFieldName: string, inputFieldName: string, transformFn: (value: any, index?: number, state?: TState) => T, options?: { batchSize?: number; }): this; /** * Gets execution plan information for debugging automatic parallelization * * @returns Object with execution plan details */ getExecutionPlan(): { totalSteps: number; parallelGroups: number; maxParallelism: number; autoParallelEnabled: boolean; steps?: AxFlowExecutionStep[]; groups?: AxFlowParallelGroup[]; }; getSignature(): AxSignature; /** * Creates a new AxFlow node from an existing signature by extending it with additional fields. * * @param name - The name of the new node * @param baseSignature - The base signature to extend (string or AxSignature) * @param extensions - Object defining how to extend the signature * @returns New AxFlow instance with the extended node * * @example * ```typescript * // Create a chain-of-thought node * flow.nodeExtended('reasoner', 'question:string -> answer:string', { * prependOutputs: [ * { name: 'reasoning', type: f.internal(f.string('Step-by-step reasoning')) } * ] * }) * * // Create a node with context and confidence * flow.nodeExtended('analyzer', 'input:string -> output:string', { * appendInputs: [{ name: 'context', type: f.optional(f.string('Context')) }], * appendOutputs: [{ name: 'confidence', type: f.number('Confidence score') }] * }) * ``` */ nodeExtended(name: TName, baseSignature: string | AxSignature, extensions: { prependInputs?: Array<{ name: string; type: AxFieldType; }>; appendInputs?: Array<{ name: string; type: AxFieldType; }>; prependOutputs?: Array<{ name: string; type: AxFieldType; }>; appendOutputs?: Array<{ name: string; type: AxFieldType; }>; }): AxFlow; }, TState>; /** * Short alias for nodeExtended() - creates nodes with extended signatures */ nx(name: TName, baseSignature: string | AxSignature, extensions: { prependInputs?: Array<{ name: string; type: AxFieldType; }>; appendInputs?: Array<{ name: string; type: AxFieldType; }>; prependOutputs?: Array<{ name: string; type: AxFieldType; }>; appendOutputs?: Array<{ name: string; type: AxFieldType; }>; }): AxFlow; }, TState>; /** * Applies a final transformation to the state object that updates both state and output type. * This is specifically designed for terminal transformations that shape the final output. * * @param transform - Function that takes the current state and returns the final output * @returns New AxFlow instance with updated OUT and TState types * * @example * ``` * const result = await flow * .node('analyzer', 'userQuestion:string -> analysisResult:string') * .execute('analyzer', state => ({ userQuestion: state.userQuestion })) * .mapOutput(state => ({ * // Note: Node results are typed as AxFieldValue, so you may need to cast * finalAnswer: state.analyzerResult.analysisResult as string * })) * .forward(ai, { userQuestion: 'test' }); * * // result is typed as { finalAnswer: string } * ``` */ mapOutput(transform: (_state: TState) => TOutput): AxFlow; /** * Short alias for mapOutput() */ mo(transform: (_state: TState) => TOutput): AxFlow; } /** * Factory function to create a new AxFlow instance * Similar to ai() for AI services, this creates a fluent flow * * @param options - Optional configuration for the flow * @returns New AxFlow instance * * @example * ```typescript * // Input type is required - provides type safety throughout the flow * const workflow = flow<{ userInput: string }>() * .node('summarizer', 'documentText:string -> summaryText:string') * .execute('summarizer', state => ({ documentText: state.userInput })); * * // Complex input types work great for multi-field workflows * const complexFlow = flow<{ userQuestion: string; context: string }>() * .map(state => ({ * ...state, * processedQuestion: state.userQuestion.toUpperCase() // TypeScript knows this exists! * })); * ``` */ /** * Creates a new AxFlow instance with required input type specification. * * The input type must be specified upfront to enable proper type inference * throughout the flow construction and execution. * * @example * ```typescript * // ✅ Define input type upfront for better type safety * const workflow = flow<{ userInput: string, options?: any }>() * .map(state => ({ ...state, processedInput: state.userInput.toUpperCase() })) * .node('analyzer', 'processedInput:string -> result:string') * * // ✅ Simple input types work too * const simpleFlow = flow<{ documentText: string }>() * .node('summarizer', 'documentText:string -> summary:string') * ``` */ declare function flow, TOutput = {}>(options?: { autoParallel?: boolean; batchSize?: number; logger?: AxFlowLoggerFunction; debug?: boolean; }): AxFlow; /** * Implementation of the sub-context for parallel execution */ declare class AxFlowSubContextImpl implements AxFlowSubContext { private readonly nodeGenerators; private readonly steps; constructor(nodeGenerators: Map & AxTunable & AxUsable>); execute>(nodeName: string, mapping: (state: AxFlowState) => Record, dynamicContext?: AxFlowDynamicContext): this; map(transform: (state: AxFlowState) => AxFlowState): this; executeSteps(initialState: AxFlowState, context: Readonly<{ mainAi: AxAIService; mainOptions?: AxProgramForwardOptions; }>): Promise; } /** * Typed implementation of the sub-context for parallel execution with full type safety */ declare class AxFlowTypedSubContextImpl>, TState extends AxFlowState> implements AxFlowTypedSubContext { private readonly nodeGenerators; private readonly steps; constructor(nodeGenerators: Map | AxProgram>); execute>(nodeName: TNodeName, mapping: (state: TState) => GetGenIn, dynamicContext?: AxFlowDynamicContext): AxFlowTypedSubContext>>; map(transform: (state: TState) => TNewState): AxFlowTypedSubContext; executeSteps(initialState: TState, context: Readonly<{ mainAi: AxAIService; mainOptions?: AxProgramForwardOptions; }>): Promise; } type AxDataRow = { row: Record; }; declare class AxHFDataLoader { private rows; private baseUrl; private dataset; private split; private config; private options?; constructor({ dataset, split, config, options, }: Readonly<{ dataset: string; split: string; config: string; options?: Readonly<{ offset?: number; length?: number; }>; }>); private fetchDataFromAPI; loadData(): Promise; setData(rows: AxDataRow[]): void; getData(): AxDataRow[]; getRows({ count, fields, renameMap, }: Readonly<{ count: number; fields: readonly string[]; renameMap?: Record; }>): Promise; } declare const axSpanAttributes: { LLM_SYSTEM: string; LLM_OPERATION_NAME: string; LLM_REQUEST_MODEL: string; LLM_REQUEST_MAX_TOKENS: string; LLM_REQUEST_TEMPERATURE: string; LLM_REQUEST_TOP_K: string; LLM_REQUEST_FREQUENCY_PENALTY: string; LLM_REQUEST_PRESENCE_PENALTY: string; LLM_REQUEST_STOP_SEQUENCES: string; LLM_REQUEST_LLM_IS_STREAMING: string; LLM_REQUEST_TOP_P: string; LLM_USAGE_INPUT_TOKENS: string; LLM_USAGE_OUTPUT_TOKENS: string; LLM_USAGE_TOTAL_TOKENS: string; LLM_USAGE_THOUGHTS_TOKENS: string; DB_SYSTEM: string; DB_TABLE: string; DB_NAMESPACE: string; DB_ID: string; DB_QUERY_TEXT: string; DB_VECTOR: string; DB_OPERATION_NAME: string; DB_VECTOR_QUERY_TOP_K: string; DB_QUERY_EMBEDDINGS: string; DB_QUERY_RESULT: string; DB_QUERY_EMBEDDINGS_VECTOR: string; DB_QUERY_RESULT_ID: string; DB_QUERY_RESULT_SCORE: string; DB_QUERY_RESULT_DISTANCE: string; DB_QUERY_RESULT_METADATA: string; DB_QUERY_RESULT_VECTOR: string; DB_QUERY_RESULT_DOCUMENT: string; }; declare const axSpanEvents: { GEN_AI_USER_MESSAGE: string; GEN_AI_SYSTEM_MESSAGE: string; GEN_AI_ASSISTANT_MESSAGE: string; GEN_AI_TOOL_MESSAGE: string; GEN_AI_CHOICE: string; GEN_AI_USAGE: string; }; declare enum AxLLMRequestTypeValues { COMPLETION = "completion", CHAT = "chat", RERANK = "rerank", UNKNOWN = "unknown" } declare enum AxSpanKindValues { WORKFLOW = "workflow", TASK = "task", AGENT = "agent", TOOL = "tool", UNKNOWN = "unknown" } interface AxMiPROResult extends AxOptimizerResult { optimizedGen?: AxGen; optimizedProgram?: AxOptimizedProgram; } declare class AxMiPRO extends AxBaseOptimizer { private maxBootstrappedDemos; private maxLabeledDemos; private numCandidates; private initTemperature; private numTrials; private minibatch; private minibatchSize; private minibatchFullEvalSteps; private programAwareProposer; private dataAwareProposer; private viewDataBatchSize; private tipAwareProposer; private fewshotAwareProposer; private earlyStoppingTrials; private minImprovementThreshold; private bayesianOptimization; private acquisitionFunction; private explorationWeight; private optimizeTopP; private sampleCount; private pythonClient?; private localScoreHistory; private localConfigurationHistory; private readonly customResultPicker?; constructor(args: Readonly); /** * Default result picker used when sampleCount > 1 and no custom picker is provided. * Strategy: * - Function results: pick first non-error result, else index 0 * - Field results: majority vote by JSON stringified output; ties → first seen */ private readonly defaultResultPicker; /** * Configures the optimizer for light, medium, or heavy optimization * @param level The optimization level: "light", "medium", or "heavy" */ configureAuto(level: 'light' | 'medium' | 'heavy'): void; /** * Generates creative tips for instruction generation */ private generateTips; /** * Generates program summary for context-aware instruction generation */ private generateProgramSummary; /** * Generates dataset summary for context-aware instruction generation */ private generateDatasetSummary; /** * Enhanced instruction generation using AI with program and data awareness */ private generateInstruction; /** * Generates instruction candidates using enhanced AI-powered generation * @param options Optional compile options that may override teacher AI * @returns Array of generated instruction candidates */ private proposeInstructionCandidates; /** * Bootstraps few-shot examples for the program */ private bootstrapFewShotExamples; /** * Selects labeled examples directly from the training set */ private selectLabeledExamples; /** * Runs optimization to find the best combination of few-shot examples and instructions */ private applyConfigToProgram; /** * The main compile method to run MIPROv2 optimization */ compile(program: Readonly>, examples: readonly AxTypedExample[], metricFn: AxMetricFn, options?: AxCompileOptions): Promise>; /** * Applies a configuration to an AxGen instance */ private applyConfigToAxGen; /** * Get optimizer-specific configuration * @returns Current optimizer configuration */ getConfiguration(): Record; /** * Update optimizer configuration * @param config New configuration to merge with existing */ updateConfiguration(config: Readonly>): void; /** * Reset optimizer state for reuse with different programs */ reset(): void; /** * Validate that the optimizer can handle the given program * @param program Program to validate * @returns Validation result with any issues found */ validateProgram(_program: Readonly>): { isValid: boolean; issues: string[]; suggestions: string[]; }; /** * Python-based compilation method * * This is a simplified implementation that demonstrates integration * with the Python optimizer service. For now, it focuses on basic * parameter optimization rather than full MiPRO functionality. */ private compilePython; private generateOptimizationReport; /** * Simplified evaluation method for Python optimization */ private evaluateConfiguration; } type AxMockAIServiceConfig = { name?: string; id?: string; modelInfo?: Partial; embedModelInfo?: AxModelInfoWithProvider; features?: { functions?: boolean; streaming?: boolean; }; models?: AxAIModelList; options?: AxAIServiceOptions; chatResponse?: AxChatResponse | ReadableStream | (() => Promise>) | ((req: Readonly>, options?: Readonly) => Promise>); embedResponse?: AxEmbedResponse | ((req: Readonly) => AxEmbedResponse | Promise); shouldError?: boolean; errorMessage?: string; latencyMs?: number; }; declare class AxMockAIService implements AxAIService { private readonly config; private metrics; constructor(config?: AxMockAIServiceConfig); getLastUsedChatModel(): unknown; getLastUsedEmbedModel(): unknown; getLastUsedModelConfig(): AxModelConfig | undefined; getName(): string; getId(): string; getFeatures(_model?: string): AxAIFeatures; getModelList(): AxAIModelList | undefined; getMetrics(): AxAIServiceMetrics; chat(req: Readonly>, _options?: Readonly): Promise>; embed(req: Readonly, _options?: Readonly): Promise; setOptions(options: Readonly): void; getOptions(): Readonly; getLogger(): AxLoggerFunction; private updateMetrics; } /** * Configuration options for content processing and fallback behavior */ interface ProcessingOptions { /** How to handle unsupported content types: 'error' throws, 'degrade' converts to text, 'skip' omits */ fallbackBehavior?: 'error' | 'degrade' | 'skip'; /** Service to convert images to text descriptions */ imageToText?: (imageData: string) => Promise; /** Service to convert audio to text transcriptions */ audioToText?: (audioData: string, format?: string) => Promise; /** Service to extract text from files */ fileToText?: (fileData: string, mimeType: string) => Promise; /** Service to fetch and extract text from URLs */ urlToText?: (url: string) => Promise; } /** * Represents processed content that has been converted to text format */ interface ProcessedContent { /** Content type after processing (always 'text') */ type: 'text'; /** The processed text content */ text: string; } /** * Indicates what types of media content are present in a request */ interface MediaRequirements { /** Whether the content includes images */ hasImages: boolean; /** Whether the content includes audio */ hasAudio: boolean; /** Whether the content includes files */ hasFiles: boolean; /** Whether the content includes URLs */ hasUrls: boolean; } /** * Processes content for a specific AI provider, handling unsupported media types. * * This function takes mixed content (text, images, audio, files, URLs) and transforms * it to formats supported by the target provider. Unsupported content types are * handled according to the fallback behavior: * - 'error': Throws AxMediaNotSupportedError * - 'degrade': Converts to text using fallback services or alt text * - 'skip': Omits the unsupported content * * @param content - The content to process (string, object, or array of content items) * @param provider - The target AI service provider * @param options - Processing options including fallback behavior and conversion services * @returns Promise resolving to array of processed content items (all converted to text) * @throws AxMediaNotSupportedError when fallbackBehavior is 'error' and content is unsupported * @throws AxContentProcessingError when a conversion service fails * * @example * ```typescript * const processed = await axProcessContentForProvider( * [ * { type: 'text', text: 'Analyze this:' }, * { type: 'image', image: 'base64...', altText: 'Chart showing sales data' } * ], * textOnlyProvider, * { * fallbackBehavior: 'degrade', * imageToText: async (data) => await visionService.describe(data) * } * ); * // Result: [{ type: 'text', text: 'Analyze this:' }, { type: 'text', text: 'Chart showing sales data' }] * ``` */ declare function axProcessContentForProvider(content: any, provider: AxAIService, options?: ProcessingOptions): Promise; /** * Analyzes a chat prompt to determine what media types it contains. * * Scans through chat messages to identify the types of media content present, * which can be used for provider capability matching and routing decisions. * * @param chatPrompt - Array of chat messages to analyze * @returns Object indicating which media types are present in the chat prompt * * @example * ```typescript * const requirements = axAnalyzeChatPromptRequirements([ * { * role: 'user', * content: [ * { type: 'text', text: 'Analyze this:' }, * { type: 'image', image: 'base64...' }, * { type: 'file', filename: 'report.pdf' } * ] * } * ]); * // Result: { hasImages: true, hasAudio: false, hasFiles: true, hasUrls: false } * ``` */ declare function axAnalyzeChatPromptRequirements(chatPrompt: any[]): MediaRequirements; /** * Services for converting unsupported content types to text or optimized formats */ interface AxContentProcessingServices { /** Service to convert images to text descriptions */ imageToText?: (imageData: string) => Promise; /** Service to convert audio to text transcriptions */ audioToText?: (audioData: string, format?: string) => Promise; /** Service to extract text from files */ fileToText?: (fileData: string, mimeType: string) => Promise; /** Service to fetch and extract text from URLs */ urlToText?: (url: string) => Promise; /** Service to optimize images for size/quality */ imageOptimization?: (imageData: string, options: OptimizationOptions) => Promise; } /** * Options for image optimization processing */ interface OptimizationOptions { /** Image quality (0-100) */ quality?: number; /** Maximum file size in bytes */ maxSize?: number; /** Target image format */ format?: 'jpeg' | 'png' | 'webp'; } /** * Configuration for multi-provider routing with fallback capabilities */ interface AxMultiProviderConfig { /** Provider hierarchy for routing */ providers: { /** Primary provider to try first */ primary: AxAIService; /** Alternative providers for fallback */ alternatives: AxAIService[]; }; /** Routing behavior configuration */ routing: { /** Order of preferences when selecting providers */ preferenceOrder: ('capability' | 'cost' | 'speed' | 'quality')[]; /** Capability matching requirements */ capability: { /** Only use providers with full capability support */ requireExactMatch: boolean; /** Allow providers that require content processing fallbacks */ allowDegradation: boolean; }; }; /** Content processing services for unsupported media types */ processing: AxContentProcessingServices; } /** * Result of the routing process including provider selection and processing information */ interface AxRoutingResult { /** The selected AI service provider */ provider: AxAIService; /** List of content processing steps that were applied */ processingApplied: string[]; /** List of capability degradations that occurred */ degradations: string[]; /** Non-critical warnings about the routing decision */ warnings: string[]; } /** * Multi-provider router that automatically selects optimal AI providers and handles content processing. * * The router analyzes requests to determine capability requirements, scores available providers, * and automatically handles content transformation for unsupported media types. It provides * graceful degradation and fallback mechanisms for robust multi-modal AI applications. * * @example * ```typescript * const router = new AxProviderRouter({ * providers: { * primary: openaiProvider, * alternatives: [geminiProvider, cohereProvider] * }, * routing: { * preferenceOrder: ['capability', 'quality'], * capability: { * requireExactMatch: false, * allowDegradation: true * } * }, * processing: { * imageToText: async (data) => await visionService.describe(data), * audioToText: async (data) => await speechService.transcribe(data) * } * }); * * const result = await router.chat(multiModalRequest); * console.log(`Used: ${result.routing.provider.getName()}`); * ``` */ declare class AxProviderRouter { private providers; private processingServices; private config; /** * Creates a new provider router with the specified configuration. * * @param config - Router configuration including providers, routing preferences, and processing services */ constructor(config: AxMultiProviderConfig); /** * Routes a chat request to the most appropriate provider with automatic content processing. * * This method analyzes the request, selects the optimal provider, preprocesses content * for compatibility, and executes the request with fallback support. * * @param request - The chat request to process * @param options - Extended options including fallback providers and routing preferences * @param options.fallbackProviders - Additional providers to try if primary selection fails * @param options.processingOptions - Content processing options and conversion services * @param options.routingOptions - Provider selection and routing behavior options * @param options.routingOptions.requireExactMatch - Only use providers with full capability support * @param options.routingOptions.allowDegradation - Allow content processing for unsupported types * @param options.routingOptions.maxRetries - Maximum number of fallback providers to try * @returns Promise resolving to the AI response and routing information * @throws AxMediaNotSupportedError when no suitable provider can handle the request * * @example * ```typescript * const result = await router.chat( * { chatPrompt: [{ role: 'user', content: [{ type: 'image', image: '...' }] }] }, * { * processingOptions: { fallbackBehavior: 'degrade' }, * routingOptions: { allowDegradation: true } * } * ); * * console.log(`Provider: ${result.routing.provider.getName()}`); * console.log(`Processing applied: ${result.routing.processingApplied}`); * ``` */ chat(request: AxChatRequest, options?: AxAIServiceOptions & { fallbackProviders?: AxAIService[]; processingOptions?: ProcessingOptions; routingOptions?: { requireExactMatch?: boolean; allowDegradation?: boolean; maxRetries?: number; }; }): Promise<{ response: AxChatResponse | ReadableStream; routing: AxRoutingResult; }>; /** * Preprocesses request content for the target provider */ private preprocessRequest; /** * Selects provider with graceful degradation */ private selectProviderWithDegradation; /** * Tries fallback providers when primary provider fails */ private tryFallbackProviders; /** * Gets routing recommendation without executing the request. * * Analyzes the request and returns routing information including which provider * would be selected, what processing would be applied, and any degradations or warnings. * * @param request - The chat request to analyze * @returns Promise resolving to routing result with provider selection and processing info * * @example * ```typescript * const recommendation = await router.getRoutingRecommendation(request); * console.log(`Would use: ${recommendation.provider.getName()}`); * console.log(`Degradations: ${recommendation.degradations.join(', ')}`); * ``` */ getRoutingRecommendation(request: AxChatRequest): Promise; /** * Validates whether the configured providers can handle a specific request. * * Performs pre-flight validation to check if the request can be successfully * processed by available providers, identifies potential issues, and provides * recommendations for improving compatibility. * * @param request - The chat request to validate * @returns Promise resolving to validation result with handling capability and recommendations * * @example * ```typescript * const validation = await router.validateRequest(request); * if (!validation.canHandle) { * console.log('Issues:', validation.issues); * console.log('Recommendations:', validation.recommendations); * } * ``` */ validateRequest(request: AxChatRequest): Promise<{ canHandle: boolean; issues: string[]; recommendations: string[]; }>; /** * Gets detailed statistics about the router's provider capabilities. * * Returns information about available providers, their supported capabilities, * and routing recommendations for analysis and debugging purposes. * * @returns Object containing provider statistics and capability matrix * * @example * ```typescript * const stats = router.getRoutingStats(); * console.log(`Total providers: ${stats.totalProviders}`); * console.log('Capabilities:'); * for (const [capability, providers] of Object.entries(stats.capabilityMatrix)) { * console.log(` ${capability}: ${providers.join(', ')}`); * } * ``` */ getRoutingStats(): { totalProviders: number; capabilityMatrix: { [capability: string]: string[]; }; recommendedProvider: string; }; } interface AxRateLimiterTokenUsageOptions { debug?: boolean; } declare class AxRateLimiterTokenUsage { private options?; private maxTokens; private refillRate; private currentTokens; private lastRefillTime; constructor(maxTokens: number, refillRate: number, options?: Readonly); private refillTokens; private waitUntilTokensAvailable; acquire(tokens: number): Promise; } interface AxSimpleClassifierForwardOptions { cutoff?: number; abortSignal?: AbortSignal; } declare class AxSimpleClassifierClass { private readonly name; private readonly context; constructor(name: string, context: readonly string[]); getName(): string; getContext(): readonly string[]; } declare class AxSimpleClassifier { private readonly ai; private db; private debug?; constructor(ai: AxAIService); getState(): AxDBState | undefined; setState(state: AxDBState): void; setClasses: (classes: readonly AxSimpleClassifierClass[], options?: Readonly<{ abortSignal?: AbortSignal; }>) => Promise; forward(text: string, options?: Readonly): Promise; setOptions(options: Readonly<{ debug?: boolean; }>): void; } type AxEvaluateArgs = { ai: AxAIService; program: Readonly>; examples: Readonly; }; declare class AxTestPrompt { private ai; private program; private examples; constructor({ ai, program, examples, }: Readonly>); run(metricFn: AxMetricFn): Promise; } declare function s(signature: T): AxSignature['inputs'], ParseSignature['outputs']>; declare function ax(signature: T, options?: Readonly & { thoughtFieldName?: ThoughtKey; }>): AxGen['inputs'], ParseSignature['outputs'] & (string extends ThoughtKey ? { thought?: string; } : { [P in ThoughtKey]?: string; })>; declare function ax, TOutput extends Record, ThoughtKey extends string = 'thought'>(signature: AxSignature, options?: Readonly & { thoughtFieldName?: ThoughtKey; }>): AxGen; /** * Represents a provider's compatibility score for a specific request */ interface ProviderCapabilityScore { /** The AI service provider */ provider: AxAIService; /** Numerical score based on capability match (higher is better) */ score: number; /** List of capabilities the provider is missing for this request */ missingCapabilities: string[]; /** List of capabilities the provider supports for this request */ supportedCapabilities: string[]; } /** * Result of validating whether a provider can handle a request */ interface CapabilityValidationResult { /** Whether the provider fully supports the request */ isSupported: boolean; /** List of capabilities the provider is missing */ missingCapabilities: string[]; /** Non-critical issues or limitations */ warnings: string[]; /** Suggested alternatives for missing capabilities */ alternatives: string[]; } /** * Analyzes a chat request to determine what capabilities it requires from AI providers. * * This function examines the request content to identify: * - Media types (images, audio, files, URLs) * - Function calling requirements * - Streaming requirements * - Caching requirements * - Token usage estimation * * @param request - The chat request to analyze * @returns Object containing detailed capability requirements and token estimation * * @example * ```typescript * const requirements = axAnalyzeRequestRequirements({ * chatPrompt: [{ * role: 'user', * content: [ * { type: 'text', text: 'Analyze this image:' }, * { type: 'image', image: 'base64...', details: 'high' } * ] * }] * }); * * console.log(requirements.hasImages); // true * console.log(requirements.estimatedTokens); // ~95 * ``` */ declare function axAnalyzeRequestRequirements(request: AxChatRequest): MediaRequirements & { requiresFunctions: boolean; requiresStreaming: boolean; requiresCaching: boolean; contentTypes: Set; estimatedTokens: number; }; /** * Validates whether an AI provider can handle a request with specific requirements. * * Compares the provider's feature set against the analyzed request requirements * to determine compatibility, missing capabilities, and potential issues. * * @param provider - The AI service provider to validate * @param requirements - Requirements object from axAnalyzeRequestRequirements() * @returns Validation result with support status, missing capabilities, and alternatives * * @example * ```typescript * const requirements = axAnalyzeRequestRequirements(request); * const validation = axValidateProviderCapabilities(openaiProvider, requirements); * * if (!validation.isSupported) { * console.log('Missing:', validation.missingCapabilities); * console.log('Try:', validation.alternatives); * } * ``` */ declare function axValidateProviderCapabilities(provider: AxAIService, requirements: ReturnType): CapabilityValidationResult; /** * Scores multiple AI providers based on how well they meet request requirements. * * Uses a weighted scoring system where providers earn points for supported capabilities: * - Base functionality: +10 points * - Media support (images/audio/files/URLs): +25 points each * - Core features (functions/streaming/caching): +8-15 points each * - Missing critical capabilities: -10 points each * - Bonus points for advanced features (large file support, persistent caching, etc.) * * @param providers - Array of AI service providers to score * @param requirements - Requirements object from axAnalyzeRequestRequirements() * @returns Array of scored providers sorted by score (highest first) * * @example * ```typescript * const requirements = axAnalyzeRequestRequirements(request); * const scores = axScoreProvidersForRequest([openai, gemini, cohere], requirements); * * console.log(`Best: ${scores[0].provider.getName()} (${scores[0].score} points)`); * console.log(`Supports: ${scores[0].supportedCapabilities.join(', ')}`); * ``` */ declare function axScoreProvidersForRequest(providers: AxAIService[], requirements: ReturnType): ProviderCapabilityScore[]; /** * Automatically selects the optimal AI provider for a given request. * * Analyzes the request requirements, scores available providers, and returns * the best match based on capability compatibility and scoring algorithm. * * @param request - The chat request to find a provider for * @param availableProviders - Array of available AI service providers * @param options - Selection options * @param options.requireExactMatch - Only return providers with full capability support * @param options.allowDegradation - Allow providers that require content processing fallbacks * @returns The optimal AI service provider * @throws Error if no suitable provider found or requirements not met * * @example * ```typescript * // Automatic selection with degradation allowed * const provider = axSelectOptimalProvider( * multiModalRequest, * [openai, gemini, cohere], * { allowDegradation: true } * ); * * // Strict matching - must support all features natively * const provider = axSelectOptimalProvider( * imageRequest, * [openai, gemini], * { requireExactMatch: true } * ); * ``` */ declare function axSelectOptimalProvider(request: AxChatRequest, availableProviders: AxAIService[], options?: { requireExactMatch?: boolean; allowDegradation?: boolean; }): AxAIService; /** * Generates a comprehensive compatibility report for a request across all providers. * * Provides detailed analysis including requirement breakdown, provider scoring, * recommendations, and human-readable compatibility summary. * * @param request - The chat request to analyze * @param availableProviders - Array of available AI service providers * @returns Comprehensive compatibility report with analysis and recommendations * * @example * ```typescript * const report = axGetCompatibilityReport(request, [openai, gemini, cohere]); * * console.log(report.summary); // "OpenAI supports 4/4 requirements (100% compatibility)" * console.log('Requirements:', report.requirements); * * for (const score of report.providerScores) { * console.log(`${score.provider.getName()}: ${score.score} points`); * console.log(` Missing: ${score.missingCapabilities.join(', ')}`); * } * ``` */ declare function axGetCompatibilityReport(request: AxChatRequest, availableProviders: AxAIService[]): { requirements: ReturnType; providerScores: ProviderCapabilityScore[]; recommendedProvider: AxAIService | null; summary: string; }; /** * Filters providers that support a specific media type. * * @param providers - Array of AI service providers to filter * @param mediaType - The media type to check support for * @returns Array of providers that support the specified media type * * @example * ```typescript * const imageProviders = axGetProvidersWithMediaSupport(allProviders, 'images'); * console.log(`${imageProviders.length} providers support images`); * ``` */ declare function axGetProvidersWithMediaSupport(providers: AxAIService[], mediaType: 'images' | 'audio' | 'files' | 'urls'): AxAIService[]; /** * Analyzes format compatibility across providers for a specific media type. * * @param providers - Array of AI service providers to analyze * @param mediaType - The media type to check format support for * @returns Object mapping each supported format to the providers that support it * * @example * ```typescript * const compatibility = axGetFormatCompatibility(allProviders, 'images'); * console.log('JPEG support:', compatibility['image/jpeg']?.map(p => p.getName())); * console.log('PNG support:', compatibility['image/png']?.map(p => p.getName())); * ``` */ declare function axGetFormatCompatibility(providers: AxAIService[], mediaType: 'images' | 'audio' | 'files'): { [format: string]: AxAIService[]; }; interface AxMetricsConfig { enabled: boolean; enabledCategories: ('generation' | 'streaming' | 'functions' | 'errors' | 'performance')[]; maxLabelLength: number; samplingRate: number; } declare const axDefaultMetricsConfig: AxMetricsConfig; type AxErrorCategory = 'validation_error' | 'assertion_error' | 'timeout_error' | 'abort_error' | 'network_error' | 'auth_error' | 'rate_limit_error' | 'function_error' | 'parsing_error' | 'unknown_error'; interface AxGenMetricsInstruments { generationLatencyHistogram?: Histogram; generationRequestsCounter?: Counter; generationErrorsCounter?: Counter; multiStepGenerationsCounter?: Counter; stepsPerGenerationHistogram?: Histogram; maxStepsReachedCounter?: Counter; validationErrorsCounter?: Counter; assertionErrorsCounter?: Counter; errorCorrectionAttemptsHistogram?: Histogram; errorCorrectionSuccessCounter?: Counter; errorCorrectionFailureCounter?: Counter; maxRetriesReachedCounter?: Counter; functionsEnabledGenerationsCounter?: Counter; functionCallStepsCounter?: Counter; functionsExecutedPerGenerationHistogram?: Histogram; functionErrorCorrectionCounter?: Counter; fieldProcessorsExecutedCounter?: Counter; streamingFieldProcessorsExecutedCounter?: Counter; streamingGenerationsCounter?: Counter; streamingDeltasEmittedCounter?: Counter; streamingFinalizationLatencyHistogram?: Histogram; samplesGeneratedHistogram?: Histogram; resultPickerUsageCounter?: Counter; resultPickerLatencyHistogram?: Histogram; inputFieldsGauge?: Gauge; outputFieldsGauge?: Gauge; examplesUsedGauge?: Gauge; demosUsedGauge?: Gauge; promptRenderLatencyHistogram?: Histogram; extractionLatencyHistogram?: Histogram; assertionLatencyHistogram?: Histogram; stateCreationLatencyHistogram?: Histogram; memoryUpdateLatencyHistogram?: Histogram; } declare const axCheckMetricsHealth: () => { healthy: boolean; issues: string[]; }; declare const axUpdateMetricsConfig: (config: Readonly>) => void; declare const axGetMetricsConfig: () => AxMetricsConfig; declare const axCreateDefaultColorLogger: (output?: (message: string) => void) => AxLoggerFunction; declare const axCreateDefaultTextLogger: (output?: (message: string) => void) => AxLoggerFunction; /** * Factory function to create a default optimizer logger with color formatting */ declare const axCreateDefaultOptimizerColorLogger: (output?: (message: string) => void) => AxOptimizerLoggerFunction; /** * Factory function to create a text-only optimizer logger (no colors) */ declare const axCreateDefaultOptimizerTextLogger: (output?: (message: string) => void) => AxOptimizerLoggerFunction; /** * Default optimizer logger instance with color formatting */ declare const axDefaultOptimizerLogger: AxOptimizerLoggerFunction; type AxFunctionResultFormatter = (result: unknown) => string; declare const axGlobals: { signatureStrict: boolean; tracer: Tracer | undefined; meter: Meter | undefined; logger: AxLoggerFunction | undefined; optimizerLogger: AxOptimizerLoggerFunction | undefined; debug: boolean | undefined; functionResultFormatter: AxFunctionResultFormatter; }; /** * OpenAI: Model information */ declare const axModelInfoOpenAI: AxModelInfo[]; /** * OpenAI: Model information */ declare const axModelInfoOpenAIResponses: AxModelInfo[]; type AxChatRequestMessage = AxChatRequest['chatPrompt'][number]; /** * Validates a chat request message item to ensure it meets the required criteria * @param item - The chat request message to validate * @throws {Error} When validation fails with a descriptive error message */ declare function axValidateChatRequestMessage(item: AxChatRequestMessage): void; /** * Validates a chat response result to ensure it meets the required criteria * @param results - The chat response results to validate (single result or array) * @throws {Error} When validation fails with a descriptive error message */ declare function axValidateChatResponseResult(results: Readonly | Readonly): void; type AxFieldProcessorProcess = (value: AxFieldValue, context?: Readonly<{ values?: AxGenOut; sessionId?: string; done?: boolean; }>) => unknown | Promise; type AxStreamingFieldProcessorProcess = (value: string, context?: Readonly<{ values?: AxGenOut; sessionId?: string; done?: boolean; }>) => unknown | Promise; interface AxFieldProcessor { field: Readonly; /** * Process the field value and return a new value (or undefined if no update is needed). * The returned value may be merged back into memory. * @param value - The current field value. * @param context - Additional context (e.g. memory and session id). */ process: AxFieldProcessorProcess | AxStreamingFieldProcessorProcess; } interface AxMCPJSONRPCRequest { jsonrpc: '2.0'; id: string | number; method: string; params?: T; } interface AxMCPJSONRPCSuccessResponse { jsonrpc: '2.0'; id: string | number; result: T; } interface AxMCPJSONRPCErrorResponse { jsonrpc: '2.0'; id: string | number; error: { code: number; message: string; data?: unknown; }; } type AxMCPJSONRPCResponse = AxMCPJSONRPCSuccessResponse | AxMCPJSONRPCErrorResponse; interface AxMCPInitializeParams { protocolVersion: string; capabilities: Record; clientInfo: { name: string; version: string; }; } interface AxMCPInitializeResult { protocolVersion: string; capabilities: { tools?: unknown[]; resources?: Record; prompts?: unknown[]; }; serverInfo: { name: string; version: string; }; } interface AxMCPFunctionDescription { name: string; description: string; inputSchema: AxFunctionJSONSchema; } interface AxMCPToolsListResult { name: string; description: string; tools: AxMCPFunctionDescription[]; } interface AxMCPJSONRPCNotification { jsonrpc: '2.0'; method: string; params?: Record; } declare class AxAIOpenAIResponsesImpl> implements AxAIServiceImpl>, // ChatReq (now ResponsesReq) Readonly>, // EmbedReq Readonly, // ChatResp (now ResponsesResp) Readonly, // ChatRespDelta (now ResponsesRespDelta) Readonly> { private readonly config; private readonly streamingUsage; private readonly responsesReqUpdater?; private tokensUsed; constructor(config: Readonly>, streamingUsage: boolean, // If /v1/responses supports include_usage for streams responsesReqUpdater?: ResponsesReqUpdater | undefined); getTokenUsage(): Readonly | undefined; getModelConfig(): Readonly; private mapInternalContentToResponsesInput; private createResponsesReqInternalInput; createChatReq(req: Readonly>, config: Readonly): [Readonly, Readonly>]; createChatResp(resp: Readonly): Readonly; createChatStreamResp(streamEvent: Readonly): Readonly; createEmbedReq(req: Readonly>): [AxAPI, AxAIOpenAIEmbedRequest]; } declare class AxBootstrapFewShot extends AxBaseOptimizer { private maxRounds; private maxDemos; private maxExamples; private batchSize; private earlyStoppingPatience; private costMonitoring; private maxTokensPerGeneration; private verboseMode; private debugMode; private traces; constructor(args: Readonly); private compileRound; compile(program: Readonly>, examples: readonly AxTypedExample[], metricFn: AxMetricFn, options?: AxCompileOptions): Promise>; } declare class AxDefaultResultReranker extends AxGen { constructor(options?: Readonly>); forward: >(ai: T, input: Readonly, options?: Readonly>) => Promise; } declare class AxEmbeddingAdapter { private aiService; private info; private func; constructor({ ai, info, func, }: Readonly<{ ai: AxAIService; info: Readonly<{ name: string; description: string; argumentDescription: string; }>; func: (args: readonly number[], extra?: Readonly) => Promise; }>); private embedAdapter; toFunction(): AxFunction; } /** * Calculates the Exact Match (EM) score between a prediction and ground truth. * * The EM score is a strict metric used in machine learning to assess if the predicted * answer matches the ground truth exactly, commonly used in tasks like question answering. * * @param prediction The predicted text. * @param groundTruth The actual correct text. * @returns A number (1.0 for exact match, 0.0 otherwise). */ declare function emScore(prediction: string, groundTruth: string): number; /** * Calculates the F1 score between a prediction and ground truth. * * The F1 score is a harmonic mean of precision and recall, widely used in NLP to measure * a model's accuracy in considering both false positives and false negatives, offering a * balance for evaluating classification models. * * @param prediction The predicted text. * @param groundTruth The actual correct text. * @returns The F1 score as a number. */ declare function f1Score(prediction: string, groundTruth: string): number; /** * Calculates a novel F1 score, taking into account a history of interaction and excluding stopwords. * * This metric extends the F1 score by considering contextual relevance and filtering out common words * that might skew the assessment of the prediction's quality, especially in conversational models or * when historical context is relevant. * * @param history The historical context or preceding interactions. * @param prediction The predicted text. * @param groundTruth The actual correct text. * @param returnRecall Optionally return the recall score instead of F1. * @returns The novel F1 or recall score as a number. */ declare function novelF1ScoreOptimized(history: string, prediction: string, groundTruth: string, returnRecall?: boolean): number; declare const AxEvalUtil: { emScore: typeof emScore; f1Score: typeof f1Score; novelF1ScoreOptimized: typeof novelF1ScoreOptimized; }; /** * Analyzes mapping functions to extract state dependencies. * * This class is crucial for the automatic parallelization feature of AxFlow. * It determines which fields in the state object a mapping function accesses, * which allows the execution planner to understand dependencies between steps * and optimize execution by running independent steps in parallel. * * The analyzer uses two complementary approaches: * 1. Static analysis of the function source code * 2. Dynamic proxy-based tracking as a fallback * * This dual approach ensures robust dependency detection even for complex * mapping functions that might use destructuring, computed property access, * or other advanced JavaScript patterns. */ declare class AxFlowDependencyAnalyzer { /** * Analyzes a mapping function to determine which state fields it depends on. * * This method is called for every execute step to understand what data * the step needs from the current state. This information is used to: * - Build the dependency graph for parallel execution * - Ensure steps execute in the correct order * - Optimize performance by identifying independent operations * * The analysis process: * 1. First tries static analysis by parsing the function source * 2. Falls back to proxy-based tracking for complex cases * 3. Returns a list of field names that the mapping function accesses * * @param mapping - The mapping function that transforms state to node inputs * @param _nodeName - The name of the node (currently unused but kept for future use) * @returns Array of field names that the mapping function depends on * * @example * ```typescript * // For a mapping like: state => ({ query: state.userInput, context: state.previousResult }) * // This would return: ['userInput', 'previousResult'] * ``` */ analyzeMappingDependencies(mapping: (state: any) => any, _nodeName: string): string[]; /** * Creates a tracking proxy for dependency analysis. * * This is a public method that creates a proxy to track property access patterns. * It's used for testing and advanced dependency analysis scenarios. * * @param target - The target object to wrap with a proxy * @param accessed - Array to collect accessed property names * @returns Proxy object that tracks property access */ createTrackingProxy(target: any, accessed: string[]): any; /** * Parses function source code to extract state dependencies using static analysis. * * This method analyzes the source code of a function to find patterns like * `state.fieldName` and extracts the field names as dependencies. * * @param functionSource - The source code of the function to analyze * @returns Array of field names found in the source code */ parseStaticDependencies(functionSource: string): string[]; /** * Creates a proxy object that tracks property access for dependency analysis. * * This proxy intercepts all property access on the state object and records * which fields are being accessed. It's used as a fallback when static analysis * can't determine dependencies (e.g., for destructuring or computed properties). * * The proxy works by: * 1. Intercepting all property access via the 'get' trap * 2. Recording accessed property names in the dependencies array * 3. Returning nested proxies for chained property access * * This allows detection of complex access patterns like: * - Destructuring: const { field1, field2 } = state * - Computed properties: state[dynamicKey] * - Nested access: state.nested.field * * @param dependencies - Array to collect dependency names (modified in place) * @returns Proxy object that tracks property access */ private createDependencyTracker; } /** * Builds and manages the execution plan with automatic parallelization. * * This class is the core of AxFlow's performance optimization system. * It analyzes the dependency relationships between steps and creates * an optimized execution plan that maximizes parallelism while ensuring * correct execution order. * * Key responsibilities: * 1. **Dependency Analysis**: Tracks what fields each step depends on and produces * 2. **Parallel Grouping**: Groups independent steps that can run simultaneously * 3. **Execution Optimization**: Creates optimized execution functions that * run parallel groups concurrently * 4. **Signature Inference**: Provides data for automatic signature generation * * The planner works by building a directed acyclic graph (DAG) of dependencies * and then creating execution levels where all steps in a level can run in parallel. */ declare class AxFlowExecutionPlanner { private steps; private parallelGroups; private readonly analyzer; private initialFields; /** * Adds an execution step to the plan for analysis and optimization. * * This method is called for every operation in the flow (execute, map, merge, etc.) * and performs dependency analysis to understand what the step needs and produces. * This information is crucial for building the parallel execution plan. * * The method handles different types of steps: * - **Execute steps**: LLM node operations that depend on specific state fields * - **Map steps**: Transformations that modify the state object * - **Merge steps**: Operations that combine results from branches or parallel operations * - **Other steps**: Generic operations that don't fit other categories * * @param stepFunction - The actual function to execute for this step * @param nodeName - Name of the node (for execute steps) * @param mapping - Function that maps state to node inputs (for execute steps) * @param stepType - Type of step for specialized analysis * @param mapTransform - Transformation function (for map steps) * @param mergeOptions - Options for merge operations (result key, merge function) */ addExecutionStep(stepFunction: AxFlowStepFunction, nodeName?: string, mapping?: (state: any) => any, stepType?: 'execute' | 'map' | 'merge' | 'parallel-map' | 'parallel' | 'derive', mapTransform?: (state: any) => any, mergeOptions?: { resultKey?: string; mergeFunction?: (...args: any[]) => any; }, deriveOptions?: { inputFieldName: string; outputFieldName: string; batchSize?: number; }): void; /** * Analyzes a step function to determine what fields it produces. * * This method analyzes the step function to understand what new fields * it adds to the state. It uses a mock state approach: * 1. Creates a mock state with sample data * 2. Runs the step function on the mock state * 3. Compares the result to see what fields were added * * @param stepFunction - The step function to analyze * @returns Array of field names that the step function produces */ private analyzeStepFunctionProduction; /** * Analyzes step function source code to determine what fields it produces. * * @param stepFunction - The step function to analyze * @returns Array of field names that the step function produces */ private analyzeStepFunctionSource; /** * Analyzes a map transformation function to determine what fields it produces. * * This is a challenging problem because map transformations can produce arbitrary * new fields based on complex logic. The method uses a mock state approach: * 1. Creates a mock state with sample data * 2. Runs the transformation on the mock state * 3. Analyzes the result to see what fields were produced * * This approach works for most common transformation patterns but may miss * edge cases where the transformation behavior depends on specific data values. * * @param mapTransform - The map transformation function to analyze * @returns Array of field names that the transformation produces */ private analyzeMapTransformation; /** * Creates a mock state with sample data for transformation analysis. * * This method builds a representative state object that includes: * - Initial fields from the flow input * - Result fields from previous steps with realistic structure * - Sample data that allows transformations to execute * * The mock state is used to run map transformations in a controlled * environment to determine what fields they produce. * * @returns Mock state object with sample data */ private createMockState; /** * Creates appropriate mock values based on field names and patterns. */ private createMockValue; /** * Analyzes what fields are produced by conditional merge operations. * * Conditional merges are complex because they don't transform data like map operations, * but instead select which branch's results to use based on a condition. * The challenge is determining what fields will be available after the merge * without knowing which branch will be taken at runtime. * * This method uses heuristics to determine the likely output fields: * 1. Look at recent execute steps (likely branch operations) * 2. If found, use their output fields as potential merge results * 3. Fallback to all execute step fields if no recent pattern is found * * The analysis assumes that branches in a conditional merge will produce * similar types of fields, so we can use any branch's fields as representative * of what the merge might produce. * * @returns string[] - Array of field names that the merge operation might produce */ private analyzeBranchMergeFields; /** * Sets the initial fields and triggers parallel group rebuilding. * * This method is called once the flow knows what input fields are available. * It triggers the parallel group analysis which determines the optimal * execution strategy for the entire flow. * * @param fields - Array of field names available at the start of execution */ setInitialFields(fields: string[]): void; /** * Rebuilds the parallel execution groups based on step dependencies. * * This is the core algorithm that creates the parallel execution plan. * It uses a level-by-level approach: * * 1. **Level 0**: Steps with no dependencies (can run immediately) * 2. **Level 1**: Steps that depend only on Level 0 outputs * 3. **Level N**: Steps that depend on outputs from previous levels * * Steps within the same level can run in parallel because they don't * depend on each other's outputs. * * The algorithm ensures: * - Correct execution order (dependencies are satisfied) * - Maximum parallelism (independent steps run simultaneously) * - Deadlock prevention (circular dependencies are detected) * * Time complexity: O(n²) where n is the number of steps * Space complexity: O(n) for tracking processed steps and available fields */ private rebuildParallelGroups; /** * Gets all fields produced by previous steps. * * This is used by steps that depend on "everything produced so far" * such as map transformations and merge operations. * * @returns Array of all field names produced by previous steps */ private getAllProducedFields; /** * Creates optimized execution functions that implement the parallel execution plan. * * This method converts the parallel groups into actual executable functions. * It creates a series of steps where: * - Single-step groups execute directly * - Multi-step groups execute in parallel with batch size control * - Results are properly merged to maintain state consistency * * The optimized execution can significantly improve performance for flows * with independent operations, especially I/O-bound operations like LLM calls. * * Performance benefits: * - Reduces total execution time for independent operations * - Maximizes CPU and I/O utilization * - Maintains correctness through dependency management * - Controls resource usage through batch size limiting * * @param batchSize - Maximum number of concurrent operations (optional) * @returns Array of optimized step functions ready for execution */ createOptimizedExecution(batchSize?: number): AxFlowStepFunction[]; /** * Gets optimized execution steps for the flow. * * This method provides the optimized execution steps that can be used * to execute the flow with maximum parallelism while maintaining * dependency order. * * @returns Array of optimized step functions ready for execution */ getOptimizedExecutionSteps(): AxFlowStepFunction[]; /** * Gets detailed execution plan information for debugging and analysis. * * This method provides comprehensive information about the execution plan, * including step counts, parallel grouping details, and the complete * dependency structure. It's particularly useful for: * - Debugging execution flow issues * - Performance analysis and optimization * - Understanding parallelization effectiveness * - Monitoring execution plan complexity * * @returns Object containing detailed execution plan metrics and data */ getExecutionPlan(): { totalSteps: number; parallelGroups: number; maxParallelism: number; steps: AxFlowExecutionStep[]; groups: AxFlowParallelGroup[]; }; } /** Flow-aware GEPA (system-level reflective evolution with module selection + system-aware merge) */ declare class AxGEPAFlow extends AxBaseOptimizer { private numTrials; private minibatch; private minibatchSize; private earlyStoppingTrials; private minImprovementThreshold; private sampleCount; private crossoverEvery; private tieEpsilon; private paretoSetSize; private mergeMax; private mergesUsed; private mergesDue; private totalMergesTested; private lastIterFoundNewProgram; private rngState; private mergeAttemptKeys; private mergeCompositionKeys; private samplerState; constructor(args: Readonly); reset(): void; configureAuto(level: 'light' | 'medium' | 'heavy'): void; /** * Multi-objective GEPA-Flow: system-level reflective evolution with Pareto frontier */ compile(program: Readonly, examples: readonly AxTypedExample[], metricFn: AxMetricFn, options?: AxCompileOptions): Promise>; private getBaseInstruction; private evaluateOnSet; private evaluateAvg; private evaluateOne; private reflectModuleInstruction; private updateSamplerShuffled; private nextMinibatchIndices; private systemAwareMergeWithSig; private rand; private systemAwareMerge; } /** Single-module GEPA (reflective prompt evolution with Pareto sampling) */ declare class AxGEPA extends AxBaseOptimizer { private numTrials; private minibatch; private minibatchSize; private earlyStoppingTrials; private minImprovementThreshold; private sampleCount; private paretoSetSize; private crossoverEvery; private tieEpsilon; private feedbackMemorySize; private feedbackMemory; private mergeMax; private mergesUsed; private mergesDue; private totalMergesTested; private lastIterFoundNewProgram; private mergeAttemptKeys; private mergeCompositionKeys; private rngState; private samplerState; private localScoreHistory; private localConfigurationHistory; constructor(args: Readonly); reset(): void; /** * Multi-objective GEPA: reflective evolution with Pareto frontier */ compile(program: Readonly>, examples: readonly AxTypedExample[], metricFn: AxMetricFn, options?: AxCompileOptions): Promise>; /** Lightweight auto presets */ configureAuto(level: 'light' | 'medium' | 'heavy'): void; private getBaseInstruction; private evaluateOnSet; private evaluateAvg; private evaluateOne; private reflectInstruction; private updateSamplerShuffled; private nextMinibatchIndices; private rand; private generateOptimizationReport; private mergeInstructions; } type AxInstanceRegistryItem, IN, OUT> = T & AxUsable; declare class AxInstanceRegistry, IN, OUT> { private reg; constructor(); register(instance: AxInstanceRegistryItem): void; [Symbol.iterator](): Generator, void, unknown>; } interface AxMCPTransport { /** * Sends a JSON-RPC request or notification and returns the response * @param message The JSON-RPC request or notification to send * @returns A Promise that resolves to the JSON-RPC response */ send(message: Readonly>): Promise>; /** * Sends a JSON-RPC notification * @param message The JSON-RPC notification to send */ sendNotification(message: Readonly): Promise; /** * Connects to the transport if needed * This method is optional and only required for transports that need connection setup */ connect?(): Promise; } /** * Configuration for overriding function properties */ interface FunctionOverride { /** Original function name to override */ name: string; /** Updates to apply to the function */ updates: { /** Alternative name for the function */ name?: string; /** Alternative description for the function */ description?: string; }; } /** * Options for the MCP client */ interface AxMCPClientOptions { /** Enable debug logging */ debug?: boolean; /** Logger function for debug output */ logger?: AxLoggerFunction; /** * List of function overrides * Use this to provide alternative names and descriptions for functions * while preserving their original functionality * * Example: * ``` * functionOverrides: [ * { * name: "original-function-name", * updates: { * name: "new-function-name", * description: "New function description" * } * } * ] * ``` */ functionOverrides?: FunctionOverride[]; } declare class AxMCPClient { private readonly transport; private readonly options; private functions; private activeRequests; private capabilities; private logger; constructor(transport: AxMCPTransport, options?: Readonly); init(): Promise; private discoverFunctions; ping(timeout?: number): Promise; toFunction(): AxFunction[]; cancelRequest(id: string): void; private sendRequest; private sendNotification; } type TokenSet = { accessToken: string; refreshToken?: string; expiresAt?: number; issuer?: string; }; interface AxMCPOAuthOptions { clientId?: string; clientSecret?: string; redirectUri?: string; scopes?: string[]; selectAuthorizationServer?: (issuers: string[], resourceMetadata: unknown) => Promise | string; onAuthCode?: (authorizationUrl: string) => Promise<{ code: string; redirectUri?: string; }>; tokenStore?: { getToken: (key: string) => Promise | TokenSet | null; setToken: (key: string, token: TokenSet) => Promise | void; clearToken?: (key: string) => Promise | void; }; } interface AxMCPStreamableHTTPTransportOptions { headers?: Record; authorization?: string; oauth?: AxMCPOAuthOptions; } declare class AxMCPHTTPSSETransport implements AxMCPTransport { private endpoint; private sseUrl; private eventSource?; private customHeaders; private oauthHelper; private currentToken?; private currentIssuer?; private sseAbort?; private pendingRequests; private messageHandler?; private endpointReady?; constructor(sseUrl: string, options?: AxMCPStreamableHTTPTransportOptions); private buildHeaders; private openSSEWithFetch; private createEndpointReady; private consumeSSEStream; connect(): Promise; send(message: Readonly>): Promise>; sendNotification(message: Readonly): Promise; close(): void; } declare class AxMCPStreambleHTTPTransport implements AxMCPTransport { private mcpEndpoint; private sessionId?; private eventSource?; private pendingRequests; private messageHandler?; private customHeaders; private oauthHelper; private currentToken?; private currentIssuer?; constructor(mcpEndpoint: string, options?: AxMCPStreamableHTTPTransportOptions); setHeaders(headers: Record): void; setAuthorization(authorization: string): void; getHeaders(): Record; private buildHeaders; setMessageHandler(handler: (message: AxMCPJSONRPCRequest | AxMCPJSONRPCNotification) => void): void; connect(): Promise; openListeningStream(): Promise; private openListeningStreamWithFetch; send(message: Readonly>): Promise>; private handleSSEResponse; sendNotification(message: Readonly): Promise; terminateSession(): Promise; close(): void; } type AxAIServiceListItem = { key: TModelKey; service: AxAIService; description: string; isInternal?: boolean; }; type ExtractServiceModelKeys = T extends AxAIService ? K : T extends AxAIServiceListItem ? K : never; type ExtractAllModelKeys = T extends readonly [ infer First, ...infer Rest ] ? ExtractServiceModelKeys | ExtractAllModelKeys : never; declare class AxMultiServiceRouter)[] = readonly AxAIService[], TModelKey = ExtractAllModelKeys> implements AxAIService { private options?; private lastUsedService?; private services; /** * Constructs a new multi-service router. * It validates that each service provides a unique set of model keys, * then builds a lookup (map) for routing the chat/embed requests. */ constructor(services: TServices); /** * Static factory method for type-safe multi-service router creation with automatic model key inference. */ static create)[]>(services: TServices): AxMultiServiceRouter>; getLastUsedChatModel(): unknown | undefined; getLastUsedEmbedModel(): unknown | undefined; getLastUsedModelConfig(): AxModelConfig | undefined; /** * Delegates the chat call to the service matching the provided model key. */ chat(req: Readonly>, options?: Readonly): Promise>; /** * Delegates the embed call to the service matching the provided embed model key. */ embed(req: Readonly>, options?: Readonly): Promise; /** * Returns a composite ID built from the IDs of the underlying services. */ getId(): string; /** * Returns the name of this router. */ getName(): string; /** * Aggregates all available models across the underlying services. */ getModelList(): AxAIModelList; /** * If a model key is provided, delegate to the corresponding service's features. * Otherwise, returns a default feature set. */ getFeatures(model?: TModelKey): AxAIFeatures; /** * Returns aggregated metrics from the underlying service. * Uses the metrics from the last service that was used, * or falls back to the first service if none has been used. */ getMetrics(): AxAIServiceMetrics; /** * Sets options on all underlying services. */ setOptions(options: Readonly): void; /** * Returns the options from the last used service, * or falls back to the first service if none has been used. */ getOptions(): Readonly; /** * Returns the logger from the last used service, * or falls back to the first service if none has been used. */ getLogger(): AxLoggerFunction; /** * Sets a service entry for a given key. This method is intended for testing purposes. * @param key - The model key * @param entry - The service entry to set */ setServiceEntry(key: TModelKey, entry: { isInternal?: boolean; description: string; model?: string; embedModel?: string; service: AxAIService; }): void; } declare const AxStringUtil: { trimNonAlphaNum: (str: string) => string; splitIntoTwo: (str: string, separator: Readonly) => string[]; dedup: (seq: readonly string[]) => string[]; extractIdAndText: (input: string) => { id: number; text: string; }; extractIndexPrefixedText: (input: string) => string; batchArray: (arr: readonly T[], size: number) => T[][]; }; declare const axModelInfoAnthropic: AxModelInfo[]; declare const axModelInfoCohere: AxModelInfo[]; declare const axModelInfoDeepSeek: AxModelInfo[]; /** * AxAIGoogleGemini: Model information */ declare const axModelInfoGoogleGemini: AxModelInfo[]; declare const axModelInfoGrok: AxModelInfo[]; /** * AxAIGroq: Model information */ declare const axModelInfoGroq: AxModelInfo[]; /** * HuggingFace: Model information */ declare const axModelInfoHuggingFace: AxModelInfo[]; declare const axModelInfoMistral: AxModelInfo[]; /** * OpenAI: Model information */ declare const axModelInfoReka: AxModelInfo[]; declare const axModelInfoTogether: AxModelInfo[]; /** * WebLLM model information * Note: WebLLM runs models locally in the browser, so there are no API costs * However, we include context window and capability information */ declare const axModelInfoWebLLM: AxModelInfo[]; /** * Advanced Multi-hop RAG with iterative query refinement, context accumulation, * parallel sub-queries, and self-healing quality feedback loops * * @param queryFn - Function to execute search queries and return results * @param options - Configuration options * @returns AxFlow instance with advanced RAG capability */ declare const axRAG: (queryFn: (query: string) => Promise, options?: { maxHops?: number; qualityThreshold?: number; maxIterations?: number; qualityTarget?: number; disableQualityHealing?: boolean; logger?: AxFlowLoggerFunction; debug?: boolean; }) => AxFlow<{ originalQuestion: string; }, { finalAnswer: string; totalHops: number; retrievedContexts: string[]; iterationCount: number; healingAttempts: number; qualityAchieved: number; }, { queryGenerator: InferAxGen<"originalQuestion:string, previousContext?:string -> searchQuery:string, queryReasoning:string">; } & { contextualizer: InferAxGen<"retrievedDocument:string, accumulatedContext?:string -> enhancedContext:string">; } & { qualityAssessor: InferAxGen<"currentContext:string, originalQuestion:string -> completenessScore:number, missingAspects:string[]">; } & { questionDecomposer: InferAxGen<"complexQuestion:string -> subQuestions:string[], decompositionReason:string">; } & { evidenceSynthesizer: InferAxGen<"collectedEvidence:string[], originalQuestion:string -> synthesizedEvidence:string, evidenceGaps:string[]">; } & { gapAnalyzer: InferAxGen<"synthesizedEvidence:string, evidenceGaps:string[], originalQuestion:string -> needsMoreInfo:boolean, focusedQueries:string[]">; } & { answerGenerator: InferAxGen<"finalContext:string, originalQuestion:string -> comprehensiveAnswer:string, confidenceLevel:number">; } & { queryRefiner: InferAxGen<"originalQuestion:string, currentContext:string, missingAspects:string[] -> refinedQuery:string">; } & { qualityValidator: InferAxGen<"generatedAnswer:string, userQuery:string -> qualityScore:number, issues:string[]">; } & { answerHealer: InferAxGen<"originalAnswer:string, healingDocument:string, issues?:string[] -> healedAnswer:string">; }, { currentAnswer: string; currentQuality: number; currentIssues: string[]; shouldContinueHealing: boolean; healingResult: { healingDocument: string; }; healingAttempts: number; allEvidence: string[]; evidenceSources: string[]; needsMoreInfo: boolean; synthesizedEvidence: string; retrievalResults: string[]; currentQueries: string[]; iteration: number; searchQuery: string; accumulatedContext: string; retrievedContexts: string[]; completenessScore: number; shouldContinue: boolean; retrievalResult: { retrievedDocument: string; retrievalConfidence: number; }; currentHop: number; maxHops: number; qualityThreshold: number; maxIterations: number; qualityTarget: number; disableQualityHealing: boolean; originalQuestion: string; queryGeneratorResult: BuildObject<[{ name: "searchQuery"; optional: false; internal: false; } & { type: "string"; }, { name: "queryReasoning"; optional: false; internal: false; } & { type: "string"; }]>; contextualizerResult: BuildObject<[{ name: "enhancedContext"; optional: false; internal: false; } & { type: "string"; }]>; qualityAssessorResult: BuildObject<[{ name: "completenessScore"; optional: false; internal: false; } & { type: "number"; }, { name: "missingAspects"; optional: false; internal: false; } & { type: "string[]"; }]>; queryRefinerResult: BuildObject<[{ name: "refinedQuery"; optional: false; internal: false; } & { type: "string"; }]>; questionDecomposerResult: BuildObject<[{ name: "subQuestions"; optional: false; internal: false; } & { type: "string[]"; }, { name: "decompositionReason"; optional: false; internal: false; } & { type: "string"; }]>; evidenceSynthesizerResult: BuildObject<[{ name: "synthesizedEvidence"; optional: false; internal: false; } & { type: "string"; }, { name: "evidenceGaps"; optional: false; internal: false; } & { type: "string[]"; }]>; gapAnalyzerResult: BuildObject<[{ name: "needsMoreInfo"; optional: false; internal: false; } & { type: "boolean"; }, { name: "focusedQueries"; optional: false; internal: false; } & { type: "string[]"; }]>; answerGeneratorResult: BuildObject<[{ name: "comprehensiveAnswer"; optional: false; internal: false; } & { type: "string"; }, { name: "confidenceLevel"; optional: false; internal: false; } & { type: "number"; }]>; qualityValidatorResult: BuildObject<[{ name: "qualityScore"; optional: false; internal: false; } & { type: "number"; }, { name: "issues"; optional: false; internal: false; } & { type: "string[]"; }]>; answerHealerResult: BuildObject<[{ name: "healedAnswer"; optional: false; internal: false; } & { type: "string"; }]>; }>; interface AxAIMetricsInstruments { latencyHistogram?: Histogram; errorCounter?: Counter; requestCounter?: Counter; tokenCounter?: Counter; inputTokenCounter?: Counter; outputTokenCounter?: Counter; errorRateGauge?: Gauge; meanLatencyGauge?: Gauge; p95LatencyGauge?: Gauge; p99LatencyGauge?: Gauge; streamingRequestsCounter?: Counter; functionCallsCounter?: Counter; functionCallLatencyHistogram?: Histogram; requestSizeHistogram?: Histogram; responseSizeHistogram?: Histogram; temperatureGauge?: Gauge; maxTokensGauge?: Gauge; estimatedCostCounter?: Counter; promptLengthHistogram?: Histogram; contextWindowUsageGauge?: Gauge; timeoutsCounter?: Counter; abortsCounter?: Counter; thinkingBudgetUsageCounter?: Counter; multimodalRequestsCounter?: Counter; } interface AxSamplePickerOptions { resultPicker?: AxResultPickerFunction; } export { AxACE, type AxACEBullet, type AxACECuratorOperation, type AxACECuratorOperationType, type AxACECuratorOutput, type AxACEFeedbackEvent, type AxACEGeneratorOutput, type AxACEOptimizationArtifact, AxACEOptimizedProgram, type AxACEOptions, type AxACEPlaybook, type AxACEReflectionOutput, type AxACEResult, AxAI, AxAIAnthropic, type AxAIAnthropicArgs, type AxAIAnthropicChatError, type AxAIAnthropicChatRequest, type AxAIAnthropicChatRequestCacheParam, type AxAIAnthropicChatResponse, type AxAIAnthropicChatResponseDelta, type AxAIAnthropicConfig, type AxAIAnthropicContentBlockDeltaEvent, type AxAIAnthropicContentBlockStartEvent, type AxAIAnthropicContentBlockStopEvent, type AxAIAnthropicErrorEvent, type AxAIAnthropicFunctionTool, type AxAIAnthropicMessageDeltaEvent, type AxAIAnthropicMessageStartEvent, type AxAIAnthropicMessageStopEvent, AxAIAnthropicModel, type AxAIAnthropicPingEvent, type AxAIAnthropicRequestTool, type AxAIAnthropicThinkingConfig, type AxAIAnthropicThinkingTokenBudgetLevels, AxAIAnthropicVertexModel, type AxAIAnthropicWebSearchTool, type AxAIArgs, AxAIAzureOpenAI, type AxAIAzureOpenAIArgs, type AxAIAzureOpenAIConfig, AxAICohere, type AxAICohereArgs, type AxAICohereChatRequest, type AxAICohereChatRequestToolResults, type AxAICohereChatResponse, type AxAICohereChatResponseDelta, type AxAICohereChatResponseToolCalls, type AxAICohereConfig, AxAICohereEmbedModel, type AxAICohereEmbedRequest, type AxAICohereEmbedResponse, AxAICohereModel, AxAIDeepSeek, type AxAIDeepSeekArgs, AxAIDeepSeekModel, AxAIDreamsRouter, type AxAIDreamsRouterArgs, type AxAIEmbedModels, type AxAIFeatures, AxAIGoogleGemini, type AxAIGoogleGeminiArgs, type AxAIGoogleGeminiBatchEmbedRequest, type AxAIGoogleGeminiBatchEmbedResponse, type AxAIGoogleGeminiChatRequest, type AxAIGoogleGeminiChatResponse, type AxAIGoogleGeminiChatResponseDelta, type AxAIGoogleGeminiConfig, type AxAIGoogleGeminiContent, type AxAIGoogleGeminiContentPart, AxAIGoogleGeminiEmbedModel, AxAIGoogleGeminiEmbedTypes, type AxAIGoogleGeminiGenerationConfig, AxAIGoogleGeminiModel, type AxAIGoogleGeminiOptionsTools, type AxAIGoogleGeminiRetrievalConfig, AxAIGoogleGeminiSafetyCategory, type AxAIGoogleGeminiSafetySettings, AxAIGoogleGeminiSafetyThreshold, type AxAIGoogleGeminiThinkingConfig, type AxAIGoogleGeminiThinkingTokenBudgetLevels, type AxAIGoogleGeminiTool, type AxAIGoogleGeminiToolConfig, type AxAIGoogleGeminiToolFunctionDeclaration, type AxAIGoogleGeminiToolGoogleMaps, type AxAIGoogleGeminiToolGoogleSearchRetrieval, type AxAIGoogleVertexBatchEmbedRequest, type AxAIGoogleVertexBatchEmbedResponse, AxAIGrok, type AxAIGrokArgs, type AxAIGrokChatRequest, AxAIGrokEmbedModels, AxAIGrokModel, type AxAIGrokOptionsTools, type AxAIGrokSearchSource, AxAIGroq, type AxAIGroqArgs, AxAIGroqModel, AxAIHuggingFace, type AxAIHuggingFaceArgs, type AxAIHuggingFaceConfig, AxAIHuggingFaceModel, type AxAIHuggingFaceRequest, type AxAIHuggingFaceResponse, type AxAIInputModelList, type AxAIMemory, type AxAIMetricsInstruments, AxAIMistral, type AxAIMistralArgs, type AxAIMistralChatRequest, AxAIMistralEmbedModels, AxAIMistralModel, type AxAIModelList, type AxAIModelListBase, type AxAIModels, AxAIOllama, type AxAIOllamaAIConfig, type AxAIOllamaArgs, AxAIOpenAI, type AxAIOpenAIAnnotation, type AxAIOpenAIArgs, AxAIOpenAIBase, type AxAIOpenAIBaseArgs, type AxAIOpenAIChatRequest, type AxAIOpenAIChatResponse, type AxAIOpenAIChatResponseDelta, type AxAIOpenAIConfig, AxAIOpenAIEmbedModel, type AxAIOpenAIEmbedRequest, type AxAIOpenAIEmbedResponse, type AxAIOpenAILogprob, AxAIOpenAIModel, type AxAIOpenAIResponseDelta, AxAIOpenAIResponses, type AxAIOpenAIResponsesArgs, AxAIOpenAIResponsesBase, type AxAIOpenAIResponsesCodeInterpreterToolCall, type AxAIOpenAIResponsesComputerToolCall, type AxAIOpenAIResponsesConfig, type AxAIOpenAIResponsesContentPartAddedEvent, type AxAIOpenAIResponsesContentPartDoneEvent, type AxAIOpenAIResponsesDefineFunctionTool, type AxAIOpenAIResponsesErrorEvent, type AxAIOpenAIResponsesFileSearchCallCompletedEvent, type AxAIOpenAIResponsesFileSearchCallInProgressEvent, type AxAIOpenAIResponsesFileSearchCallSearchingEvent, type AxAIOpenAIResponsesFileSearchToolCall, type AxAIOpenAIResponsesFunctionCallArgumentsDeltaEvent, type AxAIOpenAIResponsesFunctionCallArgumentsDoneEvent, type AxAIOpenAIResponsesFunctionCallItem, type AxAIOpenAIResponsesImageGenerationCallCompletedEvent, type AxAIOpenAIResponsesImageGenerationCallGeneratingEvent, type AxAIOpenAIResponsesImageGenerationCallInProgressEvent, type AxAIOpenAIResponsesImageGenerationCallPartialImageEvent, type AxAIOpenAIResponsesImageGenerationToolCall, AxAIOpenAIResponsesImpl, type AxAIOpenAIResponsesInputAudioContentPart, type AxAIOpenAIResponsesInputContentPart, type AxAIOpenAIResponsesInputFunctionCallItem, type AxAIOpenAIResponsesInputFunctionCallOutputItem, type AxAIOpenAIResponsesInputImageUrlContentPart, type AxAIOpenAIResponsesInputItem, type AxAIOpenAIResponsesInputMessageItem, type AxAIOpenAIResponsesInputTextContentPart, type AxAIOpenAIResponsesLocalShellToolCall, type AxAIOpenAIResponsesMCPCallArgumentsDeltaEvent, type AxAIOpenAIResponsesMCPCallArgumentsDoneEvent, type AxAIOpenAIResponsesMCPCallCompletedEvent, type AxAIOpenAIResponsesMCPCallFailedEvent, type AxAIOpenAIResponsesMCPCallInProgressEvent, type AxAIOpenAIResponsesMCPListToolsCompletedEvent, type AxAIOpenAIResponsesMCPListToolsFailedEvent, type AxAIOpenAIResponsesMCPListToolsInProgressEvent, type AxAIOpenAIResponsesMCPToolCall, AxAIOpenAIResponsesModel, type AxAIOpenAIResponsesOutputItem, type AxAIOpenAIResponsesOutputItemAddedEvent, type AxAIOpenAIResponsesOutputItemDoneEvent, type AxAIOpenAIResponsesOutputMessageItem, type AxAIOpenAIResponsesOutputRefusalContentPart, type AxAIOpenAIResponsesOutputTextAnnotationAddedEvent, type AxAIOpenAIResponsesOutputTextContentPart, type AxAIOpenAIResponsesOutputTextDeltaEvent, type AxAIOpenAIResponsesOutputTextDoneEvent, type AxAIOpenAIResponsesReasoningDeltaEvent, type AxAIOpenAIResponsesReasoningDoneEvent, type AxAIOpenAIResponsesReasoningItem, type AxAIOpenAIResponsesReasoningSummaryDeltaEvent, type AxAIOpenAIResponsesReasoningSummaryDoneEvent, type AxAIOpenAIResponsesReasoningSummaryPart, type AxAIOpenAIResponsesReasoningSummaryPartAddedEvent, type AxAIOpenAIResponsesReasoningSummaryPartDoneEvent, type AxAIOpenAIResponsesReasoningSummaryTextDeltaEvent, type AxAIOpenAIResponsesReasoningSummaryTextDoneEvent, type AxAIOpenAIResponsesRefusalDeltaEvent, type AxAIOpenAIResponsesRefusalDoneEvent, type AxAIOpenAIResponsesRequest, type AxAIOpenAIResponsesResponse, type AxAIOpenAIResponsesResponseCompletedEvent, type AxAIOpenAIResponsesResponseCreatedEvent, type AxAIOpenAIResponsesResponseDelta, type AxAIOpenAIResponsesResponseFailedEvent, type AxAIOpenAIResponsesResponseInProgressEvent, type AxAIOpenAIResponsesResponseIncompleteEvent, type AxAIOpenAIResponsesResponseQueuedEvent, type AxAIOpenAIResponsesStreamEvent, type AxAIOpenAIResponsesStreamEventBase, type AxAIOpenAIResponsesToolCall, type AxAIOpenAIResponsesToolCallBase, type AxAIOpenAIResponsesToolChoice, type AxAIOpenAIResponsesToolDefinition, type AxAIOpenAIResponsesWebSearchCallCompletedEvent, type AxAIOpenAIResponsesWebSearchCallInProgressEvent, type AxAIOpenAIResponsesWebSearchCallSearchingEvent, type AxAIOpenAIResponsesWebSearchToolCall, type AxAIOpenAIUrlCitation, type AxAIOpenAIUsage, AxAIOpenRouter, type AxAIOpenRouterArgs, AxAIRefusalError, AxAIReka, type AxAIRekaArgs, type AxAIRekaChatRequest, type AxAIRekaChatResponse, type AxAIRekaChatResponseDelta, type AxAIRekaConfig, AxAIRekaModel, type AxAIRekaUsage, type AxAIService, AxAIServiceAbortedError, type AxAIServiceActionOptions, AxAIServiceAuthenticationError, AxAIServiceError, type AxAIServiceImpl, type AxAIServiceMetrics, type AxAIServiceModelType, AxAIServiceNetworkError, type AxAIServiceOptions, AxAIServiceResponseError, AxAIServiceStatusError, AxAIServiceStreamTerminatedError, AxAIServiceTimeoutError, AxAITogether, type AxAITogetherArgs, AxAIWebLLM, type AxAIWebLLMArgs, type AxAIWebLLMChatRequest, type AxAIWebLLMChatResponse, type AxAIWebLLMChatResponseDelta, type AxAIWebLLMConfig, type AxAIWebLLMEmbedModel, type AxAIWebLLMEmbedRequest, type AxAIWebLLMEmbedResponse, AxAIWebLLMModel, type AxAPI, type AxAPIConfig, AxAgent, type AxAgentConfig, type AxAgentFeatures, type AxAgentOptions, type AxAgentic, AxApacheTika, type AxApacheTikaArgs, type AxApacheTikaConvertOptions, type AxAssertion, AxAssertionError, AxBalancer, type AxBalancerOptions, AxBaseAI, type AxBaseAIArgs, AxBaseOptimizer, AxBootstrapFewShot, type AxBootstrapOptimizerOptions, type AxChatRequest, type AxChatResponse, type AxChatResponseFunctionCall, type AxChatResponseResult, type AxCheckpointLoadFn, type AxCheckpointSaveFn, type AxCitation, type AxCompileOptions, AxContentProcessingError, type AxContentProcessingServices, type AxCostTracker, type AxCostTrackerOptions, AxDB, type AxDBArgs, AxDBBase, type AxDBBaseArgs, type AxDBBaseOpOptions, AxDBCloudflare, type AxDBCloudflareArgs, type AxDBCloudflareOpOptions, type AxDBLoaderOptions, AxDBManager, type AxDBManagerArgs, type AxDBMatch, AxDBMemory, type AxDBMemoryArgs, type AxDBMemoryOpOptions, AxDBPinecone, type AxDBPineconeArgs, type AxDBPineconeOpOptions, type AxDBQueryRequest, type AxDBQueryResponse, type AxDBQueryService, type AxDBService, type AxDBState, type AxDBUpsertRequest, type AxDBUpsertResponse, AxDBWeaviate, type AxDBWeaviateArgs, type AxDBWeaviateOpOptions, type AxDataRow, AxDefaultCostTracker, AxDefaultResultReranker, type AxDockerContainer, AxDockerSession, type AxEmbedRequest, type AxEmbedResponse, AxEmbeddingAdapter, type AxErrorCategory, AxEvalUtil, type AxEvaluateArgs, type AxExample, type AxExamples, type AxField, type AxFieldProcessor, type AxFieldProcessorProcess, type AxFieldTemplateFn, type AxFieldType, type AxFieldValue, AxFlow, type AxFlowAutoParallelConfig, type AxFlowBranchContext, type AxFlowBranchEvaluationData, type AxFlowCompleteData, AxFlowDependencyAnalyzer, type AxFlowDynamicContext, type AxFlowErrorData, AxFlowExecutionPlanner, type AxFlowExecutionStep, type AxFlowLogData, type AxFlowLoggerData, type AxFlowLoggerFunction, type AxFlowNodeDefinition, type AxFlowParallelBranch, type AxFlowParallelGroup, type AxFlowParallelGroupCompleteData, type AxFlowParallelGroupStartData, type AxFlowStartData, type AxFlowState, type AxFlowStepCompleteData, type AxFlowStepFunction, type AxFlowStepStartData, type AxFlowSubContext, AxFlowSubContextImpl, type AxFlowTypedParallelBranch, type AxFlowTypedSubContext, AxFlowTypedSubContextImpl, type AxFlowable, type AxFluentFieldInfo, AxFluentFieldType, type AxForwardable, type AxFunction, AxFunctionError, type AxFunctionHandler, type AxFunctionJSONSchema, AxFunctionProcessor, type AxFunctionResult, type AxFunctionResultFormatter, AxGEPA, type AxGEPAAdapter, type AxGEPAEvaluationBatch, AxGEPAFlow, AxGen, type AxGenDeltaOut, type AxGenIn, type AxGenInput, type AxGenMetricsInstruments, type AxGenOut, type AxGenOutput, type AxGenStreamingOut, AxGenerateError, type AxGenerateErrorDetails, type AxGenerateResult, AxHFDataLoader, type AxIField, type AxInputFunctionType, AxInstanceRegistry, type AxInternalChatRequest, type AxInternalEmbedRequest, AxLLMRequestTypeValues, type AxLoggerData, type AxLoggerFunction, AxMCPClient, type AxMCPFunctionDescription, AxMCPHTTPSSETransport, type AxMCPInitializeParams, type AxMCPInitializeResult, type AxMCPJSONRPCErrorResponse, type AxMCPJSONRPCNotification, type AxMCPJSONRPCRequest, type AxMCPJSONRPCResponse, type AxMCPJSONRPCSuccessResponse, type AxMCPOAuthOptions, type AxMCPStreamableHTTPTransportOptions, AxMCPStreambleHTTPTransport, type AxMCPToolsListResult, type AxMCPTransport, AxMediaNotSupportedError, AxMemory, type AxMemoryData, type AxMessage, type AxMetricFn, type AxMetricFnArgs, type AxMetricsConfig, AxMiPRO, type AxMiPROOptimizerOptions, type AxMiPROResult, AxMockAIService, type AxMockAIServiceConfig, type AxModelConfig, type AxModelInfo, type AxModelInfoWithProvider, type AxModelUsage, type AxMultiMetricFn, type AxMultiProviderConfig, AxMultiServiceRouter, type AxOptimizationCheckpoint, type AxOptimizationProgress, type AxOptimizationStats, type AxOptimizedProgram, AxOptimizedProgramImpl, type AxOptimizer, type AxOptimizerArgs, type AxOptimizerLoggerData, type AxOptimizerLoggerFunction, type AxOptimizerMetricsConfig, type AxOptimizerMetricsInstruments, type AxOptimizerResult, type AxParetoResult, AxProgram, type AxProgramDemos, type AxProgramExamples, type AxProgramForwardOptions, type AxProgramForwardOptionsWithModels, type AxProgramOptions, type AxProgramStreamingForwardOptions, type AxProgramStreamingForwardOptionsWithModels, type AxProgramTrace, type AxProgramUsage, type AxProgrammable, AxPromptTemplate, type AxPromptTemplateOptions, AxProviderRouter, type AxRateLimiterFunction, AxRateLimiterTokenUsage, type AxRateLimiterTokenUsageOptions, type AxRerankerIn, type AxRerankerOut, type AxResponseHandlerArgs, type AxResultPickerFunction, type AxResultPickerFunctionFieldResults, type AxResultPickerFunctionFunctionResults, type AxRewriteIn, type AxRewriteOut, type AxRoutingResult, type AxSamplePickerOptions, type AxSetExamplesOptions, AxSignature, AxSignatureBuilder, type AxSignatureConfig, AxSimpleClassifier, AxSimpleClassifierClass, type AxSimpleClassifierForwardOptions, AxSpanKindValues, AxStopFunctionCallException, type AxStreamingAssertion, type AxStreamingEvent, type AxStreamingFieldProcessorProcess, AxStringUtil, AxTestPrompt, type AxTokenUsage, type AxTunable, type AxTypedExample, type AxUsable, agent, ai, ax, axAIAnthropicDefaultConfig, axAIAnthropicVertexDefaultConfig, axAIAzureOpenAIBestConfig, axAIAzureOpenAICreativeConfig, axAIAzureOpenAIDefaultConfig, axAIAzureOpenAIFastConfig, axAICohereCreativeConfig, axAICohereDefaultConfig, axAIDeepSeekCodeConfig, axAIDeepSeekDefaultConfig, axAIDreamsRouterDefaultConfig, axAIGoogleGeminiDefaultConfig, axAIGoogleGeminiDefaultCreativeConfig, axAIGrokBestConfig, axAIGrokDefaultConfig, axAIHuggingFaceCreativeConfig, axAIHuggingFaceDefaultConfig, axAIMistralBestConfig, axAIMistralDefaultConfig, axAIOllamaDefaultConfig, axAIOllamaDefaultCreativeConfig, axAIOpenAIBestConfig, axAIOpenAICreativeConfig, axAIOpenAIDefaultConfig, axAIOpenAIFastConfig, axAIOpenAIResponsesBestConfig, axAIOpenAIResponsesCreativeConfig, axAIOpenAIResponsesDefaultConfig, axAIOpenRouterDefaultConfig, axAIRekaBestConfig, axAIRekaCreativeConfig, axAIRekaDefaultConfig, axAIRekaFastConfig, axAITogetherDefaultConfig, axAIWebLLMCreativeConfig, axAIWebLLMDefaultConfig, axAnalyzeChatPromptRequirements, axAnalyzeRequestRequirements, axBaseAIDefaultConfig, axBaseAIDefaultCreativeConfig, axCheckMetricsHealth, axCreateDefaultColorLogger, axCreateDefaultOptimizerColorLogger, axCreateDefaultOptimizerTextLogger, axCreateDefaultTextLogger, axCreateFlowColorLogger, axCreateFlowTextLogger, axDefaultFlowLogger, axDefaultMetricsConfig, axDefaultOptimizerLogger, axDefaultOptimizerMetricsConfig, axGetCompatibilityReport, axGetFormatCompatibility, axGetMetricsConfig, axGetOptimizerMetricsConfig, axGetProvidersWithMediaSupport, axGlobals, axModelInfoAnthropic, axModelInfoCohere, axModelInfoDeepSeek, axModelInfoGoogleGemini, axModelInfoGrok, axModelInfoGroq, axModelInfoHuggingFace, axModelInfoMistral, axModelInfoOpenAI, axModelInfoOpenAIResponses, axModelInfoReka, axModelInfoTogether, axModelInfoWebLLM, axProcessContentForProvider, axRAG, axScoreProvidersForRequest, axSelectOptimalProvider, axSpanAttributes, axSpanEvents, axUpdateMetricsConfig, axUpdateOptimizerMetricsConfig, axValidateChatRequestMessage, axValidateChatResponseResult, axValidateProviderCapabilities, f, flow, s };