AI Platform

AI Agents with Tool Calling

Build AI agents in TypeScript with AxilJS: tool calling, custom and built-in tools, multi-step execution, streaming steps, logging, and HTTP agent endpoints.

5 min readUpdated DocumentationEdit this page
On this page9

AxilJS provides an AI agent API for building TypeScript and Node.js AI applications with tool calling, multi-step execution, custom tools, and streaming.

An Agent follows the ReAct pattern: it receives a request, decides which tools to use, executes them, feeds the results back to the model, and repeats until the model produces a final answer. Tool calling works with OpenAI, Anthropic, Gemini, and Ollama, so an agent can run on any provider.

Create Custom AI Tools

Define application-specific tools with createTool().

TypeScript
TS
1import { createTool } from '@axiljs/ai'
2
3const weatherTool = createTool({
4  name: 'get_weather',
5  description: 'Get weather for a city',
6  parameters: {
7    type: 'object',
8    properties: { city: { type: 'string', description: 'City name' } },
9    required: ['city']
10  },
11  handler: async ({ city }) => ({ city, temp: '22C' })
12})

A custom tool defines:

  • name — the identifier used by the agent.
  • description — explains what the tool does; the model reads it to decide when to call the tool.
  • parameters — a JSON Schema object describing the tool input.
  • handler — an async function that receives the parsed arguments and returns the result.

If a handler throws, the error message is returned to the model as the tool result, so the agent can recover.

Built-in Tools

ToolNameDescription
calculatorToolcalculatorEvaluates arithmetic with a safe parser (no eval): + - * / % ^ **, parentheses, and Math functions and constants such as sqrt, pow, log, PI
currentDateTimeToolget_current_datetimeReturns the current date and time in ISO 8601 format
jsonTooljson_processorParses, validates, and formats JSON

The calculator's parser is also exported as evaluateMathExpression(expr).

Setup

Create an agent with an AI provider and one or more tools.

TypeScript
TS
1import { Agent, AnthropicProvider, calculatorTool } from '@axiljs/ai'
2
3const ai = new AnthropicProvider({ apiKey: process.env.ANTHROPIC_API_KEY! })
4
5const agent = new Agent({
6  provider: ai,
7  model: 'claude-sonnet-5-5',
8  tools: [calculatorTool, weatherTool],
9  maxIterations: 10
10})

Agent Options

OptionDefaultDescription
providerrequiredAI provider used for reasoning
toolsrequiredTools the agent can call
systemPromptbuilt-in agent promptDescribes the agent's role and behavior
maxIterations10Maximum reasoning iterations before giving up
modelprovider's default modelModel used for reasoning
temperature0.1Sampling temperature (low for deterministic reasoning)
onStepnoneCallback invoked with each AgentStep
loggercoloured console outputfalse to silence, or an object with info(msg) and warn(msg)

Note

Changed in 0.3.3: the logger option is new. By default run() logs its progress to the console; pass logger: false to keep it silent, or route the messages to your own logger.

TypeScript
TS
1const agent = new Agent({
2  provider: ai,
3  tools: [calculatorTool],
4  logger: {
5    info: msg => appLogger.info(msg),
6    warn: msg => appLogger.warn(msg)
7  }
8})

Run an AI Agent

Use agent.run() to execute a request and receive the result.

TypeScript
TS
1const result = await agent.run('What is 25 * 4?')
2
3result.response    // final answer
4result.steps       // AgentStep[]: thought, toolCalls, toolResults, finalAnswer
5result.iterations  // iterations used
6result.success     // false if maxIterations was reached
7result.usage       // { totalTokens, steps }

run() takes an optional second argument with earlier conversation messages, for multi-turn use:

TypeScript
TS
1const result = await agent.run('And divided by 5?', [
2  { role: 'user', content: 'What is 25 * 4?' },
3  { role: 'assistant', content: '100' }
4])

If the model still requests tools after maxIterations, the result has success: false and a response explaining that the task could not be completed.

Stream Agent Execution

For applications that need incremental agent execution, use runStream().

TypeScript
TS
1for await (const step of agent.runStream('Calculate 2^10')) {
2  console.log(step.iteration, step.thought, step.toolCalls, step.finalAnswer)
3
4  if (step.done) {
5    console.log(step.finalResult)  // same shape as run()'s result
6  }
7}

A step is yielded before its tools run (so a UI can show the model "thinking"), and the stream always ends with a done: true step whose finalResult matches what run() returns, including success: false when maxIterations is hit.

Agents over HTTP

aiAgent() creates a route handler around an agent. The request body takes a task and an optional context message array.

TypeScript
TS
1import { aiAgent, calculatorTool } from '@axiljs/ai'
2
3app.post('/agent', aiAgent({
4  provider: ai,
5  tools: [calculatorTool],
6  maxIterations: 5
7}))
8
9app.post('/agent/stream', aiAgent({
10  provider: ai,
11  tools: [calculatorTool],
12  stream: true   // sends each step as an SSE "step" event
13}))

aiAgent() accepts provider, tools, systemPrompt, maxIterations, model, and stream.

Agent Workflow

A typical AxilJS agent workflow consists of:

  1. Create an Agent with an AI provider.
  2. Register built-in or custom tools.
  3. Send a request with agent.run().
  4. Allow the agent to execute the required tools.
  5. Read the final response and execution steps.
  6. Use runStream() when incremental execution is required.
User Request
Agent
Tool Call
Tool Handler
Tool Result
Final Response
Each tool result goes back to the agent, which loops until it produces the final response.

Tools from an MCP server can be added with MCPClient.asAgentTools(); see MCP.

When to Use AxilJS Agents

AxilJS agents are useful when an AI application needs to go beyond generating text and interact with executable tools.

Common use cases include:

  • AI assistants with external tools
  • Calculator and utility agents
  • Weather and API integrations
  • Database-aware AI applications
  • Automated workflows
  • Multi-step AI operations
  • Interactive streaming agents

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY