TypeError
pydantic.errors.PydanticTypeError
Stack trace
pydantic.errors.PydanticTypeError: value is not a valid dict (type=type_error.dict) During handling of the above exception, the agent run raised a TypeError: Expected dict but got str
Why it happens
Pydantic AI agents expect the LLM output to conform exactly to the defined Pydantic model schema. If the LLM returns a string, list, or malformed JSON instead of the expected dict structure, Pydantic raises a TypeError during validation. This often happens when the prompt or output parser does not enforce strict JSON or dict output formats.
Detection
Catch PydanticTypeError or TypeError exceptions around agent run calls and log the raw LLM output to detect type mismatches before the app crashes.
Causes & fixes
LLM returns a raw string or JSON string instead of a parsed dict object expected by Pydantic.
Use a JSON output parser that parses the LLM response into a dict before passing it to the Pydantic model.
The Pydantic model schema fields do not match the keys or structure of the LLM output.
Align the Pydantic model field names and types exactly with the expected LLM output structure.
The prompt or LLM does not enforce strict JSON output, causing malformed or unexpected formats.
Add explicit instructions in the prompt to return only valid JSON matching the schema, or use an instruction-tuned model.
Code: broken vs fixed
from pydantic_ai import PydanticAgent
agent = PydanticAgent(model='gpt-4o-mini', schema=MySchema)
result = agent.run('Tell me a joke') # Raises TypeError here import os
from pydantic_ai import PydanticAgent
from pydantic_ai.parsers import JsonOutputParser
os.environ['OPENAI_API_KEY'] = os.environ.get('OPENAI_API_KEY', '') # Use env var in real code
agent = PydanticAgent(model='gpt-4o-mini', schema=MySchema, output_parser=JsonOutputParser())
result = agent.run('Tell me a joke') # Fixed: output parsed to dict before validation
print(result) Workaround
Catch the TypeError, extract JSON substring from the raw LLM output using regex, then parse it manually with json.loads() before passing to the Pydantic model.
Prevention
Use structured output enforcement via output parsers or OpenAI's response_format to guarantee the LLM returns schema-valid dicts, avoiding type mismatches.