agentleFS
ax-llmax-llm/ax/docs/CLAUDE.md

ax

CLAUDE.md3k starsChanged 57 days agoApache-2.0View on GitHub

Ax is a TypeScript framework for building LLM-powered agents with end-to-end streaming, multi-modal DSPy capabilities, and typed signatures. It provides a standard interface across all top LLMs with features like prompt compilation, native streaming, agent orchestration, RAG, vector databases, and automatic prompt tuning. This is a multi-repository monorepo with the following structure: Each sub-repository under src/ has its own package.json and can be developed independently. IMPORTANT: Use workspace-specific package installation commands: DO NOT run npm install in individual sub-directories. Always…

  • Reads credentials
  • Installs packages

Trending

More talk lately.about the whole repository

Dec 2025: 0 mentionsJan 2026: 0 mentionsFeb 2026: 3 mentionsMar 2026: 6 mentionsApr 2026: 8 mentionsMay 2026: 6 mentionsJun 2026: 4 mentionsJul 2026: 1 mentionAug 2026: 4 mentionsSep 2026: 11 mentionsOct 2026: 1 mentionNov 2026: 0 mentions
Dec 2025Jun 2026Nov 2026
Mentions a month of the ax-llm/ax repository that our weekly crawl found. There is no adoption data for this file yet.

Who's talking about ax-llm/ax

The biggest 5 of 45 mentions linking to the repository that our crawl found. Each line is their own headline.

See all 45

Talked about on GitHub and Bluesky (45 times).

On GitHub · 44

39 more on GitHub

On Bluesky · 1

  • In this repositoryOne other file it gives its agents.

The file

Show its rules and text

We split this CLAUDE.md into the rules it gives an agent

51 rules. About 0 are common, 34 are distinctive, and 17 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈34

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 17

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  • could be automatic: a setting could enforce it
  1. Distinctive:

    IMPORTANT: Use workspace-specific package installation commands:

    line 31
  2. Very specific:

    DO NOT: run npm install in individual sub-directories.

    line 45
  3. Distinctive:

    When you name a model anywhere (examples, defaults, tests), use a current generation — newer beats biggest.

    line 50
  4. Distinctive:

    All commands should be run from the repository root:

    line 99
  5. Distinctive:

    Purpose: Test individual functions, classes, and modules

    line 122
  6. Distinctive:

    Purpose: Test real-world usage patterns and end-to-end functionality

    line 145
  7. Distinctive:

    Type Safety: All public APIs must have type tests

    line 221
  8. Very specific:

    Use examples in src/examples/ for load testing

    line 238
  9. Distinctive:

    Test with multiple concurrent requests

    line 239
  10. Distinctive:

    Ensure you're in the repo root when running commands

    line 258
  11. Very specific:

    Use the Node.js version in .node-version (Node 24).

    line 259
  12. Very specific:

    Verify workspace structure with npm run --workspace=@ax-llm/ax

    line 260
  13. Distinctive:

    Test one thing: Break complex scenarios into multiple tests

    line 284
  14. Distinctive:

    KEEP DEMOS SIMPLE AND DIRECT: - No unnecessary abstractions or complexity:

    line 310
  15. Distinctive:

    Top-level code: Put all code at the top level, no function wrappers

    line 314
  16. Distinctive:

    Minimal console logs: Only essential output, avoid verbose logging

    line 318
  17. Distinctive:

    No fallback logic: Keep examples clean and focused on the main functionality

    line 319
  18. Distinctive:

    Public vs Private functions: Only functions or classes exported publicly outside the library should be prefixed with Ax or ax not internal …

    line 321
  19. Distinctive:

    Save minimal data: Only save essential data (like demos), not complex config objects

    line 328
  20. Distinctive:

    Import and reuse: Import exported components in other examples rather than recreating them

    line 330
  21. Distinctive:

    Do not fill the examples with console.log messages just use one of two

    line 336
  22. Distinctive:

    Do not use try .. catch in examples

    line 337
  23. Distinctive:

    Do not use top level functions

    line 338
  24. Distinctive:

    Keep it simple but make the example interesting

    line 339
  25. Very specific:

    It just works: Don't overthink it, modern Node.js handles top-level await fine

    line 359
  26. Distinctive:

    No abstractions: Avoid function wrappers, IIFEs, or unnecessary error handling

    line 361
  27. Distinctive:

    Clean and direct: No try-catch blocks, minimal logging, no fallback complexity

    line 367
  28. Very specific:

    CRITICAL: All publicly exported (to the users of this library) functions and utilities must be prefixed with ax or classes Ax do not do …

    line 698
  29. Distinctive:

    Classes and Types: Follow existing patterns:

    line 702
  30. Distinctive:

    All LLM operations are async and support streaming

    line 722
  31. Distinctive:

    Use async generators for streaming responses

    line 723
  32. Very specific:

    Use descriptive field names following the emailText not text pattern

    line 752
  33. Very specific:

    Write tests in .test.ts files

    line 769
  34. Distinctive:

    Use Vitest for unit testing

    line 770
  35. Distinctive:

    Never commit API keys

    line 784
  36. Distinctive:

    Use environment variables for configuration

    line 785
  37. Distinctive:

    Follow principle of least privilege for LLM permissions

    line 788
  38. Distinctive:

    Use connection pooling for database operations

    line 795
  39. Very specific:

    Creating AI Instance: Always use ai() factory function: ai({ name: 'provider', apiKey: '...' })

    line 820
  40. Very specific:

    Signature Creation: Use s() function for type-safe string-based signatures

    line 822
  41. Very specific:

    Generator Creation: Use ax() function for direct generator creation

    line 824
  42. Very specific:

    Agent Creation: Use agent() factory function OR AxAgent.create() static method for type safety

    line 825
  43. Distinctive:

    Signature Design: Keep signatures simple and descriptive with meaningful field names

    line 829
  44. Distinctive:

    Streaming Handling: Always handle both success and error states in streams

    line 832
  45. Very specific:

    Variable Naming: Use llm instead of ai to avoid naming conflicts with factory function

    line 836
  46. Very specific:

    Field naming: Use descriptive names like userQuestion, emailText, responseText

    line 854
  47. Very specific:

    Dynamic fields: Use f.<type>() helpers with signature methods for dynamic field creation

    line 857
  48. Distinctive:

    When implementing big new features, ask to update the top-level README.md with examples and documentation

    line 863
  49. Distinctive:

    Update TypeDoc comments for new APIs

    line 866
  50. Very specific:

    Add corresponding examples in src/examples/ for new functionality

    line 867
  51. Very specific:

    IMPORTANT: Only edit the top-level README.md file.

    line 872

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

Ax LLM Framework - Cursor Rules

Project Overview

Ax is a TypeScript framework for building LLM-powered agents with end-to-end streaming, multi-modal DSPy capabilities, and typed signatures. It provides a standard interface across all top LLMs with features like prompt compilation, native streaming, agent orchestration, RAG, vector databases, and automatic prompt tuning.

Repository Structure

This is a multi-repository monorepo with the following structure:

  • src/ax/ - Main Ax library (@ax-llm/ax)
  • src/ai-sdk-provider/ - Vercel AI SDK provider (@ax-llm/ax-ai-sdk-provider)
  • src/examples/ - Example implementations (@ax-llm/ax-examples)
  • website/ - Hugo documentation site (deployed to axllm.dev via GitHub Pages)

Each sub-repository under src/ has its own package.json and can be developed independently.

Package Management

IMPORTANT: Use workspace-specific package installation commands:

# Install packages in specific workspaces
npm i <package-name> --workspace=@ax-llm/ax
npm i <package-name> --workspace=@ax-llm/ax-ai-sdk-provider
npm i <package-name> --workspace=@ax-llm/ax-examples
npm i <package-name> --workspace=@ax-llm/ax-docs

# Examples:
npm i typescript --workspace=@ax-llm/ax
npm i react --workspace=@ax-llm/ax-docs

