Skip to content

TypeError: Object of type ValueError is not JSON serializable #671

@HampB

Description

@HampB

Description

Sorry if this is already reported or if there is a solution im missing.

I've encountered a sporadic issue while using a Pydantic model with a custom validator (but i guess that does not have to be related). About 2% of the runs result in the following error:

Exception: TypeError: Object of type ValueError is not JSON serializable

I haven’t yet found a reliable way to reproduce the issue, below is a mocked-up code snippet and a stack trace to demonstrate the scenario.


Code Example

from typing import Any
import pydantic_ai
from pydantic import BaseModel, model_validator

VALID_TYPES = {"test": ["testing"]}

class TypeModel(BaseModel):
    type: str

    @model_validator(mode="before")
    def validate_type(cls, values: dict[str, Any]):
        type_ = values.get("type")
        if type_ not in VALID_TYPES:
            raise ValueError(
                f"Invalid type '{type_}'. Valid types are: {list(VALID_TYPES.keys())}."
            )
        return values

agent = pydantic_ai.Agent(model="openai:gpt-4o", result_type=TypeModel)
agent.run_sync("toast")

Stack Trace

    response = self.agent.run_sync(prompt)
  File "/home/site/wwwroot/.python_packages/lib/site-packages/pydantic_ai/agent.py", line 220, in run_sync
    return asyncio.run(self.run(user_prompt, message_history=message_history, model=model, deps=deps))
  File "/usr/local/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/local/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
    return future.result()
  File "/home/site/wwwroot/.python_packages/lib/site-packages/pydantic_ai/agent.py", line 172, in run
    model_response, request_cost = await agent_model.request(messages)
  File "/home/site/wwwroot/.python_packages/lib/site-packages/pydantic_ai/models/openai.py", line 125, in request
    response = await self._completions_create(messages, False)
  File "/home/site/wwwroot/.python_packages/lib/site-packages/pydantic_ai/models/openai.py", line 155, in _completions_create
    openai_messages = [self._map_message(m) for m in messages]
  File "/home/site/wwwroot/.python_packages/lib/site-packages/pydantic_ai/models/openai.py", line 155, in <listcomp>
    openai_messages = [self._map_message(m) for m in messages]
  File "/home/site/wwwroot/.python_packages/lib/site-packages/pydantic_ai/models/openai.py", line 236, in _map_message
    content=message.model_response(),
  File "/home/site/wwwroot/.python_packages/lib/site-packages/pydantic_ai/messages.py", line 121, in model_response
    description = f'{len(self.content)} validation errors: {json.dumps(self.content, indent=2)}'
  File "/usr/local/lib/python3.10/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/usr/local/lib/python3.10/json/encoder.py", line 201, in encode
    chunks = list(chunks)
  File "/usr/local/lib/python3.10/json/encoder.py", line 429, in _iterencode
    yield from _iterencode_list(o, _current_indent_level)
  File "/usr/local/lib/python3.10/json/encoder.py", line 325, in _iterencode_list
    yield from chunks
  File "/usr/local/lib/python3.10/json/encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "/usr/local/lib/python3.10/json/encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "/usr/local/lib/python3.10/json/encoder.py", line 438, in _iterencode
    o = _default(o)
  File "/usr/local/lib/python3.10/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions