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

# Autogen

> Use Prisma AIRS AI Gateway with Autogen to take your AI Agents to production

## Getting Started

### 1. Install the required packages

```sh theme={"system"}
pip install -U "autogen-agentchat" "autogen-ext[openai,azure]"
```

### 2. Quickstart: Autogen AgentChat with the AI Gateway

```python theme={"system"}
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.ui import Console
from autogen_core.models import ModelFamily

from autogen_ext.models.openai import OpenAIChatCompletionClient
import asyncio

# Define a model client that talks to the AI Gateway's OpenAI-compatible endpoint.
# Use a Model Catalog model string: "@provider_slug/model_name"
model_client = OpenAIChatCompletionClient(
    base_url="https://aigw.portkey.ai/v1",
    api_key="YOUR_PORTKEY_API_KEY",
    model="@your-provider-slug/gpt-4o",
    model_info={
        "vision": True,
        "function_calling": True,
        "json_output": True,
        "structured_output": True,
        # Use GPT family for gpt-4o to allow tools + system message
        "family": ModelFamily.GPT_45,
    },
    # Optional headers: attach AI Gateway Configs, tracing, or metadata
    default_headers={
        "x-portkey-config": "pc-xxxx",
        "x-portkey-trace-id": "trace-id",
    }
)

# Define a simple function tool that the agent can use.
async def get_weather(city: str) -> str:
    """Get the weather for a given city."""
    return f"The weather in {city} is 73 degrees and Sunny."

# Create an AssistantAgent with the Portkey-backed model client
agent = AssistantAgent(
    name="weather_agent",
    model_client=model_client,
    tools=[get_weather],
    system_message="You are a helpful assistant.",
    reflect_on_tool_use=True,
    model_client_stream=True,  # Enable token streaming
)

async def main() -> None:
    await Console(agent.run_stream(task="What is the weather in New York?"))
    await model_client.close()

if __name__ == "__main__":
    asyncio.run(main())
```

<Note>
  #### Model Catalog

  * The AI Gateway now uses Model Catalog instead of Virtual Keys. Reference models directly with `model="@provider_slug/model_name"`.
  * Learn more: [Upgrade to Model Catalog](/docs/support/upgrade-to-model-catalog) and [Model Catalog](/docs/aigw/product/model-catalog).
</Note>

## Production Features

### 1. Enhanced Observability

The AI Gateway provides comprehensive observability for your Autogen agents, helping you understand exactly what's happening during each execution.

<Tabs>
  <Tab title="Traces">
    Traces provide a hierarchical view of your agent's execution, showing the sequence of LLM calls, tool invocations, and state transitions.

    ```python theme={"system"}
    from autogen_agentchat.agents import AssistantAgent
    from autogen_agentchat.ui import Console
    from autogen_ext.models.openai import OpenAIChatCompletionClient
    from autogen_core.models import ModelFamily
    import asyncio

    # Add tracing to your Autogen agents via gateway headers
    model_client = OpenAIChatCompletionClient(
        base_url="https://aigw.portkey.ai/v1",
        api_key="YOUR_PORTKEY_API_KEY",
        model="@your-provider-slug/gpt-4o",
        model_info={"family": ModelFamily.GPT_45},
        default_headers={
            "x-portkey-trace-id": "unique_execution_trace_id"
        }
    )

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

    async def main():
        await Console(agent.run_stream(task="Say hello"))
        await model_client.close()

    asyncio.run(main())
    ```
  </Tab>

  <Tab title="Logs">
    AI Gateway logs every interaction with LLMs, including:

    * Complete request and response payloads
    * Latency and token usage metrics
    * Cost calculations
    * Tool calls and function executions

    All logs can be filtered by metadata, trace IDs, models, and more, making it easy to debug specific agent runs.
  </Tab>

  <Tab title="Metrics & Dashboards">
    The AI Gateway provides built-in dashboards that help you:

    * Track cost and token usage across all agent runs
    * Analyze performance metrics like latency and success rates
    * Identify bottlenecks in your agent workflows
    * Compare different agent configurations and LLMs

    You can filter and segment all metrics by custom metadata to analyze specific agent types, user groups, or use cases.
  </Tab>

  <Tab title="Metadata Filtering">
    Add custom metadata to your Autogen agent calls to enable powerful filtering and segmentation:

    This metadata can be used to filter logs, traces, and metrics on Strata Cloud Manager, allowing you to analyze specific agent runs, users, or environments.
  </Tab>
