UNPKG

@axarai/axar

Version:

TypeScript-based agent framework for building agentic applications powered by LLMs

196 lines (195 loc) 7.59 kB
import { ZodSchema } from 'zod'; import { CoreTool, LanguageModelV1 } from 'ai'; import { StreamResult, ModelConfig } from './types'; /** * Base class for creating AI agents with standardized input/output handling, * tool management, and model integration. * * @typeParam TInput - The type of input the agent accepts * @typeParam TOutput - The type of output the agent produces */ export declare abstract class Agent<TInput = any, TOutput = any> { private telemetry; constructor(); /** * Retrieves metadata from a decorator. * * @param key - The metadata key symbol * @param target - The target object to get metadata from * @param defaultValue - The default value to return if metadata is not found * @returns The metadata value or default empty array */ private static getMetadata; /** * Gets the configured language model for this agent. * * @returns Promise resolving to the language model instance * @throws {Error} If model metadata is not found */ protected getModel(): Promise<LanguageModelV1>; /** * Gets the model config configured through the @model decorator. * * @returns The model config */ protected getModelConfig(): ModelConfig; /** * Gets the tools configured for this agent through the @tool decorator. * * @returns A record of tool names to their implementations */ protected getTools(): Record<string, CoreTool>; /** * Gets the system prompts configured through the @systemPrompt decorator. * * @returns An array of functions that generate system prompt strings */ protected getSystemPrompts(): Array<() => Promise<string>>; /** * Gets the output schema configured through the @output decorator. * * @returns The Zod schema for validating agent outputs, fallbacks to string schema if not configured */ protected getOutputSchema(): ZodSchema<any>; /** * Gets the input schema configured through the @input decorator. * * @returns The Zod schema for validating agent inputs, if configured */ protected getInputSchema(): ZodSchema<any> | undefined; /** * Serializes the input into a string format for the language model. * * @param input - The input to serialize * @param inputSchema - Optional schema to validate the input * @returns The serialized input string * @throws {Error} If serialization or validation fails */ protected serializeInput(input: TInput, inputSchema: ZodSchema<TInput> | undefined): string; /** * Creates the base configuration for both run and stream operations. * * @param input - The input to process * @returns Base configuration object with model, tools, schemas, and messages */ private createConfig; /** * Wraps an async operation with error handling and telemetry. * * @param operation - The async operation to execute * @returns The result of the operation * @throws The caught error after recording it in telemetry */ private withErrorHandling; /** * Adds telemetry attributes for monitoring and debugging purposes. * Records information about the model, tools, and schemas being used. * * @param model - The language model being used * @param tools - The tools available to the agent * @param outputSchema - The schema for validating outputs * @param inputSchema - The schema for validating inputs, if any */ private addTelemetry; /** * Creates a processed stream that automatically handles the output type. * For string schemas, returns the text stream directly. * For other types, returns the experimental partial output stream. * * @param stream - The raw stream result from the model * @param schema - The schema defining the output type * @returns An async iterable of processed chunks matching the output type */ private processStream; /** * Processes the output from generateText based on the schema type. * * @param result - The result from generateText * @param schema - The output schema * @returns Processed output matching the schema type */ private processOutput; /** * Runs the agent with the given input and returns the output. * * @example * ```typescript * // Simple text input/output * const agent = new SimpleAgent(); * const response = await agent.run("What is TypeScript?"); * console.log(response); // "TypeScript is a typed superset of JavaScript..." * * // Structured input/output * const greetingAgent = new GreetingAgent(); * const response = await greetingAgent.run({ * userName: "Alice", * userMood: "happy", * dayOfWeek: "Saturday" * }); * console.log(response); // { greeting: "Hello Alice!", moodResponse: "..." } * ``` * * @param input - The input (user prompt) to process * @returns Promise resolving to the processed output * @throws {Error} If input validation fails or processing errors occur */ run(input: TInput): Promise<TOutput>; /** * Streams the agent's response for the given input. Useful for real-time UI updates * or processing long responses chunk by chunk. * * @example * ```typescript * // Simple text streaming * const agent = new SimpleAgent(); * const { stream } = await agent.stream("What is TypeScript?"); * for await (const chunk of stream) { * process.stdout.write(chunk); // Chunks: "Type" ... "Script" ... "is a" ... * } * * // Structured output streaming * const greetingAgent = new GreetingAgent(); * const { stream } = await greetingAgent.stream({ * userName: "Alice", * userMood: "happy" * }); * for await (const chunk of stream) { * console.log(chunk); // Partial objects that build up the complete response * } * ``` * * @param input - The input (user prompt) to process * @returns Promise resolving to an enhanced stream result containing the output stream * @throws {Error} If input validation fails or processing errors occur */ stream(input: TInput): Promise<StreamResult<TOutput>>; } /** * `model` decorator to associate a model identifier and configuration with an agent. * * @param modelIdentifier - The model identifier string (e.g., 'openai:gpt-4-mini') * @param config - Optional configuration for the model * @param config.maxTokens - Maximum number of tokens to generate * @param config.temperature - Sampling temperature between 0 and 1 (use either temperature or topP, not both) * @param config.maxRetries - Maximum number of retries for failed requests (defaults to 2 in SDK) * @param config.maxSteps - Maximum number of steps for tool calling (defaults to 3) * @param config.toolChoice - Tool choice mode - 'auto' or 'none' * @returns A class decorator function * * @example * ```typescript * // Basic usage * @model('openai:gpt-4-mini') * class MyAgent extends Agent<string, string> {} * * // With configuration * @model('openai:gpt-4-mini', { * maxTokens: 100, // limit response length * temperature: 0.7, // control randomness * maxRetries: 3, // retry failed requests * maxSteps: 5, // allow multi-step tool calling * toolChoice: 'auto' // enable automatic tool selection * }) * class MyConfiguredAgent extends Agent<string, string> {} * ``` */