The BadRequestError you're encountering usually stems from a misconfiguration or incompatibility between CrewAI, LangChain, and Ollama. Let's break down the most common causes and step-by-step fixes.
Error Analysis: BadRequestError
This error typically means:
- Ollama isn't properly serving the model (wrong endpoint, model not loaded).
- Incompatible model parameters (e.g.,
max_tokens too low, invalid temperature).
- LangChain-Ollama adapter misconfigured (e.g., missing
base_url, API mismatch).
- CrewAI defaults overriding your LLM settings.
Troubleshooting Checklist
Follow these steps in order. Test after each fix.
1. Verify Ollama Service & Model
Ensure:
- Ollama is running: Execute
ollama serve in a terminal (keep it open).
- Model is loaded: Run
ollama run llama3 (or your model) once to initialize it.
- Test the model directly:
curl http://localhost:11434/api/generate -d '{
"model": "llama3",
"prompt": "Hello, how are you?",
"max_tokens": 50
}'
Expected output: A JSON stream with text responses. If this fails:
- Reinstall Ollama.
- Check if another process blocks port
11434 (e.g., lsof -i :11434 on macOS/Linux).
2. Update LangChain-Ollama Integration
Ensure you're using compatible versions:
pip install --upgrade langchain-ollama crewai langchain
- Critical:
langchain-ollama>=0.1.0 is required for recent Ollama compatibility.
3. Explicitly Set base_url in OllamaLLM
Hardcode the Ollama endpoint (default is http://localhost:11434 but let's be explicit):
from langchain_ollama import OllamaLLM
llm = OllamaLLM(
model="llama3", # Your model name
base_url="http://127.0.0.1:11434", # Force IPv4 & exact port
temperature=0.7,
max_tokens=1024, # Increase if truncated responses occur
verbose=True
)
- Why this matters: Some systems resolve
localhost weirdly. 127.0.0.1 bypasses DNS issues.
4. Simplify Model Parameters (Remove max_tokens Initially)
BadRequestError often arises from invalid combinations. Try:
llm = OllamaLLM(
model="llama3",
base_url="http://127.0.0.1:11434",
temperature=0.7, # Keep this
# Remove max_tokens entirely (let Ollama default)
verbose=True
)
- Re-add
max_tokens=1024 later if responses are too long.
5. Validate Model Name (Case & Spelling)
Run ollama list in your terminal. Confirm the exact model name:
$ ollama list
NAME SIZE
llama3 4.7G
mistral 4.1G # If you use Mistral, ensure it's "mistral", not "Mistral"
- Update
model="llama3" to match exactly (lowercase, no spaces).
6. Disable Streaming (Workaround for LangChain Bug)
Some versions of LangChain-Ollama clash with streaming responses. Force non-streaming:
llm = OllamaLLM(
model="llama3",
base_url="http://127.0.0.1:11434",
temperature=0.7,
verbose=True,
streaming=False # Add this line
)
- Re-enable streaming later (
streaming=True) if performance improves.
7. Test a Different Model (Ruling Out Model-Specific Issues)
Switch to another Ollama model:
llm = OllamaLLM(
model="mistral", # Try "mistral" or "gemma2"
base_url="http://127.0.0.1:11434",
temperature=0.7,
verbose=True
)
Full Debugged Code
Here's the updated snippet with all fixes applied:
from crewai import Agent, Task, Crew
from langchain_ollama import OllamaLLM
# Step 1: Configure LLM with explicit endpoint & simplified params
llm = OllamaLLM(
model="llama3", # Confirm model name via `ollama list`
base_url="http://127.0.0.1:11434", # Force IP & port
temperature=0.7,
max_tokens=1024, # Optional (remove if errors persist)
streaming=False, # Workaround for streaming bugs
verbose=True
)
# Step 2: Define Agents (unchanged)
researcher = Agent(
role="Renewable Energy Researcher",
goal="Summarize top 3 renewable energy trends 2023–2024.",
backstory="Expert analyst with 10+ years in clean energy.",
llm=llm,
verbose=True
)
writer = Agent(
role="Tech Blog Writer",
goal="Write a 500-word blog post on renewable trends.",
backstory="Simplifies complex tech for general audiences.",
llm=llm,
verbose=True
)
# Step 3: Tasks (unchanged)
research_task = Task(
description="List top 3 renewable energy trends with data.",
expected_output="Bullet points: 3 trends, data, context.",
agent=researcher
)
write_task = Task(
description="Turn research into a blog post.",
expected_output="Markdown blog post: hook, trends, call-to-action.",
agent=writer,
context=[research_task]
)
# Step 4: Run Crew
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
verbose=2
)
print("Starting workflow...")
result = crew.kickoff()
print("\nFinal Output:")
print(result)
Last Resorts
- Reinstall Ollama: Fresh install often fixes service issues.
- Downgrade LangChain: Rarely, the latest
langchain-ollama breaks compatibility. Try:
pip install langchain-ollama==0.0.9
- Check System Logs: On macOS/Linux:
tail -f /var/log/system.log | grep ollama
Windows: Check Event Viewer for Ollama errors.
If all else fails, share:
- Your OS (Windows/Linux/macOS).
- Exact error stack trace (paste the full
BadRequestError text).
- Output of
ollama --version and pip show langchain-ollama.
Let's get this running!