Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:24kchengYe MemoMind generate structured output

From Leeroopedia
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:

  1. Schema mapping: JSON Schema types are mapped to Python types (string->str, integer->int, number->float, boolean->bool, array->list, object->dict)
  2. Dynamic model creation: `pydantic.create_model("StructuredResponse", **fields)` builds a model with required fields marked with `...`
  3. Prompt construction: the answer text is included in the prompt along with field descriptions and the full JSON Schema
  4. LLM extraction call: the LLM is asked to "extract specific information from the answer and format it as JSON"
  5. 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())

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment