> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# AutoGen multi-agent integration

> Connect Microsoft AutoGen to the AI Gateway for multi-agent workflows. Build collaborative AI systems with enhanced routing, caching, and observability.

> [card] [AI Gateway](#ai-gateway)
>
> Route your LLM calls through the AI Gateway with a single base URL change. Zero vendor lock-in: always run on the best model at the lowest cost for your use case.

> [card] [Observability](#observability)
>
> Instrument your code with OpenTelemetry to capture traces, logs, and metrics for every LLM call, agent step, and tool use.

## AI Gateway

### Overview

Microsoft AutoGen is a framework for building multi-agent conversational AI systems with collaborative problem-solving through automated agent interactions. By connecting AutoGen to Toqan Router's AI Gateway, you get access to 500+ models for your multi-agent workflows with a single configuration change.

### Key Benefits

Toqan Router's AI Gateway enhances your AutoGen applications with:

> [card] Complete Observability
>
> Track every agent conversation, tool use, and multi-agent interaction

> [card] Built-in Reliability
>
> Automatic fallbacks, retries, and load balancing for production resilience

> [card] Cost Optimization
>
> Real-time cost tracking and spend management across all your AI operations

> [card] Multi-Provider Access
>
> Access 500+ LLMs and 30+ providers through a single, unified integration

### Prerequisites

Before integrating AutoGen with Toqan Router, ensure you have:

* A Toqan Router account and API Key
* Python 3.10 or higher

> [!NOTE]
>
> To setup your API key, see API keys & Endpoints.

### Installation

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
pip install "autogen-agentchat" "autogen-ext[openai]"
```

### Configuration

Configure AutoGen to use Toqan Router's AI Gateway via `OpenAIChatCompletionClient` with a custom `base_url`:

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import os
from autogen_ext.models.openai import OpenAIChatCompletionClient

model_client = OpenAIChatCompletionClient(
    model="openai/gpt-5.6-sol",
    base_url="https://router.toqan.ai/eu/v3/router",
    api_key=os.getenv("TOQAN_API_KEY"),
    model_info={
        "vision": False,
        "function_calling": True,
        "json_output": True,
        "family": "unknown",
        "structured_output": True,
    },
)
```

> **base\_url**: `https://router.toqan.ai/eu/v3/router`

> [!NOTE]
>
> Set `model_info` for models AutoGen does not recognize, including provider-prefixed **AI Gateway** model IDs. It describes the model's capabilities.
>
> AutoGen can emit a `Resolved model mismatch` warning when the model name returned in a response differs from the requested model or AutoGen's model mapping. The warning does not by itself mean the request failed, and `model_info` does not suppress it. Check the returned model against the intended model and keep using a model ID supported by the **AI Gateway**.

### Basic Agent Example

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import asyncio
import os
from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient

async def main():
    model_client = OpenAIChatCompletionClient(
        model="openai/gpt-5.6-sol",
        base_url="https://router.toqan.ai/eu/v3/router",
        api_key=os.getenv("TOQAN_API_KEY"),
        model_info={
            "vision": False,
            "function_calling": True,
            "json_output": True,
            "family": "unknown",
            "structured_output": True,
        },
    )

    agent = AssistantAgent(
        name="assistant",
        model_client=model_client,
        system_message="You are a helpful assistant.",
    )

    result = await agent.run(task="What is quantum computing?")
    print(result.messages[-1].content)
    await model_client.close()

asyncio.run(main())
```

### Multi-Agent Team

Orchestrate multiple specialized agents with `RoundRobinGroupChat`:

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import asyncio
import os
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.conditions import MaxMessageTermination
from autogen_ext.models.openai import OpenAIChatCompletionClient

async def main():
    model_client = OpenAIChatCompletionClient(
        model="openai/gpt-5.6-sol",
        base_url="https://router.toqan.ai/eu/v3/router",
        api_key=os.getenv("TOQAN_API_KEY"),
        model_info={
            "vision": False,
            "function_calling": True,
            "json_output": True,
            "family": "unknown",
            "structured_output": True,
        },
    )

    researcher = AssistantAgent(
        name="researcher",
        model_client=model_client,
        system_message="You research topics and provide key facts.",
    )

    writer = AssistantAgent(
        name="writer",
        model_client=model_client,
        system_message="You write clear summaries based on research.",
    )

    team = RoundRobinGroupChat(
        participants=[researcher, writer],
        termination_condition=MaxMessageTermination(max_messages=2),
    )

    result = await team.run(task="Research and summarize what LLMs are.")
    print(result.messages[-1].content)
    await model_client.close()

asyncio.run(main())
```

### Model Selection

With Toqan Router, you can use any supported model from 30+ providers:

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import os
from autogen_ext.models.openai import OpenAIChatCompletionClient

model_info = {
    "vision": False,
    "function_calling": True,
    "json_output": True,
    "family": "unknown",
    "structured_output": True,
}

# Use Claude
claude_client = OpenAIChatCompletionClient(
    model="anthropic/claude-sonnet-5",
    base_url="https://router.toqan.ai/eu/v3/router",
    api_key=os.getenv("TOQAN_API_KEY"),
    model_info=model_info,
)

# Use Gemini
gemini_client = OpenAIChatCompletionClient(
    model="google-ai/gemini-2.5-flash",
    base_url="https://router.toqan.ai/eu/v3/router",
    api_key=os.getenv("TOQAN_API_KEY"),
    model_info=model_info,
)

# Use Groq
groq_client = OpenAIChatCompletionClient(
    model="groq/qwen/qwen3.8-27b",
    base_url="https://router.toqan.ai/eu/v3/router",
    api_key=os.getenv("TOQAN_API_KEY"),
    model_info=model_info,
)
```

## Observability

### Getting Started

Microsoft AutoGen enables sophisticated multi-agent conversations and collaborative AI systems. Tracing AutoGen with Toqan Router provides deep insights into agent interactions, conversation flows, tool usage, and multi-agent coordination patterns to optimize your conversational AI applications.

### Prerequisites

Before you begin, ensure you have:

* A Toqan Router account and API Key
* Python 3.8+
* Microsoft AutoGen installed in your project
* OpenAI API key (or other LLM provider credentials)

### Install Dependencies

```bash Bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Core AutoGen and OpenTelemetry packages
pip install pyautogen opentelemetry-sdk opentelemetry-exporter-otlp-proto-http opentelemetry-instrumentation-openai

# LLM providers
pip install openai
```

### Configure Toqan Router

Set up your environment variables to connect to Toqan Router's OpenTelemetry collector:

**Unix/Linux/macOS:**

```bash Bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
export OTEL_EXPORTER_OTLP_ENDPOINT="https://router.toqan.ai/eu/v2/otel"
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer <TOQAN_API_KEY>"
export OTEL_RESOURCE_ATTRIBUTES="service.name=autogen-app,service.version=1.0.0"
export OPENAI_API_KEY="<YOUR_OPENAI_API_KEY>"
```

**Windows (PowerShell):**

```bash Bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
$env:OTEL_EXPORTER_OTLP_ENDPOINT = "https://router.toqan.ai/eu/v2/otel"
$env:OTEL_EXPORTER_OTLP_HEADERS = "Authorization=Bearer <TOQAN_API_KEY>"
$env:OTEL_RESOURCE_ATTRIBUTES = "service.name=autogen-app,service.version=1.0.0"
$env:OPENAI_API_KEY = "<YOUR_OPENAI_API_KEY>"
```

**Using .env file:**

```bash Bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
OTEL_EXPORTER_OTLP_ENDPOINT=https://router.toqan.ai/eu/v2/otel
OTEL_EXPORTER_OTLP_HEADERS=Authorization=Bearer <TOQAN_API_KEY>
OTEL_RESOURCE_ATTRIBUTES=service.name=autogen-app,service.version=1.0.0
OPENAI_API_KEY=<YOUR_OPENAI_API_KEY>
```

### Integration

AutoGen has built-in OpenTelemetry support. Configure the tracer provider and pass it to the AutoGen runtime.

> Set up OpenTelemetry tracing in your application:

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import os
import autogen
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.instrumentation.openai import OpenAIInstrumentor
from opentelemetry.sdk.trace.export import BatchSpanProcessor

# Configure tracer provider
tracer_provider = TracerProvider(
    resource=Resource({"service.name": "autogen-app"})
)

# Set up OTLP exporter
otlp_exporter = OTLPSpanExporter()

tracer_provider.add_span_processor(BatchSpanProcessor(otlp_exporter))
trace.set_tracer_provider(tracer_provider)

# Instrument OpenAI calls for automatic tracing
OpenAIInstrumentor().instrument(tracer_provider=tracer_provider)

config_list = [{"model": "gpt-5.6-sol", "api_key": os.getenv("OPENAI_API_KEY")}]

# Create agents
assistant = autogen.AssistantAgent(
    name="assistant",
    llm_config={"config_list": config_list, "temperature": 0}
)

user_proxy = autogen.UserProxyAgent(
    name="user_proxy",
    human_input_mode="NEVER",
    max_consecutive_auto_reply=3,
    code_execution_config={"work_dir": "coding", "use_docker": False}
)

print("Starting AutoGen conversation (this will be traced)...")

# Start conversation (automatically traced)
user_proxy.initiate_chat(
    assistant,
    message="Write a Python function to calculate fibonacci numbers up to n=10"
)
```

> [!TIP]
>
> All AutoGen agent conversations and interactions will be instrumented and exported to Toqan Router through the OTLP exporter. For more details, see [Traces](/docs/ai-studio/observability/traces.md).

### Advanced Examples

**Multi-Agent Group Chat**

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import autogen
import os
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.instrumentation.openai import OpenAIInstrumentor
from opentelemetry.sdk.trace.export import BatchSpanProcessor

# Configure tracer provider
tracer_provider = TracerProvider(
  resource=Resource({"service.name": "autogen-app"})
)

# Set up OTLP exporter
otlp_exporter = OTLPSpanExporter()

tracer_provider.add_span_processor(BatchSpanProcessor(otlp_exporter))
trace.set_tracer_provider(tracer_provider)

# Instrument OpenAI calls for automatic tracing
OpenAIInstrumentor().instrument(tracer_provider=tracer_provider)

# Setup done as shown in Integration section above

config_list = [{"model": "gpt-5.6-sol", "api_key": os.getenv("OPENAI_API_KEY")}]

# Create specialized agents
coder = autogen.AssistantAgent(
    name="coder",
    system_message="You are an expert Python developer.",
    llm_config={"config_list": config_list}
)

reviewer = autogen.AssistantAgent(
    name="code_reviewer",
    system_message="You review code for quality and best practices.",
    llm_config={"config_list": config_list}
)

user_proxy = autogen.UserProxyAgent(
    name="user_proxy",
    human_input_mode="NEVER",
    max_consecutive_auto_reply=5,
    code_execution_config={"work_dir": "workspace"}
)

# Create group chat
groupchat = autogen.GroupChat(
    agents=[user_proxy, coder, reviewer],
    messages=[],
    max_round=10
)

manager = autogen.GroupChatManager(
    groupchat=groupchat,
    llm_config={"config_list": config_list}
)

# Start group conversation (automatically traced)
user_proxy.initiate_chat(
    manager,
    message="Create a REST API for user management with FastAPI"
)
```

**Agent with Custom Tools**

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import autogen
import os
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.instrumentation.openai import OpenAIInstrumentor
from opentelemetry.sdk.trace.export import BatchSpanProcessor

# Configure tracer provider
tracer_provider = TracerProvider(
  resource=Resource({"service.name": "autogen-app"})
)

# Set up OTLP exporter
otlp_exporter = OTLPSpanExporter()

tracer_provider.add_span_processor(BatchSpanProcessor(otlp_exporter))
trace.set_tracer_provider(tracer_provider)

# Instrument OpenAI calls for automatic tracing
OpenAIInstrumentor().instrument(tracer_provider=tracer_provider)

config_list = [{"model": "gpt-5.6-sol", "api_key": os.getenv("OPENAI_API_KEY")}]

# Define custom tools/functions
def get_weather(location: str) -> str:
    """Get current weather for a location."""
    return f"Weather in {location}: Sunny, 75°F"

def calculate_distance(city1: str, city2: str) -> str:
    """Calculate distance between two cities."""
    return f"Distance between {city1} and {city2}: 500 km"

# Create agent with function calling
travel_planner = autogen.AssistantAgent(
    name="travel_planner",
    system_message="You help plan travel itineraries.",
    llm_config={
        "config_list": config_list,
        "functions": [
            {
                "name": "get_weather",
                "description": "Get current weather for a location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {"type": "string"}
                    },
                    "required": ["location"]
                }
            },
            {
                "name": "calculate_distance",
                "description": "Calculate distance between cities",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "city1": {"type": "string"},
                        "city2": {"type": "string"}
                    },
                    "required": ["city1", "city2"]
                }
            }
        ]
    }
)

user_proxy = autogen.UserProxyAgent(
    name="user",
    human_input_mode="NEVER",
    max_consecutive_auto_reply=5,
    function_map={
        "get_weather": get_weather,
        "calculate_distance": calculate_distance
    },
    code_execution_config=False
)

# Use agent with tools (automatically traced)
user_proxy.initiate_chat(
    travel_planner,
    message="Plan a 3-day trip from New York to London"
)
```

> [!NOTE]
>
> AutoGen is also usable through our [AI Gateway](#ai-gateway). To learn more, see [AutoGen Gateway](#ai-gateway).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.