Agno provides a beautiful UI for interacting with your agents, completely open source, free to use and build on top of. It's a simple interface that allows you to chat with your agents, view their memory, knowledge, and more.
### Message Metrics
Here, you can see the metrics for each message response from the agent. All "assistant" responses will have metrics like this, helping you understand the performance and resource usage at the message level.
### Aggregated Run Metrics
The aggregated metrics provide a comprehensive view of the entire run. This includes a summary of all messages and tool calls, giving you an overall picture of the agent's performance and resource usage.
Similarly for the session metrics, you can see the aggregated metrics across all runs in the session, providing insights into the overall performance and resource usage of the agent across multiple runs.
## How Metrics Are Aggregated
* **Per-message**: Each message (assistant, tool, etc.) has its own metrics object.
* **Run-level**: RunResponse.metrics is a dictionary where each key (e.g., input\_tokens) maps to a list of values from all assistant messages in the run.
* **Session-level**: `SessionMetrics` (see `agent.session_metrics`) aggregates metrics across all runs in the session.
## `MessageMetrics` Params
You can see more examples in our [AG-UI integration examples](/examples/applications/ag-ui) section.
## Core Components
* `AGUIApp`: Wraps Agno agents/teams for in a FastAPI app.
* `serve`: Serves the FastAPI AG-UI app using Uvicorn.
`AGUIApp` uses helper functions for routing.
## `AGUIApp` Class
Main entry point for Agno AG-UI apps.
### Initialization Parameters
| Parameter | Type | Default | Description |
| ------------- | -------------------------- | ------- | ------------------------------------------------ |
| `agent` | `Optional[Agent]` | `None` | Agno `Agent` instance. |
| `team` | `Optional[Team]` | `None` | Agno `Team` instance. |
| `settings` | `Optional[APIAppSettings]` | `None` | API configuration. Defaults if `None`. |
| `api_app` | `Optional[FastAPI]` | `None` | Existing FastAPI app. New one created if `None`. |
| `router` | `Optional[APIRouter]` | `None` | Existing APIRouter. New one created if `None`. |
| `app_id` | `Optional[str]` | `None` | App identifier (autogenerated if not set). |
| `name` | `Optional[str]` | `None` | Name for the App. |
| `description` | `Optional[str]` | `None` | Description for the App. |
*Provide `agent` or `team`, not both.*
### Key Method
| Method | Parameters | Return Type | Description |
| --------- | ------------------------ | ----------- | ------------------------------------------------------------------------------------------- |
| `get_app` | `use_async: bool = True` | `FastAPI` | Returns configured FastAPI app (async by default). Sets prefix, error handlers, CORS, docs. |
## Endpoints
Endpoints are available at the specified `prefix` (default `/v1`).
### 1. `POST /agui`
This is the main entrypoint to interact with your Agno Agent or Team.
It expects a `RunAgentInput` object (from the `ag-ui-protocol` package) as defined by the protocol. You can read more about it in [their docs](https://docs.ag-ui.com/quickstart/server).
## Serving the Application (`serve`)
Serves the FastAPI app using Uvicorn.
### Parameters
| Parameter | Type | Default | Description |
| --------- | --------------------- | ------------- | ------------------------------------------------- |
| `app` | `Union[str, FastAPI]` | `N/A` | FastAPI app instance or import string (Required). |
| `host` | `str` | `"localhost"` | Host to bind. |
| `port` | `int` | `7777` | Port to bind. |
| `reload` | `bool` | `False` | Enable auto-reload for development. |
You can check some usage examples in our [AG-UI integration examples](/examples/applications/ag-ui) section.
You can also check the [CopilotKit docs](https://docs.copilotkit.ai/agno) on working with Agno, to learn more on how to build the UI side.
# Discord Bot
Source: https://docs-v1.agno.com/applications/discord/introduction
Host agents as Discord Bots.
The Discord Bot integration allows you to serve Agents or Teams via Discord, using the discord.py library to handle Discord events and send messages.
## Setup Steps
## New Features:
* **Workflows Revamped (beta):** Our new Workflows implementation (internally referred to as Workflows 2.0) is a complete redesign of the workflow system in Agno, introducing a step-based architecture that provides better structure, flexibility, and control over multi-stage AI agent processes
* Core Concepts:
* **Flexible Execution**: Sequential, parallel, conditional, and loop-based execution
* **Smart Routing**: Dynamic step selection based on content analysis or user intent
* **Mixed Components**: Combine agents, teams, and functions seamlessly
* **State Management:** Share data across steps with session state
* For a comprehensive guide to the new Workflows system, check out the [docs](https://docs-v1.agno.com/workflows_2/overview).
* **Pydantic Input for Agents/Teams:** Both Agent and Team now accepts structured input (i.e. a pydantic model) on run() and print\_response().
You can also run the `AccuracyEval` on an existing output (without running the Agent).
```python accuracy_eval_with_output.py
from typing import Optional
from agno.agent import Agent
from agno.eval.accuracy import AccuracyEval, AccuracyResult
from agno.models.openai import OpenAIChat
from agno.tools.calculator import CalculatorTools
evaluation = AccuracyEval(
model=OpenAIChat(id="o4-mini"),
input="What is 10*5 then to the power of 2? do it step by step",
expected_output="2500",
num_iterations=1,
)
result_with_given_answer: Optional[AccuracyResult] = evaluation.run_with_output(
output="2500", print_results=True
)
assert result_with_given_answer is not None and result_with_given_answer.avg_score >= 8
```
## Performance
Performance evals measure the latency and memory footprint of an Agent or Team.
## Track your evaluations
Apart from running your evaluations on the CLI, you can also track them on the Agno platform. This is useful to keep track of results and share them with your team.
Do it following these steps:
Follow the instructions on [Ollama.com](https://ollama.com) to download and install Ollama.
Reason for CLI authentication failure:
* Some browsers like Safari and Brave block connection to the localhost domain. Browsers like Chrome work great with `ag setup`.
# Connecting to Tableplus
Source: https://docs-v1.agno.com/faq/connecting-to-tableplus
If you want to inspect your pgvector container to explore your storage or knowledge base, you can use TablePlus. Follow these steps:
## Step 1: Start Your `pgvector` Container
Run the following command to start a `pgvector` container locally:
```bash
docker run -d \
-e POSTGRES_DB=ai \
-e POSTGRES_USER=ai \
-e POSTGRES_PASSWORD=ai \
-e PGDATA=/var/lib/postgresql/data/pgdata \
-v pgvolume:/var/lib/postgresql/data \
-p 5532:5432 \
--name pgvector \
agno/pgvector:16
```
* `POSTGRES_DB=ai` sets the default database name.
* `POSTGRES_USER=ai` and `POSTGRES_PASSWORD=ai` define the database credentials.
* The container exposes port `5432` (mapped to `5532` on your local machine).
## Step 2: Configure TablePlus
1. **Open TablePlus**: Launch the TablePlus application.
2. **Create a New Connection**: Click on the `+` icon to add a new connection.
3. **Select `PostgreSQL`**: Choose PostgreSQL as the database type.
Fill in the following connection details:
* **Host**: `localhost`
* **Port**: `5532`
* **Database**: `ai`
* **User**: `ai`
* **Password**: `ai`
# Could Not Connect To Docker
Source: https://docs-v1.agno.com/faq/could-not-connect-to-docker
If you have Docker up and running and get the following error, please read on:
```bash
ERROR Could not connect to docker. Please confirm docker is installed and running
ERROR Error while fetching server API version: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))
```
## Quick fix
Create the `/var/run/docker.sock` symlink using:
```shell
sudo ln -s "$HOME/.docker/run/docker.sock" /var/run/docker.sock
```
In 99% of the cases, this should work. If it doesnt, try:
```shell
sudo chown $USER /var/run/docker.sock
```
## Full details
Agno uses [docker-py](https://github.com/docker/docker-py) to run containers, and if the `/var/run/docker.sock` is missing or has incorrect permissions, it cannot connect to docker.
**To fix, please create the `/var/run/docker.sock` file using:**
```shell
sudo ln -s "$HOME/.docker/run/docker.sock" /var/run/docker.sock
```
If that does not work, check the permissions using `ls -l /var/run/docker.sock`.
If the `/var/run/docker.sock` does not exist, check if the `$HOME/.docker/run/docker.sock` file is missing. If its missing, please reinstall Docker.
**If none of this works and the `/var/run/docker.sock` exists:**
* Give your user permissions to the `/var/run/docker.sock` file:
```shell
sudo chown $USER /var/run/docker.sock
```
* Give your user permissions to the docker group:
```shell
sudo usermod -a -G docker $USER
```
## More info
* [Docker-py Issue](https://github.com/docker/docker-py/issues/3059#issuecomment-1294369344)
* [Stackoverflow answer](https://stackoverflow.com/questions/48568172/docker-sock-permission-denied/56592277#56592277)
# Setting Environment Variables
Source: https://docs-v1.agno.com/faq/environment-variables
To configure your environment for applications, you may need to set environment variables. This guide provides instructions for setting environment variables in both macOS (Shell) and Windows (PowerShell and Windows Command Prompt).
## macOS
### Setting Environment Variables in Shell
#### Temporary Environment Variables
These environment variables will only be available in the current shell session.
```shell
export VARIABLE_NAME="value"
```
To display the environment variable:
```shell
echo $VARIABLE_NAME
```
#### Permanent Environment Variables
To make environment variables persist across sessions, add them to your shell configuration file (e.g., `.bashrc`, `.bash_profile`, `.zshrc`).
For Zsh:
```shell
echo 'export VARIABLE_NAME="value"' >> ~/.zshrc
source ~/.zshrc
```
To display the environment variable:
```shell
echo $VARIABLE_NAME
```
## Windows
### Setting Environment Variables in PowerShell
#### Temporary Environment Variables
These environment variables will only be available in the current PowerShell session.
```powershell
$env:VARIABLE_NAME = "value"
```
To display the environment variable:
```powershell
echo $env:VARIABLE_NAME
```
#### Permanent Environment Variables
To make environment variables persist across sessions, add them to your PowerShell profile script (e.g., `Microsoft.PowerShell_profile.ps1`).
```powershell
notepad $PROFILE
```
Add the following line to the profile script:
```powershell
$env:VARIABLE_NAME = "value"
```
Save and close the file, then reload the profile:
```powershell
. $PROFILE
```
To display the environment variable:
```powershell
echo $env:VARIABLE_NAME
```
### Setting Environment Variables in Windows Command Prompt
#### Temporary Environment Variables
These environment variables will only be available in the current Command Prompt session.
```cmd
set VARIABLE_NAME=value
```
To display the environment variable:
```cmd
echo %VARIABLE_NAME%
```
#### Permanent Environment Variables
To make environment variables persist across sessions, you can use the `setx` command:
```cmd
setx VARIABLE_NAME "value"
```
Note: After setting an environment variable using `setx`, you need to restart the Command Prompt or any applications that need to read the new environment variable.
To display the environment variable in a new Command Prompt session:
```cmd
echo %VARIABLE_NAME%
```
By following these steps, you can effectively set and display environment variables in macOS Shell, Windows Command Prompt, and PowerShell. This will ensure your environment is properly configured for your applications.
# Memory V2
Source: https://docs-v1.agno.com/faq/memoryv2
Starting with Agno version 1.4.0, **Memory V2** is now the default memory for the Agno Agent. This replaces the previous `AgentMemory` and `TeamMemory` classes which is now deprecated but still available to use.
Memory V2 is a more powerful and flexible memory system that allows you to manage message history, session summaries, and long-term user memories.
## How to Continue Using AgentMemory (Memory V1)
If you want to continue using `AgentMemory` and avoid breaking changes, you can do so by updating your imports. By default, the Agent now uses the `Memory` class:
```python
from agno.memory.v2 import Memory
```
To use the legacy AgentMemory class instead, import it like this:
```python
from agno.memory import AgentMemory
agent = Agent(
memory=AgentMemory()
)
```
## Key Memory V2 Changes
* **Accessing Messages:**
* **Before:**
```python
agent.memory.messages
```
* **Now:**
```python
[run.messages for run in agent.memory.runs]
# or
agent.get_messages_for_session()
```
* **User Memories:**
* **Before:**
```python
from agno.memory import AgentMemory
memory = AgentMemory(create_user_memories=True)
agent = Agent(memory=memory)
```
* **Now:**
```python
from agno.memory.v2 import Memory
memory = Memory()
agent = Agent(create_user_memories=True, memory=memory) or team = Team(create_user_memories=True, memory=memory)
```
* **Session Summaries:**
* **Before:**
```python
from agno.memory import AgentMemory
memory = AgentMemory(create_session_summary=True)
agent = Agent(memory=memory)
```
* **Now:**
```python
from agno.memory.v2 import Memory
memory = Memory()
agent = Agent(enable_session_summaries=True, memory=memory) or team = Team(enable_session_summaries=True, memory=memory)
```
# OpenAI Key Request While Using Other Models
Source: https://docs-v1.agno.com/faq/openai-key-request-for-other-models
If you see a request for an OpenAI API key but haven't explicitly configured OpenAI, it's because Agno uses OpenAI models by default in several places, including:
* The default model when unspecified in `Agent`
* The default embedder is OpenAIEmbedder with VectorDBs, unless specified
## Quick fix: Configure a Different Model
It is best to specify the model for the agent explicitly, otherwise it would default to `OpenAIChat`.
For example, to use Google's Gemini instead of OpenAI:
```python
from agno.agent import Agent, RunResponse
from agno.models.google import Gemini
agent = Agent(
model=Gemini(id="gemini-1.5-flash"),
markdown=True,
)
# Print the response in the terminal
agent.print_response("Share a 2 sentence horror story.")
```
For more details on configuring different model providers, check our [models documentation](../models/)
## Quick fix: Configure a Different Embedder
The same applies to embeddings. If you want to use a different embedder instead of `OpenAIEmbedder`, configure it explicitly.
For example, to use Google's Gemini as an embedder, use `GeminiEmbedder`:
```python
from agno.agent import AgentKnowledge
from agno.vectordb.pgvector import PgVector
from agno.embedder.google import GeminiEmbedder
# Embed sentence in database
embeddings = GeminiEmbedder().get_embedding("The quick brown fox jumps over the lazy dog.")
# Print the embeddings and their dimensions
print(f"Embeddings: {embeddings[:5]}")
print(f"Dimensions: {len(embeddings)}")
# Use an embedder in a knowledge base
knowledge_base = AgentKnowledge(
vector_db=PgVector(
db_url="postgresql+psycopg://ai:ai@localhost:5532/ai",
table_name="gemini_embeddings",
embedder=GeminiEmbedder(),
),
num_documents=2,
)
```
For more details on configuring different model providers, check our [Embeddings documentation](../embedder/)
# Playground Connection Issues
Source: https://docs-v1.agno.com/faq/playground-connection
If you're experiencing connection issues in the Agno Playground, particularly when trying to connect to **local endpoints**, this guide will help you resolve them.
## Browser Compatibility
Some browsers have security restrictions that prevent connections to localhost domains due to mixed content security issues. Here's what you need to know about different browsers:
### Recommended Browsers
* **Chrome & Edge**: These browsers work well with local connections by default and are our recommended choices
* **Firefox**: Generally works well with local connections
### Browsers with Known Issues
* **Safari**: May block local connections due to its strict security policies
* **Brave**: Blocks local connections by default due to its shield feature
## Solutions
### For Brave Users
If you're using Brave browser, you can try these steps:
1. Click on the Brave shield icon in the address bar
2. Turn off the shield for the current site
3. Refresh the endpoint and try connecting again
### For Other Browsers
If you're using Safari or experiencing issues with other browsers, you can use one of these solutions:
#### 1. Use Chrome or Edge
The simplest solution is to use Chrome or Edge browsers which have better support for local connections.
#### 2. Use Tunneling Services
You can use tunneling services to expose your local endpoint to the internet:
##### Using ngrok
1. Install ngrok from [ngrok.com](https://ngrok.com)
2. Run your local server
3. Create a tunnel with ngrok:
```bash
ngrok http
If you face any problems with proprietary models (like OpenAI models) where you are rate limited, we provide the option to set `exponential_backoff=True` and to change `delay_between_retries` to a value in seconds (defaults to 1 second).
For example:
```python
from agno.agent import Agent
from agno.models.openai import OpenAIChat
agent = Agent(
model=OpenAIChat(id="gpt-4o"),
description="You are an enthusiastic news reporter with a flair for storytelling!",
markdown=True,
exponential_backoff=True,
delay_between_retries=2
)
agent.print_response("Tell me about a breaking news story from New York.", stream=True)
```
See our [models documentation](../models/) for specific information about rate limiting.
In the case of OpenAI, they have tier based rate limits. See the [docs](https://platform.openai.com/docs/guides/rate-limits/usage-tiers) for more information.
# null
Source: https://docs-v1.agno.com/filters/agentic-filters
# Agentic Knowledge Filters
Agentic filtering lets the Agent automatically extract filter criteria from your query text, making the experience more natural and interactive.
## Step 1: Attach Metadata
There are two ways to attach metadata to your documents:
1. **Attach Metadata When Initializing the Knowledge Base**
```python
knowledge_base = PDFKnowledgeBase(
path=[
{
"path": "path/to/cv1.pdf",
"metadata": {
"user_id": "jordan_mitchell",
"document_type": "cv",
"year": 2025,
},
},
# ... more documents ...
],
vector_db=vector_db,
)
knowledge_base.load(recreate=True)
```
2. **Attach Metadata When Loading Documents One by One**
```python
# Initialize the PDFKnowledgeBase
knowledge_base = PDFKnowledgeBase(
vector_db=vector_db,
num_documents=5,
)
# Load first document with user_1 metadata
knowledge_base.load_document(
path=path/to/cv1.pdf,
metadata={"user_id": "jordan_mitchell", "document_type": "cv", "year": 2025},
recreate=True, # Set to True only for the first run, then set to False
)
# Load second document with user_2 metadata
knowledge_base.load_document(
path=path/to/cv2.pdf,
metadata={"user_id": "taylor_brooks", "document_type": "cv", "year": 2025},
)
```
***
## How It Works
When you enable agentic filtering (`enable_agentic_knowledge_filters=True`), the Agent analyzes your query and applies filters based on the metadata it detects.
**Example:**
```python
agent = Agent(
knowledge=knowledge_base,
search_knowledge=True,
enable_agentic_knowledge_filters=True,
)
agent.print_response(
"Tell me about Jordan Mitchell's experience and skills with jordan_mitchell as user id and document type cv",
markdown=True,
)
```
In this example, the Agent will automatically use:
* `user_id = "jordan_mitchell"`
* `document_type = "cv"`
***
## 🌟 See Agentic Filters in Action!
Experience how agentic filters automatically extract relevant metadata from your query.
*The Agent intelligently narrows down results based on your query.*
***
## When to Use Agentic Filtering
* When you want a more conversational, user-friendly experience.
* When users may not know the exact filter syntax.
## Try It Out!
* Enable `enable_agentic_knowledge_filters=True` on your Agent.
* Ask questions naturally, including filter info in your query.
* See how the Agent narrows down results automatically!
***
## Developer Resources
* [Agentic filtering](https://github.com/agno-agi/agno/blob/main/cookbook/agent_concepts/knowledge/filters/pdf/agentic_filtering.py)
# null
Source: https://docs-v1.agno.com/filters/introduction
# Knowledge Filters
Knowledge filters allow you to restrict and refine searches within your knowledge base using metadata such as user IDs, document types, years, and more. This feature is especially useful when you have a large collection of documents and want to retrieve information relevant to specific users or contexts.
## Why Use Knowledge Filters?
* **Personalization:** Retrieve information for a specific user or group.
* **Security:** Restrict access to sensitive documents.
* **Efficiency:** Reduce noise by narrowing down search results.
## How Do Knowledge Filters Work?
When you load documents into your knowledge base, you can attach metadata (like user ID, document type, year, etc.). Later, when querying, you can specify filters to only search documents matching certain criteria.
**Example Metadata:**
```python
{
"user_id": "jordan_mitchell",
"document_type": "cv",
"year": 2025,
}
```
## Ways to Apply Filters
You can apply knowledge filters in two main ways:
1. **Manual Filters:** Explicitly pass filters when querying.
2. **Agentic Filters:** Let the Agent automatically extract filters from your query.
> **Tip:** You can combine multiple filters for more precise results!
## Filters in Traditional RAG vs. Agentic RAG
When configuring your Agent it is important to choose the right approach for your use case. There are two broad approaches to RAG with Agno agents: traditional RAG and agentic RAG. With a traditional RAG approach you set `add_references=True` to ensure that references are included in the system message sent to the LLM. For Agentic RAG, you set `search_knowledge=True` to leverage the agent's ability search the knowledge base directly.
Example:
```python
agent = Agent(
name="KnowledgeFilterAgent",
search_knowledge=False, # Do not use agentic search
add_references=True, # Add knowledge base references to the system prompt
knowledge_filters={"user_id": "jordan_mitchell"}, # Pass filters like this
)
```
The Playground gives a robust interface to test your agentic systems with extensive features.
* **Streaming Support**: Real-time response streaming and intermediate states back to the user.
* **Session History**: Visualize conversation history right in the playground.
* **User Memory**: Visualize user details and preferences across conversations.
* **Configuration**: Comprehensive configuration interface allowing you to see agent parameters, model settings, tool configurations.
* **Reasoning Support**: Built-in support for detailed reasoning traces displayed in the playground interface.
* **Human in Loop Support**: Enable manual intervention in agent workflows with specialized human oversight and approval.
* **Multimodal Support**: Support for processing and generating text, images, audio, and other media types.
* **Multi-Agent Systems**: Support for multi-agent teams and workflows.
## Interact with your agents Locally
### Get Started with Agent UI
```bash
# Create a new Agent UI project
npx create-agent-ui@latest
# Or clone and run manually
git clone https://github.com/agno-agi/agent-ui.git
cd agent-ui && pnpm install && pnpm dev
```
The UI will connect to `localhost:7777` by default, matching the Playground setup above. Visit [GitHub](https://github.com/agno-agi/agent-ui) for more details.
* ### Example: Local Collector Setup
For local development, you can run a local collector using
```bash
phoenix serve
```
```python
import os
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.duckduckgo import DuckDuckGoTools
from phoenix.otel import register
# Set the local collector endpoint
os.environ["PHOENIX_COLLECTOR_ENDPOINT"] = "http://localhost:6006"
# Configure the Phoenix tracer
tracer_provider = register(
project_name="agno-research-agent", # Default is 'default'
auto_instrument=True, # Automatically use the installed OpenInference instrumentation
)
# Create and configure the agent
agent = Agent(
name="Research Agent",
model=OpenAIChat(id="gpt-4o-mini"),
tools=[DuckDuckGoTools(search=True, news=True)],
instructions="You are a research agent. Answer questions in the style of a professional researcher.",
debug_mode=True,
)
# Use the agent
agent.print_response("What is the latest news about artificial intelligence?")
```
## Notes
* **Environment Variables**: Ensure your environment variables are correctly set for the API key and collector endpoint.
* **Local Development**: Use `phoenix serve` to start a local collector for development purposes.
By following these steps, you can effectively integrate Agno with Arize Phoenix, enabling comprehensive observability and monitoring of your AI agents.
# Atla
Source: https://docs-v1.agno.com/observability/atla
Integrate `Atla` with Agno for real-time monitoring, automated evaluation, and performance analytics of your AI agents.
[Atla](https://www.atla-ai.com/) is an advanced observability platform designed specifically for AI agent monitoring and evaluation.
This integration provides comprehensive insights into agent performance, automated quality assessment, and detailed analytics for production AI systems.
## Prerequisites
* **API Key**: Obtain your API key from the [Atla dashboard](https://app.atla-ai.com)
Install the Atla Insights SDK with Agno support:
```bash
pip install "atla-insights"
```
## Configuration
Configure your API key as an environment variable:
```bash
export ATLA_API_KEY="your_api_key_from_atla_dashboard"
```
## Example
```python
from os import getenv
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.duckduckgo import DuckDuckGoTools
from atla_insights import configure, instrument_agno
# Step 1: Configure Atla
configure(token=getenv("ATLA_API_KEY"))
# Step 2: Create your Agno agent
agent = Agent(
name="Market Analysis Agent",
model=OpenAIChat(id="gpt-4o-mini"),
tools=[DuckDuckGoTools()],
instructions="Provide professional market analysis with data-driven insights.",
debug_mode=True,
)
# Step 3: Instrument and execute
with instrument_agno("openai"):
response = agent.run("Retrieve the latest news about the stock market.")
print(response.content)
```
Now go to the [Atla dashboard](https://app.atla-ai.com/app/) and view the traces created by your agent. You can visualize the execution flow, monitor performance, and debug issues directly from the Atla dashboard.
# OpenTelemetry
Source: https://docs-v1.agno.com/observability/introduction
Agno supports observability through OpenTelemetry, integrating seamlessly with popular tracing and monitoring platforms.
Observability helps us understand, debug, and improve AI agents. Agno supports observability through [OpenTelemetry](https://opentelemetry.io/), integrating seamlessly with popular tracing and monitoring platforms.
## Key Benefits
* **Trace**: Visualize and analyze agent execution flows.
* **Monitor**: Track performance, errors, and usage.
* **Debug**: Quickly identify and resolve issues.
## OpenTelemetry Support
Agno offers first-class support for OpenTelemetry, the industry standard for distributed tracing and observability.
* **Auto-Instrumentation**: Automatically instrument your agents and tools.
* **Flexible Export**: Send traces to any OpenTelemetry-compatible backend.
* **Custom Tracing**: Extend or customize tracing as needed.
## Prerequisites
1. **Install Dependencies**
Ensure you have the necessary packages installed:
```bash
pip install agno 'pylangdb[agno]'
```
2. **Setup LangDB Account**
* Sign up for an account at [LangDB](https://app.langdb.ai/signup)
* Create a new project in the LangDB dashboard
* Obtain your API key and Project ID from the project settings
3. **Set Environment Variables**
Configure your environment with the LangDB credentials:
```bash
export LANGDB_API_KEY="
## Advanced Features
### LangDB Capabilities
* **Virtual Models**: Save, share, and reuse model configurations—combining prompts, parameters, tools, and routing logic into a single named unit for consistent behavior across apps
* **MCP Support**: Enhanced tool capabilities through Model Context Protocol servers
* **Multi-Provider**: Support for OpenAI, Anthropic, Google, xAI, and other providers
## Notes
* **Initialization Order**: Always call `init()` before creating any Agno agents or teams
* **Environment Variables**: With `LANGDB_API_KEY` and `LANGDB_PROJECT_ID` set, you can create models with just `LangDB(id="model_name")`
## Resources
* [LangDB Documentation](https://docs.langdb.ai/)
* [Building a Reasoning Finance Team Guide](https://docs.langdb.ai/guides/building-agents/building-a-reasoning-finance-team-with-agno)
* [LangDB GitHub Samples](https://github.com/langdb/langdb-samples/tree/main/examples/agno)
* [LangDB Dashboard](https://app.langdb.ai/)
By following these steps, you can effectively integrate Agno with LangDB, enabling comprehensive observability and monitoring of your AI agents.
# Langfuse
Source: https://docs-v1.agno.com/observability/langfuse
Integrate Agno with Langfuse to send traces and gain insights into your agent's performance.
## Integrating Agno with Langfuse
Langfuse provides a robust platform for tracing and monitoring AI model calls. By integrating Agno with Langfuse, you can utilize OpenInference and OpenLIT to send traces and gain insights into your agent's performance.
## Prerequisites
1. **Install Dependencies**
Ensure you have the necessary packages installed:
```bash
pip install agno openai opentelemetry-sdk opentelemetry-exporter-otlp openinference-instrumentation-agno arize-otel
```
2. **Setup Langfuse Account**
* Either self-host or sign up for an account at [Langfuse](https://us.cloud.langfuse.com).
* Obtain your public and secret API keys from the Langfuse dashboard.
3. **Set Environment Variables**
Configure your environment with the Langfuse API keys:
```bash
export LANGFUSE_PUBLIC_KEY=
### Aggregated Team Leader Metrics
The aggregated metrics provide a comprehensive view of the team leader's run. This includes a summary of all messages and tool calls, giving you an overall picture of the team leader's performance and resource usage.
## Team Member Metrics
### Individual Member Metrics
Each team member has their own metrics that can be accessed through `team.run_response.member_responses`. This allows you to analyze the performance of individual team members.
### Member Response Structure
Each member response contains:
* `messages`: List of messages with individual metrics
* `metrics`: Aggregated metrics for that member's run
* `tools`: Tool executions with their own metrics
## Session-Level Metrics
### Team Leader Session Metrics
The `team.session_metrics` provides aggregated metrics across all runs in the session for the team leader only.
### Full Team Session Metrics
The `team.full_team_session_metrics` provides comprehensive metrics that include both the team leader and all team members across all runs in the session.
## How Metrics Are Aggregated
### Team Leader Level
* **Per-message**: Each message (assistant, tool, etc.) has its own metrics object.
* **Run-level**: `TeamRunResponse.metrics` is a dictionary where each key (e.g., input\_tokens) maps to a list of values from all assistant messages in the run.
* **Session-level**: `team.session_metrics` aggregates metrics across all team leader runs in the session.
### Team Member Level
* **Per-member**: Each team member has their own metrics tracked separately.
* **Member aggregation**: Individual member metrics are aggregated within their respective `RunResponse` objects.
* **Full team aggregation**: `team.full_team_session_metrics` combines metrics from the team leader and all team members.
### Cross-Member Aggregation
* **Session-level**: `team.full_team_session_metrics` provides a complete view of all token usage and performance metrics across the entire team.
## Accessing Member Metrics Programmatically
You can access individual member metrics in several ways:
```python
# Access metrics for a specific member
for member_response in team.run_response.member_responses:
print(f"Member: {member_response.member_id}")
print(f"Member metrics: {member_response.metrics}")
# Access individual messages
for message in member_response.messages:
if message.role == "assistant":
print(f"Message metrics: {message.metrics}")
```
## Metrics Comparison
| Metric Level | Access Method | Description |
| ----------------------- | -------------------------------- | ---------------------------------------------- |
| **Team Leader Run** | `team.run_response.metrics` | Aggregated metrics for the current run |
| **Team Leader Session** | `team.session_metrics` | Aggregated metrics across all team leader runs |
| **Individual Member** | `member_response.metrics` | Metrics for a specific team member's run |
| **Full Team Session** | `team.full_team_session_metrics` | Complete team metrics including all members |
## `MessageMetrics` Params
# Updating Tools
Source: https://docs-v1.agno.com/tools/attaching-tools
Learn how to add/update tools on Agents and Teams after they have been created.
Tools can be added to Agents and Teams post-creation. This gives you the flexibility to add tools to an existing Agent or Team instance after initialization, which is useful for dynamic tool management or when you need to conditionally add tools based on runtime requirements.
The whole collection of tools available to an Agent or Team can also be updated by using the `set_tools` call. Note that this will remove any other tools already assigned to your Agent or Team and override it with the list of tools provided to `set_tools`.
## Agent Example
Create your own tool, for example `get_weather`. Then call `add_tool` to attach it to your Agent.
```python add_agent_tool_post_initialization.py
import random
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools import tool
@tool(show_result=True, stop_after_tool_call=True)
def get_weather(city: str) -> str:
"""Get the weather for a city."""
# In a real implementation, this would call a weather API
weather_conditions = ["sunny", "cloudy", "rainy", "snowy", "windy"]
random_weather = random.choice(weather_conditions)
return f"The weather in {city} is {random_weather}."
agent = Agent(
model=OpenAIChat(id="gpt-4o-mini"),
markdown=True,
)
agent.print_response("What can you do?", stream=True)
agent.add_tool(get_weather)
agent.print_response("What is the weather in San Francisco?", stream=True)
```
# Team Example
Create a list of tools, and assign them to your Team with `set_tools`
```python add_team_tool_post_initialization.py
import random
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.team.team import Team
from agno.tools import tool
from agno.tools.calculator import CalculatorTools
agent1 = Agent(
name="Stock Searcher",
model=OpenAIChat("gpt-4o"),
)
agent2 = Agent(
name="Company Info Searcher",
model=OpenAIChat("gpt-4o"),
)
team = Team(
name="Stock Research Team",
mode="route",
model=OpenAIChat("gpt-4o"),
members=[agent1, agent2],
tools=[CalculatorTools()],
markdown=True,
show_members_responses=True,
)
@tool
def get_stock_price(stock_symbol: str) -> str:
"""Get the current stock price of a stock."""
return f"The current stock price of {stock_symbol} is {random.randint(100, 1000)}."
@tool
def get_stock_availability(stock_symbol: str) -> str:
"""Get the current availability of a stock."""
return f"The current stock available of {stock_symbol} is {random.randint(100, 1000)}."
team.set_tools([get_stock_price, get_stock_availability])
team.print_response("What is the current stock price of NVDA?", stream=True)
team.print_response("How much stock NVDA stock is available?", stream=True)
```
Cassandra also supports asynchronous operations, enabling concurrency and leading to better performance.
```python async_cassandra.py import asyncio from agno.agent import Agent from agno.embedder.mistral import MistralEmbedder from agno.knowledge.pdf_url import PDFUrlKnowledgeBase from agno.models.mistral import MistralChat from agno.vectordb.cassandra import Cassandra try: from cassandra.cluster import Cluster # type: ignore except (ImportError, ModuleNotFoundError): raise ImportError( "Could not import cassandra-driver python package.Please install it with pip install cassandra-driver." ) cluster = Cluster() session = cluster.connect() session.execute( """ CREATE KEYSPACE IF NOT EXISTS testkeyspace WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 } """ ) knowledge_base = PDFUrlKnowledgeBase( urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"], vector_db=Cassandra( table_name="recipes", keyspace="testkeyspace", session=session, embedder=MistralEmbedder(), ), ) agent = Agent( model=MistralChat(), knowledge=knowledge_base, show_tool_calls=True, ) if __name__ == "__main__": # Comment out after first run asyncio.run(knowledge_base.aload(recreate=False)) # Create and use the agent asyncio.run( agent.aprint_response( "What are the health benefits of Khao Niew Dam Piek Maphrao Awn?", markdown=True, ) ) ```aload() and aprint\_response() methods with asyncio.run() for non-blocking operations in high-throughput applications.
ChromaDB also supports asynchronous operations, enabling concurrency and leading to better performance.
```python async_chroma_db.py # install chromadb - `pip install chromadb` import asyncio from agno.agent import Agent from agno.knowledge.pdf_url import PDFUrlKnowledgeBase from agno.vectordb.chroma import ChromaDb # Initialize ChromaDB vector_db = ChromaDb(collection="recipes", path="tmp/chromadb", persistent_client=True) # Create knowledge base knowledge_base = PDFUrlKnowledgeBase( urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"], vector_db=vector_db, ) # Create and use the agent agent = Agent(knowledge=knowledge_base, show_tool_calls=True) if __name__ == "__main__": # Comment out after first run asyncio.run(knowledge_base.aload(recreate=False)) # Create and use the agent asyncio.run(agent.aprint_response("How to make Tom Kha Gai", markdown=True)) ```aload() and aprint\_response() methods with asyncio.run() for non-blocking operations in high-throughput applications.
Clickhouse also supports asynchronous operations, enabling concurrency and leading to better performance.
```python async_clickhouse.py import asyncio from agno.agent import Agent from agno.knowledge.pdf_url import PDFUrlKnowledgeBase from agno.storage.agent.sqlite import SqliteAgentStorage from agno.vectordb.clickhouse import Clickhouse agent = Agent( storage=SqliteAgentStorage(table_name="recipe_agent"), knowledge=PDFUrlKnowledgeBase( urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"], vector_db=Clickhouse( table_name="recipe_documents", host="localhost", port=8123, username="ai", password="ai", ), ), # Show tool calls in the response show_tool_calls=True, # Enable the agent to search the knowledge base search_knowledge=True, # Enable the agent to read the chat history read_chat_history=True, ) if __name__ == "__main__": # Comment out after first run asyncio.run(agent.knowledge.aload(recreate=False)) # Create and use the agent asyncio.run(agent.aprint_response("How to make Tom Kha Gai", markdown=True)) ```aload() and aprint\_response() methods with asyncio.run() for non-blocking operations in high-throughput applications.
Couchbase also supports asynchronous operations, enabling concurrency and leading to better performance.
```python async_couchbase.py import asyncio import os import time from agno.agent import Agent from agno.embedder.openai import OpenAIEmbedder from agno.knowledge.pdf_url import PDFUrlKnowledgeBase from agno.vectordb.couchbase import CouchbaseSearch from couchbase.options import ClusterOptions, KnownConfigProfiles from couchbase.auth import PasswordAuthenticator from couchbase.management.search import SearchIndex # Couchbase connection settings username = os.getenv("COUCHBASE_USER") password = os.getenv("COUCHBASE_PASSWORD") connection_string = os.getenv("COUCHBASE_CONNECTION_STRING") # Create cluster options with authentication auth = PasswordAuthenticator(username, password) cluster_options = ClusterOptions(auth) cluster_options.apply_profile(KnownConfigProfiles.WanDevelopment) knowledge_base = PDFUrlKnowledgeBase( urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"], vector_db=CouchbaseSearch( bucket_name="recipe_bucket", scope_name="recipe_scope", collection_name="recipes", couchbase_connection_string=connection_string, cluster_options=cluster_options, search_index="vector_search_fts_index", embedder=OpenAIEmbedder( id="text-embedding-3-large", dimensions=3072, api_key=os.getenv("OPENAI_API_KEY") ), wait_until_index_ready=60, overwrite=True ), ) # Create and use the agent agent = Agent(knowledge=knowledge_base, show_tool_calls=True) async def run_agent(): await knowledge_base.aload(recreate=True) time.sleep(5) # Wait for the vector index to sync with KV await agent.aprint_response("How to make Thai curry?", markdown=True) if __name__ == "__main__": # Comment out after the first run asyncio.run(run_agent()) ```aload() and aprint\_response() methods with asyncio.run() for non-blocking operations in high-throughput applications.
Several vector databases support asynchronous operations, offering improved performance through non-blocking operations, concurrent processing, reduced latency, and seamless integration with FastAPI and async agents.
aload methods for async
knowledge base loading in production environments.
LanceDB also supports asynchronous operations, enabling concurrency and leading to better performance.
```python async_lance_db.py # install lancedb - `pip install lancedb` import asyncio from agno.agent import Agent from agno.knowledge.pdf_url import PDFUrlKnowledgeBase from agno.vectordb.lancedb import LanceDb # Initialize LanceDB vector_db = LanceDb( table_name="recipes", uri="tmp/lancedb", # You can change this path to store data elsewhere ) # Create knowledge base knowledge_base = PDFUrlKnowledgeBase( urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"], vector_db=vector_db, ) agent = Agent(knowledge=knowledge_base, show_tool_calls=True, debug_mode=True) if __name__ == "__main__": # Load knowledge base asynchronously asyncio.run(knowledge_base.aload(recreate=False)) # Comment out after first run # Create and use the agent asynchronously asyncio.run(agent.aprint_response("How to make Tom Kha Gai", markdown=True)) ```aload() and aprint\_response() methods with asyncio.run() for non-blocking operations in high-throughput applications.
Milvus also supports asynchronous operations, enabling concurrency and leading to better performance.
```python async_milvus_db.py # install pymilvus - `pip install pymilvus` import asyncio from agno.agent import Agent from agno.knowledge.pdf_url import PDFUrlKnowledgeBase from agno.vectordb.milvus import Milvus # Initialize Milvus with local file vector_db = Milvus( collection="recipes", uri="tmp/milvus.db", # For local file-based storage ) # Create knowledge base knowledge_base = PDFUrlKnowledgeBase( urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"], vector_db=vector_db, ) # Create agent with knowledge base agent = Agent(knowledge=knowledge_base) if __name__ == "__main__": # Load knowledge base asynchronously asyncio.run(knowledge_base.aload(recreate=False)) # Comment out after first run # Query the agent asynchronously asyncio.run(agent.aprint_response("How to make Tom Kha Gai", markdown=True)) ```aload() and aprint\_response() methods with asyncio.run() for non-blocking operations in high-throughput applications.
MongoDB also supports asynchronous operations, enabling concurrency and leading to better performance.
```python async_mongodb.py import asyncio from agno.agent import Agent from agno.knowledge.pdf_url import PDFUrlKnowledgeBase from agno.vectordb.mongodb import MongoDb # MongoDB Atlas connection string """ Example connection strings: "mongodb+srv://aload() and aprint\_response() methods with asyncio.run() for non-blocking operations in high-throughput applications.
PgVector also supports asynchronous operations, enabling concurrency and leading to better performance.
```python async_pgvector.py import asyncio from agno.agent import Agent from agno.knowledge.pdf_url import PDFUrlKnowledgeBase from agno.vectordb.pgvector import PgVector db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai" vector_db = PgVector(table_name="recipes", db_url=db_url) knowledge_base = PDFUrlKnowledgeBase( urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"], vector_db=vector_db, ) agent = Agent(knowledge=knowledge_base, show_tool_calls=True) if __name__ == "__main__": # Comment out after first run asyncio.run(knowledge_base.aload(recreate=False)) # Create and use the agent asyncio.run(agent.aprint_response("How to make Tom Kha Gai", markdown=True)) ```aload() and aprint\_response() methods with asyncio.run() for non-blocking operations in high-throughput applications.
Pinecone also supports asynchronous operations, enabling concurrency and leading to better performance.
```python async_pinecone.py import asyncio from os import getenv from agno.agent import Agent from agno.knowledge.pdf_url import PDFUrlKnowledgeBase from agno.vectordb.pineconedb import PineconeDb api_key = getenv("PINECONE_API_KEY") index_name = "thai-recipe-index" vector_db = PineconeDb( name=index_name, dimension=1536, metric="cosine", spec={"serverless": {"cloud": "aws", "region": "us-east-1"}}, api_key=api_key, ) knowledge_base = PDFUrlKnowledgeBase( urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"], vector_db=vector_db, ) agent = Agent( knowledge=knowledge_base, # Show tool calls in the response show_tool_calls=True, # Enable the agent to search the knowledge base search_knowledge=True, # Enable the agent to read the chat history read_chat_history=True, ) if __name__ == "__main__": # Comment out after first run asyncio.run(knowledge_base.aload(recreate=False, upsert=True)) # Create and use the agent asyncio.run(agent.aprint_response("How to make Tom Kha Gai", markdown=True)) ```aload() and aprint\_response() methods with asyncio.run() for non-blocking operations in high-throughput applications.
Qdrant also supports asynchronous operations, enabling concurrency and leading to better performance.
```python async_qdrant_db.py import asyncio from agno.agent import Agent from agno.knowledge.pdf_url import PDFUrlKnowledgeBase from agno.vectordb.qdrant import Qdrant COLLECTION_NAME = "thai-recipes" # Initialize Qdrant with local instance vector_db = Qdrant( collection=COLLECTION_NAME, url="http://localhost:6333" ) # Create knowledge base knowledge_base = PDFUrlKnowledgeBase( urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"], vector_db=vector_db, ) agent = Agent(knowledge=knowledge_base, show_tool_calls=True) if __name__ == "__main__": # Load knowledge base asynchronously asyncio.run(knowledge_base.aload(recreate=False)) # Comment out after first run # Create and use the agent asynchronously asyncio.run(agent.aprint_response("How to make Tom Kha Gai", markdown=True)) ```aload() and aprint\_response() with asyncio provides non-blocking operations, making your application more responsive under load.
SurrealDB also supports asynchronous operations, enabling concurrency and leading to better performance.
```python async_surrealdb_db.py import asyncio from agno.agent import Agent from agno.embedder.openai import OpenAIEmbedder from agno.knowledge.pdf_url import PDFUrlKnowledgeBase from agno.vectordb.surrealdb import SurrealDb from surrealdb import AsyncSurreal # SurrealDB connection parameters SURREALDB_URL = "ws://localhost:8000" SURREALDB_USER = "root" SURREALDB_PASSWORD = "root" SURREALDB_NAMESPACE = "test" SURREALDB_DATABASE = "test" # Create a client client = AsyncSurreal(url=SURREALDB_URL) surrealdb = SurrealDb( async_client=client, collection="recipes", # Collection name for storing documents efc=150, # HNSW construction time/accuracy trade-off m=12, # HNSW max number of connections per element search_ef=40, # HNSW search time/accuracy trade-off ) async def async_demo(): """Demonstrate asynchronous usage of SurrealDb""" await client.signin({"username": SURREALDB_USER, "password": SURREALDB_PASSWORD}) await client.use(namespace=SURREALDB_NAMESPACE, database=SURREALDB_DATABASE) knowledge_base = PDFUrlKnowledgeBase( urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"], vector_db=surrealdb, embedder=OpenAIEmbedder(), ) await knowledge_base.aload(recreate=True) agent = Agent(knowledge=knowledge_base, show_tool_calls=True) await agent.aprint_response( "What are the 3 categories of Thai SELECT is given to restaurants overseas?", markdown=True, ) if __name__ == "__main__": # Run asynchronous demo print("\nRunning asynchronous demo...") asyncio.run(async_demo()) ```aload() and aprint\_response() with asyncio provides non-blocking operations, making your application more responsive under load.
Weaviate also supports asynchronous operations, enabling concurrency and leading to better performance.
```python async_weaviate_db.py import asyncio from agno.agent import Agent from agno.knowledge.pdf_url import PDFUrlKnowledgeBase from agno.vectordb.search import SearchType from agno.vectordb.weaviate import Distance, VectorIndex, Weaviate vector_db = Weaviate( collection="recipes_async", search_type=SearchType.hybrid, vector_index=VectorIndex.HNSW, distance=Distance.COSINE, local=True, # Set to False if using Weaviate Cloud and True if using local instance ) # Create knowledge base knowledge_base = PDFUrlKnowledgeBase( urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"], vector_db=vector_db, ) agent = Agent( knowledge=knowledge_base, search_knowledge=True, show_tool_calls=True, ) if __name__ == "__main__": # Comment out after first run asyncio.run(knowledge_base.aload(recreate=False)) # Create and use the agent asyncio.run(agent.aprint_response("How to make Tom Kha Gai", markdown=True)) ```WeaviateAsyncClient to provide non-blocking vector operations. This is particularly valuable for applications requiring high concurrency and throughput.
Checkout more [usecases](/examples/workflows/) and [examples](/examples/concepts/storage/workflow_storage) related to workflows.
## Design decisions
```python
from agno.workflow.v2 import Step, Workflow
from agno.workflow.v2.types import StepInput, StepOutput
def security_gate(step_input: StepInput) -> StepOutput:
"""Security gate that stops deployment if vulnerabilities found"""
security_result = step_input.previous_step_content or ""
if "VULNERABLE" in security_result.upper():
return StepOutput(
content="🚨 SECURITY ALERT: Critical vulnerabilities detected. Deployment blocked.",
stop=True # Stop the entire workflow
)
else:
return StepOutput(
content="✅ Security check passed. Proceeding with deployment...",
stop=False
)
# Secure deployment pipeline
workflow = Workflow(
name="Secure Deployment Pipeline",
steps=[
Step(name="Security Scan", agent=security_scanner),
Step(name="Security Gate", executor=security_gate), # May stop here
Step(name="Deploy Code", agent=code_deployer), # Only if secure
Step(name="Setup Monitoring", agent=monitoring_agent), # Only if deployed
]
)
# Test with vulnerable code - workflow stops at security gate
workflow.print_response("Scan this code: exec(input('Enter command: '))")
```
**More Examples**:
* [Early Stop Workflow](/examples/workflows_2/06-workflows-advanced-concepts/early_stop_workflow)
## Access Multiple Previous Steps Output
Advanced workflows often need to access data from multiple previous steps, not just the immediate previous step. The `StepInput` object provides powerful methods to access any previous step's output by name or get all previous content.
```python
def create_comprehensive_report(step_input: StepInput) -> StepOutput:
"""
Custom function that creates a report using data from multiple previous steps.
This function has access to ALL previous step outputs and the original workflow message.
"""
# Access original workflow input
original_topic = step_input.workflow_message or ""
# Access specific step outputs by name
hackernews_data = step_input.get_step_content("research_hackernews") or ""
web_data = step_input.get_step_content("research_web") or ""
# Or access ALL previous content
all_research = step_input.get_all_previous_content()
# Create a comprehensive report combining all sources
report = f"""
# Comprehensive Research Report: {original_topic}
## Executive Summary
Based on research from HackerNews and web sources, here's a comprehensive analysis of {original_topic}.
## HackerNews Insights
{hackernews_data[:500]}...
## Web Research Findings
{web_data[:500]}...
"""
return StepOutput(
step_name="comprehensive_report",
content=report.strip(),
success=True
)
# Use in workflow
workflow = Workflow(
name="Enhanced Research Workflow",
steps=[
Step(name="research_hackernews", agent=hackernews_agent),
Step(name="research_web", agent=web_agent),
Step(name="comprehensive_report", executor=create_comprehensive_report), # Accesses both previous steps
Step(name="final_reasoning", agent=reasoning_agent),
],
)
```
**Key Methods:**
* `step_input.get_step_content("step_name")` - Get content from specific step by name
* `step_input.get_all_previous_content()` - Get all previous step content combined
* `step_input.message` - Access the original workflow input message
* `step_input.previous_step_content` - Get content from immediate previous step
## Why should you use Workflows?
Workflows are a great way to automate complex processes by defining a series of steps that are executed in a flow that you control. This is particularly useful when you need to:
* Automate a series of tasks
* Orchestrate multiple agents or teams of agents
* Have complex logic where you require agents to run in loops, or in parallel, or route different flows based on the output of previous steps
When building multi-agent systems, there is often a need to control the flow of execution, and this is where Workflows come in. Workflows are best suited for deterministic agent automation, in comparison to [Teams](/teams) which are designed for agentic coordination between agents.
## Step-Wise Controlled Execution
Agno Workflows are fundamentally an execution of a series of steps. These steps are executed in sequence, and the output of each step is passed to the next step.
Each step can be executed by an agent, a team, or a custom Python function. These are individual components that can work independently but gain enhanced capabilities when orchestrated together:
* **Agents**: Individual AI executors with specific capabilities and instructions
* **Teams**: Coordinated groups of agents working together on complex problems
* **Functions**: Custom Python functions for specialized processing logic
The beauty of this approach is that you have access to the full power of Agno Agents and Teams, with the flexibility of a sophisticated orchestration system.
Your agents and teams retain their individual characteristics, memory, and behavior patterns, but now operate within a structured workflow that provides:
* Sequential step execution with output chaining
* Session management and state persistence
* Error handling and retry mechanisms
* Streaming capabilities for real-time feedback
## Workflow Input
Workflows support multiple input types for maximum flexibility:
| Input Type | Example | Use Case |
| ------------------ | ------------------------------------------------- | -------------------------- |
| **String** | `"Analyze AI trends"` | Simple text prompts |
| **Pydantic Model** | `ResearchRequest(topic="AI", depth=5)` | Type-safe structured input |
| **List** | `["AI", "ML", "LLMs"]` | Multiple items to process |
| **Dictionary** | `{"query": "AI", "sources": ["web", "academic"]}` | Key-value pairs |
#### Parameters
#### Parameters
#### Parameters
#### Parameters
## How Workflow Session State Works
### 1. Initialization
The workflow session state is initialized when a Workflow object is created. It can be an empty dictionary or pre-populated with initial state data.
```python
shopping_workflow = Workflow(
name="Shopping List Workflow",
steps=[manage_items_step, view_list_step],
workflow_session_state={}, # Initialize empty workflow session state
)
```
### 2. Access and Modification
Agents and teams can access and modify the workflow session state during task execution. This is typically done through methods or tools that interact with the state.
Consider the following example-
```python
from agno.agent.agent import Agent
from agno.models.openai.chat import OpenAIChat
from agno.workflow.v2.step import Step
from agno.workflow.v2.workflow import Workflow
# Define tools to manage a shopping list in workflow session state
def add_item(agent: Agent, item: str) -> str:
"""Add an item to the shopping list in workflow session state.
Args:
item (str): The item to add to the shopping list
"""
if agent.workflow_session_state is None:
agent.workflow_session_state = {}
if "shopping_list" not in agent.workflow_session_state:
agent.workflow_session_state["shopping_list"] = []
# Check if item already exists (case-insensitive)
existing_items = [
existing_item.lower()
for existing_item in agent.workflow_session_state["shopping_list"]
]
if item.lower() not in existing_items:
agent.workflow_session_state["shopping_list"].append(item)
return f"Added '{item}' to the shopping list."
else:
return f"'{item}' is already in the shopping list."
def remove_item(agent: Agent, item: str) -> str:
"""Remove an item from the shopping list in workflow session state.
Args:
item (str): The item to remove from the shopping list
"""
if agent.workflow_session_state is None:
agent.workflow_session_state = {}
if "shopping_list" not in agent.workflow_session_state:
agent.workflow_session_state["shopping_list"] = []
return f"Shopping list is empty. Cannot remove '{item}'."
# Find and remove item (case-insensitive)
shopping_list = agent.workflow_session_state["shopping_list"]
for i, existing_item in enumerate(shopping_list):
if existing_item.lower() == item.lower():
removed_item = shopping_list.pop(i)
return f"Removed '{removed_item}' from the shopping list."
return f"'{item}' not found in the shopping list."
def remove_all_items(agent: Agent) -> str:
"""Remove all items from the shopping list in workflow session state."""
if agent.workflow_session_state is None:
agent.workflow_session_state = {}
agent.workflow_session_state["shopping_list"] = []
return "Removed all items from the shopping list."
def list_items(agent: Agent) -> str:
"""List all items in the shopping list from workflow session state."""
if (
agent.workflow_session_state is None
or "shopping_list" not in agent.workflow_session_state
or not agent.workflow_session_state["shopping_list"]
):
return "Shopping list is empty."
items = agent.workflow_session_state["shopping_list"]
items_str = "\n".join([f"- {item}" for item in items])
return f"Shopping list:\n{items_str}"
# Create agents with tools that use workflow session state
shopping_assistant = Agent(
name="Shopping Assistant",
model=OpenAIChat(id="gpt-4o-mini"),
tools=[add_item, remove_item, list_items],
instructions=[
"You are a helpful shopping assistant.",
"You can help users manage their shopping list by adding, removing, and listing items.",
"Always use the provided tools to interact with the shopping list.",
"Be friendly and helpful in your responses.",
],
)
list_manager = Agent(
name="List Manager",
model=OpenAIChat(id="gpt-4o-mini"),
tools=[list_items, remove_all_items],
instructions=[
"You are a list management specialist.",
"You can view the current shopping list and clear it when needed.",
"Always show the current list when asked.",
"Confirm actions clearly to the user.",
],
)
# Create steps
manage_items_step = Step(
name="manage_items",
description="Help manage shopping list items (add/remove)",
agent=shopping_assistant,
)
view_list_step = Step(
name="view_list",
description="View and manage the complete shopping list",
agent=list_manager,
)
# Create workflow with workflow_session_state
shopping_workflow = Workflow(
name="Shopping List Workflow",
steps=[manage_items_step, view_list_step],
workflow_session_state={}, # Initialize empty workflow session state
)
if __name__ == "__main__":
# Example 1: Add items to the shopping list
print("=== Example 1: Adding Items ===")
shopping_workflow.print_response(
message="Please add milk, bread, and eggs to my shopping list."
)
print("Workflow session state:", shopping_workflow.workflow_session_state)
# Example 2: Add more items and view list
print("\n=== Example 2: Adding More Items ===")
shopping_workflow.print_response(
message="Add apples and bananas to the list, then show me the complete list."
)
print("Workflow session state:", shopping_workflow.workflow_session_state)
# Example 3: Remove items
print("\n=== Example 3: Removing Items ===")
shopping_workflow.print_response(
message="Remove bread from the list and show me what's left."
)
print("Workflow session state:", shopping_workflow.workflow_session_state)
# Example 4: Clear the entire list
print("\n=== Example 4: Clearing List ===")
shopping_workflow.print_response(
message="Clear the entire shopping list and confirm it's empty."
)
print("Final workflow session state:", shopping_workflow.workflow_session_state)
```
In the example, the `add_item` function which is passed as a tool to the `Agent` modifies the workflow session state by adding an item to the shopping list.
## Build Docker Images with Github Releases
If you're using [Dockerhub](https://hub.docker.com/) for images, you can buld and push the images throug a Github Release. This action is defined in the `.github/workflows/docker-images.yml` file.
1. Create a [Docker Access Token](https://hub.docker.com/settings/security) for Github Actions
2. Create secret variables `DOCKERHUB_REPO`, `DOCKERHUB_TOKEN` and `DOCKERHUB_USERNAME` in your github repo. These variables are used by the action in `.github/workflows/docker-images.yml`
3. Run workflow using a Github Release
This workflow is configured to run when a release is created. Create a new release using:
8. Assign a Role to the provider.
9. Create a new role.
10. Confirm that Web identity is already selected as the trusted entity and the Identity provider field is populated with the IdP. In the Audience list, select sts.amazonaws.com, and then select Next.
11. Add the `AmazonEC2ContainerRegistryPowerUser` permission to this role.
12. Create the role with the name `GithubActionsRole`.
13. Find the role `GithubActionsRole` and copy the ARN.
14. Create the ECR Repositories: `llm` and `jupyter-llm` which are built by the workflow.
15. Update the workflow with the `GithubActionsRole` ARN and ECR Repository.
```yaml .github/workflows/ecr-images.yml
name: Build ECR Images
on:
release:
types: [published]
permissions:
# For AWS OIDC Token access as per https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services#updating-your-github-actions-workflow
id-token: write # This is required for requesting the JWT
contents: read # This is required for actions/checkout
env:
ECR_REPO: [YOUR_ECR_REPO]
# Create role using https://aws.amazon.com/blogs/security/use-iam-roles-to-connect-github-actions-to-actions-in-aws/
AWS_ROLE: [GITHUB_ACTIONS_ROLE_ARN]
AWS_REGION: us-east-1
```
16. Update the `docker-images` workflow to **NOT** run on a release
```yaml .github/workflows/docker-images.yml
name: Build Docker Images
on: workflow_dispatch
```
17. Run workflow using a Github Release
You can visit the app at [http://app.aidev.run](http://app.aidev.run)
You can access the api at [http://api.aidev.run](http://api.aidev.run)
2. Creating records in Route 53.
3. Add the certificate ARN to Apps
## Create a new workspace
Run `ag ws create` to create a new workspace, the command will ask your for a starter template and workspace name.
**2. Authenticate with ECR**
```bash Authenticate with ECR
aws ecr get-login-password --region [region] | docker login --username AWS --password-stdin [account].dkr.ecr.[region].amazonaws.com
```
You can also use a helper script to avoid running the full command