Principle:AIScientists Dev WorldSeed Structured LLM Output
| Knowledge Sources | |
|---|---|
| Domains | LLM, API_Integration |
| Last Updated | 2026-10-26 18:00 GMT |
Overview
A provider pattern that wraps LiteLLM multi-provider LLM calls with Instructor's Pydantic-validated structured output, enabling reliable JSON-structured responses (DMJjudgments, GazetteContent) with automatic retry on validation failure and token/cost tracking.
Description
WorldSeed uses two external libraries for LLM integration:
- LiteLLM: A unified API client that supports 100+ LLM providers through a single `acompletion` interface. Model format is `"provider/model-name"`.
- Instructor: A library that wraps LLM calls with Pydantic model validation. It passes the Pydantic model as a `response_model`, parses the LLM output, validates it, and retries with error feedback on validation failure.
The `LiteLLMDMProvider` uses Instructor's `Mode.TOOLS` (function calling) for DM judgments, while the Gazette generator uses `Mode.JSON`. Both extract token usage from the raw response for cost tracking.
The `DMProvider` is defined as a `Protocol` class — any object with an async `judge()` method is a valid DM. This enables mock providers for testing and alternative implementations without changing the engine.
Usage
Use this principle when integrating LLM calls that require structured output. The DM provider and gazette generator both follow this pattern. The provider is lazy-initialized (the Instructor client is created on first use, not at construction).
Theoretical Basis
The structured output pattern wraps LLM calls with validation:
# Abstract pattern (NOT real implementation)
class LiteLLMDMProvider:
def _get_client(self):
if self._client is None:
import instructor, litellm
self._client = instructor.from_litellm(
litellm.acompletion, mode=instructor.Mode.TOOLS
)
return self._client
async def judge(self, context):
judgment = await client.chat.completions.create(
model=self._model,
response_model=DMJudgment, # Pydantic validation
messages=[system, user],
max_retries=self._max_retries,
)
return DMResponse(narrative=judgment.narrative,
effects=judgment.effects, ...)
The fallback model mechanism tries a secondary model if the primary fails, providing resilience against provider outages.
Related Pages
Implemented By
- Implementation:AIScientists_Dev_WorldSeed_LiteLLMDMProvider_judge
- Implementation:AIScientists_Dev_WorldSeed_generate_gazette