CrewAI integrates with multiple LLM providers through providers native sdks, giving you the flexibility to choose the right model for your specific use case. This guide will help you understand how to configure and use different LLM providers in your CrewAI projects.
What are LLMs?
Large Language Models (LLMs) are the core intelligence behind CrewAI agents. They enable agents to understand context, make decisions, and generate human-like responses. Here's what you need to know:
LLM Basics
Large Language Models are AI systems trained on vast amounts of text data. They power the intelligence of your CrewAI agents, enabling them to understand and generate human-like text.
Context Window
The context window determines how much text an LLM can process at once. Larger windows (e.g., 128K tokens) allow for more context but may be more expensive and slower.
Temperature
Temperature is a sampling control supported by some models. Lower values
generally make sampling more focused, while higher values increase
variability. Some newer reasoning models ignore, deprecate, or reject this
parameter, so check the selected model's documentation before setting it.
Provider Selection
Each LLM provider (e.g., OpenAI, Anthropic, Google) offers different models with varying capabilities, pricing, and features. Choose based on your needs for accuracy, speed, and cost.
Setting up your LLM
There are different places in CrewAI code where you can specify the model to use. Once you specify the model you are using, you will need to provide the configuration (like an API key) for each of the model providers you use. See the provider configuration examples section for your provider.
1. Environment Variables
2. YAML Configuration
3. Direct Code
The simplest way to get started. Set the model in your environment directly, through an .env file or in your app code. If you used crewai create to bootstrap your project, it will be set already.
MODEL=provider/model-id # e.g. openai/gpt-5.6-terra# Be sure to set your API keys here too. See the Provider# section below.
Warning
Never commit API keys to version control. Use environment files (.env) or your system's secret management.
Create a YAML file to define your agent configurations. This method is great for version control and team collaboration:
researcher: role: Research Specialist goal: Conduct comprehensive research and analysis backstory: A dedicated research professional with years of experience verbose: true llm: provider/model-id # e.g. anthropic/claude-sonnet-4-6 # (see provider configuration examples below for more)
Info
The YAML configuration allows you to:
Version control your agent settings
Easily switch between different models
Share configurations across team members
Document model choices and their purposes
For maximum flexibility, configure LLMs directly in your Python code:
from crewai import LLM# Basic configurationllm = LLM(model="provider/model-id") # e.g. gemini/gemini-3.6-flash# Advanced configuration with detailed parametersllm = LLM( model="provider/model-id", timeout=120, max_tokens=4000, response_format={"type": "json"}, # For structured outputs)
Info
Parameter explanations:
timeout: Maximum wait time for response
max_tokens: Limits response length
response_format: Specifies output structure
Sampling controls such as temperature and top_p, penalty parameters,
token-limit names, and reasoning controls are model-specific. Add them
only when the selected provider and model support them. See the provider
examples below and the provider's model documentation.
Info
CrewAI provides native SDK integrations for OpenAI, Anthropic, Google (Gemini API), Azure, AWS Bedrock, and Snowflake Cortex — no extra install needed beyond the provider-specific extras (e.g. uv add "crewai[openai]").
All other providers are powered by LiteLLM. If you plan to use any of them, add it as a dependency to your project:
uv add 'crewai[litellm]'
Provider Configuration Examples
CrewAI supports a multitude of LLM providers, each offering unique features, authentication methods, and model capabilities.
In this section, you'll find detailed examples that help you select, configure, and optimize the LLM that best fits your project's needs.
Warning
Model availability changes frequently and can vary by account, region, and
cloud platform. The examples below use models that are current at the time of
writing, but they are not exhaustive support lists. Before deploying, verify
the model ID and lifecycle status in the provider's linked model catalog.
CrewAI provides native integration with OpenAI through the OpenAI Python SDK.
from crewai import LLMllm = LLM( model="openai/gpt-5.6-terra", api_key="your-api-key", # Or set OPENAI_API_KEY reasoning_effort="medium", max_completion_tokens=4000)
Custom OpenAI-Compatible Endpoint:
from crewai import LLMllm = LLM( model="anthropic/claude-sonnet-4-6", custom_openai=True, base_url="https://your-gateway.example.com/v1", api_key="your-gateway-api-key",)
Advanced Configuration:
from crewai import LLMllm = LLM( model="openai/gpt-5.6-terra", api_key="your-api-key", base_url="https://api.openai.com/v1", # Optional custom endpoint organization="org-...", # Optional organization ID project="proj_...", # Optional project ID max_completion_tokens=4000, reasoning_effort="medium", stream=True, # Enable streaming timeout=60.0, # Request timeout in seconds max_retries=3 # Maximum retry attempts)
Structured Outputs:
from pydantic import BaseModelfrom crewai import LLMclass ResponseFormat(BaseModel): name: str age: int summary: strllm = LLM( model="openai/gpt-5.6-terra",)
Supported Environment Variables:
OPENAI_API_KEY: Your OpenAI API key (required)
OPENAI_BASE_URL: Custom base URL for OpenAI API (optional)
Features:
Native function calling support
Structured outputs with JSON schema
Streaming support for real-time responses
Token usage tracking
Provider-specific generation controls
Log probabilities for token-level insights
Reasoning effort control for supported models
OpenAI regularly adds models and retires older snapshots. See the
OpenAI model catalog for
current model IDs, context windows, endpoint compatibility, and lifecycle
information.
Responses API:
OpenAI offers two APIs: Chat Completions (default) and the newer Responses API. The Responses API was designed from the ground up with native multimodal support—text, images, audio, and function calls are all first-class citizens. It provides better performance with reasoning models and supports additional features like auto-chaining and built-in tools.
from crewai import LLM# Use the Responses API instead of Chat Completionsllm = LLM( model="openai/gpt-4o", api="responses", # Enable Responses API store=True, # Store responses for multi-turn (optional) auto_chain=True, # Auto-chain for reasoning models (optional))
Responses API Parameters:
api: Set to "responses" to use the Responses API (default: "completions")
instructions: System-level instructions (Responses API only)
store: Whether to store responses for multi-turn conversations
previous_response_id: ID of previous response for multi-turn
include: Additional data to include in response (e.g., ["reasoning.encrypted_content"])
builtin_tools: List of OpenAI built-in tools: "web_search", "file_search", "code_interpreter", "computer_use"
parse_tool_outputs: Return structured ResponsesAPIResult with parsed built-in tool outputs
auto_chain: Automatically track and use response IDs for multi-turn conversations
auto_chain_reasoning: Track encrypted reasoning items for ZDR (Zero Data Retention) compliance
Tip
Use the Responses API for new projects, especially when working with reasoning models (o1, o3, o4) or when you need native multimodal support for files.
Note: To use OpenAI, install the required dependencies:
uv add "crewai[openai]"
Meta's Llama API provides access to Meta's family of large language models.
The API is available through the Meta Llama API.
Set the following environment variables in your .env file:
# Meta Llama API Key ConfigurationLLAMA_API_KEY=LLM|your_api_key_here
Example usage in your CrewAI project:
from crewai import LLM# Initialize Meta Llama LLMllm = LLM( model="meta_llama/Llama-4-Scout-17B-16E-Instruct-FP8", temperature=0.8, stop=["END"], seed=42)
Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'
CrewAI provides native integration with the Snowflake Cortex REST API through its OpenAI-compatible Chat Completions endpoint. This avoids LiteLLM fallback for snowflake/... models. Snowflake Cortex currently supports Chat Completions only in CrewAI, so use the default api mode and do not set api="responses".
# RequiredSNOWFLAKE_PAT=<your-programmatic-access-token>SNOWFLAKE_ACCOUNT_URL=https://<account-identifier>.snowflakecomputing.com# Alternative account configurationSNOWFLAKE_ACCOUNT=<account-identifier>
Basic Usage:
from crewai import LLMllm = LLM( model="snowflake/openai-gpt-4.1", temperature=0.7, max_completion_tokens=1024,)
Claude Models on Cortex:
from crewai import LLMllm = LLM( model="snowflake/claude-sonnet-4-5", max_completion_tokens=1024, stream=True,)
Supported Environment Variables:
SNOWFLAKE_PAT, SNOWFLAKE_TOKEN, or SNOWFLAKE_JWT: token used as the Bearer credential
SNOWFLAKE_ACCOUNT_URL: full Snowflake account URL
SNOWFLAKE_ACCOUNT, SNOWFLAKE_ACCOUNT_ID, or SNOWFLAKE_ACCOUNT_IDENTIFIER: account identifier used to build the account URL
Snowflake REST requests use the user's default Snowflake role. Make sure that role has SNOWFLAKE.CORTEX_USER or SNOWFLAKE.CORTEX_REST_API_USER. Database, schema, warehouse, and explicit role parameters are not required by the Cortex REST Chat Completions endpoint.
Features:
Native provider selection with model="snowflake/<model-name>"
Streaming and non-streaming Chat Completions only; api="responses" is not supported
Token usage tracking
Function calling for Snowflake-hosted OpenAI and Claude models
Automatic removal of invalid trailing assistant prefill for Snowflake Claude models
CrewAI provides native integration with Anthropic through the Anthropic Python SDK.
# RequiredANTHROPIC_API_KEY=sk-ant-...
Basic Usage:
from crewai import LLMllm = LLM( model="anthropic/claude-sonnet-4-6", api_key="your-api-key", # Or set ANTHROPIC_API_KEY max_tokens=4096 # Required for Anthropic)
CrewAI supports Anthropic's Extended Thinking feature, which allows Claude to think through problems in a more human-like way before responding. This is particularly useful for complex reasoning, analysis, and problem-solving tasks.
type: Set to "enabled" to activate extended thinking mode
budget_tokens (optional): Maximum tokens to use for thinking (helps control costs)
Thinking modes and accepted parameters vary across Claude generations.
Check the selected model's capabilities before enabling thinking.
When to Use Extended Thinking:
Complex reasoning and multi-step problem solving
Mathematical calculations and proofs
Code analysis and debugging
Strategic planning and decision making
Research and analytical tasks
Note: Extended thinking consumes additional tokens but can significantly improve response quality for complex tasks.
Supported Environment Variables:
ANTHROPIC_API_KEY: Your Anthropic API key (required)
Features:
Native tool use support for Claude 3+ models
Extended Thinking support for compatible Claude models
Streaming support for real-time responses
Automatic system message handling
Stop sequences for controlled output
Token usage tracking
Multi-turn tool use conversations
Token usage and prompt caching:
Anthropic reports billed input in separate counters — input_tokens (uncached),
cache_read_input_tokens, and cache_creation_input_tokens. CrewAI folds all
three into prompt_tokens (and native input_tokens in provider responses) so
total_tokens reflects full billed usage on cached workloads.
cached_prompt_tokens records the cache-read portion as a breakdown only; it is
already included in prompt_tokens and must not be added again to
total_tokens. cache_creation_tokens records cache writes the same way.
usage = llm.get_token_usage_summary()# total_tokens == prompt_tokens + completion_tokens# prompt_tokens includes cache read + cache write for Anthropic
See the UsageMetrics field semantics section in the Flows concept
documentation for the provider-neutral contract used by crew.usage_metrics
and flow.usage_metrics.
Important Notes:
max_tokens is a required parameter for all Anthropic models
Claude uses stop_sequences instead of stop
System messages are handled separately from conversation messages
First message must be from the user (automatically handled)
Messages must alternate between user and assistant
Note: To use Anthropic, install the required dependencies:
uv add "crewai[anthropic]"
CrewAI provides native integration with Google Gemini through the Google Gen AI Python SDK.
Set your API key in your .env file. If you need a key, check AI Studio.
# Required (one of the following)GOOGLE_API_KEY=<your-api-key>GEMINI_API_KEY=<your-api-key># For Vertex AI Express mode (API key authentication)GOOGLE_GENAI_USE_VERTEXAI=trueGOOGLE_API_KEY=<your-api-key># For Vertex AI with service accountGOOGLE_CLOUD_PROJECT=<your-project-id>GOOGLE_CLOUD_LOCATION=<location> # Defaults to us-central1
Basic Usage:
from crewai import LLMllm = LLM( model="gemini/gemini-3.6-flash", api_key="your-api-key", # Or set GOOGLE_API_KEY/GEMINI_API_KEY)
Vertex AI Express mode allows you to use Vertex AI with simple API key authentication instead of service account credentials. This is the quickest way to get started with Vertex AI.
To enable Express mode, set both environment variables in your .env file:
GOOGLE_API_KEY or GEMINI_API_KEY: Your Google API key (required for Gemini API and Vertex AI Express mode)
GOOGLE_GENAI_USE_VERTEXAI: Set to true to use Vertex AI (required for Express mode)
GOOGLE_CLOUD_PROJECT: Google Cloud project ID (for Vertex AI with service account)
GOOGLE_CLOUD_LOCATION: GCP location (defaults to us-central1)
Features:
Native function calling support for compatible Gemini models
Streaming support for real-time responses
Multimodal capabilities (text, images, video)
Safety settings configuration
Support for both Gemini API and Vertex AI
Automatic system instruction handling
Token usage tracking
Google publishes current Gemini IDs, capabilities, and lifecycle stages in
the Gemini model catalog.
Check the deprecation schedule
before choosing a stable or preview model. The Gemini API also hosts
Gemma models.
Note: To use Google Gemini, install the required dependencies:
AZURE_ENDPOINT: Your Azure endpoint URL (required, also checks AZURE_OPENAI_ENDPOINT and AZURE_API_BASE)
AZURE_API_VERSION: API version (optional, defaults to 2024-06-01)
Features:
Native function calling support for Azure OpenAI models (gpt-4, gpt-4o, gpt-3.5-turbo, etc.)
Streaming support for real-time responses
Automatic endpoint URL validation and correction
Comprehensive error handling with retry logic
Token usage tracking
Note: To use Azure AI Inference, install the required dependencies:
uv add "crewai[azure-ai-inference]"
CrewAI provides native integration with AWS Bedrock through the boto3 SDK using the Converse API.
# RequiredAWS_ACCESS_KEY_ID=<your-access-key>AWS_SECRET_ACCESS_KEY=<your-secret-key># OptionalAWS_SESSION_TOKEN=<your-session-token> # For temporary credentialsAWS_DEFAULT_REGION=<your-region> # Defaults to us-east-1AWS_REGION_NAME=<your-region> # Alternative configuration for backwards compatibility with LiteLLM. Defaults to us-east-1
Basic Usage:
from crewai import LLMllm = LLM( model="bedrock/us.anthropic.claude-sonnet-4-6", region_name="us-east-1")
Advanced Configuration:
from crewai import LLMllm = LLM( model="bedrock/us.anthropic.claude-sonnet-4-6", aws_access_key_id="your-access-key", # Or set AWS_ACCESS_KEY_ID aws_secret_access_key="your-secret-key", # Or set AWS_SECRET_ACCESS_KEY aws_session_token="your-session-token", # For temporary credentials region_name="us-east-1", temperature=0.7, max_tokens=4096, top_p=0.9, top_k=250, # For Claude models stop_sequences=["END", "STOP"], stream=True, # Enable streaming guardrail_config={ # Optional content filtering "guardrailIdentifier": "your-guardrail-id", "guardrailVersion": "1" }, additional_model_request_fields={ # Model-specific parameters "top_k": 250 })
Supported Environment Variables:
AWS_ACCESS_KEY_ID: AWS access key (required)
AWS_SECRET_ACCESS_KEY: AWS secret key (required)
AWS_SESSION_TOKEN: AWS session token for temporary credentials (optional)
AWS_DEFAULT_REGION: AWS region (defaults to us-east-1)
AWS_REGION_NAME: AWS region (defaults to us-east-1). Alternative configuration for backwards compatibility with LiteLLM
Features:
Native tool calling support via Converse API
Streaming and non-streaming responses
Comprehensive error handling with retry logic
Guardrail configuration for content filtering
Model-specific parameters via additional_model_request_fields
Token usage tracking and stop reason logging
Support for all Bedrock foundation models
Automatic conversation format handling
Important Notes:
Uses the modern Converse API for unified model access
Automatic handling of model-specific conversation requirements
System messages are handled separately from conversation
First message must be from user (automatically handled)
Some models (like Cohere) require conversation to end with user message
Amazon Bedrock model access and IDs vary by region. Use AWS's
supported models and regions
reference to select a model and verify Converse API support.
Note: To use AWS Bedrock, install the required dependencies:
NVIDIA NIM's hosted catalog changes frequently. Use the
NVIDIA NIM model catalog to select a
current endpoint and verify its model ID, modalities, and context limits.
Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'
NVIDIA Nemotron models are designed for demanding agentic workloads, including complex reasoning, long-context analysis, tool use, multilingual tasks, and high-stakes RAG.
The NVIDIA-Nemotron-3-Ultra-550B-A55B-NVFP4 model is a frontier-scale open-weight model from NVIDIA with 550B total parameters and 55B active parameters. It uses a LatentMoE architecture that combines Mamba-2, MoE, Attention, and Multi-Token Prediction (MTP), and supports context lengths up to 1M tokens.
Info
NVIDIA-Nemotron-3-Ultra-550B-A55B-NVFP4 is a very large model. NVIDIA lists minimum serving requirements of 4x GB200, 4x B200, 4x GB300, 4x B300, or 8x H100 GPUs. For most CrewAI users, the recommended path is to use NVIDIA NIM or another OpenAI-compatible hosted endpoint rather than running it locally.
Hosted NVIDIA NIM usage:
NVIDIA_API_KEY=<your-api-key>
from crewai import LLMllm = LLM( model="nvidia_nim/nvidia/nvidia-nemotron-3-ultra-550b-a55b", temperature=0.2, max_tokens=4096,)
Reasoning mode: Nemotron 3 Ultra supports configurable reasoning via its chat template using enable_thinking=True or enable_thinking=False. If you are using a hosted endpoint, check your provider's documentation for how that flag is exposed.
Note: Hosted NVIDIA NIM usage uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'
NVIDIA NIM enables you to run powerful LLMs locally on your Windows machine using WSL2 (Windows Subsystem for Linux).
This approach allows you to leverage your NVIDIA GPU for private, secure, and cost-effective AI inference without relying on cloud services.
Perfect for development, testing, or production scenarios where data privacy or offline capabilities are required.
Here is a step-by-step guide to setting up a local NVIDIA NIM model:
Install the local model. For Llama 3.1-8b follow instructions
Configure your crewai local models:
from crewai.llm import LLMlocal_nvidia_nim_llm = LLM( model="openai/meta/llama-3.1-8b-instruct", # it's an openai-api compatible model base_url="http://localhost:8000/v1", api_key="<your_api_key|any text if you have not configured it>", # api_key is required, but you can use any text)# Then you can use it in your crew:@CrewBaseclass MyCrew(): # ... @agent def researcher(self) -> Agent: return Agent( config=self.agents_config['researcher'], # type: ignore[index] llm=local_nvidia_nim_llm ) # ...
Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'
Set the following environment variables in your .env file:
Groq distinguishes production and preview models and retires model IDs
regularly. Check the Groq model catalog
and deprecation page before
selecting a model for production.
Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'
Set the following environment variables in your .env file:
Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'
Set the following environment variables in your .env file:
NEBIUS_API_KEY=<your-api-key>
Example usage in your CrewAI project:
llm = LLM(
model="nebius/Qwen/Qwen3-30B-A3B"
)
Info
Nebius AI Studio features:
Large collection of open source models
Higher rate limits
Competitive pricing
Good balance of speed and quality
Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'
CrewAI talks to DeepInfra through its native OpenAI client, so no LiteLLM install is needed.
Set the following environment variables in your .env file:
# Required
DEEPINFRA_API_KEY=<your-api-key>
# Optional, point at a proxy or a private deployment endpoint
DEEPINFRA_BASE_URL=https://api.deepinfra.com/v1/openai
Open-weight models (Llama, Qwen, DeepSeek, GLM, Mistral and more) behind one OpenAI-compatible API
Tool calling, streaming and JSON schema structured outputs
Per-token pricing and context length published in the model catalog
Model ids are already in org/model form, so a full reference carries three segments,
for example deepinfra/meta-llama/Llama-4-Scout-17B-16E-Instruct. See the
model catalog curated for CrewAI,
which is public and needs no authentication, for current ids, context lengths and pricing.
Streaming Responses
CrewAI supports streaming responses from LLMs, allowing your application to receive and process outputs in real-time as they're generated.
Basic Setup
Event Handling
Agent & Task Tracking
Enable streaming by setting the stream parameter to True when initializing your LLM:
from crewai import LLM
# Create an LLM with streaming enabled
llm = LLM(
model="openai/gpt-5.6-terra",
stream=True # Enable streaming
)
When streaming is enabled, responses are delivered in chunks as they're generated, creating a more responsive user experience.
CrewAI emits events for each chunk received during streaming:
from crewai.events import (
LLMStreamChunkEvent
)
from crewai.events import BaseEventListener
class MyCustomListener(BaseEventListener):
def setup_listeners(self, crewai_event_bus):
@crewai_event_bus.on(LLMStreamChunkEvent)
def on_llm_stream_chunk(self, event: LLMStreamChunkEvent):
# Process each chunk as it arrives
print(f"Received chunk: {event.chunk}")
my_listener = MyCustomListener()
All LLM events in CrewAI include agent and task information, allowing you to track and filter LLM interactions by specific agents or tasks:
from crewai import LLM, Agent, Task, Crew
from crewai.events import LLMStreamChunkEvent
from crewai.events import BaseEventListener
class MyCustomListener(BaseEventListener):
def setup_listeners(self, crewai_event_bus):
@crewai_event_bus.on(LLMStreamChunkEvent)
def on_llm_stream_chunk(source, event):
if researcher.id == event.agent_id:
print("\n==============\n Got event:", event, "\n==============\n")
my_listener = MyCustomListener()
llm = LLM(model="openai/gpt-5.6-terra", stream=True)
researcher = Agent(
role="About User",
goal="You know everything about the user.",
backstory="""You are a master at understanding people and their preferences.""",
llm=llm,
)
search = Task(
description="Answer the following questions about the user: {question}",
expected_output="An answer to the question.",
agent=researcher,
)
crew = Crew(agents=[researcher], tasks=[search])
result = crew.kickoff(
inputs={"question": "..."}
)
Info
This feature is particularly useful for:
Debugging specific agent behaviors
Logging LLM usage by task type
Auditing which agents are making what types of LLM calls
Performance monitoring of specific tasks
Async LLM Calls
CrewAI supports asynchronous LLM calls for improved performance and concurrency in your AI workflows. Async calls allow you to run multiple LLM requests concurrently without blocking, making them ideal for high-throughput applications and parallel agent operations.
Basic Usage
With Streaming
Use the acall method for asynchronous LLM requests:
import asyncio
from crewai import LLM
async def main():
llm = LLM(model="openai/gpt-4o")
# Single async call
response = await llm.acall("What is the capital of France?")
print(response)
asyncio.run(main())
The acall method supports all the same parameters as the synchronous call method, including messages, tools, and callbacks.
Combine async calls with streaming for real-time concurrent responses:
import asyncio
from crewai import LLM
async def stream_async():
llm = LLM(model="openai/gpt-4o", stream=True)
response = await llm.acall("Write a short story about AI")
print(response)
asyncio.run(stream_async())
Structured LLM Calls
CrewAI supports structured responses from LLM calls by allowing you to define a response_format using a Pydantic model. This enables the framework to automatically parse and validate the output, making it easier to integrate the response into your application without manual post-processing.
Structured output support varies by provider and model. Test your chosen model before relying on structured responses in production.
For example, you can define a Pydantic model to represent the expected response structure and pass it as the response_format when instantiating the LLM. The model will then be used to convert the LLM output into a structured Python object.
from crewai import LLM
class Dog(BaseModel):
name: str
age: int
breed: str
llm = LLM(model="openai/gpt-5.6-terra", response_format=Dog)
response = llm.call(
"Analyze the following messages and return the name, age, and breed. "
"Meet Kona! She is 3 years old and is a black german shepherd."
)
print(response)
# Output:
# Dog(name='Kona', age=3, breed='black german shepherd')
Advanced Features and Optimization
Learn how to get the most out of your LLM configuration:
CrewAI includes smart context management features:
from crewai import LLM
# CrewAI automatically handles:
# 1. Token counting and tracking
# 2. Content summarization when needed
# 3. Task splitting for large contexts
llm = LLM(
model="openai/gpt-5.6-terra",
max_completion_tokens=4000, # Limit response length
)
Info
Best practices for context management:
Choose models with appropriate context windows
Pre-process long inputs when possible
Use chunking for large documents
Monitor token usage to optimize costs
Token Usage Optimization
Choose the right context window for your task:
Small tasks (up to 4K tokens): Standard models
Medium tasks (between 4K-32K): Enhanced models
Large tasks (over 32K): Large context models
# Configure model with appropriate settings
llm = LLM(
model="openai/gpt-5.6-terra",
reasoning_effort="medium",
max_completion_tokens=4096,
timeout=300
)
Tip
Use the controls supported by your selected model. Depending on the
provider, this may be temperature, a reasoning or thinking level,
or prompt instructions that define the desired style and variability.
Best Practices
Monitor token usage
Implement rate limiting
Use caching when possible
Set appropriate max_tokens limits
Info
Remember to regularly monitor your token usage and adjust your configuration as needed to optimize costs and performance.
CrewAI internally uses native sdks for LLM calls, which allows you to drop additional parameters that are not needed for your specific use case. This can help simplify your code and reduce the complexity of your LLM configuration.
For example, if you don't need to send the stop parameter, you can simply omit it from your LLM call:
from crewai import LLM
import os
os.environ["OPENAI_API_KEY"] = "<api-key>"
o3_llm = LLM(
model="o3",
drop_params=True,
additional_drop_params=["stop"]
)
CrewAI provides message interceptors for several providers, allowing you to hook into request/response cycles at the transport layer.
Supported Providers:
✅ OpenAI
✅ Anthropic
Basic Usage:
import httpx
from crewai import LLM
from crewai.llms.hooks import BaseInterceptor
class CustomInterceptor(BaseInterceptor[httpx.Request, httpx.Response]):
"""Custom interceptor to modify requests and responses."""
def on_outbound(self, request: httpx.Request) -> httpx.Request:
"""Print request before sending to the LLM provider."""
print(request)
return request
def on_inbound(self, response: httpx.Response) -> httpx.Response:
"""Process response after receiving from the LLM provider."""
print(f"Status: {response.status_code}")
print(f"Response time: {response.elapsed}")
return response
# Use the interceptor with an LLM
llm = LLM(
model="openai/gpt-4o",
interceptor=CustomInterceptor()
)
Important Notes:
Both methods must return the received object or type of object.
Modifying received objects may result in unexpected behavior or application crashes.
Not all providers support interceptors - check the supported providers list above
Info
Interceptors operate at the transport layer. This is particularly useful for:
Message transformation and filtering
Debugging API interactions
Common Issues and Solutions
Authentication
Model Names
Gateway Errors
Context Length
Warning
Most authentication issues can be resolved by checking API key format and environment variable names.
Gateways such as OpenRouter return 200 OK as soon as the upstream provider accepts the request, so a provider timeout arrives in the response body instead of the status code.
CrewAI raises the same exception the upstream code would have produced as a real HTTP status, so a masked failure is caught by the retry handling you already have:
import openai
from pydantic import BaseModel
from crewai import LLM
class Report(BaseModel):
summary: str
llm = LLM(model="openrouter/z-ai/glm-5.3", response_format=Report)
try:
result = llm.call("Summarize the incident", response_model=Report)
except openai.InternalServerError as e:
# "z-ai/glm-5.3 via openrouter.ai returned HTTP 200 with an upstream error
# and no choices: The operation was aborted (upstream code 504)"
print(f"Upstream provider failed, safe to retry: {e}")
Warning
A large or deeply nested response_model makes upstream timeouts more likely. Treat these as transient provider failures, not as the model producing malformed structured output.
Tip
Use larger context models for extensive tasks
# Large context model
llm = LLM(model="openai/gpt-4o") # 128K tokens