AutoGen
Use @codespar/autogen to give Microsoft AutoGen agents commerce capabilities in Latin America.
AutoGen Adapter
The @codespar/autogen adapter converts CodeSpar session tools into Microsoft AutoGen's function tool format. Each tool includes a callable that routes execution through the CodeSpar session for billing and audit. Use it to give your AutoGen multi-agent conversations access to payments, invoicing, and shipping in Latin America.
Installation
npm install @codespar/sdk @codespar/autogenpnpm add @codespar/sdk @codespar/autogenyarn add @codespar/sdk @codespar/autogen@codespar/autogen has a peer dependency on @codespar/sdk@^0.2.0. Make sure it is installed.
API Reference
getTools(session): Promise<AutoGenFunctionTool[]>
Fetches all tools from the session and converts them to AutoGen's function tool format. Each tool has type: "function", a function object with name, description, and parameters, plus a callable for execution.
import { CodeSpar } from "@codespar/sdk";
import { getTools } from "@codespar/autogen";
const codespar = new CodeSpar({ apiKey: process.env.CODESPAR_API_KEY });
const session = await codespar.sessions.create({
servers: ["stripe", "mercadopago"],
});
const tools = await getTools(session);
console.log(JSON.stringify(tools[0], null, 2));{
"type": "function",
"function": {
"name": "codespar_checkout",
"description": "Create a checkout session for a product or service",
"parameters": {
"type": "object",
"properties": {
"provider": { "type": "string" },
"amount": { "type": "number" },
"currency": { "type": "string" }
},
"required": ["provider", "amount", "currency"]
}
}
}toAutoGenTool(tool, session): AutoGenFunctionTool
Converts a single CodeSpar tool to AutoGen format with a bound callable.
import { toAutoGenTool } from "@codespar/autogen";
const allTools = await session.tools();
const paymentTools = allTools
.filter((t) => t.name.includes("pay"))
.map((t) => toAutoGenTool(t, session));handleToolCall(session, toolName, args): Promise<ToolResult>
Convenience executor that routes a tool call through the CodeSpar session.
Full agent loop
This is a complete example of an AutoGen multi-agent conversation with CodeSpar tools:
import { CodeSpar } from "@codespar/sdk";
import { getTools } from "@codespar/autogen";
const codespar = new CodeSpar({ apiKey: process.env.CODESPAR_API_KEY });
async function run(userMessage: string) {
// 1. Create a session
const session = await codespar.sessions.create({
servers: ["stripe", "asaas", "correios"],
});
// 2. Get tools in AutoGen format
const tools = await getTools(session);
// 3. Create a tool registry for easy lookup
const toolRegistry = new Map(
tools.map((t) => [t.function.name, t])
);
// 4. Simulate an agent loop (adapt to your AutoGen setup)
const toolName = "codespar_checkout";
const tool = toolRegistry.get(toolName);
if (tool) {
const result = await tool.callable({
provider: "stripe",
amount: 25000,
currency: "BRL",
description: "Order #1234",
});
console.log("Tool result:", result);
}
// 5. Clean up
await session.close();
}
await run("Process payment of R$250 via Pix");Handling parallel tool calls
Execute multiple tool callables in parallel when the agent requests them:
const toolCalls = [
{ name: "codespar_checkout", args: { provider: "stripe", amount: 4990, currency: "BRL" } },
{ name: "codespar_notify", args: { channel: "email", to: "customer@example.com" } },
];
const results = await Promise.all(
toolCalls.map(async (tc) => {
const tool = toolRegistry.get(tc.name);
if (!tool) throw new Error(`Unknown tool: ${tc.name}`);
return { name: tc.name, result: await tool.callable(tc.args) };
})
);Streaming
AutoGen supports streaming conversations. Use the callable in your tool execution handler:
import { CodeSpar } from "@codespar/sdk";
import { getTools } from "@codespar/autogen";
const codespar = new CodeSpar({ apiKey: process.env.CODESPAR_API_KEY });
const session = await codespar.sessions.create({ servers: ["stripe"] });
const tools = await getTools(session);
// Register tools with your AutoGen agent's tool executor
async function executeToolCall(name: string, args: Record<string, unknown>) {
const tool = tools.find((t) => t.function.name === name);
if (!tool) return JSON.stringify({ error: `Unknown tool: ${name}` });
return tool.callable(args);
}Error handling
Wrap callable invocations in try-catch:
async function safeExecute(tool: AutoGenFunctionTool, args: Record<string, unknown>) {
try {
return await tool.callable(args);
} catch (error) {
return JSON.stringify({
error: error instanceof Error ? error.message : "Tool call failed",
tool_name: tool.function.name,
});
}
}Returning errors as JSON strings lets the AutoGen agent reason about failures and decide whether to retry or try a different approach.
Best practices
-
Always close sessions. Use
try/finallyto ensuresession.close()runs. -
Scope servers narrowly. Only connect the MCP servers your agents need.
-
Build a tool registry. Use a
Mapkeyed by tool name for O(1) lookups in the tool execution handler. -
Set conversation limits. Configure
max_consecutive_auto_replyto prevent infinite agent loops. -
Return errors as strings. Let agents reason about failures instead of crashing the conversation.
-
Use typed tool calls. The
AutoGenFunctionToolinterface ensures type safety in your tool execution handler.
Next steps
- Sessions -- Session lifecycle and configuration
- Tools and Meta-Tools -- Understand the 6 meta-tools and routing
- OpenAI Adapter -- Direct OpenAI SDK integration
- LangChain Adapter -- Use with LangChain.js agents
- Quickstart -- End-to-end setup in under 5 minutes