feat: structured-output repair loop on validation failure
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Aptitud para principiantes
- 35/100
Línea de trabajo
Empieza con Chat.chat_structured() y chat_structured_async() en chatlas/_chat.py, y después compara el flujo de extracción y validación en chatlas/_parallel.py y la gestión del proveedor en chatlas/_provider_anthropic.py. Revisa las rutas existentes de _submit_turns y la representación de UserTurn antes de resolver las cuestiones abiertas sobre los valores predeterminados de los reintentos, la visibilidad del historial, los validadores y extract_data(). La implementación terminada debe cubrir de forma coherente los fallos de validación en todos los puntos de entrada de salida estructurada sin cambiar el tratamiento de la truncación.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Motivation
Pydantic AI's validation-retry loop (ModelRetry, described at https://ai.pydantic.dev/output/) is one of its most-cited primitives: when the model's output fails Pydantic validation (or a user-supplied validator raises ModelRetry), the validation error is fed back to the model as a correction message and it gets another shot, up to a configurable number of attempts. Chatlas has no equivalent. Chat.chat_structured() (chatlas/_chat.py) calls data_model.model_validate(dat) on whatever JSON came back from _submit_and_extract_data() — if that raises pydantic.ValidationError, it propagates straight to the caller with no chance for the model to self-correct. The same is true of parallel_chat_structured() in chatlas/_parallel.py, which does its own data_model.model_validate(dat) per conversation.
This is a distinct failure mode from truncation: chatlas just landed check_finish_reason() in chatlas/_turn.py (gh-315 / PR #344, merged to main as commit 9b5755a — not yet in this branch), which raises a clear ValueError before parsing when finish_reason is max_tokens/context_window/content_filter for a requested data model. That fix is about "nothing useful can be done with a partial response" and is out of scope here. This issue is about the case where the model did return complete, parseable JSON that simply doesn't satisfy the schema (wrong type, missing required field, a custom @field_validator rejecting a value) — a case a retry-with-feedback loop can often fix.
Proposed approach
import chatlas as ctl
from pydantic import BaseModel, field_validator
class Person(BaseModel):
name: str
age: int
@field_validator("age")
@classmethod
def must_be_reasonable(cls, v):
if not (0 < v < 130):
raise ValueError(f"age {v} is not plausible")
return v
chat = ctl.ChatOpenAI()
# On pydantic.ValidationError, chatlas appends the error as a user-turn
# correction (e.g. "Your last response didn't match the schema: <error>.
# Please try again.") and resubmits, up to `max_retries` times.
person = chat.chat_structured("Rin, age 900", data_model=Person, max_retries=2)
Candidate implementation: wrap the data_model.model_validate(dat) call in Chat.chat_structured()/.chat_structured_async() (and the Chat._extract_turn_json() + model_validate() pattern reused in parallel_chat_structured()/batch_chat_structured()) in a loop that catches pydantic.ValidationError, builds a corrective UserTurn from err.errors() (Pydantic's structured error list gives field paths + messages, which read well as feedback), and resubmits via the same _submit_turns/_submit_turns_async path already used internally. Consider a validator: Callable[[dict], None] | None escape hatch so users can raise on custom business-rule failures beyond what the Pydantic schema encodes, going through the same retry loop.
Provider interaction to check: for Anthropic, _provider_anthropic.py's structured_output_mode ("auto"/"native"/"tool") means native structured outputs (JSON-schema-constrained) rarely produce schema-invalid JSON, but the tool-based fallback (and any custom @field_validator) can still fail — the repair loop should apply uniformly regardless of structured_output_mode since validation happens after the provider-specific extraction, in chat_structured() itself.
Alternatives / prior art
- Pydantic AI:
ModelRetry/ output validators (https://ai.pydantic.dev/output/). - ellmer: no equivalent found —
chat_structured()/type_object()in ellmer raise directly on invalid output as well (checkedR/source and searchedtidyverse/ellmerissues for "retry"/"validation"/"structured output" prior art; nothing on point). This would be a chatlas-specific addition, not one aligning with existing ellmer behavior — worth flagging upstream if it proves valuable. - Related, but distinct: gh-315 / PR #344 (
check_finish_reason) handles truncated/incomplete responses, not schema-validity of complete responses.
Open questions
- Default
max_retries? Pydantic AI defaults to 1 retry; given cost concerns (see the sibling retry/fallback issue), a conservative default (1) with opt-out (max_retries=0) seems safest. - Should the correction be a new
UserTurn(visible inget_turns()/history) or an ephemeral resubmission that doesn't pollute the conversation record? ellmer's and Pydantic AI's approaches both keep it in-context since the model needs to see its own bad output to correct it. - Should this also apply to
extract_data()(deprecated but still present) or only the currentchat_structured()?
Drafted from a competitive review of llm / Pydantic AI / LangChain / LiteLLM (July 2026); filed via Claude Code on behalf of @cpsievert.
- Lenguaje dominante
- Python
- Estrellas
- 179
- Forks
- 32
- Merge medio
- 1 d 3 h
- PR fusionados (30 d)
- 10
Preparar el entorno
Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de posit-dev/chatlas
-
A streaming text delta that repeats everything streamed so far is missing from the recorded turnPosiblemente ocupada @cpsievert la tomó hace 81 días. Abiertoai-triage:done Priority: Medium
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
Los mantenedores suelen responder en 1 día
-
ai-triage:needs-review documentation
Dificultad 2/5 1-2 días Aptitud para principiantes 76/100
Los mantenedores suelen responder en 1 día
-
Dificultad 4/5 3-5 días Aptitud para principiantes 42/100
Los mantenedores suelen responder en 1 día
-
Dificultad 4/5 1-2 días Aptitud para principiantes 35/100
Los mantenedores suelen responder en 1 día
-
ai-triage:done Priority: Low
Dificultad 3/5 1-2 días Aptitud para principiantes 55/100
Los mantenedores suelen responder en 1 día
Todos los issues de posit-dev/chatlas
Issues similares
-
bot-triaged module: decompositions module: edge cases module: int overflow module: primTorch oncall: pt2 triage review
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
[TV SHOW]: Dynasty (1981)Abiertocountry:US rating:6 request-theme type:TV SHOW
Dificultad 1/5 Menos de una hora Aptitud para principiantes 65/100
LizardByte/ThemerrDB#10501 · 1 comentario ·
-
triage/confirmed
Dificultad 2/5 1-3 horas Aptitud para principiantes 77/100
agentscope-ai/agentscope#4563 ·
Los mantenedores suelen responder en 2 días
-
comp/desktop desktop/chat P3 type/bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 77/100
NousResearch/hermes-agent#164451 ·
Los mantenedores suelen responder en 1 día
-
external integration integration-submission
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
langchain-ai/docs#8426 ·
Los mantenedores suelen responder en 1 día