AutoGen Tutorial (TypeScript): handling async tools for beginners

By Cyprian AaronsUpdated 2026-04-21
autogenhandling-async-tools-for-beginnerstypescript

This tutorial shows you how to register and use async tools in AutoGen with TypeScript, then wire them into an agent that can call them reliably. You need this when your tool does I/O — database reads, HTTP requests, file access, or any operation that returns a Promise instead of a plain value.

What You'll Need

  • Node.js 18+
  • TypeScript 5+
  • npm or pnpm
  • An OpenAI API key
  • These packages:
    • autogen
    • openai
    • zod

Step-by-Step

  1. Start with a minimal TypeScript project and install the dependencies. I’m using the AutoGen TypeScript SDK plus Zod for tool input validation.
npm init -y
npm install autogen openai zod
npm install -D typescript tsx @types/node
  1. Create a small async tool. The important part is that the function returns a Promise, because that is what you’ll usually have when calling external systems.
import { z } from "zod";

export const weatherInput = z.object({
  city: z.string().min(1),
});

export async function getWeather(city: string): Promise<string> {
  await new Promise((resolve) => setTimeout(resolve, 500));
  return `Weather for ${city}: 22°C, clear sky`;
}
  1. Register the tool with an AutoGen agent. The agent needs a typed schema so it can decide when to call the tool and how to format arguments.
import OpenAI from "openai";
import { AssistantAgent, FunctionTool } from "autogen";
import { weatherInput, getWeather } from "./weather";

const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

const weatherTool = new FunctionTool({
  name: "get_weather",
  description: "Get the current weather for a city",
  parameters: weatherInput,
  execute: async ({ city }) => {
    return await getWeather(city);
  },
});

const agent = new AssistantAgent({
  name: "assistant",
  modelClient: client,
  tools: [weatherTool],
});
  1. Send a prompt that encourages the model to use the tool. Keep the request simple at first so you can see the tool call in action before you add more complex workflows.
async function main() {
  const result = await agent.run([
    {
      role: "user",
      content: "What's the weather in Nairobi?",
    },
  ]);

  console.log(JSON.stringify(result.messages, null, 2));
}

main().catch(console.error);
  1. If your async tool talks to an API, keep the same pattern but replace the fake delay with real I/O. This is where beginners usually trip up: they return a Promise correctly, but forget to validate input or handle failures.
import { z } from "zod";

const quoteInput = z.object({
  symbol: z.string().min(1),
});

export async function getStockQuote(symbol: string): Promise<string> {
  const response = await fetch(`https://example.com/quotes/${symbol}`);
  if (!response.ok) {
    throw new Error(`Quote request failed for ${symbol}`);
  }

  const data = (await response.json()) as { price: number };
  return `${symbol}: $${data.price}`;
}
  1. Add error handling around your tool execution path. In production, async tools fail more often than LLM calls do, so you want explicit exceptions and useful messages.
const safeWeatherTool = new FunctionTool({
  name: "get_weather_safe",
  description: "Get weather with error handling",
  parameters: weatherInput,
  execute: async ({ city }) => {
    try {
      return await getWeather(city);
    } catch (error) {
      const message =
        error instanceof Error ? error.message : "Unknown tool failure";
      throw new Error(`weather tool failed for ${city}: ${message}`);
    }
  },
});

Testing It

Run the script with your API key set in the environment:

OPENAI_API_KEY=your_key_here npx tsx src/index.ts

If it works, you should see a tool call in the returned messages and then a final assistant answer that uses the weather result. If it fails before calling the tool, check that your schema matches the argument shape exactly and that your execute function is marked async. If it fails during execution, inspect the thrown error message first; with async tools, that message is usually enough to pinpoint bad network calls or invalid input.

Next Steps

  • Add retries and timeouts around network-based tools.
  • Learn how to chain multiple tools in one AutoGen conversation.
  • Replace mock data with real integrations like Postgres, Redis, or internal REST APIs.

Keep learning

By Cyprian Aarons, AI Consultant at Topiax.

Want the complete 8-step roadmap?

Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.

Get the Starter Kit

Related Guides