Skip to main content

AutoGen

Use @codespar/autogen to give Microsoft AutoGen agents commerce capabilities in Latin America.

1 min read · updated

AutoGen Adapter

@codespar/autogenv0.4.0

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.

Pick this adapter when you need group-chat style multi-agent conversations (proposer + critic + executor patterns), Python-first workflows, or integration with Microsoft's Azure OpenAI ecosystem.

Framework-specific notes

  • Functions register per agent — each ConversableAgent can have its own subset of CodeSpar tools. Good fit for the group-chat pattern where a "proposer" agent does codespar_discover and an "executor" only gets codespar_charge / codespar_pay.
  • Human-in-the-loop is first-class — AutoGen's UserProxyAgent can approve each tool call before it runs, perfect for high-risk commerce actions (payouts, bulk refunds) that need human sign-off.
  • Group chat for escalation — three-agent patterns (customer service + fraud-check + finance-ops) resolve complex refund decisions more reliably than single-agent loops.
  • Azure OpenAI compatible — the adapter does not care which OpenAI-compatible endpoint you use. Point AutoGen at Azure OpenAI deployments if your compliance requires keeping inference in your cloud.
  • Python — the full codespar Python package (sync + async) works from AutoGen directly; see Quickstart (Python).

Installation

npm install @codespar/sdk @codespar/autogen
pnpm add @codespar/sdk @codespar/autogen
yarn add @codespar/sdk @codespar/autogen

@codespar/autogen has a peer dependency on @codespar/sdk@^0.9.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.create("user_123", {
  servers: ["stripe", "mercadopago"],
});

const tools = await getTools(session);
console.log(JSON.stringify(tools[0], null, 2));
Output: AutoGenFunctionTool
{
  "type": "function",
  "function": {
    "name": "codespar_charge",
    "description": "Create an inbound charge (buyer pays merchant) — Pix / boleto / card",
    "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:

autogen-agent.ts
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.create("user_123", {
    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_charge";
  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_charge", 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:

autogen-streaming.ts
import { CodeSpar } from "@codespar/sdk";
import { getTools } from "@codespar/autogen";

const codespar = new CodeSpar({ apiKey: process.env.CODESPAR_API_KEY });
const session = await codespar.create("user_123", { 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

  1. Always close sessions. Use try/finally to ensure session.close() runs.

  2. Scope servers narrowly. Only connect the MCP servers your agents need.

  3. Build a tool registry. Use a Map keyed by tool name for O(1) lookups in the tool execution handler.

  4. Set conversation limits. Configure max_consecutive_auto_reply to prevent infinite agent loops.

  5. Return errors as strings. Let agents reason about failures instead of crashing the conversation.

  6. Use typed tool calls. The AutoGenFunctionTool interface ensures type safety in your tool execution handler.

Newer SDK wrappers

getTools(session) is the agent-facing path. From any handler or callback you can also call typed wrappers on the session — same routing, no LLM hop:

  • session.discover(query) / session.charge(args) / session.pay(args) / session.ship(args) — typed shortcuts for the meta-tools.
  • session.connectionWizard(serverId) — open a hosted auth flow for a missing connection.
  • session.paymentStatus(toolCallId) and session.paymentStatusStream(toolCallId) — async settlement correlation (poll or SSE).
  • session.verificationStatus(toolCallId) and session.verificationStatusStream(toolCallId) — KYC outcome polling / SSE.

Full reference at /docs/api/sdk.

Next steps

Edit on GitHub

Last updated on