本页还没有译文
本页 221 段还没译成한국어,下面显示的是英文原文。LLMs
还没翻译译自英文(docs.crewai.com)本页 221 段都还没译
Overview
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 Variables2. YAML Configuration3. 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 configuration
llm = LLM(model="provider/model-id") # e.g. gemini/gemini-3.6-flash
# Advanced configuration with detailed parameters
llm = 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 responsemax_tokens: Limits response lengthresponse_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.
OpenAI
CrewAI provides native integration with OpenAI through the OpenAI Python SDK.
# Required
OPENAI_API_KEY=sk-...
# Optional
OPENAI_BASE_URL=<custom-base-url>Basic Usage:
from crewai import LLM
llm = 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 LLM
llm = 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 LLM
llm = 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 BaseModel
from crewai import LLM
class ResponseFormat(BaseModel):
name: str
age: int
summary: str
llm = 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 Completions
llm = 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 conversationsprevious_response_id: ID of previous response for multi-turninclude: 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 structuredResponsesAPIResultwith parsed built-in tool outputsauto_chain: Automatically track and use response IDs for multi-turn conversationsauto_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-Llama
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 Configuration
LLAMA_API_KEY=LLM|your_api_key_hereExample usage in your CrewAI project:
from crewai import LLM
# Initialize Meta Llama LLM
llm = LLM(
model="meta_llama/Llama-4-Scout-17B-16E-Instruct-FP8",
temperature=0.8,
stop=["END"],
seed=42
)See the Meta Llama model overview for current model families, modalities, and context guidance.
Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'Snowflake Cortex
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".
# Required
SNOWFLAKE_PAT=<your-programmatic-access-token>
SNOWFLAKE_ACCOUNT_URL=https://<account-identifier>.snowflakecomputing.com
# Alternative account configuration
SNOWFLAKE_ACCOUNT=<account-identifier>Basic Usage:
from crewai import LLM
llm = LLM(
model="snowflake/openai-gpt-4.1",
temperature=0.7,
max_completion_tokens=1024,
)Claude Models on Cortex:
from crewai import LLM
llm = LLM(
model="snowflake/claude-sonnet-4-5",
max_completion_tokens=1024,
stream=True,
)Supported Environment Variables:
SNOWFLAKE_PAT,SNOWFLAKE_TOKEN, orSNOWFLAKE_JWT: token used as the Bearer credentialSNOWFLAKE_ACCOUNT_URL: full Snowflake account URLSNOWFLAKE_ACCOUNT,SNOWFLAKE_ACCOUNT_ID, orSNOWFLAKE_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
Anthropic
CrewAI provides native integration with Anthropic through the Anthropic Python SDK.
# Required
ANTHROPIC_API_KEY=sk-ant-...Basic Usage:
from crewai import LLM
llm = LLM(
model="anthropic/claude-sonnet-4-6",
api_key="your-api-key", # Or set ANTHROPIC_API_KEY
max_tokens=4096 # Required for Anthropic
)Advanced Configuration:
from crewai import LLM
llm = LLM(
model="anthropic/claude-sonnet-4-6",
api_key="your-api-key",
base_url="https://api.anthropic.com", # Optional custom endpoint
max_tokens=4096, # Required parameter
stop_sequences=["END", "STOP"], # Anthropic uses stop_sequences
stream=True, # Enable streaming
timeout=60.0, # Request timeout in seconds
max_retries=3 # Maximum retry attempts
)Extended Thinking:
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.
from crewai import LLM
# Enable extended thinking with default settings
llm = LLM(
model="anthropic/claude-sonnet-4-6",
thinking={"type": "enabled"},
max_tokens=10000
)
# Configure thinking with budget control
llm = LLM(
model="anthropic/claude-sonnet-4-6",
thinking={
"type": "enabled",
"budget_tokens": 5000 # Limit thinking tokens
},
max_tokens=10000
)Thinking Configuration Options:
type: Set to"enabled"to activate extended thinking modebudget_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 AnthropicSee 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_tokensis a required parameter for all Anthropic models- Claude uses
stop_sequencesinstead ofstop - System messages are handled separately from conversation messages
- First message must be from the user (automatically handled)
- Messages must alternate between user and assistant
See Anthropic's models overview for current model IDs and capabilities, and review the model deprecation table before pinning a model in production.
Note: To use Anthropic, install the required dependencies:
uv add "crewai[anthropic]"Google (Gemini API)
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=true
GOOGLE_API_KEY=<your-api-key>
# For Vertex AI with service account
GOOGLE_CLOUD_PROJECT=<your-project-id>
GOOGLE_CLOUD_LOCATION=<location> # Defaults to us-central1Basic Usage:
from crewai import LLM
llm = LLM(
model="gemini/gemini-3.6-flash",
api_key="your-api-key", # Or set GOOGLE_API_KEY/GEMINI_API_KEY
)Advanced Configuration:
from crewai import LLM
llm = LLM(
model="gemini/gemini-3.6-flash",
api_key="your-api-key",
max_output_tokens=8192,
stop_sequences=["END", "STOP"],
stream=True, # Enable streaming
safety_settings={
"HARM_CATEGORY_HARASSMENT": "BLOCK_NONE",
"HARM_CATEGORY_HATE_SPEECH": "BLOCK_NONE"
}
)Vertex AI Express Mode (API Key Authentication):
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_GENAI_USE_VERTEXAI=true
GOOGLE_API_KEY=<your-api-key>Then use the LLM as usual:
from crewai import LLM
llm = LLM(
model="gemini/gemini-3.6-flash"
)Info
To get an Express mode API key:
- New Google Cloud users: Get an express mode API key
- Existing Google Cloud users: Get a Google Cloud API key bound to a service account
For more details, see the Vertex AI Express mode documentation.
Vertex AI Configuration (Service Account):
from crewai import LLM
llm = LLM(
model="gemini/gemini-3.6-flash",
project="your-gcp-project-id",
location="us-central1" # GCP region
)Supported Environment Variables:
GOOGLE_API_KEYorGEMINI_API_KEY: Your Google API key (required for Gemini API and Vertex AI Express mode)GOOGLE_GENAI_USE_VERTEXAI: Set totrueto 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 tous-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:
uv add "crewai[google-genai]"Google (Vertex AI)
Authenticate with Application Default Credentials, then configure the native Gemini provider for Vertex AI:
GOOGLE_GENAI_USE_VERTEXAI=true
GOOGLE_CLOUD_PROJECT=<your-project-id>
GOOGLE_CLOUD_LOCATION=<location>Example usage in your CrewAI project:
from crewai import LLM
llm = LLM(
model="gemini/gemini-3.6-flash"
)Vertex AI availability varies by region. Use the Vertex AI model catalog to verify the model ID and location before deployment.
Note: This route uses CrewAI's native Gemini integration. Add it as a dependency to your project:
uv add "crewai[google-genai]"Azure
CrewAI provides native integration with Azure AI Inference and Azure OpenAI through the Azure AI Inference Python SDK.
# Required
AZURE_API_KEY=<your-api-key>
AZURE_ENDPOINT=<your-endpoint-url>
# Optional
AZURE_API_VERSION=<api-version> # Defaults to 2024-06-01Endpoint URL Formats:
For Azure OpenAI deployments:
https://<resource-name>.openai.azure.com/openai/deployments/<deployment-name>
For Azure AI Inference endpoints:
https://<resource-name>.inference.azure.com
Basic Usage:
llm = LLM(
model="azure/gpt-4",
api_key="<your-api-key>", # Or set AZURE_API_KEY
endpoint="<your-endpoint-url>",
api_version="2024-06-01"
)Advanced Configuration:
llm = LLM(
model="azure/gpt-4o",
temperature=0.7,
max_tokens=4000,
top_p=0.9,
frequency_penalty=0.0,
presence_penalty=0.0,
stop=["END"],
stream=True,
timeout=60.0,
max_retries=3
)Supported Environment Variables:
AZURE_API_KEY: Your Azure API key (required)AZURE_ENDPOINT: Your Azure endpoint URL (required, also checksAZURE_OPENAI_ENDPOINTandAZURE_API_BASE)AZURE_API_VERSION: API version (optional, defaults to2024-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]"AWS Bedrock
CrewAI provides native integration with AWS Bedrock through the boto3 SDK using the Converse API.
# Required
AWS_ACCESS_KEY_ID=<your-access-key>
AWS_SECRET_ACCESS_KEY=<your-secret-key>
# Optional
AWS_SESSION_TOKEN=<your-session-token> # For temporary credentials
AWS_DEFAULT_REGION=<your-region> # Defaults to us-east-1
AWS_REGION_NAME=<your-region> # Alternative configuration for backwards compatibility with LiteLLM. Defaults to us-east-1Basic Usage:
from crewai import LLM
llm = LLM(
model="bedrock/us.anthropic.claude-sonnet-4-6",
region_name="us-east-1"
)Advanced Configuration:
from crewai import LLM
llm = 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 tous-east-1)AWS_REGION_NAME: AWS region (defaults tous-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:
uv add "crewai[bedrock]"Amazon SageMaker
AWS_ACCESS_KEY_ID=<your-access-key>
AWS_SECRET_ACCESS_KEY=<your-secret-key>
AWS_DEFAULT_REGION=<your-region>Example usage in your CrewAI project:
llm = LLM(
model="sagemaker/<my-endpoint>"
)Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'Mistral
Set the following environment variables in your .env file:
MISTRAL_API_KEY=<your-api-key>Example usage in your CrewAI project:
llm = LLM(
model="mistral/mistral-large-latest",
temperature=0.7
)Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'Nvidia NIM
Set the following environment variables in your .env file:
NVIDIA_API_KEY=<your-api-key>Example usage in your CrewAI project:
llm = LLM(
model="nvidia_nim/nvidia/nvidia-nemotron-3-ultra-550b-a55b",
temperature=0.7
)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
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 LLM
llm = LLM(
model="nvidia_nim/nvidia/nvidia-nemotron-3-ultra-550b-a55b",
temperature=0.2,
max_tokens=4096,
)Self-hosted OpenAI-compatible endpoint:
from crewai import LLM
llm = LLM(
model="openai/nvidia-nemotron-3-ultra-550b-a55b-nvfp4",
base_url="https://your-nemotron-endpoint.example.com/v1",
api_key="your-api-key",
temperature=0.2,
max_tokens=4096,
)Model details:
| Model | Context Window | Best For |
|---|---|---|
nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-NVFP4 | Up to 1M tokens | Frontier reasoning, complex agentic workflows, long-context analysis, tool use, multilingual reasoning, and high-stakes RAG |
Supported languages: English, French, Spanish, Italian, German, Japanese, Korean, Hindi, Brazilian Portuguese, and Chinese.
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.
For model details, license, and deployment guidance, see the NVIDIA Nemotron 3 Ultra model card.
Note: Hosted NVIDIA NIM usage uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'Local NVIDIA NIM Deployed using WSL2
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:
-
Follow installation instructions from NVIDIA Website
-
Install the local model. For Llama 3.1-8b follow instructions
-
Configure your crewai local models:
from crewai.llm import LLM
local_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:
@CrewBase
class 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]'Groq
Set the following environment variables in your .env file:
GROQ_API_KEY=<your-api-key>Example usage in your CrewAI project:
llm = LLM(
model="groq/qwen/qwen3.6-27b",
temperature=0.7
)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]'IBM watsonx.ai
Set the following environment variables in your .env file:
# Required
WATSONX_URL=<your-url>
WATSONX_APIKEY=<your-apikey>
WATSONX_PROJECT_ID=<your-project-id>
# Optional
WATSONX_TOKEN=<your-token>
WATSONX_DEPLOYMENT_SPACE_ID=<your-space-id>Example usage in your CrewAI project:
llm = LLM(
model="watsonx/meta-llama/llama-3-1-70b-instruct",
base_url="https://api.watsonx.ai/v1"
)Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'Ollama (Local LLMs)
- Install Ollama: ollama.ai
- Run a model:
ollama run llama3 - Configure:
llm = LLM(
model="ollama/llama3:70b",
base_url="http://localhost:11434"
)Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'Fireworks AI
Set the following environment variables in your .env file:
FIREWORKS_API_KEY=<your-api-key>Example usage in your CrewAI project:
llm = LLM(
model="fireworks_ai/accounts/fireworks/models/llama-v3-70b-instruct",
temperature=0.7
)Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'Perplexity AI
Set the following environment variables in your .env file:
PERPLEXITY_API_KEY=<your-api-key>Example usage in your CrewAI project:
llm = LLM(
model="perplexity/sonar-pro"
)See the Perplexity model catalog and changelog for current model IDs and deprecation notices.
Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'Hugging Face
Set the following environment variables in your .env file:
HF_TOKEN=<your-api-key>Example usage in your CrewAI project:
llm = LLM(
model="huggingface/meta-llama/Meta-Llama-3.1-8B-Instruct"
)Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'SambaNova
Set the following environment variables in your .env file:
SAMBANOVA_API_KEY=<your-api-key>Example usage in your CrewAI project:
llm = LLM(
model="sambanova/Meta-Llama-3.3-70B-Instruct",
temperature=0.7
)SambaNova Cloud's hosted models can change independently of CrewAI. Query the models endpoint and check the deprecation guide before deployment.
Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'Cerebras
Set the following environment variables in your .env file:
# Required
CEREBRAS_API_KEY=<your-api-key>Example usage in your CrewAI project:
llm = LLM(
model="cerebras/gpt-oss-120b",
temperature=0.7,
max_tokens=8192
)Info
Cerebras features:
- Fast inference speeds
- Competitive pricing
- Good balance of speed and quality
- Support for long context windows
See the Cerebras model catalog and deprecation notices for current public endpoint IDs.
Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'
Open Router
Set the following environment variables in your .env file:
OPENROUTER_API_KEY=<your-api-key>
Example usage in your CrewAI project:
llm = LLM(
model="openrouter/deepseek/deepseek-r1",
base_url="https://openrouter.ai/api/v1",
api_key=OPENROUTER_API_KEY
)
Info
Open Router models:
- openrouter/deepseek/deepseek-r1
- openrouter/deepseek/deepseek-chat
Note: This provider uses LiteLLM. Add it as a dependency to your project:
uv add 'crewai[litellm]'
Nebius AI Studio
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]'
DeepInfra
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
Example usage in your CrewAI project:
llm = LLM(
model="deepinfra/deepseek-ai/DeepSeek-V4-Flash-0731",
temperature=0.7
)
Info
DeepInfra features:
- 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 SetupEvent HandlingAgent & 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()
Tip
Click here for more details
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 UsageWith 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:
Context Window Management
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
Performance Optimization
-
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.
Drop Additional Parameters
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"]
)
Transport Interceptors
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
AuthenticationModel NamesGateway ErrorsContext Length
Warning
Most authentication issues can be resolved by checking API key format and environment variable names.
# OpenAI
OPENAI_API_KEY=sk-...
# Anthropic
ANTHROPIC_API_KEY=sk-ant-...
Check
Always include the provider prefix in model names
# Correct
llm = LLM(model="openai/gpt-4")
# Incorrect
llm = LLM(model="gpt-4")
Tip
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