### Clone AXAR Repository and Install Dependencies (Bash) Source: https://github.com/axar-ai/axar/blob/main/CONTRIBUTING.md Instructions for cloning the AXAR repository from GitHub and installing project dependencies using npm. This is the initial setup step before making any code changes. ```bash git clone https://github.com/your-username/axar.git cd axar npm install ``` -------------------------------- ### Project Setup and Configuration (Bash) Source: https://github.com/axar-ai/axar/blob/main/README.md Commands to set up a new project for AXAR AI, install necessary dependencies including the AXAR package, TypeScript, and ts-node. It also includes instructions for initializing TypeScript configuration. ```bash mkdir axar-demo cd axar-demo npm init -y npm i @axarai/axar ts-node typescript npx tsc --init ``` -------------------------------- ### Hello World AXAR Agent (TypeScript) Source: https://github.com/axar-ai/axar/blob/main/README.md A minimal example demonstrating how to define and run a simple AXAR agent. This agent uses the 'openai:gpt-4o-mini' model and is configured to be concise. It takes a string input and returns a string output. ```typescript import { model, systemPrompt, Agent } from '@axarai/axar'; // Define the agent. @model('openai:gpt-4o-mini') @systemPrompt('Be concise, reply with one sentence') export class SimpleAgent extends Agent {} // Run the agent. async function main() { const response = await new SimpleAgent().run( 'Where does "hello world" come from?', ); console.log(response); } main().catch(console.error); ``` -------------------------------- ### Agent.run() with Structured Input/Output using @schema Source: https://context7.com/axar-ai/axar/llms.txt This example demonstrates using the Agent.run() method with structured inputs and outputs defined using the @schema decorator. It showcases how to define custom input and output classes with properties and use them with an agent for question answering. ```typescript import { model, systemPrompt, Agent, input, output, schema, property } from '@axarai/axar'; @schema() class UserQuery { @property("User's question") question!: string; @property("User's preferred language") language!: string; } @schema() class BotResponse { @property("Answer to the question") answer!: string; @property("Confidence level 0-1") confidence!: number; } @model('openai:gpt-4o-mini') @systemPrompt('Answer questions concisely and provide a confidence score') @input(UserQuery) @output(BotResponse) class QAAgent extends Agent {} async function main() { const agent = new QAAgent(); const result = await agent.run({ question: 'What is TypeScript?', language: 'English' }); console.log(result.answer); console.log(`Confidence: ${result.confidence}`); // Output: { answer: "TypeScript is a typed superset...", confidence: 0.95 } } main().catch(console.error); ``` -------------------------------- ### Configuring Agents with the @model Decorator Source: https://context7.com/axar-ai/axar/llms.txt This example demonstrates how to use the @model decorator to specify the LLM provider and its configuration options. It shows both basic usage with just the model identifier and advanced usage with parameters like maxTokens, temperature, and tool calling configurations. ```typescript import { model, Agent, systemPrompt } from '@axarai/axar'; // Basic usage with model identifier @model('openai:gpt-4o-mini') @systemPrompt('You are a helpful assistant') class BasicAgent extends Agent {} // Advanced usage with configuration options @model('openai:gpt-4o-mini', { maxTokens: 500, // Limit response length temperature: 0.7, // Control randomness (0-1) maxRetries: 3, // Retry failed requests maxSteps: 5, // Allow multi-step tool calling toolChoice: 'auto' // Enable automatic tool selection }) @systemPrompt('You are an expert coding assistant') class ConfiguredAgent extends Agent {} async function main() { const basic = await new BasicAgent().run('What is AI?'); console.log(basic); const configured = await new ConfiguredAgent().run('Explain recursion'); console.log(configured); } main().catch(console.error); ``` -------------------------------- ### AXAR Agent Implementation (TypeScript) Source: https://github.com/axar-ai/axar/blob/main/README.md A practical example of creating an AXAR agent named 'TextAgent' that interacts with the 'openai:gpt-4o-mini' model. The agent is instructed to provide concise, one-sentence replies and is demonstrated by querying the origin of the internet. ```typescript import { model, systemPrompt, Agent } from '@axarai/axar'; @model('openai:gpt-4o-mini') @systemPrompt('Be concise, reply with one sentence') class TextAgent extends Agent {} (async () => { const response = await new TextAgent().run('Who invented the internet?'); console.log(response); })(); ``` -------------------------------- ### Dependency Injection with Axar AI Agents (TypeScript) Source: https://context7.com/axar-ai/axar/llms.txt This snippet showcases dependency injection in Axar AI, where a 'BankAgent' receives a 'DatabaseConn' interface as a dependency. This allows the agent to interact with external services like databases or APIs. The example defines input/output schemas and demonstrates how to run the agent with mock dependencies. ```typescript import { model, systemPrompt, Agent, tool, output, schema, property, optional, min, max } from '@axarai/axar'; // Database interface interface DatabaseConn { customerName(id: number): Promise; customerBalance(id: number, name: string, includePending: boolean): Promise; } @schema() class SupportResponse { @property('Advice for customer') support_advice!: string; @property("Whether to block customer's card") block_card!: boolean; @property('Risk level 0-1') @min(0) @max(1) risk!: number; @property("Customer's emotional state") @optional() status?: 'Happy' | 'Sad' | 'Neutral'; } @schema() class ToolParams { @property("Customer's name") customerName!: string; @property('Include pending transactions') @optional() includePending?: boolean; } @model('openai:gpt-4o-mini') @systemPrompt('You are a bank support agent. Provide advice and assess risk.') @output(SupportResponse) class BankAgent extends Agent { constructor( private customerId: number, private db: DatabaseConn ) { super(); } @systemPrompt() async getCustomerContext(): Promise { const name = await this.db.customerName(this.customerId); return `The customer's name is '${name}'`; } @tool("Get customer's current balance") async customerBalance(params: ToolParams): Promise { return this.db.customerBalance( this.customerId, params.customerName, params.includePending ?? true ); } } async function main() { // Mock database const db: DatabaseConn = { async customerName(id: number) { return 'John Doe'; }, async customerBalance(id: number, name: string, includePending: boolean) { return 5047.71; } }; const agent = new BankAgent(123, db); const result = await agent.run('What is my balance?'); console.log(result); // Output: { support_advice: "Hi John, your balance is $5,047.71", block_card: false, risk: 0.1, status: "Happy" } const cardResult = await agent.run('I just lost my card!'); console.log(cardResult); // Output: { support_advice: "I'll block your card immediately...", block_card: true, risk: 0.8, status: "Sad" } } main().catch(console.error); ``` -------------------------------- ### Multi-Agent Orchestration with Axar AI (TypeScript) Source: https://context7.com/axar-ai/axar/llms.txt This example demonstrates multi-agent orchestration in Axar AI, where a main 'AirlineAgent' delegates tasks to specialized sub-agents ('FlightModificationAgent', 'LostBaggageAgent'). This pattern is useful for creating complex workflows by composing simpler, focused agents. The code defines schemas for each agent's output and shows how the orchestrator routes queries. ```typescript import { model, systemPrompt, Agent, tool, output, schema, property } from '@axarai/axar'; @schema() class FlightModificationResponse { @property('Confirmation message') confirmation!: string; @property('New flight details') details?: string; } @schema() class LostBaggageResponse { @property('Baggage claim ticket number') claimNumber!: string; @property('Status update') status!: string; } @schema() class TriggerResponse { @property('Confirmation of intent') confirmation!: string; @property('Action details') details?: string; } // Sub-agent for flight modifications @model('openai:gpt-4o-mini') @systemPrompt('Handle flight changes and cancellations') @output(FlightModificationResponse) class FlightModificationAgent extends Agent {} // Sub-agent for lost baggage @model('openai:gpt-4o-mini') @systemPrompt('Handle lost baggage claims') @output(LostBaggageResponse) class LostBaggageAgent extends Agent {} // Orchestrator agent @model('openai:gpt-4o-mini') @systemPrompt('Route customer queries to appropriate sub-agents') @output(TriggerResponse) class AirlineAgent extends Agent { constructor( private flightAgent: FlightModificationAgent, private baggageAgent: LostBaggageAgent ) { super(); } @tool('Handle flight modifications (cancel or change)') async handleFlightModification(query: string): Promise { return this.flightAgent.run(query); } @tool('Handle lost baggage claims') async handleLostBaggage(query: string): Promise { return this.baggageAgent.run(query); } } async function main() { const flightAgent = new FlightModificationAgent(); const baggageAgent = new LostBaggageAgent(); const orchestrator = new AirlineAgent(flightAgent, baggageAgent); // Automatically routes to flight agent const flightResult = await orchestrator.run('I want to cancel my flight due to emergency'); console.log(flightResult); // Automatically routes to baggage agent const baggageResult = await orchestrator.run('My luggage is missing from flight AA123'); console.log(baggageResult); } main().catch(console.error); ``` -------------------------------- ### Define a Simple Agent with @model and @systemPrompt Source: https://context7.com/axar-ai/axar/llms.txt This snippet shows how to define a basic agent using the Agent base class and apply the @model and @systemPrompt decorators to configure the LLM and its behavior. It demonstrates a simple agent that takes a string input and returns a string output. ```typescript import { model, systemPrompt, Agent } from '@axarai/axar'; @model('openai:gpt-4o-mini') @systemPrompt('Be concise, reply with one sentence') export class SimpleAgent extends Agent {} async function main() { const response = await new SimpleAgent().run( 'Where does "hello world" come from?' ); console.log(response); // Output: "The term 'hello world' originated from a 1974 programming book..." } main().catch(console.error); ``` -------------------------------- ### Running the AXAR Agent (Bash) Source: https://github.com/axar-ai/axar/blob/main/README.md Instructions for executing a TypeScript file containing an AXAR agent using ts-node. This includes setting the necessary environment variable for the OpenAI API key and the command to run the script. ```bash export OPENAI_API_KEY="sk-proj-YOUR-API-KEY" npx ts-node text-agent.ts ``` -------------------------------- ### AXAR Bank Agent with Schema and Tools (TypeScript) Source: https://github.com/axar-ai/axar/blob/main/README.md Defines a bank support agent using AXAR, including structured response schemas, tool parameter schemas, AI model specification, system prompts, and tool definitions. It demonstrates how to fetch customer context and interact with simulated database functions. This agent is designed to provide support, judge query risk, and manage card-related actions. ```typescript // ... // Define the structured response that the agent will produce. @schema() export class SupportResponse { @property('Human-readable advice to give to the customer.') support_advice!: string; @property("Whether to block customer's card.") block_card!: boolean; @property('Risk level of query') @min(0) @max(1) risk!: number; @property("Customer's emotional state") @optional() status?: 'Happy' | 'Sad' | 'Neutral'; } // Define the schema for the parameters used by tools (functions accessible to the agent). @schema() class ToolParams { @property("Customer's name") customerName!: string; @property('Whether to include pending transactions') @optional() includePending?: boolean; } // Specify the AI model used by the agent (e.g., OpenAI GPT-4 mini version). @model('openai:gpt-4o-mini') // Provide a system-level prompt to guide the agent's behavior and tone. @systemPrompt(` You are a support agent in our bank. Give the customer support and judge the risk level of their query. Reply using the customer's name. `) // Define the expected output format of the agent. @output(SupportResponse) export class SupportAgent extends Agent { // Initialize the agent with a customer ID and a DB connection for fetching customer-specific data. constructor( private customerId: number, private db: DatabaseConn, ) { super(); } // Provide additional context for the agent about the customer's details. @systemPrompt() async getCustomerContext(): Promise { // Fetch the customer's name from the database and provide it as context. const name = await this.db.customerName(this.customerId); return `The customer's name is '${name}'`; } // Define a tool (function) accessible to the agent for retrieving the customer's balance. @tool("Get customer's current balance") async customerBalance(params: ToolParams): Promise { // Fetch the customer's balance, optionally including pending transactions. return this.db.customerBalance( this.customerId, params.customerName, params.includePending ?? true, ); } } async function main() { // Mock implementation of the database connection for this example. const db: DatabaseConn = { async customerName(id: number) { // Simulate retrieving the customer's name based on their ID. return 'John'; }, async customerBalance( id: number, customerName: string, includePending: boolean, ) { // Simulate retrieving the customer's balance with optional pending transactions. return 123.45; }, }; // Initialize the support agent with a sample customer ID and the mock database connection. const agent = new SupportAgent(123, db); // Run the agent with a sample query to retrieve the customer's balance. const balanceResult = await agent.run('What is my balance?'); console.log(balanceResult); // Run the agent with a sample query to block the customer's card. const cardResult = await agent.run('I just lost my card!'); console.log(cardResult); } // Entry point for the application. Log any errors that occur during execution. main().catch(console.error); ``` -------------------------------- ### Run Project Tests with Jest (Bash) Source: https://github.com/axar-ai/axar/blob/main/CONTRIBUTING.md Command to execute the test suite for the AXAR project using Jest. Ensures that all changes adhere to the project's quality standards and do not introduce regressions. ```bash npx jest ``` -------------------------------- ### Create a New Branch for Feature Development (Bash) Source: https://github.com/axar-ai/axar/blob/main/CONTRIBUTING.md Demonstrates how to create a new Git branch for developing a specific feature or bug fix within the AXAR project. This isolates changes and facilitates easier management. ```bash git checkout -b cool-feature ``` -------------------------------- ### Define System Prompts with @systemPrompt Decorator in TypeScript Source: https://context7.com/axar-ai/axar/llms.txt The @systemPrompt decorator defines static or dynamic system prompts for agent behavior. It can be applied at the class level for a static prompt or at the method level for dynamic prompts, influencing agent responses and context. ```typescript import { model, systemPrompt, Agent } from '@axarai/axar'; // Class-level static prompt @model('openai:gpt-4o-mini') @systemPrompt('You are a helpful customer support agent. Be polite and professional.') class SupportAgent extends Agent { constructor(private customerName: string, private accountTier: string) { super(); } // Method-level dynamic prompt @systemPrompt() async getCustomerContext(): Promise { return `The customer's name is ${this.customerName} and they have ${this.accountTier} tier access.`; } } async function main() { const agent = new SupportAgent('Alice Johnson', 'Premium'); const response = await agent.run('What are my account benefits?'); console.log(response); // The agent has context about Alice's Premium tier } main().catch(console.error); ``` -------------------------------- ### TypeScript Configuration for AXAR (JSON) Source: https://github.com/axar-ai/axar/blob/main/README.md Essential 'tsconfig.json' settings for AXAR AI projects, emphasizing strict mode, CommonJS module system, ES2020 target, and enabling experimental decorators for AOP-like features. ```json { "compilerOptions": { "strict": true, "module": "CommonJS", "target": "es2020", "esModuleInterop": true, "experimentalDecorators": true, "emitDecoratorMetadata": true } } ``` -------------------------------- ### Agent.stream() for Chunked Responses Source: https://context7.com/axar-ai/axar/llms.txt This snippet illustrates the use of the Agent.stream() method to receive responses in chunks, which is ideal for real-time UI updates or handling large amounts of data. It defines a streaming agent with a structured output and shows how to iterate over the streamed chunks. ```typescript import { model, systemPrompt, Agent, output, schema, property, optional } from '@axarai/axar'; @schema() class GreetingResponse { @property("A greeting message") greeting!: string; @property('Time acknowledgment') timeResponse!: string; @property("Personalized message") @optional() moodMessage?: string; } @model('openai:gpt-4o-mini') @systemPrompt('Greet users warmly and acknowledge the current time') @output(GreetingResponse) class StreamingAgent extends Agent {} async function main() { const agent = new StreamingAgent(); const { stream, raw } = await agent.stream('Hello, my name is Alice'); console.log('Streaming response:'); for await (const partial of stream) { console.log('Chunk:', partial); // Outputs progressive partial objects building to complete response } // Access full result after streaming const finalResult = await raw.response; console.log('Final:', finalResult); } main().catch(console.error); ``` -------------------------------- ### Specify Schemas with @input and @output Decorators in TypeScript Source: https://context7.com/axar-ai/axar/llms.txt The @input and @output decorators specify typed schemas for agent input and output validation using decorators like @schema, @property, @min, @max, and @optional. This ensures data integrity and predictable agent interactions. It supports custom classes, primitives, and Zod schemas. ```typescript import { model, systemPrompt, Agent, input, output, schema, property, min, max } from '@axarai/axar'; import { z } from 'zod'; @schema() class RiskAssessmentInput { @property('Transaction amount in USD') @min(0) amount!: number; @property('Merchant category') merchantCategory!: string; } @schema() class RiskAssessmentOutput { @property('Risk score 0-100') @min(0) @max(100) riskScore!: number; @property('Whether to approve transaction') approved!: boolean; @property('Explanation for decision') reason!: string; } @model('openai:gpt-4o-mini') @systemPrompt('Assess transaction risk based on amount and merchant category') @input(RiskAssessmentInput) @output(RiskAssessmentOutput) class RiskAgent extends Agent {} // Can also use primitives or Zod schemas directly @model('openai:gpt-4o-mini') @input(String) @output(z.boolean()) class BooleanAgent extends Agent {} async function main() { const riskAgent = new RiskAgent(); const assessment = await riskAgent.run({ amount: 5000, merchantCategory: 'Electronics' }); console.log(assessment); // Output: { riskScore: 35, approved: true, reason: "Amount is reasonable..." } const boolAgent = new BooleanAgent(); const isValid = await boolAgent.run('Is this email valid: test@example.com?'); console.log(isValid); // true or false } main().catch(console.error); ``` -------------------------------- ### Commit and Push Changes for Pull Request (Bash) Source: https://github.com/axar-ai/axar/blob/main/CONTRIBUTING.md Steps to commit local changes with a descriptive message and push the feature branch to the remote repository, preparing for a pull request in AXAR. ```bash git commit -m "Fix: Handle null inputs in getCustomerContext" git push origin cool-feature ``` -------------------------------- ### Add Metadata and Validation with Property Decorators Source: https://context7.com/axar-ai/axar/llms.txt Property decorators like @property, @uuid, @pattern, @email, @datetime, @minItems, @maxItems, and @arrayItems enhance schema properties with descriptive metadata and validation rules. These decorators, when applied to class properties within a @schema decorated class, ensure data integrity and structure. ```typescript import { schema, property, optional, min, max, email, url, pattern, uuid, datetime, minimum, maximum, integer, minItems, maxItems, uniqueItems, arrayItems } from '@axarai/axar'; @schema() class Product { @property('Unique product identifier') @uuid() id!: string; @property('Product SKU') @pattern(/^[A-Z]{3}-\d{4}$/) sku!: string; } @schema() class Order { @property('Order total in cents') @minimum(0) @integer() totalCents!: number; @property('Customer email') @email() customerEmail!: string; @property('Created timestamp') @datetime() createdAt!: string; @property('Product tags') @minItems(1) @maxItems(5) @uniqueItems() tags!: string[]; @property('Discount percentage') @minimum(0) @maximum(100) @optional() discountPercent?: number; } @schema() class OrderList { @property('List of orders') @arrayItems(() => Order) orders!: Order[]; } // Use with agent import { model, systemPrompt, Agent, output } from '@axarai/axar'; @model('openai:gpt-4o-mini') @systemPrompt('Parse order information from text') @output(Order) class OrderParser extends Agent {} async function main() { const agent = new OrderParser(); const order = await agent.run('Order total $45.99, email: alice@test.com'); console.log(order); // Validates all constraints automatically } main().catch(console.error); ``` -------------------------------- ### Generate Zod Schemas with @schema Decorator Source: https://context7.com/axar-ai/axar/llms.txt The @schema decorator automatically generates Zod schemas from TypeScript classes, leveraging property metadata for validation. It requires importing necessary decorators from '@axarai/axar'. The generated schema can be used with Axar agents for structured input and output. ```typescript import { schema, property, optional, min, max, email, url, enumValues } from '@axarai/axar'; @schema('User profile information') class UserProfile { @property("User's full name") name!: string; @property("User's email address") @email() email!: string; @property("User's age") @min(18) @max(120) age!: number; @property("User's website") @url() @optional() website?: string; @property("Account type") @enumValues(['free', 'premium', 'enterprise']) accountType!: 'free' | 'premium' | 'enterprise'; } // Schema can be used with agents import { model, systemPrompt, Agent, output } from '@axarai/axar'; @model('openai:gpt-4o-mini') @systemPrompt('Extract user profile information from text') @output(UserProfile) class ProfileExtractor extends Agent {} async function main() { const agent = new ProfileExtractor(); const profile = await agent.run( 'My name is Bob Smith, email bob@example.com, age 25, website https://bob.dev, premium account' ); console.log(profile); // Output: { name: "Bob Smith", email: "bob@example.com", age: 25, ... } } main().catch(console.error); ``` -------------------------------- ### Mark Methods as Tools with @tool Decorator in TypeScript Source: https://context7.com/axar-ai/axar/llms.txt The @tool decorator marks methods as tools that an agent can call during execution. It allows specifying parameters and return types for the tool, enabling the agent to interact with external functionalities or data sources. ```typescript import { model, systemPrompt, Agent, tool, schema, property, optional } from '@axarai/axar'; @schema() class WeatherParams { @property('City name') city!: string; @property('Include forecast') @optional() includeForecast?: boolean; } @schema() class DatabaseParams { @property('User ID to lookup') userId!: number; } @model('openai:gpt-4o-mini') @systemPrompt('You are a helpful assistant. Use tools to fetch real-time information.') class ToolAgent extends Agent { @tool('Get current weather for a city') async getWeather(params: WeatherParams): Promise { // Simulate API call const forecast = params.includeForecast ? ', sunny tomorrow' : ''; return `Weather in ${params.city}: 72°F, partly cloudy${forecast}`; } @tool('Fetch user profile from database', DatabaseParams) async getUserProfile(params: DatabaseParams): Promise { // Simulate database query return `User ${params.userId}: John Doe, joined 2023`; } @tool('Get current server time') getCurrentTime(): string { return new Date().toISOString(); } } async function main() { const agent = new ToolAgent(); // Agent will automatically call getWeather tool const weatherResponse = await agent.run('What is the weather in San Francisco?'); console.log(weatherResponse); // Agent will call getUserProfile tool const userResponse = await agent.run('Tell me about user 12345'); console.log(userResponse); } main().catch(console.error); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.