structured_output_retryTier 1 · 70% confidence
ai-agents-structured-output-re-when-using-structured-llm-in-llama-index-the-llm-r-1d255352
agent: ai_agents
When does this happen?
IF When using Structured LLM in llama_index, the LLM response may be a plain string instead of a Pydantic model, causing an AttributeError: 'str' object has no attribute 'model_dump_json'.
How others solved it
THEN Implement a retry mechanism that catches Pydantic validation errors during structured output parsing. After receiving the LLM response, attempt to parse it into the Pydantic model. If parsing fails, re-prompt the LLM with an error message asking for valid output. Limit retries to a maximum number (e.g., 3) and raise a custom exception if all fail. This approach mirrors the ReflectionWorkflow pattern used in llama_index examples.
from pydantic import BaseModel, ValidationError
async def structured_chat_with_retry(llm, messages, output_cls, max_retries=3):
for attempt in range(max_retries):
response = await llm.chat(messages)
try:
return output_cls.model_validate_json(response.message.content)
except ValidationError as e:
messages.append({"role": "user", "content": f"Invalid output: {e}. Please respond with valid JSON for {output_cls.model_json_schema()}."})
raise Exception("Failed to get valid structured output after retries")Related patterns
github
ai-agents-github-support-for-reasoning-in-openrouter-and-deepseek-p-48add6f0
Tier 1 · 40%
githubai-agents-github-server-capabilities-not-affecting-the-stream-of-ca-ca806d9e
Tier 1 · 40%
githubai-agents-github-patrick-von-platen-cd4d7ceb
Tier 1 · 40%
model_loadingai-agents-model-loading-loading-a-gemma-3-checkpoint-with-automodelforcaus-cc5b7a71
Tier 1 · 70%
githubai-agents-github-runtimeerror-cuda-error-cublas-status-not-initiali-9b601119
Tier 1 · 40%
githubai-agents-github-bug-frequent-ide-disconnections-disrupting-workflo-e9f35aca
Tier 1 · 40%
Have you seen this in your site?
Connect AgentMinds to match against your tech stack automatically.