DO NOT run npm install in individual sub-directories. Always use workspace commands from the root.

Model Selection

When you name a model anywhere (examples, defaults, tests), use a current generation — newer beats biggest. The provider enums are the source of truth for what's current: src/ax/ai/openai/chat_types.ts, src/ax/ai/google-gemini/types.ts, src/ax/ai/anthropic/types.ts. Prefer a newer small/cheap model (e.g. gpt-5.4-mini, gemini-3.5-flash) over an old flagship (gpt-4o, gemini-2.x); never pin a dated -preview when a stable newer one exists. (See also AGENTS.md.)

🧪 TESTING GUIDE

Test Framework & Overview

  • Primary Framework: Vitest (configured in root)
  • Type Testing: TypeScript definition files (.test-d.ts)
  • Lint/Format: Biome for code quality
  • Coverage: C8 integration with Vitest

🚀 Quick Test Commands

Running Tests Globally

# Run all tests across all workspaces
npm run test

# Run all unit tests in main workspace
npm run test --workspace=@ax-llm/ax

# Build all workspaces (includes type checking)
npm run build

Running Specific Tests

# Run a specific test file
npx vitest run src/ax/dsp/generate.test.ts

# Run tests matching a pattern
npx vitest run src/ax/dsp/

# Run tests in watch mode (re-runs on file changes)
npx vitest --watch

# Run tests with coverage report
npx vitest --coverage

📋 Main Workspace Test Commands (@ax-llm/ax)

All commands should be run from the repository root:

# Full test suite for main library
npm run test --workspace=@ax-llm/ax

# Individual test types
npm run test:unit --workspace=@ax-llm/ax          # Unit tests only
npm run test:type-check --workspace=@ax-llm/ax    # TypeScript validation
npm run test:lint --workspace=@ax-llm/ax          # Biome linting
npm run test:format --workspace=@ax-llm/ax        # Biome formatting

# Fix issues automatically
npm run fix --workspace=@ax-llm/ax                # Fix lint + format
npm run fix:lint --workspace=@ax-llm/ax           # Fix linting only
npm run fix:format --workspace=@ax-llm/ax         # Fix formatting only

🎯 Test Categories

