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.
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().
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
| Tool | Name | Description |
|---|---|---|
calculatorTool | calculator | Evaluates arithmetic with a safe parser (no eval): + - * / % ^ **, parentheses, and Math functions and constants such as sqrt, pow, log, PI |
currentDateTimeTool | get_current_datetime | Returns the current date and time in ISO 8601 format |
jsonTool | json_processor | Parses, 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.
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
| Option | Default | Description |
|---|---|---|
provider | required | AI provider used for reasoning |
tools | required | Tools the agent can call |
systemPrompt | built-in agent prompt | Describes the agent's role and behavior |
maxIterations | 10 | Maximum reasoning iterations before giving up |
model | provider's default model | Model used for reasoning |
temperature | 0.1 | Sampling temperature (low for deterministic reasoning) |
onStep | none | Callback invoked with each AgentStep |
logger | coloured console output | false 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.
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.
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:
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().
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.
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:
- Create an
Agentwith an AI provider. - Register built-in or custom tools.
- Send a request with
agent.run(). - Allow the agent to execute the required tools.
- Read the final response and execution steps.
- Use
runStream()when incremental execution is required.
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?