CrewAI is a framework for orchestrating role-playing, autonomous AI agents designed to solve complex, open-ended tasks through collaboration. It provides a robust structure for agents to work together, leverage tools, and exchange insights to accomplish sophisticated objectives.Portkey enhances CrewAI with production-readiness features, turning your experimental agent crews into robust systems by providing:
Complete observability of every agent step, tool use, and interaction
Built-in reliability with fallbacks, retries, and load balancing
Cost tracking and optimization to manage your AI spend
Access to 1600+ LLMs through a single integration
Guardrails to keep agent behavior safe and compliant
Version-controlled prompts for consistent agent performance
CrewAI Official Documentation
Learn more about CrewAI’s core concepts and features
Create a Portkey API key with optional budget/rate limits from the Portkey dashboard. You can also attach configurations for reliability, caching, and more to this key. More on this later.
3
Configure CrewAI with Portkey
The integration is simple - you just need to update the LLM configuration in your CrewAI setup:
Copy
Ask AI
from crewai import LLMfrom portkey_ai import createHeaders, PORTKEY_GATEWAY_URL# Create an LLM instance with Portkey integrationgpt_llm = LLM( model="gpt-4o", base_url=PORTKEY_GATEWAY_URL, api_key="dummy", extra_headers=createHeaders( api_key="YOUR_PORTKEY_API_KEY", provider="@YOUR_LLM_PROVIDER", trace_id="unique-trace-id", # Optional, for request tracing ))#Use them in your Crew Agents like this: @agent def lead_market_analyst(self) -> Agent: return Agent( config=self.agents_config['lead_market_analyst'], verbose=True, memory=False, llm=gpt_llm )
Portkey provides comprehensive observability for your CrewAI agents, helping you understand exactly what’s happening during each execution.
Traces
Logs
Metrics & Dashboards
Metadata Filtering
Traces provide a hierarchical view of your crew’s execution, showing the sequence of LLM calls, tool invocations, and state transitions.
Copy
Ask AI
# Add trace_id to enable hierarchical tracing in Portkeyportkey_llm = LLM( model="gpt-4o", base_url=PORTKEY_GATEWAY_URL, api_key="dummy", extra_headers=createHeaders( api_key="YOUR_PORTKEY_API_KEY", provider="@YOUR_OPENAI_PROVIDER", trace_id="unique-session-id" # Add unique trace ID ))
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 crew runs.
Portkey provides built-in dashboards that help you:
Track cost and token usage across all crew runs
Analyze performance metrics like latency and success rates
Identify bottlenecks in your agent workflows
Compare different crew configurations and LLMs
You can filter and segment all metrics by custom metadata to analyze specific crew types, user groups, or use cases.
Add custom metadata to your CrewAI LLM configuration to enable powerful filtering and segmentation:
Copy
Ask AI
portkey_llm = LLM( model="gpt-4o", base_url=PORTKEY_GATEWAY_URL, api_key="dummy", extra_headers=createHeaders( api_key="YOUR_PORTKEY_API_KEY", provider="@YOUR_OPENAI_PROVIDER", metadata={ "crew_type": "research_crew", "environment": "production", "_user": "user_123", # Special _user field for user analytics "request_source": "mobile_app" } ))
This metadata can be used to filter logs, traces, and metrics on the Portkey dashboard, allowing you to analyze specific crew runs, users, or environments.
When running crews 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 simple to enable fallback in your CrewAI setup by using a Portkey Config:
Copy
Ask AI
from crewai import LLMfrom portkey_ai import createHeaders, PORTKEY_GATEWAY_URL# Create LLM with fallback configurationportkey_llm = LLM( model="gpt-4o", max_tokens=1000, base_url=PORTKEY_GATEWAY_URL, api_key="dummy", extra_headers=createHeaders( api_key="YOUR_PORTKEY_API_KEY", config={ "strategy": { "mode": "fallback" }, "targets": [ { "provider": "openai", "api_key": "YOUR_OPENAI_API_KEY", "override_params": {"model": "gpt-4o"} }, { "provider": "anthropic", "api_key": "YOUR_ANTHROPIC_API_KEY", "override_params": {"model": "claude-3-opus-20240229"} } ] } ))# Use this LLM configuration with your agents
This configuration will automatically try Claude if the GPT-4o request fails, ensuring your crew can continue operating.
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.
Request Timeouts
Prevent your agents from hanging. Set timeouts to ensure you get responses (or can fail gracefully) within your required timeframes.
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.
Fallbacks
Keep running even if your primary provider fails. Automatically switch to backup providers to maintain availability.
Load Balancing
Spread requests across multiple API keys or providers. Great for high-volume crew operations and staying within rate limits.
Portkey’s Prompt Engineering Studio helps you create, manage, and optimize the prompts used in your CrewAI agents. Instead of hardcoding prompts or instructions, use Portkey’s prompt rendering API to dynamically fetch and apply your versioned prompts.
Prompt Playground
Using Prompt Templates
Prompt Versioning
Mustache Templating for variables
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:
Iteratively develop prompts before using them in your agents
Test prompts with different variables and models
Compare outputs between different prompt versions
Collaborate with team members on prompt development
This visual environment makes it easier to craft effective prompts for each step in your CrewAI agents’ workflow.
The Prompt Render API retrieves your prompt templates with all parameters configured:
Copy
Ask AI
from crewai import Agent, LLMfrom portkey_ai import createHeaders, PORTKEY_GATEWAY_URL, Portkey# Initialize Portkey admin clientportkey_admin = Portkey(api_key="YOUR_PORTKEY_API_KEY")# Retrieve prompt using the render APIprompt_data = portkey_client.prompts.render( prompt_id="YOUR_PROMPT_ID", variables={ "agent_role": "Senior Research Scientist", })backstory_agent_prompt=prompt_data.data.messages[0]["content"]# Set up LLM with Portkey integrationportkey_llm = LLM( model="gpt-4o", base_url=PORTKEY_GATEWAY_URL, api_key="dummy", extra_headers=createHeaders( api_key="YOUR_PORTKEY_API_KEY", provider="@YOUR_OPENAI_PROVIDER" ))# Create agent using the rendered promptresearcher = Agent( role="Senior Research Scientist", goal="Discover groundbreaking insights about the assigned topic", backstory=backstory_agent, # Use the rendered prompt verbose=True, llm=portkey_llm)
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:
Copy
Ask AI
# Use a specific prompt versionprompt_data = portkey_admin.prompts.render( prompt_id="YOUR_PROMPT_ID@version_number", variables={ "agent_role": "Senior Research Scientist", "agent_goal": "Discover groundbreaking insights" })
Portkey prompts use Mustache-style templating for easy variable substitution:
Copy
Ask AI
You are a {{agent_role}} with expertise in {{domain}}.Your mission is to {{agent_goal}} by leveraging your knowledgeand experience in the field.Always maintain a {{tone}} tone and focus on providing {{focus_area}}.
Guardrails ensure your CrewAI agents operate safely and respond appropriately in all situations.Why Use Guardrails?CrewAI 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 add protections for both inputs and outputs.Implementing Guardrails
Copy
Ask AI
from crewai import Agent, LLMfrom portkey_ai import createHeaders, PORTKEY_GATEWAY_URL# Create LLM with guardrailsportkey_llm = LLM( model="gpt-4o", base_url=PORTKEY_GATEWAY_URL, api_key="dummy", extra_headers=createHeaders( api_key="YOUR_PORTKEY_API_KEY", provider="@YOUR_OPENAI_PROVIDER", config={ "input_guardrails": ["guardrails-id-xxx", "guardrails-id-yyy"], "output_guardrails": ["guardrails-id-zzz"] } ))# Create agent with guardrailed LLMresearcher = Agent( role="Senior Research Scientist", goal="Discover groundbreaking insights about the assigned topic", backstory="You are an expert researcher with deep domain knowledge.", verbose=True, llm=portkey_llm)
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
Learn More About Guardrails
Explore Portkey’s guardrail features to enhance agent safety
Track individual users through your CrewAI 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.
Copy
Ask AI
from crewai import Agent, LLMfrom portkey_ai import createHeaders, PORTKEY_GATEWAY_URL# Configure LLM with user trackingportkey_llm = LLM( model="gpt-4o", base_url=PORTKEY_GATEWAY_URL, api_key="dummy", extra_headers=createHeaders( api_key="YOUR_PORTKEY_API_KEY", provider="@YOUR_OPENAI_PROVIDER", metadata={ "_user": "user_123", # Special _user field for user analytics "user_tier": "premium", "user_company": "Acme Corp", "session_id": "abc-123" } ))# Create agent with tracked LLMresearcher = Agent( role="Senior Research Scientist", goal="Discover groundbreaking insights about the assigned topic", backstory="You are an expert researcher with deep domain knowledge.", verbose=True, llm=portkey_llm)
Filter Analytics by UserWith metadata in place, you can filter analytics by user and analyze performance metrics on a per-user basis:
This enables:
Per-user cost tracking and budgeting
Personalized user analytics
Team or organization-level metrics
Environment-specific monitoring (staging vs. production)
Learn More About Metadata
Explore how to use custom metadata to enhance your analytics
CrewAI supports multiple LLM providers, and Portkey extends this capability by providing access to over 200 LLMs through a unified interface. You can easily switch between different models without changing your core agent logic:
Copy
Ask AI
from crewai import Agent, LLMfrom portkey_ai import createHeaders, PORTKEY_GATEWAY_URL# Set up LLMs with different providersopenai_llm = LLM( model="gpt-4o", base_url=PORTKEY_GATEWAY_URL, api_key="dummy", extra_headers=createHeaders( api_key="YOUR_PORTKEY_API_KEY", provider="@YOUR_OPENAI_PROVIDER" ))anthropic_llm = LLM( model="claude-3-5-sonnet-latest", max_tokens=1000, base_url=PORTKEY_GATEWAY_URL, api_key="dummy", extra_headers=createHeaders( api_key="YOUR_PORTKEY_API_KEY", provider="@YOUR_ANTHROPIC_PROVIDER" ))# Choose which LLM to use for each agent based on your needsresearcher = Agent( role="Senior Research Scientist", goal="Discover groundbreaking insights about the assigned topic", backstory="You are an expert researcher with deep domain knowledge.", verbose=True, llm=openai_llm # Use anthropic_llm for Anthropic)
Portkey provides access to LLMs from providers including:
OpenAI (GPT-4o, GPT-4 Turbo, etc.)
Anthropic (Claude 3.5 Sonnet, Claude 3 Opus, etc.)
Mistral AI (Mistral Large, Mistral Medium, etc.)
Google Vertex AI (Gemini 1.5 Pro, etc.)
Cohere (Command, Command-R, etc.)
AWS Bedrock (Claude, Titan, etc.)
Local/Private Models
Supported Providers
See the full list of LLM providers supported by Portkey
After setting up your Portkey API key with the attached config, connect it to your CrewAI agents:
Copy
Ask AI
from crewai import Agent, LLMfrom portkey_ai import PORTKEY_GATEWAY_URL# Configure LLM with your API keyportkey_llm = LLM( model="gpt-4o", base_url=PORTKEY_GATEWAY_URL, api_key="YOUR_PORTKEY_API_KEY")# Create agent with Portkey-enabled LLMresearcher = Agent( role="Senior Research Scientist", goal="Discover groundbreaking insights about the assigned topic", backstory="You are an expert researcher with deep domain knowledge.", verbose=True, llm=portkey_llm)
As your AI usage scales, controlling which teams can access specific models becomes crucial. Portkey Configs provide this control layer with features like:
After distributing API keys to your team members, your enterprise-ready CrewAI setup is ready to go. Each team member can now use their designated API keys with appropriate access levels and budget controls.Monitor usage in Portkey dashboard:
Portkey adds production-readiness to CrewAI through comprehensive observability (traces, logs, metrics), reliability features (fallbacks, retries, caching), and access to 1600+ LLMs through a unified interface. This makes it easier to debug, optimize, and scale your agent applications.
Can I use Portkey with existing CrewAI applications?
Yes! Portkey integrates seamlessly with existing CrewAI applications. You just need to update your LLM configuration code with the Portkey-enabled version. The rest of your agent and crew code remains unchanged.
Does Portkey work with all CrewAI features?
Portkey supports all CrewAI features, including agents, tools, human-in-the-loop workflows, and all task process types (sequential, hierarchical, etc.). It adds observability and reliability without limiting any of the framework’s functionality.
Can I track usage across multiple agents in a crew?
Yes, Portkey allows you to use a consistent trace_id across multiple agents in a crew to track the entire workflow. This is especially useful for complex crews where you want to understand the full execution path across multiple agents.
How do I filter logs and traces for specific crew runs?
Portkey allows you to add custom metadata to your LLM configuration, which you can then use for filtering. Add fields like crew_name, crew_type, or session_id to easily find and analyze specific crew executions.
Can I use my own API keys with Portkey?
Yes! Portkey uses your own API keys for the various LLM providers. It securely stores them, allowing you to easily manage and rotate keys without changing your code.