# AutoGen Integration Guide

Source: https://molted.email/docs/autogen-integration-guide

Add a governed email mailbox to your AutoGen agents and multi-agent conversations. Send, receive, and track email with built-in policy enforcement.

AutoGen's conversational agent framework makes it easy for agents to call tools during a multi-agent conversation. Without a governed mailbox, any agent in the conversation can trigger an email send with no policy checks - no deduplication, no rate limiting, no suppression. One misconfigured agent in a conversation can burn your sender reputation.

This guide shows how to register a governed send tool with your AutoGen agents. Every email proposed during a conversation runs through the Molted policy engine before it leaves. Policy is enforced at the infrastructure layer - no agent in the conversation can override it.

## Prerequisites

- A Molted account with an API key (sign up at [molted.email/signup](https://molted.email/signup))
- A verified sending domain (see [Domains](https://molted.email/docs/domains.md))
- AutoGen installed: `pip install pyautogen` for the classic API (sections 3 and 4), or `pip install autogen-agentchat "autogen-ext[openai]"` for AutoGen 0.4+ (section 5)
- Requests installed: `pip install requests`

> **Note:** If your framework can connect to a remote MCP server, you can skip the hand-written tools in this guide: point it at `https://mcp.molted.email/mcp` with your API key as a bearer token, and the agent gets `send_email`, `reply`, `read_inbox`, `get_thread`, `check_suppression` and the rest of Molted's tools, with the same policy checks. See [MCP Server](https://molted.email/docs/mcp-server.md). The tools below call the REST API directly, which works with any framework.

## 1. Create a mailbox

Each AutoGen application (or conversation group) should have its own mailbox. In the portal, press **⌘K** and type `new mailbox`, or use the CLI or the API:

```bash title="CLI"
molted mailboxes create --address agent@yourdomain.com --display-name "AutoGen Outreach"
```

```bash title="curl"
curl -X POST https://mailbox.molted.email/v1/agent/mailboxes \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "address": "agent@yourdomain.com",
    "displayName": "AutoGen Outreach"
  }'
```

The response's `id` is the mailbox id: pass it as `mailboxId` on each send. The examples below read it from `MOLTED_MAILBOX_ID`, your API key from `MOLTED_API_KEY`. The examples call `https://mailbox.molted.email`, which fills in your tenant from the key, so they need no tenant id. A send without a `mailboxId` goes out from your [default mailbox](https://molted.email/docs/mailboxes.md#default-mailbox).

## 2. Define the send and status functions

AutoGen uses Python functions as tools. Define two functions - one to send (`POST /v1/agent/request-send`), one to read a send's delivery events (`GET /v1/agent/messages/:requestId/events`, the same as `molted events get <requestId>`):

```python title="email_tools.py"
import os
import requests
from typing import Annotated


def send_email(
    to: Annotated[str, "Recipient email address"],
    subject: Annotated[str, "Email subject line"],
    body: Annotated[str, "Email body in plain text or HTML"],
    dedupe_key: Annotated[
        str,
        "Unique key to prevent duplicate sends. Use a descriptive value like 'welcome-user@example.com'.",
    ],
) -> str:
    """
    Send an email through the Molted policy engine. The email is checked against
    20+ policy rules before delivery. Returns the requestId on success or the
    block reason if rejected. Do not retry blocked sends.
    """
    response = requests.post(
        "https://mailbox.molted.email/v1/agent/request-send",
        headers={
            "Authorization": f"Bearer {os.environ['MOLTED_API_KEY']}",
            "Content-Type": "application/json",
        },
        json={
            "mailboxId": os.environ["MOLTED_MAILBOX_ID"],
            "recipientEmail": to,
            "templateId": "_default",
            "dedupeKey": dedupe_key,
            "payload": {
                "subject": subject,
                "html": body,
                "text": body,
            },
        },
        timeout=10,
    )
    data = response.json()

    if not response.ok:
        return f"FAILED (HTTP {response.status_code}): {data.get('message') or data.get('error')}"

    if data.get("status") == "blocked":
        return (
            f"BLOCKED: {data.get('reason')}. "
            f"Decision trace ID: {data.get('requestId')}. "
            "Do not retry this send."
        )

    return f"Queued: requestId={data.get('requestId')}, status={data.get('status')}"


def check_email_status(
    request_id: Annotated[str, "The requestId returned when the email was queued"],
) -> str:
    """Check the delivery events (sent, delivered, bounced, ...) of a previously queued email."""
    response = requests.get(
        f"https://mailbox.molted.email/v1/agent/messages/{request_id}/events",
        headers={"Authorization": f"Bearer {os.environ['MOLTED_API_KEY']}"},
        timeout=10,
    )
    events = response.json().get("events", [])
    if not events:
        return "No delivery events yet."
    # Oldest first: e.g. "sent", then "delivered" or "bounced"
    return "\n".join(f"{e['created_at']} {e['event_type']}" for e in events)
```

## 3. Register tools with AssistantAgent

```python title="agents.py"
import os
from autogen import AssistantAgent, UserProxyAgent
from email_tools import send_email, check_email_status

llm_config = {
    "config_list": [{"model": "gpt-4o", "api_key": os.environ["OPENAI_API_KEY"]}],
    "temperature": 0,
}

assistant = AssistantAgent(
    name="EmailAgent",
    system_message=(
        "You are an email outreach agent. You send policy-checked emails on behalf of "
        "the user. When sending emails:\n"
        "- Always provide a descriptive dedupeKey (e.g. 'welcome-alice@example.com') "
        "  to prevent accidental duplicate sends.\n"
        "- If a send returns BLOCKED, report the reason to the user and do not retry.\n"
        "- After sending, confirm the requestId to the user.\n"
        "- Do not attempt to send to suppressed or opted-out contacts."
    ),
    llm_config=llm_config,
)

user_proxy = UserProxyAgent(
    name="User",
    human_input_mode="NEVER",
    max_consecutive_auto_reply=5,
    code_execution_config=False,
)

# Register the send and status tools
assistant.register_for_llm(name="send_email", description=send_email.__doc__)(send_email)
assistant.register_for_llm(name="check_email_status", description=check_email_status.__doc__)(check_email_status)

user_proxy.register_for_execution(name="send_email")(send_email)
user_proxy.register_for_execution(name="check_email_status")(check_email_status)

# Start a conversation
user_proxy.initiate_chat(
    assistant,
    message=(
        "Send a trial welcome email to alice@example.com. "
        "Subject: 'Welcome to your trial'. "
        "Body: 'Your 14-day trial starts today. Reply if you have any questions.'"
    ),
)
```

## 4. Multi-agent conversations with email

In GroupChat setups, you may want only specific agents to be able to send email. Assign the tools only to the agents that should have send access:

```python title="group_chat.py"
import os
from autogen import AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager
from email_tools import send_email, check_email_status

llm_config = {
    "config_list": [{"model": "gpt-4o", "api_key": os.environ["OPENAI_API_KEY"]}],
}

# Outreach agent - can send email
outreach_agent = AssistantAgent(
    name="OutreachAgent",
    system_message=(
        "You send policy-compliant outreach emails. "
        "Always use a descriptive dedupeKey. "
        "Report BLOCKED sends to the group without retrying."
    ),
    llm_config=llm_config,
)

# Research agent - no email access
research_agent = AssistantAgent(
    name="ResearchAgent",
    system_message=(
        "You research contacts and draft email content. "
        "You do not send emails - pass your drafts to OutreachAgent."
    ),
    llm_config=llm_config,
)

user_proxy = UserProxyAgent(
    name="User",
    human_input_mode="TERMINATE",
    code_execution_config=False,
)

# Only register email tools on the outreach agent and executor
outreach_agent.register_for_llm(name="send_email", description=send_email.__doc__)(send_email)
outreach_agent.register_for_llm(name="check_email_status", description=check_email_status.__doc__)(check_email_status)
user_proxy.register_for_execution(name="send_email")(send_email)
user_proxy.register_for_execution(name="check_email_status")(check_email_status)

group_chat = GroupChat(
    agents=[user_proxy, research_agent, outreach_agent],
    messages=[],
    max_round=10,
)

manager = GroupChatManager(groupchat=group_chat, llm_config=llm_config)

user_proxy.initiate_chat(
    manager,
    message="Research and send a personalized trial invitation to bob@example.com who leads engineering at Acme Corp.",
)
```

## 5. Using the function-calling API directly (AutoGen 0.4+)

AutoGen 0.4+ uses a different tool registration pattern with `FunctionTool`:

```python title="agents_v04.py"
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import TextMentionTermination
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_core.tools import FunctionTool
from autogen_ext.models.openai import OpenAIChatCompletionClient
from email_tools import send_email, check_email_status

model_client = OpenAIChatCompletionClient(model="gpt-4o")

send_tool = FunctionTool(send_email, description=send_email.__doc__ or "Send a policy-checked email")
status_tool = FunctionTool(check_email_status, description=check_email_status.__doc__ or "Check email delivery status")

email_agent = AssistantAgent(
    name="EmailAgent",
    model_client=model_client,
    tools=[send_tool, status_tool],
    system_message=(
        "You send policy-checked emails. Always include a descriptive dedupeKey. "
        "Report BLOCKED sends without retrying. "
        "Say 'TERMINATE' when the task is complete."
    ),
)

termination = TextMentionTermination("TERMINATE")
team = RoundRobinGroupChat([email_agent], termination_condition=termination)

import asyncio

async def main():
    result = await team.run(
        task="Send a welcome email to carol@example.com. Subject: 'Welcome!' Body: 'Thanks for signing up.'"
    )
    print(result)

asyncio.run(main())
```

## 6. Policy block handling

The policy engine may block a send for several reasons. Include explicit handling instructions in each agent's `system_message`:

| Reason | What it means | Recommended agent behavior |
| - | - | - |
| `duplicate` | This `dedupeKey` was already used by an earlier request. Dedupe is permanent, whatever became of that request | Do not retry with the same key. To send the same email again on purpose, use a new key |
| `suppressed` | The recipient is suppressed (unsubscribed, hard-bounced, or complained) | Skip this contact, do not retry |
| `cooldown` | The recipient was emailed too recently | Try later, or report it |
| `hourly_limit_exceeded`, `daily_limit_exceeded`, `monthly_limit_exceeded` | A send quota is used up | Pause and report; retry after the window with a new `dedupeKey` |
| `no_consent` | The tenant turned on `requireConsentForMarketing` and the recipient has no consent on file | Do not send; record consent first |
| `lease_conflict` | Another agent holds a lease on this contact | Wait for the lease to end (see [Agent Coordination](https://molted.email/docs/agents.md#contact-leases)) |
| `trial_not_activated` | The account has no active plan yet | Ask a human to activate billing |

A blocked request has used up its `dedupeKey`: once the cause is fixed, retry with a new one. Every reason is listed in [Errors](https://molted.email/docs/errors.md).

## 7. Per-agent registration for accountability

Register each AutoGen agent that sends email with Molted, using a separate API key per agent. With `bindKey: true` the key is bound to that agent for good, so the decision trace attributes every send the key makes to it, and the agent's own config (such as its humanizer setting) applies. Rate limits stay per mailbox and tenant, not per agent.

```python
import os
import requests

agents_to_register = [
    {"agentName": "outreach-agent", "key": os.environ["OUTREACH_AGENT_KEY"]},
    {"agentName": "followup-agent", "key": os.environ["FOLLOWUP_AGENT_KEY"]},
]

for agent in agents_to_register:
    response = requests.post(
        "https://mailbox.molted.email/v1/agent/register",
        headers={
            "Authorization": f"Bearer {agent['key']}",
            "Content-Type": "application/json",
        },
        json={"agentName": agent["agentName"], "bindKey": True},
    )
    data = response.json()
    print(f"Registered {agent['agentName']}: agentId={data['id']}, key binding: {data['apiKeyBinding']}")
```

Each agent's send function then uses its own key. See [Agent Coordination](https://molted.email/docs/agents.md) for leases and consensus.

## Related

- [Quickstart](https://molted.email/docs/quickstart.md) - send your first policy-checked email
- [LangChain Integration Guide](https://molted.email/docs/langchain-integration-guide.md) - LangChain TypeScript setup
- [CrewAI Integration Guide](https://molted.email/docs/crewai-integration-guide.md) - CrewAI Python setup
- [Policy Simulation](https://molted.email/docs/policy-simulation.md) - test policy rules before going live
- [Reactive Agent Guide](https://molted.email/docs/reactive-agent-guide.md) - respond to inbound replies
- [Agent Coordination](https://molted.email/docs/agents.md) - multi-agent leases and consensus
- [Autonomy Levels](https://molted.email/docs/autonomy-levels.md) - require human approval for high-risk sends
