AI SystemLLM System
LLM System
ClayDiary calls language models through PydanticAI, with OpenRouter as the provider. Each LLM task is a class that wraps one PydanticAI agent:
- Classifier: decides whether the question is about pottery.
- Router: decides whether the question is structured (counts, filters) or descriptive.
- SQL agent: writes and runs a read-only query.
- Generator: writes the answer and names the pieces it used.
PydanticAI provides four features that all four agents use:
- Structured output: the agent returns a Pydantic model instead of text to parse. PydanticAI implements it with tool calling, so the chat model must support tool calling. The model produces the fields in the order they are declared, so field order in the output model matters.
- Retries: when the model's output fails validation, PydanticAI sends the error back to the model and asks again, with no retry code of our own. The SQL agent uses it to fix invalid or failing queries, with up to two retries.
- Message history: each agent receives the earlier turns of the conversation as chat messages, separate from its system prompt, so follow-up questions can be understood. ClayDiary stores only the plain question and answer of each turn, not the retrieved pieces or SQL rows.
- Instrumentation: each agent has it enabled, so every run is logged to Langfuse under its own name.
Each agent class adds its own conventions:
- Lazy initialization: an agent is created on first use, so importing the code needs no credentials.
- Dynamic system prompt: the prompt is rendered per call from a versioned Jinja template, so a prompt version can change without touching code.
- Fixed settings: all agents use the same chat model, set by the
chat_modelvalue in the backend configuration, so it can be changed without touching agent code. The classifier, router and SQL agent run at temperature 0 for repeatable decisions.