Which LLM are you using? It’s working for me on every run (I’ve tested it with both Gemini and OpenAI):
from crewai import Agent, LLM
from pydantic import BaseModel, Field
from typing import Optional, List, Annotated
import asyncio
import os
os.environ["OPENAI_API_KEY"] = "<your-key>"
async def get_founders_names():
class FounderNames(BaseModel):
names: Optional[Annotated[
List[str],
Field(description="List of the full names of the company founders")
]] = None
llm = LLM(
model="gpt-4o",
temperature=0.5
)
researcher_agent = Agent(
role="Data Extraction Research Specialist",
goal=(
"Extract relevant information from sources and structure it into "
"clean, organized data formats"
),
backstory=(
"You are a detail-oriented researcher who specializes in finding "
"key information and organizing it into clear, structured outputs."
),
llm=llm,
allow_delegation=False,
verbose=True
)
query = (
"Extract the names of the founders of Dunder Mifflin company from the "
"text below:\n\n"
"Willy Wonka founded the Wonka Chocolate Factory. Dunder Mifflin (The "
"Office) was founded in 1949 by Robert Dunder and Robert Mifflin. Elon "
"Musk founded SpaceX in 2002."
)
result = await researcher_agent.kickoff_async(
query, response_format=FounderNames
)
print("\nresult:\n")
print(f"{result.pydantic=}")
print(f"{type(result.pydantic)=}\n")
async def main():
await get_founders_names()
if __name__ == "__main__":
asyncio.run(main())