</Tabs>

### 2. Reliability - Keep Your Autogen Agents Running Smoothly

When running agents in production, things can go wrong - API rate limits, network issues, or provider outages. The AI Gateway's reliability features ensure your agents keep running smoothly even when problems occur.

It's this simple to enable fallback in your Autogen agents:

```python theme={"system"}
import json
from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_core.models import ModelFamily

# Create a config with fallbacks (prefer creating this in Strata Cloud Manager)
config = {
  "strategy": {"mode": "fallback"},
  "targets": [
    {"override_params": {"model": "@your-provider-slug/gpt-4o"}},
    {"override_params": {"model": "@your-anthropic-provider/claude-3-opus-20240229"}}
  ]
}

model_client = OpenAIChatCompletionClient(
    base_url="https://aigw.portkey.ai/v1",
    api_key="YOUR_PORTKEY_API_KEY",
    model="@your-provider-slug/gpt-4o",
    model_info={"family": ModelFamily.GPT_45},
    default_headers={"x-portkey-config": json.dumps(config)}
)

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

This configuration will automatically try Claude if the GPT-4o request fails, ensuring your agent can continue operating.

<CardGroup cols="2">
  <Card title="Automatic Retries" icon="rotate" href="../../product/ai-gateway/automatic-retries">
    Handles temporary failures automatically. If an LLM call fails, the AI Gateway will retry the same request for the specified number of times - perfect for rate limits or network blips.
  </Card>

  <Card title="Request Timeouts" icon="clock" href="../../product/ai-gateway/request-timeouts">
    Prevent your agents from hanging. Set timeouts to ensure you get responses (or can fail gracefully) within your required timeframes.
  </Card>

  <Card title="Conditional Routing" icon="route" href="../../product/ai-gateway/conditional-routing">
    Send different requests to different providers. Route complex reasoning to GPT-4, creative tasks to Claude, and quick responses to Gemini based on your needs.
  </Card>

  <Card title="Fallbacks" icon="shield" href="../../product/ai-gateway/fallbacks">
    Keep running even if your primary provider fails. Automatically switch to backup providers to maintain availability.
  </Card>

  <Card title="Load Balancing" icon="scale-balanced" href="../../product/ai-gateway/load-balancing">
    Spread requests across multiple API keys or providers. Great for high-volume agent operations and staying within rate limits.
  </Card>
</CardGroup>

### 3. Prompting in Autogen Agents

The AI Gateway's Prompt Engineering Studio helps you create, manage, and optimize the prompts used in your Autogen agents. Instead of hardcoding prompts or instructions, use the AI Gateway's prompt rendering API to dynamically fetch and apply your versioned prompts.

<Tabs>
  <Tab title="Prompt Playground">
    Prompt Playground is a place to compare, test and deploy perfect prompts for your AI application. It's where you experiment with different models, test variables, compare outputs, and refine your prompt engineering strategy before deploying to production. It allows you to:

    1. Iteratively develop prompts before using them in your agents
    2. Test prompts with different variables and models
    3. Compare outputs between different prompt versions
    4. Collaborate with team members on prompt development

    This visual environment makes it easier to craft effective prompts for each step in your Autogen agent's workflow.
  </Tab>

  <Tab title="Using Prompt Templates">
    The Prompt Render API retrieves your prompt templates with all parameters configured:
  </Tab>

  <Tab title="Prompt Versioning">
    You can:

    * Create multiple versions of the same prompt
    * Compare performance between versions
    * Roll back to previous versions if needed
    * Specify which version to use in your request
  </Tab>

  <Tab title="Mustache Templating for variables">
    AI Gateway prompts use Mustache-style templating for easy variable substitution:

    ```
    You are an AI assistant helping with {{task_type}}.

    User question: {{user_input}}

    Please respond in a {{tone}} tone and include {{required_elements}}.
    ```

    When rendering, simply pass the variables:
  </Tab>
</Tabs>

### 4. Guardrails for Safe Autogen Agents

Guardrails ensure your Autogen agents operate safely and respond appropriately in all situations.

**Why Use Guardrails?**

Autogen agents can experience various failure modes:

* Generating harmful or inappropriate content
* Leaking sensitive information like PII
* Hallucinating incorrect information
* Generating outputs in incorrect formats

The AI Gateway's guardrails protect against these issues by validating both inputs and outputs.

**Implementing Guardrails**

```python theme={"system"}
import json
from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_core.models import ModelFamily

# Create a config with input and output guardrails (prefer using Strata Cloud Manager)
config = {
    "input_guardrails": ["guardrails-id-xxx", "guardrails-id-yyy"],
    "output_guardrails": ["guardrails-id-xxx"]
}

model_client = OpenAIChatCompletionClient(
    base_url="https://aigw.portkey.ai/v1",
    api_key="YOUR_PORTKEY_API_KEY",
    model="@your-provider-slug/gpt-4o",
    model_info={"family": ModelFamily.GPT_45},
    default_headers={"x-portkey-config": json.dumps(config)}
)

agent = AssistantAgent(
    name="safe_agent",
    model_client=model_client,
    system_message="You are a helpful assistant that provides safe responses."
)
```

The AI Gateway's guardrails can:

* Detect and redact PII in both inputs and outputs
* Filter harmful or inappropriate content
* Validate response formats against schemas
* Check for hallucinations against ground truth
* Apply custom business logic and rules

<Card title="Learn More About Guardrails" icon="shield-check" href="/docs/aigw/product/guardrails">
  Explore the AI Gateway's guardrail features to enhance agent safety
</Card>

### 5. User Tracking with Metadata

Track individual users through your Autogen agents using the AI Gateway's metadata system.

**What is Metadata in the AI Gateway?**

Metadata allows you to associate custom data with each request, enabling filtering, segmentation, and analytics. The special `_user` field is specifically designed for user tracking.

**Filter Analytics by User**

With metadata in place, you can filter analytics by user and analyze performance metrics on a per-user basis:

This enables:

* Per-user cost tracking and budgeting
* Personalized user analytics
* Team or organisation-level metrics
* Environment-specific monitoring (staging vs. production)

<Card title="Learn More About Metadata" icon="tags" href="/docs/aigw/product/observability/metadata">
  Explore how to use custom metadata to enhance your analytics
</Card>

### 6. Caching for Efficient Agents

Implement caching to make your Autogen agents more efficient and cost-effective:

<Tabs>
  <Tab title="Simple Caching">
    ```python theme={"system"}
    import json
    from autogen_agentchat.agents import AssistantAgent
    from autogen_ext.models.openai import OpenAIChatCompletionClient
    from autogen_core.models import ModelFamily

    gateway_config = {"cache": {"mode": "simple"}}

    model_client = OpenAIChatCompletionClient(
        base_url="https://aigw.portkey.ai/v1",
        api_key="YOUR_PORTKEY_API_KEY",
        model="@your-provider-slug/gpt-4o",
        model_info={"family": ModelFamily.GPT_45},
        default_headers={"x-portkey-config": json.dumps(gateway_config)}
    )

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

    Simple caching performs exact matches on input prompts, caching identical requests to avoid redundant model executions.
  </Tab>
</Tabs>

### 7. Model Interoperability: using different LLMs

One of the AI Gateway's key strengths is providing access to 3,000+ LLMs through a unified interface. Here's how to use different providers with Autogen:

<Card title="Supported Providers" icon="server" href="/docs/aigw/integrations/llms">
  See the full list of LLM providers supported by the AI Gateway
</Card>

<Tabs>
  <Tab title="OpenAI">
    ```python theme={"system"}
    model_client = OpenAIChatCompletionClient(
        base_url="https://aigw.portkey.ai/v1",
        api_key="YOUR_PORTKEY_API_KEY",
        model="@your-openai-provider-slug/gpt-4o",
    )
    ```
  </Tab>

  <Tab title="Anthropic">
    ```python theme={"system"}
    model_client = OpenAIChatCompletionClient(
        base_url="https://aigw.portkey.ai/v1",
        api_key="YOUR_PORTKEY_API_KEY",
        model="@your-anthropic-provider-slug/claude-3-7-sonnet-latest",
    )
    ```
  </Tab>

  <Tab title="Google">
    ```python theme={"system"}
    model_client = OpenAIChatCompletionClient(
        base_url="https://aigw.portkey.ai/v1",
        api_key="YOUR_PORTKEY_API_KEY",
        model="@your-google-provider-slug/gemini-2.5-pro",
    )
    ```
  </Tab>
</Tabs>

## Set Up Enterprise Governance for Autogen agents

**Why Enterprise Governance?**
If you are using Autogen agents inside your organisation, you need to consider several governance aspects:

* **Cost Management**: Controlling and tracking AI spending across teams
* **Access Control**: Managing which teams can use specific models
* **Usage Analytics**: Understanding how AI is being used across the organisation
* **Security & Compliance**: Maintaining enterprise security standards
* **Reliability**: Ensuring consistent service across all users

The AI Gateway adds a comprehensive governance layer to address these enterprise needs. Let's implement these controls step by step.

**Enterprise Implementation Guide**

The AI Gateway allows you to use 3,000+ LLMs with your Autogen setup, with minimal configuration required. Let's set up the core components in the AI Gateway that you'll need for integration.

