Implementation:24kchengYe MemoMind generate structured output
| Knowledge Sources | |
|---|---|
| Domains | LLM_Engineering, Structured_Prediction |
| Last Updated | 2026-10-28 00:00 GMT |
Overview
Concrete tool for extracting structured data conforming to a JSON Schema from a free-form LLM answer using a dynamic Pydantic model and a secondary LLM extraction call.
Description
The _generate_structured_output function takes a free-form answer text and a JSON Schema, builds a dynamic Pydantic model from the schema's properties, and makes a secondary LLM call to extract structured fields from the answer.
The process:
- Schema mapping: JSON Schema types are mapped to Python types (string->str, integer->int, number->float, boolean->bool, array->list, object->dict)
- Dynamic model creation: `pydantic.create_model("StructuredResponse", **fields)` builds a model with required fields marked with `...`
- Prompt construction: the answer text is included in the prompt along with field descriptions and the full JSON Schema
- LLM extraction call: the LLM is asked to "extract specific information from the answer and format it as JSON"
- Validation: required fields are checked for non-empty values
The companion _clean_answer_text and _clean_done_answer functions strip leaked tool-call syntax and JSON artifacts from the raw answer text before processing.
Usage
Import this function when you need to convert an LLM's free-form answer into structured data. It is called by run_reflect_agent when a response_schema is provided.
Code Reference
Source Location
- Repository: MemoMind
- File: engine/hindsight_api/engine/reflect/agent.py
- Lines: _clean_answer_text at L96-104; _clean_done_answer at L107-131; _generate_structured_output at L134-265
Signature
def _clean_answer_text(text: str) -> str:
...
def _clean_done_answer(text: str) -> str:
...
async def _generate_structured_output(
answer: str,
response_schema: dict,
llm_config: "LLMProvider",
reflect_id: str,
) -> tuple[dict[str, Any] | None, int, int]:
Import
from hindsight_api.engine.reflect.agent import _generate_structured_output, _clean_answer_text
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| answer | str | Yes | Raw answer text from the agent's done() tool call |
| response_schema | dict | Yes | JSON Schema for expected output structure |
| llm_config | LLMProvider | Yes | LLM provider for making the extraction call |
| reflect_id | str | Yes | Reflect ID for logging |
Outputs
| Name | Type | Description |
|---|---|---|
| structured_output | dict[str, Any] or None | Parsed structured data (None if generation fails) |
| input_tokens | int | Input tokens used by the extraction call |
| output_tokens | int | Output tokens used by the extraction call |
Usage Examples
Extracting Structured Output
import asyncio
from hindsight_api.engine.reflect.agent import _generate_structured_output
async def main():
response_schema = {
"type": "object",
"properties": {
"summary": {"type": "string", "description": "Brief summary of findings"},
"key_points": {"type": "array", "description": "Key points identified"},
"confidence": {"type": "number", "description": "Confidence score 0-1"},
},
"required": ["summary", "confidence"],
}
structured, input_tokens, output_tokens = await _generate_structured_output(
answer="The user's lessons show a pattern of...",
response_schema=response_schema,
llm_config=llm_config,
reflect_id="bank1-12345",
)
if structured:
print(f"Summary: {structured['summary']}")
print(f"Confidence: {structured['confidence']}")
asyncio.run(main())