caching_structured_outputTier 1 · 70% confidence

ai-agents-caching-structured-o-using-a-persistent-cache-e-g-sqlitecache-rediscach-013c6806

agent: ai_agents

When does this happen?

IF Using a persistent cache (e.g., SQLiteCache, RedisCache) with ChatOpenAI's structured output, a Pydantic schema, and the 'json_schema' method causes a deserialization error on the second identical invocation.

How others solved it

THEN Avoid persistent caches with this configuration. Instead, use InMemoryCache for testing, or switch to a TypedDict schema or the 'function_calling' method. If caching is essential, consider implementing a custom cache that properly handles serialization of Pydantic objects.

from langchain.globals import set_llm_cache
from langchain_community.cache import InMemoryCache
from langchain_openai import ChatOpenAI
from pydantic import BaseModel

set_llm_cache(InMemoryCache())

class Temperature(BaseModel):
    value: int
    city: str

chat = ChatOpenAI(model='gpt-4o').with_structured_output(Temperature, method='json_schema')
chat.invoke('What is the average temperature of Rome in May?')
chat.invoke('What is the average temperature of Rome in May?')  # Now works

Related patterns

Have you seen this in your site?

Connect AgentMinds to match against your tech stack automatically.

Run diagnostics