<AccordionGroup>
  <Accordion title="Step 1: Implement Budget Controls & Rate Limits">
    ### Step 1: Implement Budget Controls & Rate Limits

    Model Catalog enables you to have granular control over LLM access at the team/department level. This helps you:

    * Set up [budget limits](/docs/aigw/product/model-catalog/integrations#3-budget-%26-rate-limits)
    * Prevent unexpected usage spikes using Rate limits
    * Track departmental spending

    #### Setting Up Department-Specific Controls:

    1. Navigate to [Model Catalog](https://stratacloudmanager.paloaltonetworks.com/) in Strata Cloud Manager
    2. Create new Provider for each engineering team with budget limits and rate limits
    3. Configure department-specific limits
  </Accordion>

  <Accordion title="Step 2: Define Model Access Rules">
    ### Step 2: Define Model Access Rules

    As your AI usage scales, controlling which teams can access specific models becomes crucial. You can simply manage AI models in your org by provisioning model at the top integration level.
  </Accordion>

  <Accordion title="Step 4: Set Routing Configuration">
    The AI Gateway allows you to control your routing logic very simply with it's Configs feature. AI Gateway Configs provide this control layer with things like:

    * **Data Protection**: Implement guardrails for sensitive code and data
    * **Reliability Controls**: Add fallbacks, load-balance, retry and smart conditional routing logic
    * **Caching**: Implement Simple and Semantic Caching. and more....

    #### Example Configuration:

    Here's a basic configuration to load-balance requests to OpenAI and Anthropic:

    ```json theme={"system"}
    {
      "strategy": {
    		"mode": "load-balance"
      },
      "targets": [
        {
    			"override_params": {
    				"model": "@YOUR_OPENAI_PROVIDER-SLUG/MODEL_NAME"
    			}
        },
        {
    			"override_params": {
    				"model": "@YOUR_ANTHROPIC_PROVIDER-SLUG/MODEL_NAME"
    			}
        }
      ]
    }
    ```

    Create your config on the [Configs page](https://stratacloudmanager.paloaltonetworks.com/) in Strata Cloud Manager. You'll need the config ID for connecting to your Autogen setup.

    <Note>
      Configs can be updated anytime to adjust controls without affecting running applications.
    </Note>
  </Accordion>

  <Accordion title="Step 4: Implement Access Controls">
    ### Step 3: Implement Access Controls

    Create User-specific API keys that automatically:

    * Track usage per developer/team with the help of metadata
    * Apply appropriate configs to route requests
    * Collect relevant metadata to filter logs
    * Enforce access permissions

    Create API keys through:

    * [Strata Cloud Manager](https://stratacloudmanager.paloaltonetworks.com/)
    * [API Key Management API](/docs/api-reference/admin-api/control-plane/api-keys/create-api-key)

    Example using Python SDK:

    For detailed key management instructions, see our [API Keys documentation](/docs/api-reference/admin-api/control-plane/api-keys/create-api-key).
  </Accordion>

  <Accordion title="Step 5: Deploy & Monitor">
    ### Step 4: Deploy & Monitor

    After distributing API keys to your engineering teams, your enterprise-ready Autogen setup is ready to go. Each developer can now use their designated API keys with appropriate access levels and budget controls.
    Apply your governance setup using the integration steps from earlier sections
    Monitor usage in Strata Cloud Manager:

    * Cost tracking by engineering team
    * Model usage patterns for AI agent tasks
    * Request volumes
    * Error rates and debugging logs
  </Accordion>
</AccordionGroup>

<Check>
  ### Enterprise Features Now Available

  **Autogen agents now have:**

  * Departmental budget controls
  * Model access governance
  * Usage tracking & attribution
  * Security guardrails
  * Reliability features
</Check>

## Frequently Asked Questions

<AccordionGroup>
  <Accordion title="How does the AI Gateway enhance my Autogen agents?">
    The AI Gateway adds production-grade features to Autogen agents including comprehensive observability (traces, logs, analytics), reliability (fallbacks, retries, load balancing), access to 3,000+ LLMs, cost management, and enterprise governance - all without changing your agent logic.
  </Accordion>

  <Accordion title="Can I use any LLM with Autogen through the AI Gateway?">
    Yes! The AI Gateway provides access to 3,000+ LLMs from providers like OpenAI, Anthropic, Google, Cohere, and many more. Just change the model ID in your configuration to switch between providers.
  </Accordion>

  <Accordion title="How do I track costs for different agents?">
    The AI Gateway automatically tracks costs for all LLM calls. You can segment costs by agent type, user, or custom metadata. Set up AI Provider integrations with budget limits to control spending on Model Catalog.
  </Accordion>

  <Accordion title="Does Palo Alto Networks support all Autogen features?">
    Yes! The AI Gateway works seamlessly with Autogen's tool use and agent workflows. It adds observability and reliability without limiting any Autogen functionality.
  </Accordion>

  <Accordion title="How do I debug agent failures?">
    The AI Gateway's detailed logs and traces make debugging easy. You can see the complete execution flow, including failed tool calls, LLM errors, and retry attempts. Filter by trace ID or metadata to find specific issues.
  </Accordion>
</AccordionGroup>

## Resources

<CardGroup cols="3">
  <Card title="Autogen Documentation" icon="book" href="https://microsoft.github.io/autogen/stable/">
    Learn more about building agents with Autogen
  </Card>

  <Card title="AI Gateway Features" icon="sparkles" href="/docs/aigw/product/ai-gateway">
    Explore all AI Gateway capabilities
  </Card>
</CardGroup>


## Related topics

- [Autogen (DEPRECATED)](/docs/aigw/integrations/libraries/autogen.md)
- [Overview](/docs/aigw/integrations/agents.md)
- [Features](/docs/aigw/introduction/feature-overview.md)