1. Unit Tests (.test.ts files)

  • Location: Throughout src/ax/ directory
  • Purpose: Test individual functions, classes, and modules
  • Key Areas:
    • Signature parsing and validation (dsp/sig.test.ts, dsp/parser.test.ts)
    • AI service integrations (ai/*.test.ts)
    • Flow orchestration (flow/*.test.ts)
    • Memory operations (mem/*.test.ts)

2. Type Definition Tests (.test-d.ts files)

  • Location: src/ax/**/*.test-d.ts (e.g. index.test-d.ts, dsp/sigtypes.test-d.ts, agent/agent.test-d.ts)
  • Purpose: Validate TypeScript type inference and type safety
  • Testing: Multi-modal types, signature parsing, optional fields
  • Note: These test compile-time type behavior, not runtime
  • Runner: npm run test:type-tests in src/ax (tsc with tsconfig.typetests.json; part of npm test). Use the Equal/Expect witnesses from src/ax/util/typetest.ts plus @ts-expect-error for negative cases

3. Integration Tests

  • Examples: src/examples/ directory serves as integration tests
  • Usage: npm run tsx ./src/examples/<example-file>.ts
  • Purpose: Test real-world usage patterns and end-to-end functionality

🔍 Key Test Files to Know

Core Framework Tests

# Signature system (most important for type inference)
npx vitest run src/ax/dsp/sig.test.ts
npx vitest run src/ax/dsp/template.test.ts
npx vitest run src/ax/dsp/parser.test.ts

# AI services and providers  
npx vitest run src/ax/ai/base.test.ts
npx vitest run src/ax/ai/router.test.ts

# Flow orchestration
npx vitest run src/ax/flow/flow.test.ts
npx vitest run src/ax/flow/executionPlanner.test.ts

Performance & Streaming Tests

# Streaming and generation
npx vitest run src/ax/dsp/generate.test.ts
npx vitest run src/ax/dsp/streaming-optional.test.ts

# Memory and database performance
npx vitest run src/ax/mem/memory.test.ts

🐛 Test-Driven Development Workflow

When Adding New Features

  1. Write tests first in appropriate .test.ts file
  2. Add type tests in index.test-d.ts for public APIs
  3. Run specific tests: npx vitest run src/ax/path/to/your.test.ts
  4. Implement feature until tests pass
  5. Run full test suite: npm run test --workspace=@ax-llm/ax

When Fixing Bugs

  1. Create reproduction test that fails
  2. Fix the bug until test passes
  3. Run related tests: npx vitest run src/ax/module/
  4. Verify no regressions: Full test suite

Before Committing

# Essential pre-commit checks
npm run test:type-check --workspace=@ax-llm/ax  # TypeScript validation
npm run test:unit --workspace=@ax-llm/ax        # All unit tests
npm run fix --workspace=@ax-llm/ax              # Auto-fix lint/format issues

📊 Test Coverage & Quality

Coverage Reports

# Generate coverage report
npx vitest --coverage

# View detailed coverage in browser
npx vitest --coverage --reporter=html
open coverage/index.html

Quality Checks

  • Minimum Coverage: Aim for >80% coverage on new code
  • Critical Paths: Signature parsing, AI communication, streaming must be 100%
  • Type Safety: All public APIs must have type tests
  • Performance: Include performance regression tests for core operations

⚡ Performance Testing

Benchmarking

# Run performance-specific tests
npx vitest run src/ax/dsp/generate.metrics.test.ts

# Profile memory usage
npx vitest run --reporter=verbose src/ax/mem/

Load Testing

  • Use examples in src/examples/ for load testing
  • Test with multiple concurrent requests
  • Monitor token usage and response times

🚨 Common Test Issues & Solutions

Test Failures

# If tests fail, check these first:
npm run test:type-check --workspace=@ax-llm/ax  # TypeScript errors?
npm run test:lint --workspace=@ax-llm/ax        # Linting issues?

# Clean and rebuild if needed
npm run clean --workspace=@ax-llm/ax
npm run build --workspace=@ax-llm/ax

Environment Issues

  • Ensure you're in the repo root when running commands
  • Use the Node.js version in .node-version (Node 24); CI also checks Node 22
  • Verify workspace structure with npm run --workspace=@ax-llm/ax

📝 Writing Good Tests

Test Structure

// Good test example
describe("AxSignature type inference", () => {
  it("should default missing types to string", () => {
    const sig = s("question, image:image -> answer");
    // Test both runtime behavior and type inference
    expect(sig.getInputFields()[0].type).toEqual({
      name: "string",
      isArray: false,
    });
  });
});

Test Naming

  • Be specific: "should default missing types to string" not "should work"
  • Include context: "AxSignature type inference" not just "type inference"
  • Test one thing: Break complex scenarios into multiple tests

Remember: Testing is critical - this library is used in production by startups. Every feature must be thoroughly tested before merging.

Development Commands

# Build all workspaces
npm run build

# Run tests across all workspaces
npm run test

# Fix formatting and linting
npm run fix

# Run examples with tsx
npm run tsx ./src/examples/<example-file>.ts

# Development mode for specific workspace
npm run dev --workspace=@ax-llm/ax

Demo Creation Guidelines

KEEP DEMOS SIMPLE AND DIRECT - No unnecessary abstractions or complexity:

Structure

  • Top-level code: Put all code at the top level, no function wrappers
  • Direct execution: Code should run immediately when file is executed
  • No try-catch blocks: It's just a demo, don't add error handling clutter
  • No IIFE wrappers: Top-level await works fine with modern Node.js/tsx
  • Minimal console logs: Only essential output, avoid verbose logging
  • No fallback logic: Keep examples clean and focused on the main functionality
  • Public vs Private functions: Only functions or classes exported publicly outside the library should be prefixed with Ax or ax not internal functions.

Code Style

  • Export reusable components: Export generators, signatures, or functions that other examples might use
  • Save minimal data: Only save essential data (like demos), not complex config objects
  • Import and reuse: Import exported components in other examples rather than recreating them
  • Clean separation: Optimize once, save demos, use anywhere

Example Creation Guidelines

  • Do not fill the examples with console.log messages just use one of two
  • Do not use try .. catch in examples
  • Do not use top level functions
  • Keep it simple but make the example interesting
// Export reusable generator
export const myGen = ax(
  `userInput:string "User input" -> aiResponse:string "AI response"`,
);

// Top-level execution - no function wrappers
console.log("=== Demo ===");

const llm = ai({ name: "openai", apiKey: process.env.OPENAI_APIKEY! });
const result = await myGen.forward(llm, { userInput: "test" });

// Save only essential data
await fs.writeFile("demos.json", JSON.stringify(demos, null, 2));

Key Principles

  • It just works: Don't overthink it, modern Node.js handles top-level await fine
  • No abstractions: Avoid function wrappers, IIFEs, or unnecessary error handling
  • Focus on functionality: Show the core feature, not error handling patterns
  • Reusable components: Export what others might want to import and use
  • Minimal persistence: Save only what's needed, not metadata or complex configs
  • Clean and direct: No try-catch blocks, minimal logging, no fallback complexity

Code Standards & Architecture

TypeScript Configuration

  • Uses @total-typescript/tsconfig as base
  • ES Modules ("type": "module")
  • NodeNext module resolution
  • Path mapping: @ax-llm/* → src/*
  • React JSX support

Key Architectural Patterns

1. Prompt Signatures & String Functions

Ax uses a unique prompt signature system with string-based function support:

CURRENT RECOMMENDED PATTERNS

import { agent, ai, ax, AxAgent, f, s } from "@ax-llm/ax";

// 1. AI Instance Creation (use factory function)
const llm = ai({
  name: "openai",
  apiKey: process.env.OPENAI_APIKEY!,
});

// 2. Signature Creation (use s function)
const signature = s(`
  userQuestion:string "User input" -> 
  responseText:string "AI response",
  confidenceScore:number "Confidence 0-1"
`);

// 3. Generator Creation (use ax function)
const generator = ax(`
  emailText:string "Email content" -> 
  categoryType:class "urgent, normal, low" "Priority level",
  actionItems:string[] "Required actions"
`);

// 4a. Agent Creation (use factory function)
const agentInstance = agent(
  '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,
  },
);

// 4b. Agent Creation (use AxAgent.create static method)
const agentInstance2 = 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,
  },
);

// 5. Field helpers can still be used for dynamic field creation
const dynamicSig = s("userInput:string -> responseText:string")
  .appendInputField("metadata", f.optional(f.json("Extra data")))
  .appendOutputField("confidence", f.number("Confidence score"));

REMOVED PATTERNS

// ❌ Removed: constructors and tagged templates
// Use ai({ name: "openai", apiKey: "..." }) instead of constructor calls.

🔧 Signatures and AxGen Deep Dive

Understanding Signatures

Signatures define the input/output structure for LLM interactions. They specify:

  • Input fields: What data the LLM receives
  • Output fields: What structured data the LLM should return
  • Field types: String, number, array, class (enum), etc.
  • Field descriptions: Help the LLM understand context

String-Based Function Syntax

Current Recommended Approach

import { ai, ax, f, s } from "@ax-llm/ax";

// Basic signature structure
const signature = s("inputField:string -> outputField:string");

// Multiple inputs and outputs with descriptions
const complexSig = s(`
  userMessage:string "User input",
  contextData:json "Background info" -> 
  responseText:string "AI response",
  sentiment:class "positive, negative, neutral" "Sentiment analysis",
  confidence:number "0-1 confidence score"
`);

// Create generator directly
const generator = ax(`
  userMessage:string "User input" -> 
  responseText:string "AI response"
`);

Field Types in String Signatures

TypeSyntaxExample
Basic typesfield:type "description"userInput:string "User question"
Numbersfield:number "description"score:number "Confidence 0-1"
Booleansfield:boolean "description"isValid:boolean "Input validity"
JSONfield:json "description"metadata:json "Extra data"
Arraysfield:type[] "description"tags:string[] "Keywords"
Optionalfield?:type "description"context?:string "Optional context"
Classificationsfield:class "opt1, opt2" "description"category:class "urgent, normal, low" "Priority"
Datesfield:date "description"dueDate:date "Due date"
DateTimefield:datetime "description"timestamp:datetime "Event time"
Media typesfield:image/audio/file/urlphoto:image "Profile picture"
Codefield:code "description"script:code "Python code"

Advanced Field Usage

// Optional fields with string syntax
const optionalSig = s(`
  userInput:string -> 
  response:string,
  metadata?:json "Optional extra data"
`);

// Array fields
const listProcessor = ax(`
  itemList:string[] "List items" -> 
  processedItems:string[] "Processed items",
  summary:string "Overall summary"
`);

// Complex nested structures
const structuredAnalysis = ax(`
  documentText:string "Document to analyze" -> 
  topics:string[] "Main topics",
  sentiment:class "positive, negative, neutral" "Sentiment analysis",
  keyPoints:string[] "Important points",
  actionItems?:string[] "Required actions"
`);

// Dynamic field creation using f helpers
const dynamicSig = s("baseField:string -> baseOutput:string")
  .appendInputField(
    "extraField",
    f.optional(f.array(f.string("Dynamic field"))),
  )
  .appendOutputField("confidence", f.number("Confidence score"));

Field Naming Requirements

CRITICAL - Field Naming Requirements:

  • NEVER use generic field names like text, result, value, item, data, input, output
  • ALWAYS use descriptive field names that indicate the content's purpose:
    • ✅ Good: documentText, userQuestion, responseText, summaryText, emailContent
    • ✅ Good: processedResult, analysisOutput, categoryType, confidenceScore
    • ✅ Good: inputData, outputResult, dataItem, iterationCount
    • ❌ Bad: text, result, value, item, data, input, output
  • Signature validation will reject generic names - this is enforced at runtime
  • Use context-specific names that make the field's role clear in the signature

Working with AxGen Instances

Creating and Using AxGen

import { ai, ax } from "@ax-llm/ax";

// 1. Create generator with ax function
const taskExtractor = ax(`
  meetingNotes:string "Raw meeting notes" -> 
  actionItems:string[] "Tasks to complete",
  decisions:string[] "Decisions made",
  nextMeetingDate?:date "Next meeting if mentioned"
`);

// 2. Set up AI provider using factory function
const llm = ai({
  name: "openai",
  apiKey: process.env.OPENAI_APIKEY!,
  config: { model: "gpt-5.4-mini" },
});

// 3. Execute the generator
const result = await taskExtractor.forward(llm, {
  meetingNotes:
    "Discussed Q4 budget. John will review numbers by Friday. Next meeting Dec 15th.",
});

// 4. Access typed results
console.log(result.actionItems); // ['John will review Q4 budget numbers by Friday']
console.log(result.decisions); // ['Discussed Q4 budget planning']
console.log(result.nextMeetingDate); // '2024-12-15'

Streaming with AxGen

const streamingGen = ax(`
  storyPrompt:string "Story premise" -> 
  storyText:string "Generated story",
  genre:class "fantasy, sci-fi, mystery" "Story genre"
`);

// Stream the response
for await (
  const chunk of streamingGen.stream(llm, {
    storyPrompt: "A robot discovers emotions",
  })
) {
  if (chunk.storyText) {
    process.stdout.write(chunk.storyText);
  }
}

Advanced Signature Usage

import { ai, ax, s } from "@ax-llm/ax";

// Create signature separately
const analysisSignature = s(`
  documentText:string "Document to analyze" -> 
  mainThemes:string[] "Key themes",
  readingLevel:class "elementary, middle, high, college" "Reading difficulty",
  wordCount:number "Approximate word count"
`);

// Create generator from signature
const analyzer = ax(analysisSignature.toString());

// Use the analyzer
const llm = ai({ name: "openai", apiKey: process.env.OPENAI_APIKEY! });
const result = await analyzer.forward(llm, {
  documentText: "Sample document text...",
});

Error Handling and Validation

try {
  const result = await generator.forward(llm, { documentText: "Sample text" });

  // Results are automatically validated against the signature
  // Type errors will be caught at compile time with TypeScript
  console.log(result.mainThemes); // Type-safe access
} catch (error) {
  // Handle validation errors, API errors, etc.
  console.error("Generation failed:", error);
}

Integration Patterns

// Chaining generators
const summarizer = ax(`
  longText:string "Text to summarize" -> 
  summary:string "Brief summary"
`);

const classifier = ax(`
  summaryText:string "Summary text" -> 
  category:class "news, opinion, tutorial" "Content type"
`);

// Chain execution
const summary = await summarizer.forward(llm, { longText: document });
const classification = await classifier.forward(llm, {
  summaryText: summary.summary,
});

String-Based Function Advantages:

  • Full TypeScript type inference and safety
  • Clean, readable syntax with s() and ax() functions
  • Better IntelliSense support than template literals
  • Consistent validation and error messages
  • Standard string format that's easy to parse and understand
  • Can combine with f.<type>() helpers for dynamic field creation
  • Automatic TypeScript inference for input/output types

2. Core Components

  • AxAI: Main AI interface for model-lab and core LLM providers (use ai() factory function)
  • AxAgent: Agent framework with inter-agent communication (use agent() factory function)
  • AxFlow: AI workflow orchestration engine for complex multi-step processes
  • GEPA / BootstrapFewShot: Optimizers for prompt and demo improvement

3. Streaming & Multi-modal

  • Native end-to-end streaming
  • Multi-modal support (text, images, audio)
  • Thinking models support with token budget control
  • Real-time validation during streaming

Code Conventions

Naming Conventions

CRITICAL: All publicly exported (to the users of this library) functions and utilities must be prefixed with ax or classes Ax do not do this with internal functions

Classes and Types: Follow existing patterns:

  • Classes: AxClassName (e.g., AxAI, AxChainOfThought)
  • Types/Interfaces: AxTypeName (e.g., AxLoggerFunction, AxOptimizerArgs)
  • Functions/Utilities: axFunctionName (e.g., axCreateOptimizerLogger, axDefaultOptimizerLogger)

Import/Export Patterns

// Prefer named exports
export { AxAgent, AxAI, AxChainOfThought };

// Use barrel exports in sub-module index.ts files (not the main index.ts which is auto-generated)
export * from "./ai/index.js";
export * from "./prompts/index.js";

Async Patterns

  • All LLM operations are async and support streaming
  • Use async generators for streaming responses
  • Implement proper cleanup for streaming connections

File Organization

Main Library (src/ax/)

  • ai/ - LLM provider implementations
  • prompts/ - Prompt signature and DSPy logic
  • agents/ - Agent framework
  • db/ - Vector database implementations
  • trace/ - OpenTelemetry integration
  • funcs/ - Function calling utilities
  • mcp/ - Model Context Protocol support
  • flow/ - AxFlow ai workflow orchastration engine
  • dsp - The AxGen implementation which sits at the core of this library

Provider Package (src/ai-sdk-provider/)

  • Integration with Vercel AI SDK
  • Provider utilities and transformations

Examples (src/examples/)

  • Comprehensive examples for all features
  • Each example should be runnable with npm run tsx
  • Include proper environment variable setup
  • ALWAYS use string-call forms (ax("...") and s("...")) in examples, not tagged template signatures
  • Use descriptive field names following the emailText not text pattern

Dependencies & Constraints

  • Node.js runtime: >= 20
  • Development tooling: Node 24 from .node-version; Node 22.18+ is also supported
  • Runtime: ES Modules only
  • Core Dependencies: Minimal, zero-dependencies philosophy
  • Peer Dependencies: Handle LLM SDKs as peer deps where possible
  • Browser Compatibility: CRITICAL - Do not add filesystem calls (fs, path, os) or other Node.js-specific APIs to the main library (src/ax/). The library must run in browser environments. Use only web-standard APIs and platform-agnostic code. Node.js-specific functionality should be in examples or separate utility packages.

Testing Guidelines

  • Write tests in .test.ts files
  • Use Vitest for unit testing
  • Test streaming scenarios
  • Mock LLM providers for deterministic tests
  • Include type-level tests in .test-d.ts files

Documentation

  • TypeDoc for API documentation
  • Markdown documentation site in website/
  • Examples serve as living documentation
  • Include prompt signature examples in code comments

Security & Best Practices

  • Never commit API keys
  • Use environment variables for configuration
  • Validate all inputs, especially in streaming contexts
  • Implement proper rate limiting and error recovery
  • Follow principle of least privilege for LLM permissions

Performance Considerations

  • Optimize for streaming performance
  • Minimize token usage through smart prompting
  • Cache embeddings and model responses where appropriate
  • Use connection pooling for database operations
  • Profile memory usage in long-running streams

OpenTelemetry Integration

  • Built-in gen_ai semantic conventions support
  • Trace all LLM operations
  • Include custom spans for agent interactions
  • Export traces in production environments

Environment Setup

# Required environment variables (examples)
OPENAI_APIKEY=your_key_here
GOOGLE_APIKEY=your_key_here
ANTHROPIC_APIKEY=your_key_here

# Optional for specific features
WEAVIATE_URL=http://localhost:8080
PINECONE_API_KEY=your_key_here

Common Patterns

  1. Creating AI Instance: Always use ai() factory function: ai({ name: 'provider', apiKey: '...' })
  2. Signature Creation: Use s() function for type-safe string-based signatures
  3. Generator Creation: Use ax() function for direct generator creation
  4. Agent Creation: Use agent() factory function OR AxAgent.create() static method for type safety
  5. Dynamic Fields: Combine string signatures with f.<type>() helpers for dynamic field creation
  6. Signature Design: Keep signatures simple and descriptive with meaningful field names
  7. Agent Composition: Agents can call other agents for complex workflows
  8. Streaming Handling: Always handle both success and error states in streams
  9. Type Safety: Leverage TypeScript's type system for compile-time validation
  10. Variable Naming: Use llm instead of ai to avoid naming conflicts with factory function

Build & Release

  • Uses tsdown for building
  • Automated versioning with standard-version
  • Multi-workspace publishing with release-it
  • GitHub Actions for CI/CD
  • Auto-generated Files: index.ts in the main library is auto-generated by running npm run build:index --workspace=@ax-llm/ax

Current Best Practices (v13.0.24+)

  • Always use factory functions: ai(), agent() for better type safety
  • Always use s() function for string-based signatures (not constructors)
  • Always use ax() function for generators (not template literals)
  • Import pattern: import { ai, agent, s, ax, f } from '@ax-llm/ax'
  • Field naming: Use descriptive names like userQuestion, emailText, responseText
  • Variable naming: Use llm instead of ai to avoid naming conflicts
  • Dynamic fields: Use f.<type>() helpers with signature methods for dynamic field creation
  • Type safety: Leverage string-based functions for full TypeScript inference

Documentation Guidelines

  • When implementing big new features, ask to update the top-level README.md with examples and documentation
  • Include the new feature in the feature list and provide clear usage examples
  • Update TypeDoc comments for new APIs
  • Add corresponding examples in src/examples/ for new functionality
  • When creating new examples, always add them to the examples table in the top-level README.md with a clear description
  • ALL examples must use current recommended patterns (factory functions, string-based signatures) instead of deprecated patterns
  • IMPORTANT: Only edit the top-level README.md file. Never edit files under website/.generated/ as they are auto-generated and will be overwritten

Remember: This is a production-ready library used by startups in production. Maintain high code quality, comprehensive testing, and backward compatibility.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.