[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6D0W3N013HJAB7ZSHW1V6B5":3,"skill-same:01M6D0W3N013HJAB7ZSHW1V6B5":58},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":26,"linkOnly":27,"markdownContent":28,"markdownBody":29,"frontMatter":30,"refName":32,"commitSha":33,"skillDirectory":34,"forksCount":13,"repositoryHtmlUrl":35,"repositoryHomepageUrl":6,"ownerHtmlUrl":36,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":37,"install":38,"resources":51},"01M6D0W3N013HJAB7ZSHW1V6B5","ax",null,"This skill helps with using the @ax-llm\u002Fax TypeScript library for building LLM applications. Use when the user asks about ax(), ai(), f(), s(), agent(), flow(), AxGen, AxAgent, AxFlow, signatures, streaming, or mentions @ax-llm\u002Fax.","marolinik\u002Fwaggle","marolinik","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F140324869?v=4","01M6D0VTXTDB9QGWTD5T7MM1HS","01M6D0VV6AS21A11J7S8X4CYSA",0,"MIT","https:\u002F\u002Fgithub.com\u002Fmarolinik\u002Fwaggle\u002Fblob\u002Fmaster\u002F.claude\u002Fskills\u002Fax\u002FSKILL.md",[],[5,18,19,20,21,22,23,24,25],"typescript","streaming","library","flow","applications","user","use","signatures","2026-11-10 10:12:30",false,"---\nname: ax\ndescription: This skill helps with using the @ax-llm\u002Fax TypeScript library for building LLM applications. Use when the user asks about ax(), ai(), f(), s(), agent(), flow(), AxGen, AxAgent, AxFlow, signatures, streaming, or mentions @ax-llm\u002Fax.\nversion: \"19.0.13\"\n---\n\n# Ax Library (@ax-llm\u002Fax) Usage Guide\n\nAx is a TypeScript library for building LLM-powered applications with type-safe signatures, streaming support, and multi-provider compatibility.\n\n## Quick Reference\n\n```typescript\nimport { ax, ai, f, agent, flow, AxGen, AxAgent, AxFlow } from '@ax-llm\u002Fax';\n\n\u002F\u002F Create AI provider\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY });\n\n\u002F\u002F Create typed generator using f() fluent API\nconst gen = ax(\n  f()\n    .input('question', f.string('User question'))\n    .output('answer', f.string('AI response'))\n    .build()\n);\nconst result = await gen.forward(llm, { question: 'What is 2+2?' });\n\u002F\u002F result.answer is typed as string\n```\n\n## 1. AI Provider Setup\n\n### Quick Setup (All Providers)\n\n```typescript\nimport { ai } from '@ax-llm\u002Fax';\n\n\u002F\u002F OpenAI\nconst openai = ai({ name: 'openai', apiKey: 'sk-...' });\n\n\u002F\u002F Anthropic Claude\nconst claude = ai({ name: 'anthropic', apiKey: 'sk-ant-...' });\n\n\u002F\u002F Google Gemini\nconst gemini = ai({ name: 'google-gemini', apiKey: 'AIza...' });\n\n\u002F\u002F Azure OpenAI\nconst azure = ai({\n  name: 'azure-openai',\n  apiKey: 'your-key',\n  resourceName: 'your-resource',\n  deploymentName: 'gpt-4'\n});\n\n\u002F\u002F Groq\nconst groq = ai({ name: 'groq', apiKey: 'gsk_...' });\n\n\u002F\u002F DeepSeek\nconst deepseek = ai({ name: 'deepseek', apiKey: 'sk-...' });\n\n\u002F\u002F Mistral\nconst mistral = ai({ name: 'mistral', apiKey: 'your-key' });\n\n\u002F\u002F Cohere\nconst cohere = ai({ name: 'cohere', apiKey: 'your-key' });\n\n\u002F\u002F Together AI\nconst together = ai({ name: 'together', apiKey: 'your-key' });\n\n\u002F\u002F OpenRouter\nconst openrouter = ai({ name: 'openrouter', apiKey: 'your-key' });\n\n\u002F\u002F Ollama (local)\nconst ollama = ai({ name: 'ollama', url: 'http:\u002F\u002Flocalhost:11434' });\n\n\u002F\u002F HuggingFace\nconst hf = ai({ name: 'huggingface', apiKey: 'hf_...' });\n\n\u002F\u002F Reka\nconst reka = ai({ name: 'reka', apiKey: 'your-key' });\n\n\u002F\u002F xAI Grok\nconst grok = ai({ name: 'grok', apiKey: 'your-key' });\n```\n\n### Full Provider Example\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\n\u002F\u002F Create provider with options\nconst llm = ai({\n  name: 'openai',\n  apiKey: process.env.OPENAI_API_KEY!,\n  config: {\n    model: 'gpt-4o',\n    temperature: 0.7,\n    maxTokens: 1000\n  }\n});\n\n\u002F\u002F Use with generator\nconst gen = ax(\n  f()\n    .input('topic', f.string())\n    .output('essay', f.string('A short essay'))\n    .build()\n);\nconst result = await gen.forward(llm, { topic: 'Climate change' });\nconsole.log(result.essay);\n```\n\n## 2. Signatures & Generators\n\nUse the `f()` fluent builder to create type-safe signatures with validation, descriptions, and constraints.\n\n### Basic Signature\n\n```typescript\nimport { ax, f } from '@ax-llm\u002Fax';\n\nconst gen = ax(\n  f()\n    .input('question', f.string('User question'))\n    .output('answer', f.string('AI response'))\n    .build()\n);\n```\n\n### Field Types\n\n```typescript\nimport { f } from '@ax-llm\u002Fax';\n\n\u002F\u002F String types\nf.string('description')               \u002F\u002F Basic string\nf.string().min(10).max(1000)          \u002F\u002F With length constraints\nf.string().email()                    \u002F\u002F Email validation\nf.string().url()                      \u002F\u002F URL validation\nf.string().regex('^[A-Z]', 'Start with capital') \u002F\u002F Pattern\n\n\u002F\u002F Numbers\nf.number('description')\nf.number().min(0).max(100)            \u002F\u002F With range\n\n\u002F\u002F Boolean\nf.boolean('description')\n\n\u002F\u002F Classification\u002FEnum\nf.class(['option1', 'option2', 'option3'], 'description')\n\n\u002F\u002F JSON (any structure)\nf.json('description')\n\n\u002F\u002F Dates and times\nf.date('description')\nf.datetime('description')\n\n\u002F\u002F Media (input only)\nf.image('description')\nf.audio('description')\nf.file('description')\n\n\u002F\u002F Code\nf.code('python', 'description')\n\n\u002F\u002F URL\nf.url('description')\n\n\u002F\u002F Nested objects\nf.object({\n  name: f.string('Person name'),\n  age: f.number('Age in years'),\n  email: f.string().email()\n}, 'Person details')\n\n\u002F\u002F Arrays\nf.string('Item description').array('List of items')\nf.object({ id: f.number(), name: f.string() }).array('List of objects')\n\n\u002F\u002F Modifiers\nf.string().optional()                  \u002F\u002F Optional field\nf.string().internal()                  \u002F\u002F Internal (not shown to LLM)\nf.string().cache()                     \u002F\u002F Enable caching\n```\n\n### Signature Examples\n\n```typescript\nimport { ax, f } from '@ax-llm\u002Fax';\n\n\u002F\u002F Basic Q&A\nconst gen1 = ax(\n  f()\n    .input('question', f.string())\n    .output('answer', f.string())\n    .build()\n);\n\n\u002F\u002F With descriptions\nconst gen2 = ax(\n  f()\n    .input('question', f.string('User question'))\n    .output('answer', f.string('AI response'))\n    .build()\n);\n\n\u002F\u002F Optional fields\nconst gen3 = ax(\n  f()\n    .input('query', f.string())\n    .input('context', f.string('Background context').optional())\n    .output('response', f.string())\n    .build()\n);\n\n\u002F\u002F Arrays\nconst gen4 = ax(\n  f()\n    .input('text', f.string())\n    .output('keywords', f.string().array())\n    .build()\n);\n\n\u002F\u002F Classification (enum)\nconst gen5 = ax(\n  f()\n    .input('review', f.string())\n    .output('sentiment', f.class(['positive', 'negative', 'neutral']))\n    .build()\n);\n\n\u002F\u002F Multiple outputs\nconst gen6 = ax(\n  f()\n    .input('article', f.string())\n    .output('title', f.string())\n    .output('summary', f.string())\n    .output('tags', f.string().array())\n    .build()\n);\n\n\u002F\u002F Numbers and booleans\nconst gen7 = ax(\n  f()\n    .input('text', f.string())\n    .output('wordCount', f.number())\n    .output('isQuestion', f.boolean())\n    .build()\n);\n\n\u002F\u002F JSON output\nconst gen8 = ax(\n  f()\n    .input('data', f.string())\n    .output('parsed', f.json())\n    .build()\n);\n\n\u002F\u002F Dates\nconst gen9 = ax(\n  f()\n    .input('text', f.string())\n    .output('extractedDate', f.date())\n    .build()\n);\n\n\u002F\u002F Code blocks\nconst gen10 = ax(\n  f()\n    .input('task', f.string())\n    .output('code', f.code('python'))\n    .build()\n);\n\n\u002F\u002F Signature description\nconst gen11 = ax(\n  f()\n    .input('text', f.string())\n    .output('translation', f.string())\n    .description('Translate text to French')\n    .build()\n);\n\n\u002F\u002F Nested objects\nconst gen12 = ax(\n  f()\n    .input('document', f.string('Document to analyze'))\n    .input('analysisType', f.class(['sentiment', 'entities', 'summary']))\n    .output('result', f.object({\n      score: f.number().min(0).max(1),\n      label: f.string(),\n      details: f.string().optional()\n    }))\n    .output('entities', f.object({\n      name: f.string(),\n      type: f.class(['person', 'org', 'location'])\n    }).array().optional())\n    .description('Analyze documents')\n    .build()\n);\n```\n\n### Complete Generator Example\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\n\u002F\u002F Create generator with options\nconst summarizer = ax(\n  f()\n    .input('article', f.string('Article to summarize'))\n    .output('summary', f.string('Concise summary'))\n    .output('keyPoints', f.string('Key point').array())\n    .build(),\n  {\n    description: 'Summarize articles and extract key points',\n    maxRetries: 3,\n    maxSteps: 5\n  }\n);\n\n\u002F\u002F Forward (non-streaming)\nconst result = await summarizer.forward(llm, {\n  article: 'Long article text here...'\n});\n\nconsole.log(result.summary);      \u002F\u002F string\nconsole.log(result.keyPoints);    \u002F\u002F string[]\n\n\u002F\u002F With model override\nconst result2 = await summarizer.forward(llm, { article: 'text' }, {\n  model: 'gpt-4o-mini'\n});\n```\n\n### String Shorthand\n\nFor simple cases, you can also use string syntax:\n\n```typescript\nimport { ax } from '@ax-llm\u002Fax';\n\n\u002F\u002F String shorthand: 'inputField:type -> outputField:type'\nconst gen = ax('question:string -> answer:string');\n\n\u002F\u002F Types: string, number, boolean, json, class, date, datetime, image, audio, file, code, url\n\u002F\u002F Modifiers: field?:type (optional), field:type[] (array), field:class \"opt1, opt2\" (enum)\n```\n\n## 3. Streaming\n\n### Basic Streaming\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('topic', f.string())\n    .output('content', f.string())\n    .build()\n);\n\n\u002F\u002F Stream responses\nfor await (const chunk of gen.streamingForward(llm, { topic: 'AI' })) {\n  \u002F\u002F chunk.delta contains partial values\n  if (chunk.delta.content) {\n    process.stdout.write(chunk.delta.content);\n  }\n}\n```\n\n### Complete Streaming Example\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst writer = ax(\n  f()\n    .input('prompt', f.string())\n    .output('story', f.string())\n    .output('title', f.string())\n    .build()\n);\n\nasync function streamStory() {\n  let fullStory = '';\n  let title = '';\n\n  for await (const chunk of writer.streamingForward(\n    llm,\n    { prompt: 'Write a short story about a robot' },\n    { stream: true }\n  )) {\n    \u002F\u002F Handle story chunks\n    if (chunk.delta.story) {\n      process.stdout.write(chunk.delta.story);\n      fullStory += chunk.delta.story;\n    }\n\n    \u002F\u002F Handle title (usually comes early)\n    if (chunk.delta.title) {\n      title = chunk.delta.title;\n    }\n  }\n\n  console.log('\\n\\nTitle:', title);\n  return { story: fullStory, title };\n}\n\nawait streamStory();\n```\n\n### Streaming with Field Processors\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst gen = ax(\n  f()\n    .input('query', f.string())\n    .output('response', f.string())\n    .build()\n);\n\n\u002F\u002F Add streaming field processor\ngen.addStreamingFieldProcessor('response', (chunk, context) => {\n  console.log('Chunk received:', chunk);\n  console.log('Full value so far:', context?.values?.response);\n  console.log('Done:', context?.done);\n});\n\nawait gen.forward(llm, { query: 'Hello' }, { stream: true });\n```\n\n## 4. Agents with Tools\n\nAgents can use functions (tools) to perform actions.\n\n### Defining Functions\n\n```typescript\nimport { ai, agent } from '@ax-llm\u002Fax';\n\n\u002F\u002F Function definition\nconst getCurrentWeather = {\n  name: 'getCurrentWeather',\n  description: 'Get the current weather for a location',\n  parameters: {\n    type: 'object',\n    properties: {\n      location: { type: 'string', description: 'City name' },\n      unit: { type: 'string', enum: ['celsius', 'fahrenheit'] }\n    },\n    required: ['location']\n  },\n  func: async ({ location, unit = 'celsius' }) => {\n    \u002F\u002F Implementation\n    return JSON.stringify({ temp: 22, unit, location });\n  }\n};\n```\n\n### Creating Agents\n\n```typescript\nimport { ai, agent, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\n\u002F\u002F Create agent with functions\nconst weatherAgent = agent(\n  f()\n    .input('query', f.string())\n    .output('response', f.string())\n    .build(),\n  {\n    name: 'weatherAssistant',\n    description: 'An assistant that helps with weather queries',\n    definition: 'You are a helpful weather assistant. Use the getCurrentWeather function to get weather data and provide friendly responses.',\n    functions: [getCurrentWeather]\n  }\n);\n\nconst result = await weatherAgent.forward(llm, {\n  query: 'What is the weather in Tokyo?'\n});\n\nconsole.log(result.response);\n```\n\n### Complete Agent Example\n\n```typescript\nimport { ai, agent, f } from '@ax-llm\u002Fax';\n\n\u002F\u002F Define tools\nconst searchDatabase = {\n  name: 'searchDatabase',\n  description: 'Search the product database',\n  parameters: {\n    type: 'object',\n    properties: {\n      query: { type: 'string', description: 'Search query' },\n      limit: { type: 'number', description: 'Max results' }\n    },\n    required: ['query']\n  },\n  func: async ({ query, limit = 5 }) => {\n    \u002F\u002F Simulate database search\n    return JSON.stringify([\n      { id: 1, name: 'Product A', price: 99 },\n      { id: 2, name: 'Product B', price: 149 }\n    ].slice(0, limit));\n  }\n};\n\nconst getProductDetails = {\n  name: 'getProductDetails',\n  description: 'Get details of a specific product',\n  parameters: {\n    type: 'object',\n    properties: {\n      productId: { type: 'number', description: 'Product ID' }\n    },\n    required: ['productId']\n  },\n  func: async ({ productId }) => {\n    return JSON.stringify({\n      id: productId,\n      name: 'Product A',\n      price: 99,\n      description: 'A great product',\n      stock: 50\n    });\n  }\n};\n\n\u002F\u002F Create agent\nconst shopAssistant = agent(\n  f()\n    .input('userQuery', f.string())\n    .output('response', f.string())\n    .output('recommendations', f.string().array())\n    .build(),\n  {\n    name: 'shoppingAssistant',\n    description: 'An AI assistant that helps users find and learn about products',\n    definition: `You are a helpful shopping assistant. Use the available tools to:\n1. Search for products when users ask about items\n2. Get product details when they want more information\n3. Provide helpful recommendations based on their needs\n\nAlways be friendly and provide clear, helpful responses.`,\n    functions: [searchDatabase, getProductDetails]\n  }\n);\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst result = await shopAssistant.forward(llm, {\n  userQuery: 'Can you find me some products and tell me about the first one?'\n});\n\nconsole.log('Response:', result.response);\nconsole.log('Recommendations:', result.recommendations);\n```\n\n### Nested Agents\n\n```typescript\nimport { ai, agent, f } from '@ax-llm\u002Fax';\n\n\u002F\u002F Child agent\nconst researcher = agent(\n  f()\n    .input('topic', f.string())\n    .output('findings', f.string())\n    .build(),\n  {\n    name: 'researchAgent',\n    description: 'Researches topics and provides detailed findings'\n  }\n);\n\n\u002F\u002F Parent agent that can use child agent\nconst writer = agent(\n  f()\n    .input('topic', f.string())\n    .output('article', f.string())\n    .build(),\n  {\n    name: 'writerAgent',\n    description: 'Writes articles using research from the research agent',\n    agents: [researcher]\n  }\n);\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst result = await writer.forward(llm, {\n  topic: 'Benefits of meditation'\n});\n```\n\n## 5. Workflows (AxFlow)\n\nAxFlow enables building complex, multi-step AI workflows with type safety.\n\n### Basic Flow\n\n```typescript\nimport { ai, flow, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst summarizerSig = f()\n  .input('text', f.string())\n  .output('summary', f.string())\n  .build();\n\nconst translatorSig = f()\n  .input('text', f.string())\n  .output('translation', f.string())\n  .build();\n\nconst pipeline = flow\u003C{ text: string }, { result: string }>()\n  .node('summarizer', summarizerSig)\n  .node('translator', translatorSig)\n  .execute('summarizer', (state) => ({ text: state.text }))\n  .execute('translator', (state) => ({ text: state.summarizerResult.summary }))\n  .map((state) => ({ result: state.translatorResult.translation }));\n\nconst result = await pipeline.forward(llm, { text: 'Long article...' });\nconsole.log(result.result);\n```\n\n### Flow with Branching\n\n```typescript\nimport { ai, flow, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst technicalSig = f()\n  .input('query', f.string())\n  .output('answer', f.string())\n  .build();\n\nconst creativeSig = f()\n  .input('query', f.string())\n  .output('answer', f.string())\n  .build();\n\nconst workflow = flow\u003C{ query: string; type: string }, { output: string }>()\n  .node('technical', technicalSig)\n  .node('creative', creativeSig)\n  .branch(\n    (state) => state.type === 'technical',\n    (branch) => branch.execute('technical', (s) => ({ query: s.query })),\n    (branch) => branch.execute('creative', (s) => ({ query: s.query }))\n  )\n  .map((state) => ({\n    output: state.technicalResult?.answer || state.creativeResult?.answer || ''\n  }));\n\nconst result = await workflow.forward(llm, {\n  query: 'Explain quantum computing',\n  type: 'technical'\n});\n```\n\n### Flow with Parallel Execution\n\n```typescript\nimport { ai, flow, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst prosSig = f()\n  .input('topic', f.string())\n  .output('arguments', f.string())\n  .build();\n\nconst consSig = f()\n  .input('topic', f.string())\n  .output('arguments', f.string())\n  .build();\n\nconst summarySig = f()\n  .input('prosArgs', f.string())\n  .input('consArgs', f.string())\n  .output('summary', f.string())\n  .build();\n\nconst parallelFlow = flow\u003C{ topic: string }, { combined: string }>()\n  .node('pros', prosSig)\n  .node('cons', consSig)\n  .node('summary', summarySig)\n  .parallel([\n    { branch: (b) => b.execute('pros', (s) => ({ topic: s.topic })) },\n    { branch: (b) => b.execute('cons', (s) => ({ topic: s.topic })) }\n  ])\n  .execute('summary', (state) => ({\n    prosArgs: state.prosResult.arguments,\n    consArgs: state.consResult.arguments\n  }))\n  .map((state) => ({ combined: state.summaryResult.summary }));\n\nconst result = await parallelFlow.forward(llm, { topic: 'Remote work' });\n```\n\n### Complete Flow Example\n\n```typescript\nimport { ai, flow, f } from '@ax-llm\u002Fax';\n\n\u002F\u002F Define nodes with proper signatures\nconst researchNode = f()\n  .input('topic', f.string())\n  .output('research', f.string())\n  .output('sources', f.string().array())\n  .build();\n\nconst outlineNode = f()\n  .input('research', f.string())\n  .input('sources', f.string().array())\n  .output('outline', f.string().array())\n  .build();\n\nconst writeNode = f()\n  .input('outline', f.string().array())\n  .input('research', f.string())\n  .output('draft', f.string())\n  .build();\n\nconst editNode = f()\n  .input('draft', f.string())\n  .output('final', f.string())\n  .output('wordCount', f.number())\n  .build();\n\n\u002F\u002F Build the flow\nconst articlePipeline = flow\u003C\n  { topic: string },\n  { article: string; wordCount: number }\n>()\n  .node('research', researchNode)\n  .node('outline', outlineNode)\n  .node('write', writeNode)\n  .node('edit', editNode)\n  .execute('research', (s) => ({ topic: s.topic }))\n  .execute('outline', (s) => ({\n    research: s.researchResult.research,\n    sources: s.researchResult.sources\n  }))\n  .execute('write', (s) => ({\n    outline: s.outlineResult.outline,\n    research: s.researchResult.research\n  }))\n  .execute('edit', (s) => ({\n    draft: s.writeResult.draft\n  }))\n  .map((s) => ({\n    article: s.editResult.final,\n    wordCount: s.editResult.wordCount\n  }));\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst result = await articlePipeline.forward(llm, {\n  topic: 'The future of renewable energy'\n});\n\nconsole.log('Article:', result.article);\nconsole.log('Word count:', result.wordCount);\n```\n\n## 6. Common Patterns\n\n### Classification\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst classifier = ax(\n  f()\n    .input('text', f.string())\n    .output('category', f.class(['spam', 'ham', 'uncertain']))\n    .output('confidence', f.number().min(0).max(1))\n    .build()\n);\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst result = await classifier.forward(llm, {\n  text: 'Congratulations! You won $1,000,000!'\n});\n\nconsole.log(result.category);    \u002F\u002F 'spam'\nconsole.log(result.confidence);  \u002F\u002F 0.95\n```\n\n### Extraction\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst extractor = ax(\n  f()\n    .input('text', f.string())\n    .output('entities', f.object({\n      people: f.string().array(),\n      organizations: f.string().array(),\n      locations: f.string().array()\n    }))\n    .build()\n);\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst result = await extractor.forward(llm, {\n  text: 'Tim Cook announced that Apple will open a new store in Paris on January 15th.'\n});\n\nconsole.log(result.entities.people);        \u002F\u002F ['Tim Cook']\nconsole.log(result.entities.organizations); \u002F\u002F ['Apple']\nconsole.log(result.entities.locations);     \u002F\u002F ['Paris']\n```\n\n### Multi-modal (Images)\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\nimport { readFileSync } from 'fs';\n\nconst imageAnalyzer = ax(\n  f()\n    .input('image', f.image('Image to analyze'))\n    .input('question', f.string('Question about the image').optional())\n    .output('description', f.string('Image description'))\n    .output('objects', f.string().array())\n    .build()\n);\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\n\u002F\u002F From file\nconst imageData = readFileSync('.\u002Fphoto.jpg').toString('base64');\nconst result = await imageAnalyzer.forward(llm, {\n  image: { mimeType: 'image\u002Fjpeg', data: imageData },\n  question: 'What objects are in this image?'\n});\n\n\u002F\u002F From URL (for providers that support it)\nconst result2 = await imageAnalyzer.forward(llm, {\n  image: { mimeType: 'image\u002Fjpeg', url: 'https:\u002F\u002Fexample.com\u002Fimage.jpg' }\n});\n```\n\n### Chaining Generators\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\n\u002F\u002F Define generators\nconst researcher = ax(\n  f()\n    .input('topic', f.string())\n    .output('research', f.string())\n    .output('keyFacts', f.string().array())\n    .build()\n);\n\nconst writer = ax(\n  f()\n    .input('research', f.string())\n    .input('keyFacts', f.string().array())\n    .output('article', f.string())\n    .build()\n);\n\nconst editor = ax(\n  f()\n    .input('article', f.string())\n    .output('editedArticle', f.string())\n    .output('suggestions', f.string().array())\n    .build()\n);\n\n\u002F\u002F Chain them\nasync function createArticle(topic: string) {\n  const research = await researcher.forward(llm, { topic });\n\n  const draft = await writer.forward(llm, {\n    research: research.research,\n    keyFacts: research.keyFacts\n  });\n\n  const final = await editor.forward(llm, {\n    article: draft.article\n  });\n\n  return final;\n}\n\nconst result = await createArticle('Artificial General Intelligence');\nconsole.log(result.editedArticle);\n```\n\n### Error Handling\n\n```typescript\nimport { ai, ax, f, AxGenerateError, AxAIServiceError } from '@ax-llm\u002Fax';\n\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .build()\n);\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\ntry {\n  const result = await gen.forward(llm, { input: 'test' });\n  console.log(result.output);\n} catch (error) {\n  if (error instanceof AxGenerateError) {\n    console.error('Generation failed:', error.message);\n    console.error('Details:', error.details);\n  } else if (error instanceof AxAIServiceError) {\n    console.error('AI service error:', error.message);\n  } else {\n    throw error;\n  }\n}\n```\n\n### Examples and Few-Shot Learning\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst classifier = ax(\n  f()\n    .input('text', f.string())\n    .output('sentiment', f.class(['positive', 'negative', 'neutral']))\n    .build()\n);\n\n\u002F\u002F Set examples for few-shot learning\nclassifier.setExamples([\n  { text: 'I love this product!', sentiment: 'positive' },\n  { text: 'This is terrible.', sentiment: 'negative' },\n  { text: 'It works as expected.', sentiment: 'neutral' }\n]);\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst result = await classifier.forward(llm, {\n  text: 'The quality exceeded my expectations!'\n});\n```\n\n### Assertions and Validation\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst gen = ax(\n  f()\n    .input('number', f.number())\n    .output('doubled', f.number())\n    .build()\n);\n\n\u002F\u002F Add assertion\ngen.addAssert(\n  (output) => output.doubled === output.number * 2,\n  'Output must be double the input'\n);\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\n\u002F\u002F This will retry if assertion fails\nconst result = await gen.forward(llm, { number: 5 }, { maxRetries: 3 });\n```\n\n### Memory and Context\n\n```typescript\nimport { ai, ax, f, AxMemory } from '@ax-llm\u002Fax';\n\nconst chatbot = ax(\n  f()\n    .input('userMessage', f.string())\n    .output('response', f.string())\n    .build()\n);\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\n\u002F\u002F Create shared memory\nconst memory = new AxMemory();\n\n\u002F\u002F Conversation with memory\nawait chatbot.forward(llm, { userMessage: 'My name is Alice' }, { mem: memory });\nconst response = await chatbot.forward(llm, { userMessage: 'What is my name?' }, { mem: memory });\n\u002F\u002F response.response will reference \"Alice\"\n```\n\n## 7. Advanced Configuration\n\n### Model Configuration\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .build()\n);\n\nconst result = await gen.forward(llm, { input: 'test' }, {\n  model: 'gpt-4o',\n  modelConfig: {\n    temperature: 0.7,\n    maxTokens: 2000,\n    topP: 0.9\n  }\n});\n```\n\n### Debugging\n\n```typescript\nimport { ai, ax, f, axCreateDefaultColorLogger } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .build()\n);\n\n\u002F\u002F Enable debug logging\nconst result = await gen.forward(llm, { input: 'test' }, {\n  debug: true,\n  logger: axCreateDefaultColorLogger()\n});\n```\n\n### Context Caching\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst gen = ax(\n  f()\n    .input('document', f.string())\n    .input('question', f.string())\n    .output('answer', f.string())\n    .build()\n);\nconst llm = ai({ name: 'anthropic', apiKey: process.env.ANTHROPIC_API_KEY! });\n\n\u002F\u002F Enable context caching for long documents\nconst result = await gen.forward(llm, {\n  document: longDocument,\n  question: 'What is the main topic?'\n}, {\n  contextCache: {\n    cacheBreakpoint: 'after-examples'\n  }\n});\n```\n\n## 8. Forward & AI Options\n\n### Quick Reference Table\n\n| Goal | Option | Example |\n|------|--------|---------|\n| Adjust creativity | `modelConfig.temperature` | `{ modelConfig: { temperature: 0.8 } }` |\n| Limit response length | `modelConfig.maxTokens` | `{ modelConfig: { maxTokens: 500 } }` |\n| Use different model | `model` | `{ model: 'gpt-4o-mini' }` |\n| Enable caching | `contextCache` | `{ contextCache: { cacheBreakpoint: 'after-examples' } }` |\n| Debug output | `debug` | `{ debug: true }` |\n| Retry on failure | `maxRetries` | `{ maxRetries: 3 }` |\n| Multi-sampling | `sampleCount` | `{ sampleCount: 5, resultPicker: bestResultPicker }` |\n| Thinking models | `thinkingTokenBudget` | `{ thinkingTokenBudget: 10000 }` |\n| Abort request | `abortSignal` | `{ abortSignal: controller.signal }` |\n| Custom timeout | `timeout` | `{ timeout: 60000 }` |\n\n### Execution Control Options\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .build()\n);\n\nconst result = await gen.forward(llm, { input: 'test' }, {\n  \u002F\u002F Retry failed generations (validation failures, API errors)\n  maxRetries: 3,\n\n  \u002F\u002F Maximum agentic steps (for agents with tools)\n  maxSteps: 10,\n\n  \u002F\u002F Fail immediately on first error (don't retry)\n  fastFail: true\n});\n```\n\n### Model Configuration\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .build()\n);\n\nconst result = await gen.forward(llm, { input: 'test' }, {\n  \u002F\u002F Override the model for this request\n  model: 'gpt-4o-mini',\n\n  \u002F\u002F Model-specific configuration\n  modelConfig: {\n    \u002F\u002F Sampling temperature (0.0 = deterministic, 2.0 = creative)\n    temperature: 0.7,\n\n    \u002F\u002F Maximum tokens in response\n    maxTokens: 2000,\n\n    \u002F\u002F Nucleus sampling threshold\n    topP: 0.9,\n\n    \u002F\u002F Top-K sampling (not all providers support this)\n    topK: 40,\n\n    \u002F\u002F Frequency penalty (-2.0 to 2.0)\n    frequencyPenalty: 0.5,\n\n    \u002F\u002F Presence penalty (-2.0 to 2.0)\n    presencePenalty: 0.5,\n\n    \u002F\u002F Stop sequences\n    stopSequences: ['\\n\\n', 'END'],\n\n    \u002F\u002F Seed for reproducible outputs (when supported)\n    seed: 12345,\n\n    \u002F\u002F Response format\n    responseFormat: 'json_object'\n  }\n});\n```\n\n### Context Caching (Gemini\u002FAnthropic)\n\nContext caching saves costs when repeatedly querying with the same large context (documents, system prompts, examples).\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'anthropic', apiKey: process.env.ANTHROPIC_API_KEY! });\nconst gen = ax(\n  f()\n    .input('document', f.string())\n    .input('question', f.string())\n    .output('answer', f.string())\n    .build()\n);\n\nconst longDocument = '... very long document ...';\n\n\u002F\u002F Multiple questions about the same document - caching saves cost\nfor (const question of questions) {\n  const result = await gen.forward(llm, { document: longDocument, question }, {\n    contextCache: {\n      \u002F\u002F Cache name (required for identifying the cache)\n      name: 'doc-analysis-cache',\n\n      \u002F\u002F Where to split the prompt for caching:\n      \u002F\u002F - 'system': Cache system prompt only\n      \u002F\u002F - 'after-functions': Cache system + function definitions\n      \u002F\u002F - 'after-examples': Cache system + functions + examples\n      cacheBreakpoint: 'after-examples',\n\n      \u002F\u002F Cache time-to-live in seconds (default: provider-specific)\n      ttlSeconds: 3600,\n\n      \u002F\u002F Minimum tokens to trigger caching (avoid caching small prompts)\n      minTokens: 1000,\n\n      \u002F\u002F Refresh cache when within this window of expiry\n      refreshWindowSeconds: 300,\n\n      \u002F\u002F Custom cache registry for external storage (Redis, etc.)\n      registry: customCacheRegistry\n    }\n  });\n}\n```\n\n### Thinking Models (o1, o3, Gemini 2.0 Flash Thinking)\n\nFor reasoning models that support extended thinking:\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('problem', f.string())\n    .output('solution', f.string())\n    .build()\n);\n\nconst result = await gen.forward(llm, { problem: 'Complex math problem' }, {\n  model: 'o1',\n\n  \u002F\u002F Token budget for thinking\u002Freasoning (model-specific)\n  thinkingTokenBudget: 10000,\n\n  \u002F\u002F Include thinking in output (when supported)\n  showThoughts: true,\n\n  \u002F\u002F Custom field name for thoughts in output\n  thoughtFieldName: 'reasoning'\n});\n```\n\n### Multi-Sampling for Quality\n\nGenerate multiple samples and pick the best one:\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .output('confidence', f.number())\n    .build()\n);\n\nconst result = await gen.forward(llm, { input: 'test' }, {\n  \u002F\u002F Generate multiple samples\n  sampleCount: 5,\n\n  \u002F\u002F Pick the best result (custom function)\n  resultPicker: (results) => {\n    \u002F\u002F Return the result with highest confidence\n    return results.reduce((best, current) =>\n      current.confidence > best.confidence ? current : best\n    );\n  }\n});\n```\n\n### Function Calling Configuration\n\nControl how agents use tools\u002Ffunctions:\n\n```typescript\nimport { ai, agent, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst myAgent = agent(\n  f()\n    .input('query', f.string())\n    .output('answer', f.string())\n    .build(),\n  {\n    name: 'toolAgent',\n    description: 'An agent that uses tools to answer queries',\n    functions: [searchTool, calculatorTool]\n  }\n);\n\nconst result = await myAgent.forward(llm, { query: 'test' }, {\n  \u002F\u002F Function calling mode:\n  \u002F\u002F - 'auto': Model decides when to call functions\n  \u002F\u002F - 'none': Disable function calling\n  \u002F\u002F - 'required': Force at least one function call\n  functionCallMode: 'auto',\n\n  \u002F\u002F Force a specific function to be called\n  functionCall: 'searchTool',\n\n  \u002F\u002F Stop after this function is called\n  stopFunction: 'finalAnswer',\n\n  \u002F\u002F Override available functions for this request\n  functions: [searchTool],\n\n  \u002F\u002F Custom caching for function results\n  cachingFunction: async (funcName, args) => {\n    const cacheKey = `${funcName}:${JSON.stringify(args)}`;\n    return await cache.get(cacheKey);\n  }\n});\n```\n\n### Debugging & Observability\n\n```typescript\nimport { ai, ax, f, axCreateDefaultColorLogger } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .build()\n);\n\nconst result = await gen.forward(llm, { input: 'test' }, {\n  \u002F\u002F Enable debug logging\n  debug: true,\n\n  \u002F\u002F Show verbose output (more details)\n  verbose: true,\n\n  \u002F\u002F Hide system prompt in debug output (security)\n  debugHideSystemPrompt: true,\n\n  \u002F\u002F Custom logger\n  logger: axCreateDefaultColorLogger(),\n\n  \u002F\u002F OpenTelemetry tracer for distributed tracing\n  tracer: openTelemetryTracer,\n\n  \u002F\u002F OpenTelemetry meter for metrics\n  meter: openTelemetryMeter,\n\n  \u002F\u002F Parent trace context\n  traceContext: parentSpan,\n\n  \u002F\u002F Custom labels for traces\u002Fmetrics\n  customLabels: { environment: 'production', version: '1.0' },\n\n  \u002F\u002F Exclude content from traces (privacy)\n  excludeContentFromTrace: true\n});\n```\n\n### Retry & Error Handling\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({\n  name: 'openai',\n  apiKey: process.env.OPENAI_API_KEY!,\n  options: {\n    \u002F\u002F Retry configuration for API calls\n    retry: {\n      \u002F\u002F Maximum retry attempts\n      maxRetries: 3,\n\n      \u002F\u002F Initial delay between retries (ms)\n      initialDelayMs: 1000,\n\n      \u002F\u002F Maximum delay between retries (ms)\n      maxDelayMs: 30000,\n\n      \u002F\u002F Backoff multiplier\n      backoffMultiplier: 2,\n\n      \u002F\u002F Jitter factor (0-1) to randomize delays\n      jitterFactor: 0.1,\n\n      \u002F\u002F HTTP status codes to retry on\n      retryOnStatusCodes: [429, 500, 502, 503, 504]\n    },\n\n    \u002F\u002F Rate limiter for API calls\n    rateLimiter: customRateLimiter,\n\n    \u002F\u002F Request timeout (ms)\n    timeout: 60000\n  }\n});\n```\n\n### Request Control\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .build()\n);\n\n\u002F\u002F Create abort controller\nconst controller = new AbortController();\n\n\u002F\u002F Cancel after 5 seconds\nsetTimeout(() => controller.abort(), 5000);\n\ntry {\n  const result = await gen.forward(llm, { input: 'test' }, {\n    \u002F\u002F Abort signal for cancellation\n    abortSignal: controller.signal,\n\n    \u002F\u002F Request timeout (ms)\n    timeout: 30000,\n\n    \u002F\u002F Custom fetch function (for proxies, etc.)\n    fetch: customFetch,\n\n    \u002F\u002F CORS proxy URL (for browser environments)\n    corsProxy: 'https:\u002F\u002Fcors-proxy.example.com'\n  });\n} catch (error) {\n  if (error.name === 'AbortError') {\n    console.log('Request was cancelled');\n  }\n}\n```\n\n### Memory Configuration\n\n```typescript\nimport { ai, ax, f, AxMemory } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('message', f.string())\n    .output('response', f.string())\n    .build()\n);\n\nconst memory = new AxMemory();\n\nconst result = await gen.forward(llm, { message: 'Hello' }, {\n  \u002F\u002F Use shared memory for conversation context\n  mem: memory,\n\n  \u002F\u002F Disable automatic memory cleanup (keep all messages)\n  disableMemoryCleanup: true\n});\n```\n\n### Validation Options\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .build()\n);\n\nconst result = await gen.forward(llm, { input: 'test' }, {\n  \u002F\u002F Strict mode: fail on any validation error\n  strictMode: true,\n\n  \u002F\u002F Custom assertions (run after generation)\n  asserts: [\n    {\n      fn: (output) => output.output.length > 10,\n      message: 'Output must be longer than 10 characters'\n    }\n  ],\n\n  \u002F\u002F Streaming assertions (run during streaming)\n  streamingAsserts: [\n    {\n      fn: (partial) => !partial.output?.includes('forbidden'),\n      message: 'Output must not contain forbidden content'\n    }\n  ]\n});\n```\n\n## 9. MCP Integration\n\nMCP (Model Context Protocol) enables AxAgent to use external tools from MCP-compliant servers. This allows your agents to interact with databases, file systems, APIs, and other services through a standardized protocol.\n\n### Quick Start\n\n```typescript\nimport { AxAgent, AxAI, AxMCPClient } from '@ax-llm\u002Fax';\nimport { AxMCPStdioTransport } from '@ax-llm\u002Fax-tools';\n\n\u002F\u002F Create transport for local MCP server\nconst transport = new AxMCPStdioTransport({\n  command: 'npx',\n  args: ['-y', '@modelcontextprotocol\u002Fserver-memory'],\n});\n\n\u002F\u002F Initialize MCP client\nconst mcpClient = new AxMCPClient(transport, { debug: false });\nawait mcpClient.init();\n\n\u002F\u002F Create agent with MCP functions\nconst agent = new AxAgent({\n  name: 'MyAssistant',\n  description: 'An assistant with MCP capabilities',\n  signature: f()\n    .input('userMessage', f.string())\n    .output('response', f.string())\n    .build(),\n  functions: [mcpClient],  \u002F\u002F Pass client directly\n});\n\nconst ai = new AxAI({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst result = await agent.forward(ai, { userMessage: 'Hello' });\n```\n\n### MCP Transports\n\n#### AxMCPStdioTransport (Local Servers)\n\nFor MCP servers that run as local processes via stdin\u002Fstdout:\n\n```typescript\nimport { AxMCPStdioTransport } from '@ax-llm\u002Fax-tools';\n\nconst transport = new AxMCPStdioTransport({\n  command: 'npx',\n  args: ['-y', '@modelcontextprotocol\u002Fserver-memory'],\n});\n\n\u002F\u002F Clean up when done\nawait transport.terminate();\n```\n\n#### AxMCPStreambleHTTPTransport (Remote Servers)\n\nFor MCP servers accessible via HTTP (e.g., Pipedream, hosted services):\n\n```typescript\nimport { AxMCPStreambleHTTPTransport } from '@ax-llm\u002Fax\u002Fmcp\u002Ftransports\u002FhttpStreamTransport.js';\n\nconst transport = new AxMCPStreambleHTTPTransport(\n  'https:\u002F\u002Fremote.mcp.pipedream.net',\n  {\n    headers: {\n      'x-pd-project-id': projectId,\n      'x-pd-environment': 'development',\n      'x-pd-external-user-id': 'user123',\n      'x-pd-app-slug': 'notion',\n    },\n    authorization: `Bearer ${accessToken}`,\n  }\n);\n```\n\n### Using MCP with Agents\n\nPass the MCP client directly to the agent's `functions` array:\n\n```typescript\nimport { AxAgent, AxAI, AxMCPClient, f } from '@ax-llm\u002Fax';\nimport { AxMCPStdioTransport } from '@ax-llm\u002Fax-tools';\n\nconst transport = new AxMCPStdioTransport({\n  command: 'npx',\n  args: ['-y', '@modelcontextprotocol\u002Fserver-memory'],\n});\n\nconst mcpClient = new AxMCPClient(transport);\nawait mcpClient.init();\n\nconst memoryAgent = new AxAgent\u003C\n  { userMessage: string; userId: string },\n  { assistantResponse: string }\n>({\n  name: 'MemoryAssistant',\n  description: 'An assistant that remembers past conversations. Use the database functions to manage, search, and add memories.',\n  signature: f()\n    .input('userMessage', f.string())\n    .input('userId', f.string())\n    .output('assistantResponse', f.string())\n    .build(),\n  functions: [mcpClient],\n});\n\nconst ai = new AxAI({\n  name: 'openai',\n  apiKey: process.env.OPENAI_API_KEY!,\n  config: { model: 'gpt-4o-mini' }\n});\n\n\u002F\u002F First interaction - stores memory\nconst first = await memoryAgent.forward(ai, {\n  userMessage: 'My name is Alice and my favorite color is blue.',\n  userId: 'user123',\n});\n\n\u002F\u002F Later interaction - retrieves memory\nconst second = await memoryAgent.forward(ai, {\n  userMessage: \"What's my favorite color?\",\n  userId: 'user123',\n});\n```\n\n### MCP Capabilities\n\nMCP servers can provide three types of capabilities:\n\n| Capability | Function Prefix | Description |\n|------------|-----------------|-------------|\n| **Tools** | *(none)* | Traditional function calls (e.g., `search`, `create`) |\n| **Prompts** | `prompt_` | Prompt templates (e.g., `prompt_summarize`) |\n| **Resources** | `resource_` | File\u002Fdata access (e.g., `resource_config_json`) |\n\nCheck available capabilities:\n\n```typescript\nconst mcpClient = new AxMCPClient(transport);\nawait mcpClient.init();\n\nconst caps = mcpClient.getCapabilities();\nconsole.log('Tools:', caps.tools);      \u002F\u002F true\u002Ffalse\nconsole.log('Prompts:', caps.prompts);  \u002F\u002F true\u002Ffalse\nconsole.log('Resources:', caps.resources); \u002F\u002F true\u002Ffalse\n\n\u002F\u002F Or check individually\nif (mcpClient.hasToolsCapability()) {\n  console.log('Server supports tools');\n}\n```\n\n### Function Overrides\n\nCustomize function names and descriptions while preserving functionality:\n\n```typescript\nconst mcpClient = new AxMCPClient(transport, {\n  functionOverrides: [\n    {\n      name: 'search_documents',\n      updates: {\n        name: 'findDocs',\n        description: 'Search through all available documents'\n      }\n    },\n    {\n      name: 'prompt_summarize',\n      updates: {\n        name: 'getSummaryPrompt',\n        description: 'Get a prompt template for summarization'\n      }\n    }\n  ]\n});\n```\n\n### Getting Functions Directly\n\nIf you need the function array instead of passing the client:\n\n```typescript\nconst mcpClient = new AxMCPClient(transport);\nawait mcpClient.init();\n\n\u002F\u002F Get all functions (tools + prompts + resources)\nconst functions = mcpClient.toFunction();\n\n\u002F\u002F Use with agent\nconst agent = new AxAgent({\n  name: 'MyAgent',\n  signature: f()\n    .input('query', f.string())\n    .output('answer', f.string())\n    .build(),\n  functions: functions,  \u002F\u002F Or spread: [...functions, otherFunction]\n});\n```\n\n### Complete Example: Remote HTTP MCP Server\n\n```typescript\nimport { AxAgent, AxAI, AxMCPClient, f } from '@ax-llm\u002Fax';\nimport { AxMCPStreambleHTTPTransport } from '@ax-llm\u002Fax\u002Fmcp\u002Ftransports\u002FhttpStreamTransport.js';\nimport { createBackendClient } from '@pipedream\u002Fsdk\u002Fserver';\n\n\u002F\u002F Initialize Pipedream SDK\nconst pd = createBackendClient({\n  environment: 'development',\n  credentials: {\n    clientId: process.env.PIPEDREAM_CLIENT_ID!,\n    clientSecret: process.env.PIPEDREAM_CLIENT_SECRET!,\n  },\n  projectId: process.env.PIPEDREAM_PROJECT_ID!,\n});\n\n\u002F\u002F Get access token and app info\nconst accessToken = await pd.rawAccessToken();\nconst apps = await pd.getApps({ q: 'notion' });\nconst appSlug = apps.data[0]?.name_slug;\n\n\u002F\u002F Create HTTP transport for Pipedream MCP\nconst httpTransport = new AxMCPStreambleHTTPTransport(\n  'https:\u002F\u002Fremote.mcp.pipedream.net',\n  {\n    headers: {\n      'x-pd-project-id': process.env.PIPEDREAM_PROJECT_ID!,\n      'x-pd-environment': 'development',\n      'x-pd-external-user-id': 'user123',\n      'x-pd-app-slug': appSlug!,\n    },\n    authorization: `Bearer ${accessToken}`,\n  }\n);\n\n\u002F\u002F Initialize MCP client\nconst mcpClient = new AxMCPClient(httpTransport, { debug: false });\nawait mcpClient.init();\n\n\u002F\u002F Create Notion agent\nconst notionAgent = new AxAgent\u003C\n  { userRequest: string },\n  { assistantResponse: string }\n>({\n  name: 'NotionAssistant',\n  description: 'An assistant that can interact with Notion documents. Use the provided functions to read, search, and analyze Notion content.',\n  signature: f()\n    .input('userRequest', f.string())\n    .output('assistantResponse', f.string())\n    .build(),\n  functions: [mcpClient],\n});\n\nconst ai = new AxAI({\n  name: 'openai',\n  apiKey: process.env.OPENAI_API_KEY!,\n  config: { model: 'gpt-4o-mini' }\n});\n\n\u002F\u002F Use the agent\nconst response = await notionAgent.forward(ai, {\n  userRequest: 'Summarize my most recently created Notion doc'\n});\nconsole.log(response.assistantResponse);\n```\n\n### Example Files\n\nFull working examples on GitHub:\n\n- [Local Memory Server (stdio)](https:\u002F\u002Fraw.githubusercontent.com\u002Fax-llm\u002Fax\u002Frefs\u002Fheads\u002Fmain\u002Fsrc\u002Fexamples\u002Fmcp-client-memory.ts) - Memory-augmented agent using local MCP server\n- [Remote HTTP Server (Pipedream\u002FNotion)](https:\u002F\u002Fraw.githubusercontent.com\u002Fax-llm\u002Fax\u002Frefs\u002Fheads\u002Fmain\u002Fsrc\u002Fexamples\u002Fmcp-client-pipedream.ts) - Notion integration via Pipedream MCP\n\n## Type Reference\n\n```typescript\n\u002F\u002F Core types\ntype AxGenIn = Record\u003Cstring, any>;\ntype AxGenOut = Record\u003Cstring, any>;\n\n\u002F\u002F Generator\nclass AxGen\u003CIN, OUT> {\n  forward(ai: AxAIService, values: IN, options?: AxProgramForwardOptions): Promise\u003COUT>;\n  streamingForward(ai: AxAIService, values: IN, options?: AxProgramStreamingForwardOptions): AsyncGenerator\u003C{ delta: Partial\u003COUT> }>;\n  setExamples(examples: Array\u003CPartial\u003CIN & OUT>>): void;\n  addAssert(fn: (output: OUT) => boolean, message?: string): void;\n  addFieldProcessor(field: keyof OUT, fn: (value: any) => any): void;\n  addStreamingFieldProcessor(field: keyof OUT, fn: (chunk: string, ctx: any) => void): void;\n}\n\n\u002F\u002F Agent\nclass AxAgent\u003CIN, OUT> {\n  forward(ai: AxAIService, values: IN, options?: AxAgentOptions): Promise\u003COUT>;\n  streamingForward(ai: AxAIService, values: IN, options?: AxAgentOptions): AsyncGenerator\u003C{ delta: Partial\u003COUT> }>;\n  getFunction(): AxFunction;\n}\n\n\u002F\u002F Flow\nclass AxFlow\u003CIN, OUT, TNodes, TState> {\n  node(name: string, signature: string | AxSignature): AxFlow;\n  execute(nodeName: string, inputMapper: (state: TState) => any): AxFlow;\n  map(transformer: (state: TState) => OUT): AxFlow;\n  branch(condition: (state: TState) => boolean, ifTrue: FlowBranch, ifFalse: FlowBranch): AxFlow;\n  parallel(branches: ParallelBranch[]): AxFlow;\n  forward(ai: AxAIService, input: IN): Promise\u003COUT>;\n}\n```\n","# Ax Library (@ax-llm\u002Fax) Usage Guide\n\nAx is a TypeScript library for building LLM-powered applications with type-safe signatures, streaming support, and multi-provider compatibility.\n\n## Quick Reference\n\n```typescript\nimport { ax, ai, f, agent, flow, AxGen, AxAgent, AxFlow } from '@ax-llm\u002Fax';\n\n\u002F\u002F Create AI provider\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY });\n\n\u002F\u002F Create typed generator using f() fluent API\nconst gen = ax(\n  f()\n    .input('question', f.string('User question'))\n    .output('answer', f.string('AI response'))\n    .build()\n);\nconst result = await gen.forward(llm, { question: 'What is 2+2?' });\n\u002F\u002F result.answer is typed as string\n```\n\n## 1. AI Provider Setup\n\n### Quick Setup (All Providers)\n\n```typescript\nimport { ai } from '@ax-llm\u002Fax';\n\n\u002F\u002F OpenAI\nconst openai = ai({ name: 'openai', apiKey: 'sk-...' });\n\n\u002F\u002F Anthropic Claude\nconst claude = ai({ name: 'anthropic', apiKey: 'sk-ant-...' });\n\n\u002F\u002F Google Gemini\nconst gemini = ai({ name: 'google-gemini', apiKey: 'AIza...' });\n\n\u002F\u002F Azure OpenAI\nconst azure = ai({\n  name: 'azure-openai',\n  apiKey: 'your-key',\n  resourceName: 'your-resource',\n  deploymentName: 'gpt-4'\n});\n\n\u002F\u002F Groq\nconst groq = ai({ name: 'groq', apiKey: 'gsk_...' });\n\n\u002F\u002F DeepSeek\nconst deepseek = ai({ name: 'deepseek', apiKey: 'sk-...' });\n\n\u002F\u002F Mistral\nconst mistral = ai({ name: 'mistral', apiKey: 'your-key' });\n\n\u002F\u002F Cohere\nconst cohere = ai({ name: 'cohere', apiKey: 'your-key' });\n\n\u002F\u002F Together AI\nconst together = ai({ name: 'together', apiKey: 'your-key' });\n\n\u002F\u002F OpenRouter\nconst openrouter = ai({ name: 'openrouter', apiKey: 'your-key' });\n\n\u002F\u002F Ollama (local)\nconst ollama = ai({ name: 'ollama', url: 'http:\u002F\u002Flocalhost:11434' });\n\n\u002F\u002F HuggingFace\nconst hf = ai({ name: 'huggingface', apiKey: 'hf_...' });\n\n\u002F\u002F Reka\nconst reka = ai({ name: 'reka', apiKey: 'your-key' });\n\n\u002F\u002F xAI Grok\nconst grok = ai({ name: 'grok', apiKey: 'your-key' });\n```\n\n### Full Provider Example\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\n\u002F\u002F Create provider with options\nconst llm = ai({\n  name: 'openai',\n  apiKey: process.env.OPENAI_API_KEY!,\n  config: {\n    model: 'gpt-4o',\n    temperature: 0.7,\n    maxTokens: 1000\n  }\n});\n\n\u002F\u002F Use with generator\nconst gen = ax(\n  f()\n    .input('topic', f.string())\n    .output('essay', f.string('A short essay'))\n    .build()\n);\nconst result = await gen.forward(llm, { topic: 'Climate change' });\nconsole.log(result.essay);\n```\n\n## 2. Signatures & Generators\n\nUse the `f()` fluent builder to create type-safe signatures with validation, descriptions, and constraints.\n\n### Basic Signature\n\n```typescript\nimport { ax, f } from '@ax-llm\u002Fax';\n\nconst gen = ax(\n  f()\n    .input('question', f.string('User question'))\n    .output('answer', f.string('AI response'))\n    .build()\n);\n```\n\n### Field Types\n\n```typescript\nimport { f } from '@ax-llm\u002Fax';\n\n\u002F\u002F String types\nf.string('description')               \u002F\u002F Basic string\nf.string().min(10).max(1000)          \u002F\u002F With length constraints\nf.string().email()                    \u002F\u002F Email validation\nf.string().url()                      \u002F\u002F URL validation\nf.string().regex('^[A-Z]', 'Start with capital') \u002F\u002F Pattern\n\n\u002F\u002F Numbers\nf.number('description')\nf.number().min(0).max(100)            \u002F\u002F With range\n\n\u002F\u002F Boolean\nf.boolean('description')\n\n\u002F\u002F Classification\u002FEnum\nf.class(['option1', 'option2', 'option3'], 'description')\n\n\u002F\u002F JSON (any structure)\nf.json('description')\n\n\u002F\u002F Dates and times\nf.date('description')\nf.datetime('description')\n\n\u002F\u002F Media (input only)\nf.image('description')\nf.audio('description')\nf.file('description')\n\n\u002F\u002F Code\nf.code('python', 'description')\n\n\u002F\u002F URL\nf.url('description')\n\n\u002F\u002F Nested objects\nf.object({\n  name: f.string('Person name'),\n  age: f.number('Age in years'),\n  email: f.string().email()\n}, 'Person details')\n\n\u002F\u002F Arrays\nf.string('Item description').array('List of items')\nf.object({ id: f.number(), name: f.string() }).array('List of objects')\n\n\u002F\u002F Modifiers\nf.string().optional()                  \u002F\u002F Optional field\nf.string().internal()                  \u002F\u002F Internal (not shown to LLM)\nf.string().cache()                     \u002F\u002F Enable caching\n```\n\n### Signature Examples\n\n```typescript\nimport { ax, f } from '@ax-llm\u002Fax';\n\n\u002F\u002F Basic Q&A\nconst gen1 = ax(\n  f()\n    .input('question', f.string())\n    .output('answer', f.string())\n    .build()\n);\n\n\u002F\u002F With descriptions\nconst gen2 = ax(\n  f()\n    .input('question', f.string('User question'))\n    .output('answer', f.string('AI response'))\n    .build()\n);\n\n\u002F\u002F Optional fields\nconst gen3 = ax(\n  f()\n    .input('query', f.string())\n    .input('context', f.string('Background context').optional())\n    .output('response', f.string())\n    .build()\n);\n\n\u002F\u002F Arrays\nconst gen4 = ax(\n  f()\n    .input('text', f.string())\n    .output('keywords', f.string().array())\n    .build()\n);\n\n\u002F\u002F Classification (enum)\nconst gen5 = ax(\n  f()\n    .input('review', f.string())\n    .output('sentiment', f.class(['positive', 'negative', 'neutral']))\n    .build()\n);\n\n\u002F\u002F Multiple outputs\nconst gen6 = ax(\n  f()\n    .input('article', f.string())\n    .output('title', f.string())\n    .output('summary', f.string())\n    .output('tags', f.string().array())\n    .build()\n);\n\n\u002F\u002F Numbers and booleans\nconst gen7 = ax(\n  f()\n    .input('text', f.string())\n    .output('wordCount', f.number())\n    .output('isQuestion', f.boolean())\n    .build()\n);\n\n\u002F\u002F JSON output\nconst gen8 = ax(\n  f()\n    .input('data', f.string())\n    .output('parsed', f.json())\n    .build()\n);\n\n\u002F\u002F Dates\nconst gen9 = ax(\n  f()\n    .input('text', f.string())\n    .output('extractedDate', f.date())\n    .build()\n);\n\n\u002F\u002F Code blocks\nconst gen10 = ax(\n  f()\n    .input('task', f.string())\n    .output('code', f.code('python'))\n    .build()\n);\n\n\u002F\u002F Signature description\nconst gen11 = ax(\n  f()\n    .input('text', f.string())\n    .output('translation', f.string())\n    .description('Translate text to French')\n    .build()\n);\n\n\u002F\u002F Nested objects\nconst gen12 = ax(\n  f()\n    .input('document', f.string('Document to analyze'))\n    .input('analysisType', f.class(['sentiment', 'entities', 'summary']))\n    .output('result', f.object({\n      score: f.number().min(0).max(1),\n      label: f.string(),\n      details: f.string().optional()\n    }))\n    .output('entities', f.object({\n      name: f.string(),\n      type: f.class(['person', 'org', 'location'])\n    }).array().optional())\n    .description('Analyze documents')\n    .build()\n);\n```\n\n### Complete Generator Example\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\n\u002F\u002F Create generator with options\nconst summarizer = ax(\n  f()\n    .input('article', f.string('Article to summarize'))\n    .output('summary', f.string('Concise summary'))\n    .output('keyPoints', f.string('Key point').array())\n    .build(),\n  {\n    description: 'Summarize articles and extract key points',\n    maxRetries: 3,\n    maxSteps: 5\n  }\n);\n\n\u002F\u002F Forward (non-streaming)\nconst result = await summarizer.forward(llm, {\n  article: 'Long article text here...'\n});\n\nconsole.log(result.summary);      \u002F\u002F string\nconsole.log(result.keyPoints);    \u002F\u002F string[]\n\n\u002F\u002F With model override\nconst result2 = await summarizer.forward(llm, { article: 'text' }, {\n  model: 'gpt-4o-mini'\n});\n```\n\n### String Shorthand\n\nFor simple cases, you can also use string syntax:\n\n```typescript\nimport { ax } from '@ax-llm\u002Fax';\n\n\u002F\u002F String shorthand: 'inputField:type -> outputField:type'\nconst gen = ax('question:string -> answer:string');\n\n\u002F\u002F Types: string, number, boolean, json, class, date, datetime, image, audio, file, code, url\n\u002F\u002F Modifiers: field?:type (optional), field:type[] (array), field:class \"opt1, opt2\" (enum)\n```\n\n## 3. Streaming\n\n### Basic Streaming\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('topic', f.string())\n    .output('content', f.string())\n    .build()\n);\n\n\u002F\u002F Stream responses\nfor await (const chunk of gen.streamingForward(llm, { topic: 'AI' })) {\n  \u002F\u002F chunk.delta contains partial values\n  if (chunk.delta.content) {\n    process.stdout.write(chunk.delta.content);\n  }\n}\n```\n\n### Complete Streaming Example\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst writer = ax(\n  f()\n    .input('prompt', f.string())\n    .output('story', f.string())\n    .output('title', f.string())\n    .build()\n);\n\nasync function streamStory() {\n  let fullStory = '';\n  let title = '';\n\n  for await (const chunk of writer.streamingForward(\n    llm,\n    { prompt: 'Write a short story about a robot' },\n    { stream: true }\n  )) {\n    \u002F\u002F Handle story chunks\n    if (chunk.delta.story) {\n      process.stdout.write(chunk.delta.story);\n      fullStory += chunk.delta.story;\n    }\n\n    \u002F\u002F Handle title (usually comes early)\n    if (chunk.delta.title) {\n      title = chunk.delta.title;\n    }\n  }\n\n  console.log('\\n\\nTitle:', title);\n  return { story: fullStory, title };\n}\n\nawait streamStory();\n```\n\n### Streaming with Field Processors\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst gen = ax(\n  f()\n    .input('query', f.string())\n    .output('response', f.string())\n    .build()\n);\n\n\u002F\u002F Add streaming field processor\ngen.addStreamingFieldProcessor('response', (chunk, context) => {\n  console.log('Chunk received:', chunk);\n  console.log('Full value so far:', context?.values?.response);\n  console.log('Done:', context?.done);\n});\n\nawait gen.forward(llm, { query: 'Hello' }, { stream: true });\n```\n\n## 4. Agents with Tools\n\nAgents can use functions (tools) to perform actions.\n\n### Defining Functions\n\n```typescript\nimport { ai, agent } from '@ax-llm\u002Fax';\n\n\u002F\u002F Function definition\nconst getCurrentWeather = {\n  name: 'getCurrentWeather',\n  description: 'Get the current weather for a location',\n  parameters: {\n    type: 'object',\n    properties: {\n      location: { type: 'string', description: 'City name' },\n      unit: { type: 'string', enum: ['celsius', 'fahrenheit'] }\n    },\n    required: ['location']\n  },\n  func: async ({ location, unit = 'celsius' }) => {\n    \u002F\u002F Implementation\n    return JSON.stringify({ temp: 22, unit, location });\n  }\n};\n```\n\n### Creating Agents\n\n```typescript\nimport { ai, agent, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\n\u002F\u002F Create agent with functions\nconst weatherAgent = agent(\n  f()\n    .input('query', f.string())\n    .output('response', f.string())\n    .build(),\n  {\n    name: 'weatherAssistant',\n    description: 'An assistant that helps with weather queries',\n    definition: 'You are a helpful weather assistant. Use the getCurrentWeather function to get weather data and provide friendly responses.',\n    functions: [getCurrentWeather]\n  }\n);\n\nconst result = await weatherAgent.forward(llm, {\n  query: 'What is the weather in Tokyo?'\n});\n\nconsole.log(result.response);\n```\n\n### Complete Agent Example\n\n```typescript\nimport { ai, agent, f } from '@ax-llm\u002Fax';\n\n\u002F\u002F Define tools\nconst searchDatabase = {\n  name: 'searchDatabase',\n  description: 'Search the product database',\n  parameters: {\n    type: 'object',\n    properties: {\n      query: { type: 'string', description: 'Search query' },\n      limit: { type: 'number', description: 'Max results' }\n    },\n    required: ['query']\n  },\n  func: async ({ query, limit = 5 }) => {\n    \u002F\u002F Simulate database search\n    return JSON.stringify([\n      { id: 1, name: 'Product A', price: 99 },\n      { id: 2, name: 'Product B', price: 149 }\n    ].slice(0, limit));\n  }\n};\n\nconst getProductDetails = {\n  name: 'getProductDetails',\n  description: 'Get details of a specific product',\n  parameters: {\n    type: 'object',\n    properties: {\n      productId: { type: 'number', description: 'Product ID' }\n    },\n    required: ['productId']\n  },\n  func: async ({ productId }) => {\n    return JSON.stringify({\n      id: productId,\n      name: 'Product A',\n      price: 99,\n      description: 'A great product',\n      stock: 50\n    });\n  }\n};\n\n\u002F\u002F Create agent\nconst shopAssistant = agent(\n  f()\n    .input('userQuery', f.string())\n    .output('response', f.string())\n    .output('recommendations', f.string().array())\n    .build(),\n  {\n    name: 'shoppingAssistant',\n    description: 'An AI assistant that helps users find and learn about products',\n    definition: `You are a helpful shopping assistant. Use the available tools to:\n1. Search for products when users ask about items\n2. Get product details when they want more information\n3. Provide helpful recommendations based on their needs\n\nAlways be friendly and provide clear, helpful responses.`,\n    functions: [searchDatabase, getProductDetails]\n  }\n);\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst result = await shopAssistant.forward(llm, {\n  userQuery: 'Can you find me some products and tell me about the first one?'\n});\n\nconsole.log('Response:', result.response);\nconsole.log('Recommendations:', result.recommendations);\n```\n\n### Nested Agents\n\n```typescript\nimport { ai, agent, f } from '@ax-llm\u002Fax';\n\n\u002F\u002F Child agent\nconst researcher = agent(\n  f()\n    .input('topic', f.string())\n    .output('findings', f.string())\n    .build(),\n  {\n    name: 'researchAgent',\n    description: 'Researches topics and provides detailed findings'\n  }\n);\n\n\u002F\u002F Parent agent that can use child agent\nconst writer = agent(\n  f()\n    .input('topic', f.string())\n    .output('article', f.string())\n    .build(),\n  {\n    name: 'writerAgent',\n    description: 'Writes articles using research from the research agent',\n    agents: [researcher]\n  }\n);\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst result = await writer.forward(llm, {\n  topic: 'Benefits of meditation'\n});\n```\n\n## 5. Workflows (AxFlow)\n\nAxFlow enables building complex, multi-step AI workflows with type safety.\n\n### Basic Flow\n\n```typescript\nimport { ai, flow, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst summarizerSig = f()\n  .input('text', f.string())\n  .output('summary', f.string())\n  .build();\n\nconst translatorSig = f()\n  .input('text', f.string())\n  .output('translation', f.string())\n  .build();\n\nconst pipeline = flow\u003C{ text: string }, { result: string }>()\n  .node('summarizer', summarizerSig)\n  .node('translator', translatorSig)\n  .execute('summarizer', (state) => ({ text: state.text }))\n  .execute('translator', (state) => ({ text: state.summarizerResult.summary }))\n  .map((state) => ({ result: state.translatorResult.translation }));\n\nconst result = await pipeline.forward(llm, { text: 'Long article...' });\nconsole.log(result.result);\n```\n\n### Flow with Branching\n\n```typescript\nimport { ai, flow, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst technicalSig = f()\n  .input('query', f.string())\n  .output('answer', f.string())\n  .build();\n\nconst creativeSig = f()\n  .input('query', f.string())\n  .output('answer', f.string())\n  .build();\n\nconst workflow = flow\u003C{ query: string; type: string }, { output: string }>()\n  .node('technical', technicalSig)\n  .node('creative', creativeSig)\n  .branch(\n    (state) => state.type === 'technical',\n    (branch) => branch.execute('technical', (s) => ({ query: s.query })),\n    (branch) => branch.execute('creative', (s) => ({ query: s.query }))\n  )\n  .map((state) => ({\n    output: state.technicalResult?.answer || state.creativeResult?.answer || ''\n  }));\n\nconst result = await workflow.forward(llm, {\n  query: 'Explain quantum computing',\n  type: 'technical'\n});\n```\n\n### Flow with Parallel Execution\n\n```typescript\nimport { ai, flow, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst prosSig = f()\n  .input('topic', f.string())\n  .output('arguments', f.string())\n  .build();\n\nconst consSig = f()\n  .input('topic', f.string())\n  .output('arguments', f.string())\n  .build();\n\nconst summarySig = f()\n  .input('prosArgs', f.string())\n  .input('consArgs', f.string())\n  .output('summary', f.string())\n  .build();\n\nconst parallelFlow = flow\u003C{ topic: string }, { combined: string }>()\n  .node('pros', prosSig)\n  .node('cons', consSig)\n  .node('summary', summarySig)\n  .parallel([\n    { branch: (b) => b.execute('pros', (s) => ({ topic: s.topic })) },\n    { branch: (b) => b.execute('cons', (s) => ({ topic: s.topic })) }\n  ])\n  .execute('summary', (state) => ({\n    prosArgs: state.prosResult.arguments,\n    consArgs: state.consResult.arguments\n  }))\n  .map((state) => ({ combined: state.summaryResult.summary }));\n\nconst result = await parallelFlow.forward(llm, { topic: 'Remote work' });\n```\n\n### Complete Flow Example\n\n```typescript\nimport { ai, flow, f } from '@ax-llm\u002Fax';\n\n\u002F\u002F Define nodes with proper signatures\nconst researchNode = f()\n  .input('topic', f.string())\n  .output('research', f.string())\n  .output('sources', f.string().array())\n  .build();\n\nconst outlineNode = f()\n  .input('research', f.string())\n  .input('sources', f.string().array())\n  .output('outline', f.string().array())\n  .build();\n\nconst writeNode = f()\n  .input('outline', f.string().array())\n  .input('research', f.string())\n  .output('draft', f.string())\n  .build();\n\nconst editNode = f()\n  .input('draft', f.string())\n  .output('final', f.string())\n  .output('wordCount', f.number())\n  .build();\n\n\u002F\u002F Build the flow\nconst articlePipeline = flow\u003C\n  { topic: string },\n  { article: string; wordCount: number }\n>()\n  .node('research', researchNode)\n  .node('outline', outlineNode)\n  .node('write', writeNode)\n  .node('edit', editNode)\n  .execute('research', (s) => ({ topic: s.topic }))\n  .execute('outline', (s) => ({\n    research: s.researchResult.research,\n    sources: s.researchResult.sources\n  }))\n  .execute('write', (s) => ({\n    outline: s.outlineResult.outline,\n    research: s.researchResult.research\n  }))\n  .execute('edit', (s) => ({\n    draft: s.writeResult.draft\n  }))\n  .map((s) => ({\n    article: s.editResult.final,\n    wordCount: s.editResult.wordCount\n  }));\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst result = await articlePipeline.forward(llm, {\n  topic: 'The future of renewable energy'\n});\n\nconsole.log('Article:', result.article);\nconsole.log('Word count:', result.wordCount);\n```\n\n## 6. Common Patterns\n\n### Classification\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst classifier = ax(\n  f()\n    .input('text', f.string())\n    .output('category', f.class(['spam', 'ham', 'uncertain']))\n    .output('confidence', f.number().min(0).max(1))\n    .build()\n);\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst result = await classifier.forward(llm, {\n  text: 'Congratulations! You won $1,000,000!'\n});\n\nconsole.log(result.category);    \u002F\u002F 'spam'\nconsole.log(result.confidence);  \u002F\u002F 0.95\n```\n\n### Extraction\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst extractor = ax(\n  f()\n    .input('text', f.string())\n    .output('entities', f.object({\n      people: f.string().array(),\n      organizations: f.string().array(),\n      locations: f.string().array()\n    }))\n    .build()\n);\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst result = await extractor.forward(llm, {\n  text: 'Tim Cook announced that Apple will open a new store in Paris on January 15th.'\n});\n\nconsole.log(result.entities.people);        \u002F\u002F ['Tim Cook']\nconsole.log(result.entities.organizations); \u002F\u002F ['Apple']\nconsole.log(result.entities.locations);     \u002F\u002F ['Paris']\n```\n\n### Multi-modal (Images)\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\nimport { readFileSync } from 'fs';\n\nconst imageAnalyzer = ax(\n  f()\n    .input('image', f.image('Image to analyze'))\n    .input('question', f.string('Question about the image').optional())\n    .output('description', f.string('Image description'))\n    .output('objects', f.string().array())\n    .build()\n);\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\n\u002F\u002F From file\nconst imageData = readFileSync('.\u002Fphoto.jpg').toString('base64');\nconst result = await imageAnalyzer.forward(llm, {\n  image: { mimeType: 'image\u002Fjpeg', data: imageData },\n  question: 'What objects are in this image?'\n});\n\n\u002F\u002F From URL (for providers that support it)\nconst result2 = await imageAnalyzer.forward(llm, {\n  image: { mimeType: 'image\u002Fjpeg', url: 'https:\u002F\u002Fexample.com\u002Fimage.jpg' }\n});\n```\n\n### Chaining Generators\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\n\u002F\u002F Define generators\nconst researcher = ax(\n  f()\n    .input('topic', f.string())\n    .output('research', f.string())\n    .output('keyFacts', f.string().array())\n    .build()\n);\n\nconst writer = ax(\n  f()\n    .input('research', f.string())\n    .input('keyFacts', f.string().array())\n    .output('article', f.string())\n    .build()\n);\n\nconst editor = ax(\n  f()\n    .input('article', f.string())\n    .output('editedArticle', f.string())\n    .output('suggestions', f.string().array())\n    .build()\n);\n\n\u002F\u002F Chain them\nasync function createArticle(topic: string) {\n  const research = await researcher.forward(llm, { topic });\n\n  const draft = await writer.forward(llm, {\n    research: research.research,\n    keyFacts: research.keyFacts\n  });\n\n  const final = await editor.forward(llm, {\n    article: draft.article\n  });\n\n  return final;\n}\n\nconst result = await createArticle('Artificial General Intelligence');\nconsole.log(result.editedArticle);\n```\n\n### Error Handling\n\n```typescript\nimport { ai, ax, f, AxGenerateError, AxAIServiceError } from '@ax-llm\u002Fax';\n\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .build()\n);\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\ntry {\n  const result = await gen.forward(llm, { input: 'test' });\n  console.log(result.output);\n} catch (error) {\n  if (error instanceof AxGenerateError) {\n    console.error('Generation failed:', error.message);\n    console.error('Details:', error.details);\n  } else if (error instanceof AxAIServiceError) {\n    console.error('AI service error:', error.message);\n  } else {\n    throw error;\n  }\n}\n```\n\n### Examples and Few-Shot Learning\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst classifier = ax(\n  f()\n    .input('text', f.string())\n    .output('sentiment', f.class(['positive', 'negative', 'neutral']))\n    .build()\n);\n\n\u002F\u002F Set examples for few-shot learning\nclassifier.setExamples([\n  { text: 'I love this product!', sentiment: 'positive' },\n  { text: 'This is terrible.', sentiment: 'negative' },\n  { text: 'It works as expected.', sentiment: 'neutral' }\n]);\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst result = await classifier.forward(llm, {\n  text: 'The quality exceeded my expectations!'\n});\n```\n\n### Assertions and Validation\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst gen = ax(\n  f()\n    .input('number', f.number())\n    .output('doubled', f.number())\n    .build()\n);\n\n\u002F\u002F Add assertion\ngen.addAssert(\n  (output) => output.doubled === output.number * 2,\n  'Output must be double the input'\n);\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\n\u002F\u002F This will retry if assertion fails\nconst result = await gen.forward(llm, { number: 5 }, { maxRetries: 3 });\n```\n\n### Memory and Context\n\n```typescript\nimport { ai, ax, f, AxMemory } from '@ax-llm\u002Fax';\n\nconst chatbot = ax(\n  f()\n    .input('userMessage', f.string())\n    .output('response', f.string())\n    .build()\n);\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\n\u002F\u002F Create shared memory\nconst memory = new AxMemory();\n\n\u002F\u002F Conversation with memory\nawait chatbot.forward(llm, { userMessage: 'My name is Alice' }, { mem: memory });\nconst response = await chatbot.forward(llm, { userMessage: 'What is my name?' }, { mem: memory });\n\u002F\u002F response.response will reference \"Alice\"\n```\n\n## 7. Advanced Configuration\n\n### Model Configuration\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .build()\n);\n\nconst result = await gen.forward(llm, { input: 'test' }, {\n  model: 'gpt-4o',\n  modelConfig: {\n    temperature: 0.7,\n    maxTokens: 2000,\n    topP: 0.9\n  }\n});\n```\n\n### Debugging\n\n```typescript\nimport { ai, ax, f, axCreateDefaultColorLogger } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .build()\n);\n\n\u002F\u002F Enable debug logging\nconst result = await gen.forward(llm, { input: 'test' }, {\n  debug: true,\n  logger: axCreateDefaultColorLogger()\n});\n```\n\n### Context Caching\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst gen = ax(\n  f()\n    .input('document', f.string())\n    .input('question', f.string())\n    .output('answer', f.string())\n    .build()\n);\nconst llm = ai({ name: 'anthropic', apiKey: process.env.ANTHROPIC_API_KEY! });\n\n\u002F\u002F Enable context caching for long documents\nconst result = await gen.forward(llm, {\n  document: longDocument,\n  question: 'What is the main topic?'\n}, {\n  contextCache: {\n    cacheBreakpoint: 'after-examples'\n  }\n});\n```\n\n## 8. Forward & AI Options\n\n### Quick Reference Table\n\n| Goal | Option | Example |\n|------|--------|---------|\n| Adjust creativity | `modelConfig.temperature` | `{ modelConfig: { temperature: 0.8 } }` |\n| Limit response length | `modelConfig.maxTokens` | `{ modelConfig: { maxTokens: 500 } }` |\n| Use different model | `model` | `{ model: 'gpt-4o-mini' }` |\n| Enable caching | `contextCache` | `{ contextCache: { cacheBreakpoint: 'after-examples' } }` |\n| Debug output | `debug` | `{ debug: true }` |\n| Retry on failure | `maxRetries` | `{ maxRetries: 3 }` |\n| Multi-sampling | `sampleCount` | `{ sampleCount: 5, resultPicker: bestResultPicker }` |\n| Thinking models | `thinkingTokenBudget` | `{ thinkingTokenBudget: 10000 }` |\n| Abort request | `abortSignal` | `{ abortSignal: controller.signal }` |\n| Custom timeout | `timeout` | `{ timeout: 60000 }` |\n\n### Execution Control Options\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .build()\n);\n\nconst result = await gen.forward(llm, { input: 'test' }, {\n  \u002F\u002F Retry failed generations (validation failures, API errors)\n  maxRetries: 3,\n\n  \u002F\u002F Maximum agentic steps (for agents with tools)\n  maxSteps: 10,\n\n  \u002F\u002F Fail immediately on first error (don't retry)\n  fastFail: true\n});\n```\n\n### Model Configuration\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .build()\n);\n\nconst result = await gen.forward(llm, { input: 'test' }, {\n  \u002F\u002F Override the model for this request\n  model: 'gpt-4o-mini',\n\n  \u002F\u002F Model-specific configuration\n  modelConfig: {\n    \u002F\u002F Sampling temperature (0.0 = deterministic, 2.0 = creative)\n    temperature: 0.7,\n\n    \u002F\u002F Maximum tokens in response\n    maxTokens: 2000,\n\n    \u002F\u002F Nucleus sampling threshold\n    topP: 0.9,\n\n    \u002F\u002F Top-K sampling (not all providers support this)\n    topK: 40,\n\n    \u002F\u002F Frequency penalty (-2.0 to 2.0)\n    frequencyPenalty: 0.5,\n\n    \u002F\u002F Presence penalty (-2.0 to 2.0)\n    presencePenalty: 0.5,\n\n    \u002F\u002F Stop sequences\n    stopSequences: ['\\n\\n', 'END'],\n\n    \u002F\u002F Seed for reproducible outputs (when supported)\n    seed: 12345,\n\n    \u002F\u002F Response format\n    responseFormat: 'json_object'\n  }\n});\n```\n\n### Context Caching (Gemini\u002FAnthropic)\n\nContext caching saves costs when repeatedly querying with the same large context (documents, system prompts, examples).\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'anthropic', apiKey: process.env.ANTHROPIC_API_KEY! });\nconst gen = ax(\n  f()\n    .input('document', f.string())\n    .input('question', f.string())\n    .output('answer', f.string())\n    .build()\n);\n\nconst longDocument = '... very long document ...';\n\n\u002F\u002F Multiple questions about the same document - caching saves cost\nfor (const question of questions) {\n  const result = await gen.forward(llm, { document: longDocument, question }, {\n    contextCache: {\n      \u002F\u002F Cache name (required for identifying the cache)\n      name: 'doc-analysis-cache',\n\n      \u002F\u002F Where to split the prompt for caching:\n      \u002F\u002F - 'system': Cache system prompt only\n      \u002F\u002F - 'after-functions': Cache system + function definitions\n      \u002F\u002F - 'after-examples': Cache system + functions + examples\n      cacheBreakpoint: 'after-examples',\n\n      \u002F\u002F Cache time-to-live in seconds (default: provider-specific)\n      ttlSeconds: 3600,\n\n      \u002F\u002F Minimum tokens to trigger caching (avoid caching small prompts)\n      minTokens: 1000,\n\n      \u002F\u002F Refresh cache when within this window of expiry\n      refreshWindowSeconds: 300,\n\n      \u002F\u002F Custom cache registry for external storage (Redis, etc.)\n      registry: customCacheRegistry\n    }\n  });\n}\n```\n\n### Thinking Models (o1, o3, Gemini 2.0 Flash Thinking)\n\nFor reasoning models that support extended thinking:\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('problem', f.string())\n    .output('solution', f.string())\n    .build()\n);\n\nconst result = await gen.forward(llm, { problem: 'Complex math problem' }, {\n  model: 'o1',\n\n  \u002F\u002F Token budget for thinking\u002Freasoning (model-specific)\n  thinkingTokenBudget: 10000,\n\n  \u002F\u002F Include thinking in output (when supported)\n  showThoughts: true,\n\n  \u002F\u002F Custom field name for thoughts in output\n  thoughtFieldName: 'reasoning'\n});\n```\n\n### Multi-Sampling for Quality\n\nGenerate multiple samples and pick the best one:\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .output('confidence', f.number())\n    .build()\n);\n\nconst result = await gen.forward(llm, { input: 'test' }, {\n  \u002F\u002F Generate multiple samples\n  sampleCount: 5,\n\n  \u002F\u002F Pick the best result (custom function)\n  resultPicker: (results) => {\n    \u002F\u002F Return the result with highest confidence\n    return results.reduce((best, current) =>\n      current.confidence > best.confidence ? current : best\n    );\n  }\n});\n```\n\n### Function Calling Configuration\n\nControl how agents use tools\u002Ffunctions:\n\n```typescript\nimport { ai, agent, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\n\nconst myAgent = agent(\n  f()\n    .input('query', f.string())\n    .output('answer', f.string())\n    .build(),\n  {\n    name: 'toolAgent',\n    description: 'An agent that uses tools to answer queries',\n    functions: [searchTool, calculatorTool]\n  }\n);\n\nconst result = await myAgent.forward(llm, { query: 'test' }, {\n  \u002F\u002F Function calling mode:\n  \u002F\u002F - 'auto': Model decides when to call functions\n  \u002F\u002F - 'none': Disable function calling\n  \u002F\u002F - 'required': Force at least one function call\n  functionCallMode: 'auto',\n\n  \u002F\u002F Force a specific function to be called\n  functionCall: 'searchTool',\n\n  \u002F\u002F Stop after this function is called\n  stopFunction: 'finalAnswer',\n\n  \u002F\u002F Override available functions for this request\n  functions: [searchTool],\n\n  \u002F\u002F Custom caching for function results\n  cachingFunction: async (funcName, args) => {\n    const cacheKey = `${funcName}:${JSON.stringify(args)}`;\n    return await cache.get(cacheKey);\n  }\n});\n```\n\n### Debugging & Observability\n\n```typescript\nimport { ai, ax, f, axCreateDefaultColorLogger } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .build()\n);\n\nconst result = await gen.forward(llm, { input: 'test' }, {\n  \u002F\u002F Enable debug logging\n  debug: true,\n\n  \u002F\u002F Show verbose output (more details)\n  verbose: true,\n\n  \u002F\u002F Hide system prompt in debug output (security)\n  debugHideSystemPrompt: true,\n\n  \u002F\u002F Custom logger\n  logger: axCreateDefaultColorLogger(),\n\n  \u002F\u002F OpenTelemetry tracer for distributed tracing\n  tracer: openTelemetryTracer,\n\n  \u002F\u002F OpenTelemetry meter for metrics\n  meter: openTelemetryMeter,\n\n  \u002F\u002F Parent trace context\n  traceContext: parentSpan,\n\n  \u002F\u002F Custom labels for traces\u002Fmetrics\n  customLabels: { environment: 'production', version: '1.0' },\n\n  \u002F\u002F Exclude content from traces (privacy)\n  excludeContentFromTrace: true\n});\n```\n\n### Retry & Error Handling\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({\n  name: 'openai',\n  apiKey: process.env.OPENAI_API_KEY!,\n  options: {\n    \u002F\u002F Retry configuration for API calls\n    retry: {\n      \u002F\u002F Maximum retry attempts\n      maxRetries: 3,\n\n      \u002F\u002F Initial delay between retries (ms)\n      initialDelayMs: 1000,\n\n      \u002F\u002F Maximum delay between retries (ms)\n      maxDelayMs: 30000,\n\n      \u002F\u002F Backoff multiplier\n      backoffMultiplier: 2,\n\n      \u002F\u002F Jitter factor (0-1) to randomize delays\n      jitterFactor: 0.1,\n\n      \u002F\u002F HTTP status codes to retry on\n      retryOnStatusCodes: [429, 500, 502, 503, 504]\n    },\n\n    \u002F\u002F Rate limiter for API calls\n    rateLimiter: customRateLimiter,\n\n    \u002F\u002F Request timeout (ms)\n    timeout: 60000\n  }\n});\n```\n\n### Request Control\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .build()\n);\n\n\u002F\u002F Create abort controller\nconst controller = new AbortController();\n\n\u002F\u002F Cancel after 5 seconds\nsetTimeout(() => controller.abort(), 5000);\n\ntry {\n  const result = await gen.forward(llm, { input: 'test' }, {\n    \u002F\u002F Abort signal for cancellation\n    abortSignal: controller.signal,\n\n    \u002F\u002F Request timeout (ms)\n    timeout: 30000,\n\n    \u002F\u002F Custom fetch function (for proxies, etc.)\n    fetch: customFetch,\n\n    \u002F\u002F CORS proxy URL (for browser environments)\n    corsProxy: 'https:\u002F\u002Fcors-proxy.example.com'\n  });\n} catch (error) {\n  if (error.name === 'AbortError') {\n    console.log('Request was cancelled');\n  }\n}\n```\n\n### Memory Configuration\n\n```typescript\nimport { ai, ax, f, AxMemory } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('message', f.string())\n    .output('response', f.string())\n    .build()\n);\n\nconst memory = new AxMemory();\n\nconst result = await gen.forward(llm, { message: 'Hello' }, {\n  \u002F\u002F Use shared memory for conversation context\n  mem: memory,\n\n  \u002F\u002F Disable automatic memory cleanup (keep all messages)\n  disableMemoryCleanup: true\n});\n```\n\n### Validation Options\n\n```typescript\nimport { ai, ax, f } from '@ax-llm\u002Fax';\n\nconst llm = ai({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst gen = ax(\n  f()\n    .input('input', f.string())\n    .output('output', f.string())\n    .build()\n);\n\nconst result = await gen.forward(llm, { input: 'test' }, {\n  \u002F\u002F Strict mode: fail on any validation error\n  strictMode: true,\n\n  \u002F\u002F Custom assertions (run after generation)\n  asserts: [\n    {\n      fn: (output) => output.output.length > 10,\n      message: 'Output must be longer than 10 characters'\n    }\n  ],\n\n  \u002F\u002F Streaming assertions (run during streaming)\n  streamingAsserts: [\n    {\n      fn: (partial) => !partial.output?.includes('forbidden'),\n      message: 'Output must not contain forbidden content'\n    }\n  ]\n});\n```\n\n## 9. MCP Integration\n\nMCP (Model Context Protocol) enables AxAgent to use external tools from MCP-compliant servers. This allows your agents to interact with databases, file systems, APIs, and other services through a standardized protocol.\n\n### Quick Start\n\n```typescript\nimport { AxAgent, AxAI, AxMCPClient } from '@ax-llm\u002Fax';\nimport { AxMCPStdioTransport } from '@ax-llm\u002Fax-tools';\n\n\u002F\u002F Create transport for local MCP server\nconst transport = new AxMCPStdioTransport({\n  command: 'npx',\n  args: ['-y', '@modelcontextprotocol\u002Fserver-memory'],\n});\n\n\u002F\u002F Initialize MCP client\nconst mcpClient = new AxMCPClient(transport, { debug: false });\nawait mcpClient.init();\n\n\u002F\u002F Create agent with MCP functions\nconst agent = new AxAgent({\n  name: 'MyAssistant',\n  description: 'An assistant with MCP capabilities',\n  signature: f()\n    .input('userMessage', f.string())\n    .output('response', f.string())\n    .build(),\n  functions: [mcpClient],  \u002F\u002F Pass client directly\n});\n\nconst ai = new AxAI({ name: 'openai', apiKey: process.env.OPENAI_API_KEY! });\nconst result = await agent.forward(ai, { userMessage: 'Hello' });\n```\n\n### MCP Transports\n\n#### AxMCPStdioTransport (Local Servers)\n\nFor MCP servers that run as local processes via stdin\u002Fstdout:\n\n```typescript\nimport { AxMCPStdioTransport } from '@ax-llm\u002Fax-tools';\n\nconst transport = new AxMCPStdioTransport({\n  command: 'npx',\n  args: ['-y', '@modelcontextprotocol\u002Fserver-memory'],\n});\n\n\u002F\u002F Clean up when done\nawait transport.terminate();\n```\n\n#### AxMCPStreambleHTTPTransport (Remote Servers)\n\nFor MCP servers accessible via HTTP (e.g., Pipedream, hosted services):\n\n```typescript\nimport { AxMCPStreambleHTTPTransport } from '@ax-llm\u002Fax\u002Fmcp\u002Ftransports\u002FhttpStreamTransport.js';\n\nconst transport = new AxMCPStreambleHTTPTransport(\n  'https:\u002F\u002Fremote.mcp.pipedream.net',\n  {\n    headers: {\n      'x-pd-project-id': projectId,\n      'x-pd-environment': 'development',\n      'x-pd-external-user-id': 'user123',\n      'x-pd-app-slug': 'notion',\n    },\n    authorization: `Bearer ${accessToken}`,\n  }\n);\n```\n\n### Using MCP with Agents\n\nPass the MCP client directly to the agent's `functions` array:\n\n```typescript\nimport { AxAgent, AxAI, AxMCPClient, f } from '@ax-llm\u002Fax';\nimport { AxMCPStdioTransport } from '@ax-llm\u002Fax-tools';\n\nconst transport = new AxMCPStdioTransport({\n  command: 'npx',\n  args: ['-y', '@modelcontextprotocol\u002Fserver-memory'],\n});\n\nconst mcpClient = new AxMCPClient(transport);\nawait mcpClient.init();\n\nconst memoryAgent = new AxAgent\u003C\n  { userMessage: string; userId: string },\n  { assistantResponse: string }\n>({\n  name: 'MemoryAssistant',\n  description: 'An assistant that remembers past conversations. Use the database functions to manage, search, and add memories.',\n  signature: f()\n    .input('userMessage', f.string())\n    .input('userId', f.string())\n    .output('assistantResponse', f.string())\n    .build(),\n  functions: [mcpClient],\n});\n\nconst ai = new AxAI({\n  name: 'openai',\n  apiKey: process.env.OPENAI_API_KEY!,\n  config: { model: 'gpt-4o-mini' }\n});\n\n\u002F\u002F First interaction - stores memory\nconst first = await memoryAgent.forward(ai, {\n  userMessage: 'My name is Alice and my favorite color is blue.',\n  userId: 'user123',\n});\n\n\u002F\u002F Later interaction - retrieves memory\nconst second = await memoryAgent.forward(ai, {\n  userMessage: \"What's my favorite color?\",\n  userId: 'user123',\n});\n```\n\n### MCP Capabilities\n\nMCP servers can provide three types of capabilities:\n\n| Capability | Function Prefix | Description |\n|------------|-----------------|-------------|\n| **Tools** | *(none)* | Traditional function calls (e.g., `search`, `create`) |\n| **Prompts** | `prompt_` | Prompt templates (e.g., `prompt_summarize`) |\n| **Resources** | `resource_` | File\u002Fdata access (e.g., `resource_config_json`) |\n\nCheck available capabilities:\n\n```typescript\nconst mcpClient = new AxMCPClient(transport);\nawait mcpClient.init();\n\nconst caps = mcpClient.getCapabilities();\nconsole.log('Tools:', caps.tools);      \u002F\u002F true\u002Ffalse\nconsole.log('Prompts:', caps.prompts);  \u002F\u002F true\u002Ffalse\nconsole.log('Resources:', caps.resources); \u002F\u002F true\u002Ffalse\n\n\u002F\u002F Or check individually\nif (mcpClient.hasToolsCapability()) {\n  console.log('Server supports tools');\n}\n```\n\n### Function Overrides\n\nCustomize function names and descriptions while preserving functionality:\n\n```typescript\nconst mcpClient = new AxMCPClient(transport, {\n  functionOverrides: [\n    {\n      name: 'search_documents',\n      updates: {\n        name: 'findDocs',\n        description: 'Search through all available documents'\n      }\n    },\n    {\n      name: 'prompt_summarize',\n      updates: {\n        name: 'getSummaryPrompt',\n        description: 'Get a prompt template for summarization'\n      }\n    }\n  ]\n});\n```\n\n### Getting Functions Directly\n\nIf you need the function array instead of passing the client:\n\n```typescript\nconst mcpClient = new AxMCPClient(transport);\nawait mcpClient.init();\n\n\u002F\u002F Get all functions (tools + prompts + resources)\nconst functions = mcpClient.toFunction();\n\n\u002F\u002F Use with agent\nconst agent = new AxAgent({\n  name: 'MyAgent',\n  signature: f()\n    .input('query', f.string())\n    .output('answer', f.string())\n    .build(),\n  functions: functions,  \u002F\u002F Or spread: [...functions, otherFunction]\n});\n```\n\n### Complete Example: Remote HTTP MCP Server\n\n```typescript\nimport { AxAgent, AxAI, AxMCPClient, f } from '@ax-llm\u002Fax';\nimport { AxMCPStreambleHTTPTransport } from '@ax-llm\u002Fax\u002Fmcp\u002Ftransports\u002FhttpStreamTransport.js';\nimport { createBackendClient } from '@pipedream\u002Fsdk\u002Fserver';\n\n\u002F\u002F Initialize Pipedream SDK\nconst pd = createBackendClient({\n  environment: 'development',\n  credentials: {\n    clientId: process.env.PIPEDREAM_CLIENT_ID!,\n    clientSecret: process.env.PIPEDREAM_CLIENT_SECRET!,\n  },\n  projectId: process.env.PIPEDREAM_PROJECT_ID!,\n});\n\n\u002F\u002F Get access token and app info\nconst accessToken = await pd.rawAccessToken();\nconst apps = await pd.getApps({ q: 'notion' });\nconst appSlug = apps.data[0]?.name_slug;\n\n\u002F\u002F Create HTTP transport for Pipedream MCP\nconst httpTransport = new AxMCPStreambleHTTPTransport(\n  'https:\u002F\u002Fremote.mcp.pipedream.net',\n  {\n    headers: {\n      'x-pd-project-id': process.env.PIPEDREAM_PROJECT_ID!,\n      'x-pd-environment': 'development',\n      'x-pd-external-user-id': 'user123',\n      'x-pd-app-slug': appSlug!,\n    },\n    authorization: `Bearer ${accessToken}`,\n  }\n);\n\n\u002F\u002F Initialize MCP client\nconst mcpClient = new AxMCPClient(httpTransport, { debug: false });\nawait mcpClient.init();\n\n\u002F\u002F Create Notion agent\nconst notionAgent = new AxAgent\u003C\n  { userRequest: string },\n  { assistantResponse: string }\n>({\n  name: 'NotionAssistant',\n  description: 'An assistant that can interact with Notion documents. Use the provided functions to read, search, and analyze Notion content.',\n  signature: f()\n    .input('userRequest', f.string())\n    .output('assistantResponse', f.string())\n    .build(),\n  functions: [mcpClient],\n});\n\nconst ai = new AxAI({\n  name: 'openai',\n  apiKey: process.env.OPENAI_API_KEY!,\n  config: { model: 'gpt-4o-mini' }\n});\n\n\u002F\u002F Use the agent\nconst response = await notionAgent.forward(ai, {\n  userRequest: 'Summarize my most recently created Notion doc'\n});\nconsole.log(response.assistantResponse);\n```\n\n### Example Files\n\nFull working examples on GitHub:\n\n- [Local Memory Server (stdio)](https:\u002F\u002Fraw.githubusercontent.com\u002Fax-llm\u002Fax\u002Frefs\u002Fheads\u002Fmain\u002Fsrc\u002Fexamples\u002Fmcp-client-memory.ts) - Memory-augmented agent using local MCP server\n- [Remote HTTP Server (Pipedream\u002FNotion)](https:\u002F\u002Fraw.githubusercontent.com\u002Fax-llm\u002Fax\u002Frefs\u002Fheads\u002Fmain\u002Fsrc\u002Fexamples\u002Fmcp-client-pipedream.ts) - Notion integration via Pipedream MCP\n\n## Type Reference\n\n```typescript\n\u002F\u002F Core types\ntype AxGenIn = Record\u003Cstring, any>;\ntype AxGenOut = Record\u003Cstring, any>;\n\n\u002F\u002F Generator\nclass AxGen\u003CIN, OUT> {\n  forward(ai: AxAIService, values: IN, options?: AxProgramForwardOptions): Promise\u003COUT>;\n  streamingForward(ai: AxAIService, values: IN, options?: AxProgramStreamingForwardOptions): AsyncGenerator\u003C{ delta: Partial\u003COUT> }>;\n  setExamples(examples: Array\u003CPartial\u003CIN & OUT>>): void;\n  addAssert(fn: (output: OUT) => boolean, message?: string): void;\n  addFieldProcessor(field: keyof OUT, fn: (value: any) => any): void;\n  addStreamingFieldProcessor(field: keyof OUT, fn: (chunk: string, ctx: any) => void): void;\n}\n\n\u002F\u002F Agent\nclass AxAgent\u003CIN, OUT> {\n  forward(ai: AxAIService, values: IN, options?: AxAgentOptions): Promise\u003COUT>;\n  streamingForward(ai: AxAIService, values: IN, options?: AxAgentOptions): AsyncGenerator\u003C{ delta: Partial\u003COUT> }>;\n  getFunction(): AxFunction;\n}\n\n\u002F\u002F Flow\nclass AxFlow\u003CIN, OUT, TNodes, TState> {\n  node(name: string, signature: string | AxSignature): AxFlow;\n  execute(nodeName: string, inputMapper: (state: TState) => any): AxFlow;\n  map(transformer: (state: TState) => OUT): AxFlow;\n  branch(condition: (state: TState) => boolean, ifTrue: FlowBranch, ifFalse: FlowBranch): AxFlow;\n  parallel(branches: ParallelBranch[]): AxFlow;\n  forward(ai: AxAIService, input: IN): Promise\u003COUT>;\n}\n```\n",{"name":5,"version":31,"description":7},"19.0.13","master","e5f02c59e583065b90e8d9ab68f9c95f371ea101",".claude\u002Fskills\u002Fax","https:\u002F\u002Fgithub.com\u002Fmarolinik\u002Fwaggle","https:\u002F\u002Fgithub.com\u002Fmarolinik","2026-03-25 16:49:49",{"source":8,"skillName":5,"commands":39,"prompt":49,"zipAvailable":50},[40,43,46],{"tool":41,"command":42},"npx","npx skills add marolinik\u002Fwaggle --skill ax",{"tool":44,"command":45},"bunx","bunx skills add marolinik\u002Fwaggle --skill ax",{"tool":47,"command":48},"pnpm","pnpm dlx skills add marolinik\u002Fwaggle --skill ax","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmarolinik\u002Fwaggle\u002Fblob\u002Fmaster\u002F.claude\u002Fskills\u002Fax\u002FSKILL.md",true,[52],{"path":53,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":56,"sourceHtmlUrl":57},"references\u002Ferror-code-map.md","REFERENCE","参考文档",6922,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fazure-skills\u002Fblob\u002Fmain\u002F.github\u002Fplugins\u002Faks-skills\u002Fskills\u002Faks-known-issues\u002Freferences\u002Ferror-code-map.md",[59,69,78],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":26},"01M6D0WA6GK85A2ACTN3HD6J4V","summarize","Summarize text or conversation into key points","https:\u002F\u002Fgithub.com\u002Fmarolinik\u002Fwaggle\u002Fblob\u002Fmaster\u002Fskills\u002Fsummarize\u002FSKILL.md",[],[61,66,67,68],"conversation","haiku","text",{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":26},"01M6D0W7K5TXDXZSHMSKMP1MS8","classify","Classify user intent or categorize text","https:\u002F\u002Fgithub.com\u002Fmarolinik\u002Fwaggle\u002Fblob\u002Fmaster\u002Fskills\u002Fclassify\u002FSKILL.md",[],[71,76,77,23,67,68],"intent","categorize",{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":26},"01M6D0VYYMNVR6DAMAHV86NRSP","ax-agent","This skill helps an LLM generate correct AxAgent code using @ax-llm\u002Fax. Use when the user asks about agent(), child agents, namespaced functions, discovery mode, shared fields, llmQuery(...), or RLM code execution.","https:\u002F\u002Fgithub.com\u002Fmarolinik\u002Fwaggle\u002Fblob\u002Fmaster\u002F.claude\u002Fskills\u002Fax-agent\u002FSKILL.md",[],[85,86,87,88,89,24,23,90,91,92,93],"ax agent","generate","rlm","shared","functions","correct","discovery","execution","code"]