Implementation:24kchengYe MemoMind run reflect agent
| Knowledge Sources | |
|---|---|
| Domains | LLM_Engineering, Agentic_Systems |
| Last Updated | 2026-10-28 00:00 GMT |
Overview
Concrete tool for executing the reflect agent's agentic tool-calling loop with hierarchical retrieval (mental models, observations, raw facts), anti-hallucination ID validation, and structured output generation.
Description
The run_reflect_agent function implements the core agentic loop of the reflect pipeline. It:
- Builds the system prompt using build_system_prompt_for_tools (with directives, retrieval strategy)
- Initializes tools from get_reflect_tools (search_mental_models, search_observations, recall, expand, done)
- Iterates: at each iteration, calls the LLM with current messages and tools; if the LLM calls a tool, dispatches it and appends the result; if the LLM calls done(), extracts the answer
- Validates IDs: tracks which memory/observation/mental_model IDs were returned by tools, and validates that any IDs cited in the answer were actually retrieved (anti-hallucination)
- Handles overflow: detects context window overflow errors and triggers a final prompt fallback
- Forces response: if max_iterations is reached, generates a final response from the context history
The agent uses hierarchical retrieval: mental models (user-curated, try first) -> observations (consolidated, second) -> raw facts (ground truth, fallback). The loop terminates when done() is called or max_iterations is reached.
Usage
Import this function when you need to run deep reasoning over memories with an agentic LLM loop. It is called by MemoryEngine.reflect_async as the core of the reflect pipeline.
Code Reference
Source Location
- Repository: MemoMind
- File: engine/hindsight_api/engine/reflect/agent.py
- Lines: L304-895 (tool implementations at reflect/tools.py:L24-388)
Signature
async def run_reflect_agent(
llm_config: "LLMProvider",
bank_id: str,
query: str,
bank_profile: dict[str, Any],
search_mental_models_fn: Callable[[str, int], Awaitable[dict[str, Any]]],
search_observations_fn: Callable[[str, int], Awaitable[dict[str, Any]]],
recall_fn: Callable[[str, int, int], Awaitable[dict[str, Any]]],
expand_fn: Callable[[list[str], str], Awaitable[dict[str, Any]]],
context: str | None = None,
max_iterations: int = DEFAULT_MAX_ITERATIONS,
max_tokens: int | None = None,
response_schema: dict | None = None,
directives: list[dict[str, Any]] | None = None,
has_mental_models: bool = False,
budget: str | None = None,
max_context_tokens: int = 100_000,
) -> ReflectAgentResult:
Import
from hindsight_api.engine.reflect.agent import run_reflect_agent
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| llm_config | LLMProvider | Yes | LLM provider for agent calls |
| bank_id | str | Yes | Bank identifier |
| query | str | Yes | Question to answer |
| bank_profile | dict[str, Any] | Yes | Bank profile with name and mission |
| search_mental_models_fn | Callable | Yes | Callback for searching mental models (query, max_results) -> result |
| search_observations_fn | Callable | Yes | Callback for searching observations (query, max_results) -> result |
| recall_fn | Callable | Yes | Callback for recall (query, max_tokens) -> result |
| expand_fn | Callable | Yes | Callback for expand (memory_ids, depth) -> result |
| max_iterations | int | No | Maximum iterations before forcing response |
| response_schema | dict | No | JSON Schema for structured output |
| directives | list[dict] | No | Directive mental models to inject |
| has_mental_models | bool | No | Whether bank has mental models (default False) |
| budget | str | No | Search depth budget ("low", "mid", "high") |
Outputs
| Name | Type | Description |
|---|---|---|
| result | ReflectAgentResult | Final answer text, structured output, iteration count, tool/LLM traces, token usage, validated IDs |
Usage Examples
Running a Reflect Agent
import asyncio
from hindsight_api.engine.reflect.agent import run_reflect_agent
async def main():
result = await run_reflect_agent(
llm_config=llm_config,
bank_id="default",
query="What patterns do I see in my student lessons?",
bank_profile={"name": "Memo", "mission": "Track teaching activities"},
search_mental_models_fn=memory_engine.search_mental_models,
search_observations_fn=memory_engine.search_observations,
recall_fn=memory_engine.recall_async,
expand_fn=memory_engine.expand,
has_mental_models=True,
budget="high",
max_iterations=10,
)
print(f"Answer: {result.text}")
print(f"Iterations: {result.iterations}, Tools called: {result.tools_called}")
print(f"Token usage: {result.usage.total_tokens}")
asyncio.run(main())