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

# Agno AI

> Use Portkey with Agno to build production-ready autonomous AI agents

## Introduction

Agno is a powerful framework for building autonomous AI agents that can reason, use tools, maintain memory, and access knowledge bases. Portkey enhances Agno agents with enterprise-grade capabilities for production deployments.

Portkey transforms your Agno agents into production-ready systems by providing:

* **Complete observability** of agent reasoning, tool usage, and knowledge retrieval
* **Access to 1600+ LLMs** through a unified interface
* **Built-in reliability** with fallbacks, retries, and load balancing
* **Cost tracking and optimization** across all agent operations
* **Advanced guardrails** for safe and compliant agent behavior
* **Enterprise governance** with budget controls and access management

<Card title="Agno AI Official Documentation" icon="arrow-up-right-from-square" href="https://docs.agno.com/introduction">
  Learn more about Agno's agent framework and core concepts
</Card>

## Setting Up Portkey

If this is your first time using Portkey, you will need to connect your LLM Provider in the app to use them in your Agno AI agents.

<Steps>
  <Step title="Create an Integration">
    Navigate to the [Integrations](https://app.portkey.ai/integrations) section on Portkey's Sidebar. This is where you'll connect your LLM providers.

    1. Find your preferred provider (e.g., OpenAI, Anthropic, etc.)
    2. Click **Connect** on the provider card
    3. In the "Create New Integration" window:
       * Enter a **Name** for reference
       * Enter a **Slug** for the integration
       * Enter your **API Key and other provider specific details** for the provider
    4. Click **Next Step**

    <Frame>
      <img src="https://mintcdn.com/portkey-docs-feature-comparison-update/gytOxJ2pz7sfAzcs/images/product/model-catalog/integrations-page.png?fit=max&auto=format&n=gytOxJ2pz7sfAzcs&q=85&s=875474079182d533672bf4f4effb9283" width="500" data-path="images/product/model-catalog/integrations-page.png" />
    </Frame>

    <Note>
      In your next step you'll see workspace provisioning options. You can select the default "Shared Team Workspace" if this is your first time OR chose your current one.
    </Note>
  </Step>

  <Step title="Configure Models">
    On the model provisioning page:

    * Leave all models selected (or customize)
    * Toggle Automatically enable new models if desired

    Click **Create Integration** to complete the integration

    <Frame>
      <img src="https://mintcdn.com/portkey-docs-feature-comparison-update/gytOxJ2pz7sfAzcs/images/product/model-catalog/model-provisioning-page.png?fit=max&auto=format&n=gytOxJ2pz7sfAzcs&q=85&s=d8fb8080c9b59c56911f1fe2d80040f9" width="500" data-path="images/product/model-catalog/model-provisioning-page.png" />
    </Frame>
  </Step>

  <Step title="Copy the Provider Slug">
    Once your Integration is created:

    1. Go to [Model Catalog](https://app.portkey.ai/model-catalog) → **AI Providers** tab
    2. Find your integration
    3. Copy the **slug** (e.g., `openai-dev`)

    <Frame>
      <img src="https://mintcdn.com/portkey-docs-feature-comparison-update/gytOxJ2pz7sfAzcs/images/product/model-catalog/model-catalog.png?fit=max&auto=format&n=gytOxJ2pz7sfAzcs&q=85&s=0443c55b09578ef92cc17be2dfe294df" width="500" data-path="images/product/model-catalog/model-catalog.png" />
    </Frame>

    <Note>
      This slug is your provider's unique identifier - you'll need it for the next step.
    </Note>
  </Step>
</Steps>

## Quickstart

You will need

* Portkey API Key & Portkey AI Provider slug from Step 1

<Steps>
  <Step title="Install required packages">
    ```bash theme={null}
    pip install -U agno portkey-ai
    ```
  </Step>

  <Step title="Get your Portkey API Key">
    Sign up at [app.portkey.ai](https://app.portkey.ai) to get your API key.

    Once you are on the Portkey follow this guide to create your first AI provider and integration that will help us connect Agno to any LLM provider.
  </Step>

  <Step title="Configure Portkey with Agno">
    Agno makes integration incredibly simple - just use the `OpenAILike` model class with Portkey's configuration:

    ```python theme={null}
    from agno.models.openai.like import OpenAILike

    portkey_model = OpenAILike(
        id="@opeani-provider-slug/gpt-4o",  # you need to use "@provider-slug/model-name" for any provider
        api_key="YOUR_PORTKEY_API_KEY",
        base_url="https://api.portkey.ai/v1",
    )
    ```
  </Step>
</Steps>

### Simple E2E example agent

Let's create a simple Agno agent that uses Portkey for LLM calls:

```python simple_agent.py theme={null}
from agno.agent import Agent
from agno.models.openai.like import OpenAILike

# Configure Portkey as the model provider
portkey_model = OpenAILike(
    id="@opeani-provider-slug/gpt-4o",  # You can use any model available on Portkey
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://api.portkey.ai/v1",
)

# Create an Agno agent with Portkey
agent = Agent(
    model=portkey_model,
    instructions="Be concise and informative.",
    markdown=True,
)

# Run the agent
agent.print_response("What is Portkey AI?", stream=True)
```

Visit your Portkey dashboard to see detailed logs of your agent's execution, including tool calls and model responses!

## Production Features

### 1. Enhanced Observability

Portkey provides comprehensive observability for your Agno agents, helping you understand exactly what's happening during each execution.

<Tabs>
  <Tab title="Traces">
    <Frame>
      <img src="https://mintcdn.com/portkey-docs-feature-comparison-update/gytOxJ2pz7sfAzcs/images/product/product-11-1.webp?fit=max&auto=format&n=gytOxJ2pz7sfAzcs&q=85&s=3b40756960c25ca14d04ed05f5fa8351" width="2224" height="1166" data-path="images/product/product-11-1.webp" />
    </Frame>

    Traces provide a hierarchical view of your agent's execution, showing the sequence of LLM calls, tool invocations, and state transitions.

    ```python theme={null}
    from agno.agent import Agent
    from agno.models.openai.like import OpenAILike
    from portkey_ai import createHeaders

    # Add tracing to your Agno agents
    portkey_model = OpenAILike(
        id="@opeani-provider-slug/gpt-4o",
        api_key="YOUR_PORTKEY_API_KEY",
        base_url="https://api.portkey.ai/v1",
        default_headers=createHeaders(
            trace_id="unique_execution_trace_id",  # Add unique trace ID
        )
    )

    agent = Agent(
        model=portkey_model,
        instructions="You are a helpful assistant.",
        markdown=True
    )
    ```
  </Tab>

  <Tab title="Logs">
    <Frame>
      <img src="https://mintcdn.com/portkey-docs-feature-comparison-update/gytOxJ2pz7sfAzcs/images/product/product-2.avif?fit=max&auto=format&n=gytOxJ2pz7sfAzcs&q=85&s=d732c10fc7d56c5d6c14c9100fcdc05b" width="800" height="492" data-path="images/product/product-2.avif" />
    </Frame>

    Portkey 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">
    <Frame>
      <img src="https://mintcdn.com/portkey-docs-feature-comparison-update/gytOxJ2pz7sfAzcs/images/product/dashboard.png?fit=max&auto=format&n=gytOxJ2pz7sfAzcs&q=85&s=c7919e29bd94f35f885833b0b5b0c1ee" width="600" height="348" data-path="images/product/dashboard.png" />
    </Frame>

    Portkey 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">
    <Frame>
      <img src="https://mintcdn.com/portkey-docs-feature-comparison-update/HqRkYxnvsa5KTaKa/images/metadata.png?fit=max&auto=format&n=HqRkYxnvsa5KTaKa&q=85&s=7216c497dcc45c1f5e31a026f59b5995" alt="Analytics with metadata filters" width="3156" height="1876" data-path="images/metadata.png" />
    </Frame>

    Add custom metadata to your Agno agent calls to enable powerful filtering and segmentation:

    ```python theme={null}
    from agno.agent import Agent
    from agno.models.openai.like import OpenAILike
    from portkey_ai import createHeaders

    # Add metadata to your Agno agents
    portkey_model = OpenAILike(
        id="@opeani-provider-slug/gpt-4o",
        api_key="YOUR_PORTKEY_API_KEY",
        base_url="https://api.portkey.ai/v1",
        default_headers=createHeaders(
            metadata={"agent_type": "research_agent"},  # Add custom metadata
        )
    )

    agent = Agent(
        model=portkey_model,
        name="Research Agent",
        instructions="You are a research assistant.",
        markdown=True
    )
    ```

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

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

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

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

```python theme={null}
from agno.agent import Agent
from agno.models.openai.like import OpenAILike
from portkey_ai import createHeaders

# Create a config with fallbacks
# It's recommended that you create the Config in Portkey App rather than hard-code the config JSON directly
config = {
  "strategy": {
    "mode": "fallback"
  },
  "targets": [
    {
      "override_params": {"model": "@opeani-provider-slug/gpt-4o"}
    },
    {
      "override_params": {"model": "claude-3-opus-20240229"}
    }
  ]
}

# Configure Portkey model with fallback config
portkey_model = OpenAILike(
    id="@opeani-provider-slug/gpt-4o",
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://api.portkey.ai/v1",
    default_headers=createHeaders(config=config)
)

agent = Agent(
    model=portkey_model,
    instructions="You are a helpful assistant.",
    markdown=True
)
```

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, Portkey 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 Agno Agents

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

<Frame caption="Manage prompts in Portkey's Prompt Library">
  <img src="https://mintcdn.com/portkey-docs-feature-comparison-update/pWqh3PZZs-u6XJtb/images/product/ai-gateway/ai-20.webp?fit=max&auto=format&n=pWqh3PZZs-u6XJtb&q=85&s=6e793c4e4e406892f472c692796d511f" alt="Prompt Playground Interface" width="2304" height="1302" data-path="images/product/ai-gateway/ai-20.webp" />
</Frame>

<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 Agno agent's workflow.
  </Tab>

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

    ```python theme={null}
    from agno.agent import Agent
    from agno.models.openai.like import OpenAILike
    from portkey_ai import Portkey, createHeaders

    # Initialize Portkey client
    portkey_client = Portkey(api_key="PORTKEY_API_KEY")

    # Retrieve prompt using the render API
    prompt_data = portkey_client.prompts.render(
        prompt_id="YOUR_PROMPT_ID",
        variables={
            "user_input": "Tell me about artificial intelligence"
        }
    )

    # Configure Agno model with Portkey
    portkey_model = OpenAILike(
        id="@opeani-provider-slug/gpt-4o",
        api_key="YOUR_PORTKEY_API_KEY",
        base_url="https://api.portkey.ai/v1",
    )

    # Use the rendered prompt in your Agno agent
    agent = Agent(
        name="Assistant",
        model=portkey_model,
        instructions=prompt_data.data.messages[0]["content"],  # Use the rendered prompt as instructions
        markdown=True
    )

    agent.print_response("Tell me about artificial intelligence", stream=True)
    ```
  </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 code:

    ```python theme={null}
    # Use a specific prompt version
    prompt_data = portkey_client.prompts.render(
        prompt_id="YOUR_PROMPT_ID@version_number",
        variables={
            "user_input": "Tell me about quantum computing"
        }
    )
    ```
  </Tab>

  <Tab title="Mustache Templating for variables">
    Portkey 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:

    ```python theme={null}
    prompt_data = portkey_client.prompts.render(
        prompt_id="YOUR_PROMPT_ID",
        variables={
            "task_type": "research",
            "user_input": "Tell me about quantum computing",
            "tone": "professional",
            "required_elements": "recent academic references"
        }
    )
    ```
  </Tab>
</Tabs>

<Card title="Prompt Engineering Studio" icon="wand-magic-sparkles" href="/product/prompt-library">
  Learn more about Portkey's prompt management features
</Card>

### 4. Guardrails for Safe Agents

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

**Why Use Guardrails?**

Agno agents can experience various failure modes:

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

Portkey's guardrails protect against these issues by validating both inputs and outputs.

**Implementing Guardrails**

```python theme={null}
from agno.agent import Agent
from agno.models.openai.like import OpenAILike
from portkey_ai import createHeaders

# Create a config with input and output guardrails
# It's recommended you create Config in Portkey App and pass the config ID in the client
config = {
    "input_guardrails": ["guardrails-id-xxx", "guardrails-id-yyy"],
    "output_guardrails": ["guardrails-id-xxx"]
}

# Configure Agno model with guardrails
portkey_model = OpenAILike(
    id="@opeani-provider-slug/gpt-4o",
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://api.portkey.ai/v1",
    default_headers=createHeaders(
        config=config,
    )
)

agent = Agent(
    model=portkey_model,
    instructions="You are a helpful assistant that provides safe responses.",
    markdown=True
)
```

Portkey'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="/product/guardrails">
  Explore Portkey's guardrail features to enhance agent safety
</Card>

### 5. User Tracking with Metadata

Track individual users through your Agno agents using Portkey's metadata system.

**What is Metadata in Portkey?**

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.

```python theme={null}
from agno.agent import Agent
from agno.models.openai.like import OpenAILike
from portkey_ai import createHeaders

# Configure model with user tracking
portkey_model = OpenAILike(
    id="@opeani-provider-slug/gpt-4o",
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://api.portkey.ai/v1",
    default_headers=createHeaders(
        metadata={
            "_user": "user_123",  # Special _user field for user analytics
            "user_name": "John Doe",
            "user_tier": "premium",
            "user_company": "Acme Corp"
        }
    )
)

agent = Agent(
    model=portkey_model,
    user_id="user_123",  # Also use Agno's user_id for agent-level tracking
    instructions="You are a personalized assistant.",
    markdown=True
)
```

**Filter Analytics by User**

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

<Frame caption="Filter analytics by user">
  <img src="https://mintcdn.com/portkey-docs-feature-comparison-update/HqRkYxnvsa5KTaKa/images/metadata-filters.png?fit=max&auto=format&n=HqRkYxnvsa5KTaKa&q=85&s=c5ef417d239254f313d0e6720a040d97" width="1158" height="732" data-path="images/metadata-filters.png" />
</Frame>

This enables:

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

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

### 6. Caching for Efficient Agents

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

<Tabs>
  <Tab title="Simple Caching">
    ```python theme={null}
    from agno.agent import Agent
    from agno.models.openai.like import OpenAILike
    from portkey_ai import createHeaders

    portkey_config = {
      "cache": {
        "mode": "simple"
      },
    }

    # Configure Agno model with caching
    portkey_model = OpenAILike(
        id="@opeani-provider-slug/gpt-4o",
        api_key="YOUR_PORTKEY_API_KEY",
        base_url="https://api.portkey.ai/v1",
        default_headers=createHeaders(config=portkey_config)
    )

    agent = Agent(
        model=portkey_model,
        instructions="You are a helpful assistant.",
        markdown=True
    )
    ```

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

  <Tab title="Semantic Caching">
    ```python theme={null}
    from agno.agent import Agent
    from agno.models.openai.like import OpenAILike
    from portkey_ai import createHeaders

    portkey_config = {
      "cache": {
        "mode": "semantic"
      },
    }

    # Configure Agno model with semantic caching
    portkey_model = OpenAILike(
        id="@opeani-provider-slug/gpt-4o",
        api_key="YOUR_PORTKEY_API_KEY",
        base_url="https://api.portkey.ai/v1",
        default_headers=createHeaders(config=portkey_config)
    )

    agent = Agent(
        model=portkey_model,
        instructions="You are a helpful assistant.",
        markdown=True
    )
    ```

    Semantic caching considers the contextual similarity between input requests, caching responses for semantically similar inputs.
  </Tab>
</Tabs>

### 7. Model Interoperability: using different LLMs

One of Portkey's key strengths is providing access to 1600+ LLMs through a unified interface. Here's how to use different providers with Agno:

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

<Tabs>
  <Tab title="OpenAI">
    ```python theme={null}
    portkey_model = OpenAILike(
        id="@opeani-provider-slug/gpt-4o",
        api_key="YOUR_PORTKEY_API_KEY",
        base_url="https://api.portkey.ai/v1",
    )
    ```
  </Tab>

  <Tab title="Anthropic">
    ```python theme={null}
    portkey_model = OpenAILike(
        id="@your-anthropic-provider-slug/claude-3-7-sonnet-latest",
        api_key="YOUR_PORTKEY_API_KEY",
        base_url="https://api.portkey.ai/v1",
    )
    ```
  </Tab>

  <Tab title="Google">
    ```python theme={null}
    portkey_model = OpenAILike(
        id="@your-google-provider-slug/gemini-2.5-pro",
        api_key="YOUR_PORTKEY_API_KEY",
        base_url="https://api.portkey.ai/v1",
    )
    ```
  </Tab>
</Tabs>

## End-to-End Examples

### Level 1: Agent with Tools and Observability

Let's build an agent that uses tools while leveraging Portkey's observability features:

```python agent_with_tools.py theme={null}
from agno.agent import Agent
from agno.models.openai.like import OpenAILike
from agno.tools.yfinance import YFinanceTools
from portkey_ai import createHeaders

# Configure Portkey with enhanced tracking
portkey_model = OpenAILike(
    id="@anthropic/claude-3-sonnet-20240320",
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://api.portkey.ai/v1",
    default_headers=createHeaders(
        trace_id="agno_finance_agent",
        metadata={
            "agent_type": "financial_analyst",
            "environment": "production"
        }
    )
)

agent = Agent(
    name="Financial Analyst",
    model=portkey_model,
    tools=[
        YFinanceTools(
            stock_price=True,
            company_info=True,
            analyst_recommendations=True,
            company_news=True
        )
    ],
    instructions=[
        "Provide comprehensive financial analysis",
        "Use tables for numerical data",
        "Include relevant news and recommendations",
        "Be concise but thorough"
    ],
    markdown=True,
    debug_mode=True  # See detailed agent reasoning
)

# Run analysis
agent.print_response(
    "Analyze Tesla's current financial position and recent performance",
    stream=True
)
```

### Level 2: Agent with Knowledge Base and Caching

Enhance your Agno agent with knowledge retrieval while using Portkey's caching to optimize costs:

```python agent_with_knowledge.py theme={null}
from agno.agent import Agent
from agno.models.openai.like import OpenAILike
from agno.knowledge.url import UrlKnowledge
from agno.vectordb.lancedb import LanceDb, SearchType
from agno.embedder.openai import OpenAIEmbedder
from agno.storage.sqlite import SqliteStorage
from portkey_ai import createHeaders

# Configure Portkey with caching
cache_config = {
    "cache": {
        "mode": "semantic",
        "max_age": 3600  # Cache for 1 hour
    }
}

portkey_model = OpenAILike(
    id="opeani-provider-slug/gpt-4o",
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://api.portkey.ai/v1",
    default_headers=createHeaders(
        config=cache_config,
        metadata={"agent_type": "knowledge_assistant"}
    )
)

# Set up knowledge base
knowledge = UrlKnowledge(
    urls=["https://docs.agno.com/introduction.md"],
    vector_db=LanceDb(
        uri="tmp/lancedb",
        table_name="agno_docs",
        search_type=SearchType.hybrid,
        embedder=OpenAIEmbedder(id="text-embedding-3-small", dimensions=1536),
    ),
)

# Configure storage
storage = SqliteStorage(table_name="agent_sessions", db_file="tmp/agent.db")

agent = Agent(
    name="Agno Assistant",
    model=portkey_model,
    knowledge=knowledge,
    storage=storage,
    instructions=[
        "Always search the knowledge base before answering",
        "Provide accurate information from the documentation",
        "If information isn't found, clearly state that"
    ],
    add_history_to_messages=True,
    num_history_runs=5,
    markdown=True
)

if __name__ == "__main__":
    # Load knowledge base (only needed first time)
    agent.knowledge.load(recreate=False)

    # Ask questions - responses will be cached by Portkey
    agent.print_response("What are the key features of Agno?", stream=True)
```

### Level 3: Agent with Memory, Reasoning, and Reliability

Build a sophisticated agent that leverages Agno's advanced features with Portkey's reliability configurations:

```python advanced_agent.py theme={null}
from agno.agent import Agent
from agno.models.openai.like import OpenAILike
from agno.memory.v2.memory import Memory
from agno.memory.v2.db.sqlite import SqliteMemoryDb
from agno.tools.reasoning import ReasoningTools
from agno.tools.yfinance import YFinanceTools
from portkey_ai import createHeaders

# Configure Portkey with fallbacks and retries
reliability_config = {
    "strategy": {
        "mode": "fallback"
    },
    "targets": [
        {
            "override_params": {"model": "@opeani-provider-slug/gpt-4o"}
        },
        {
            "override_params": {"model": "@anthropic-provider-slug/@anthropic-provider-slug/claude-3-opus-20240229"}
        }
    ],
    "retry": {
        "attempts": 3,
        "delay": 2
    }
}

portkey_model = OpenAILike(
    id="@opeani-provider-slug/gpt-4o",
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://api.portkey.ai/v1",
    default_headers=createHeaders(
        config=reliability_config,
        trace_id="advanced_trading_agent"
    )
)

# Set up memory
memory = Memory(
    model=portkey_model,
    db=SqliteMemoryDb(table_name="user_memories", db_file="tmp/agent.db"),
    delete_memories=True,
    clear_memories=True,
)

agent = Agent(
    name="Trading Assistant",
    model=portkey_model,
    tools=[
        ReasoningTools(add_instructions=True),
        YFinanceTools(
            stock_price=True,
            analyst_recommendations=True,
            company_info=True,
            company_news=True
        ),
    ],
    user_id="trader_1",
    instructions=[
        "Remember user preferences and trading patterns",
        "Use reasoning to analyze market conditions",
        "Provide data-driven recommendations",
        "Display results in clear tables"
    ],
    memory=memory,
    enable_agentic_memory=True,
    markdown=True,
)

if __name__ == "__main__":
    # First interaction - agent learns preferences
    agent.print_response(
        "I'm interested in tech stocks, particularly AI companies like NVIDIA and Microsoft",
        stream=True,
        show_full_reasoning=True,
    )

    # Second interaction - agent uses memory
    agent.print_response(
        "Based on my interests, what stocks should I watch today?",
        stream=True,
        show_full_reasoning=True,
    )
```

## Set Up Enterprise Governance for Agno AI agents

**Why Enterprise Governance?**
If you are using Agno AI agents inside your orgnaization, 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 organization
* **Security & Compliance**: Maintaining enterprise security standards
* **Reliability**: Ensuring consistent service across all users

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

**Enterprise Implementation Guide**

Portkey allows you to use 1600+ LLMs with your Agno AI agents setup, with minimal configuration required. Let's set up the core components in Portkey 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](/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://app.portkey.ai/model-catalog) in Portkey dashboard
    2. Create new Provider for each engineering team with budget limits and rate limits
    3. Configure department-specific limits

    <Frame>
      <img src="https://mintcdn.com/portkey-docs-feature-comparison-update/gytOxJ2pz7sfAzcs/images/product/model-catalog/create-provider-page.png?fit=max&auto=format&n=gytOxJ2pz7sfAzcs&q=85&s=61bb298e3559aec2fda827bc1d56dbb9" width="500" data-path="images/product/model-catalog/create-provider-page.png" />
    </Frame>
  </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.

    <Frame>
      <img src="https://mintcdn.com/portkey-docs-feature-comparison-update/gytOxJ2pz7sfAzcs/images/product/model-catalog/model-provisioning-page.png?fit=max&auto=format&n=gytOxJ2pz7sfAzcs&q=85&s=d8fb8080c9b59c56911f1fe2d80040f9" width="500" data-path="images/product/model-catalog/model-provisioning-page.png" />
    </Frame>
  </Accordion>

  <Accordion title="Step 4: Set Routing Configuration">
    Portkey allows you to control your routing logic very simply with it's Configs feature. Portkey 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={null}
    {
    	"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://app.portkey.ai/configs) in your Portkey dashboard. You'll need the config ID for connecting to Cline's 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:

    * [Portkey App](https://app.portkey.ai/)
    * [API Key Management API](/api-reference/admin-api/control-plane/api-keys/create-api-key)

    Example using Python SDK:

    ```python theme={null}
    from portkey_ai import Portkey

    portkey = Portkey(api_key="YOUR_ADMIN_API_KEY")

    api_key = portkey.api_keys.create(
        name="frontend-engineering",
        type="organisation",
        workspace_id="YOUR_WORKSPACE_ID",
        defaults={
            "config_id": "your-config-id",
            "metadata": {
                "environment": "development",
                "department": "engineering",
                "team": "frontend"
            }
        },
        scopes=["logs.view", "configs.read"]
    )
    ```

    For detailed key management instructions, see our [API Keys documentation](/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 Cline 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 Portkey dashboard:

    * 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

  **Agno AI agents now has:**

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

## Frequently Asked Questions

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

  <Accordion title="Can I use any LLM with Agno through Portkey?">
    Yes! Portkey provides access to 1600+ 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?">
    Portkey 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 Portkey support all Agno features?">
    Yes! Portkey works seamlessly with all Agno features including tools, reasoning, memory, knowledge bases, and storage. It adds observability and reliability without limiting any Agno functionality.
  </Accordion>

  <Accordion title="How do I debug agent failures?">
    Portkey'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="Agno Documentation" icon="book" href="https://docs.agno.com/introduction">
    Learn more about building agents with Agno
  </Card>

  <Card title="Portkey Features" icon="sparkles" href="/product/ai-gateway">
    Explore all Portkey capabilities
  </Card>

  <Card title="Get Support" icon="discord" href="https://portkey.ai/community">
    Join our Discord community
  </Card>
</CardGroup>
