Multi Step JSON With Memory#
Source: examples/agents/multi_step_json_with_memory.py
Introduction#
Reflexion, Generative Agents, and MemGPT each emphasize that iterative performance improves when prior state is persisted and reused rather than recomputed from scratch. This example adds memory reads/writes to JSON tool-calling so multi-step behavior remains auditable across turns.
Note
This example’s checked-in local LlamaCppServerLLMClient config uses a
Qwen3-4B GGUF model. On lower-RAM machines, swap in a smaller local
model or start with Ollama Local Client.
Technical Implementation#
Configure
Tracerwith JSONL + console output so each run emits machine-readable traces and lifecycle logs.Build the runtime surface (public APIs only) and execute
MultiStepAgent.run(...)with a fixedrequest_id.Configure and invoke
Toolboxintegrations (core/script/MCP/callable) before assembling the final payload.Persist and query context via
SQLiteMemoryStoreto demonstrate memory-backed workflow behavior.Print a compact JSON payload including
trace_infofor deterministic tests and docs examples.
flowchart LR
A["Input prompt or scenario"] --> B["main(): runtime wiring"]
B --> C["MultiStepAgent.run(...)"]
C --> D["WorkflowRuntime loop enforces explicit final-answer and max-step policy"]
C --> E["Tracer JSONL + console events"]
D --> F["ExecutionResult/payload"]
E --> F
F --> G["Printed JSON output"]
1from __future__ import annotations
2
3import json
4from pathlib import Path
5
6import design_research_agents as drag
7from design_research_agents.memory import SQLiteMemoryStore
8
9# This checked-in local config uses a Qwen3-4B GGUF model to exercise a richer
10# multi-step path. On lower-RAM machines, swap in a smaller local model or
11# start with the lighter Ollama local client example first.
12_EXAMPLE_LLAMA_CLIENT_KWARGS = {
13 "model": "Qwen_Qwen3-4B-Instruct-2507-Q4_K_M.gguf",
14 "hf_model_repo_id": "bartowski/Qwen_Qwen3-4B-Instruct-2507-GGUF",
15 "api_model": "qwen3-4b-instruct-2507-q4km",
16 "context_window": 8192,
17 "startup_timeout_seconds": 240.0,
18 "request_timeout_seconds": 240.0,
19}
20
21
22def main() -> None:
23 """Run one multi-step JSON tool call with memory retrieval and write-back."""
24 # Keep the request id stable so trace filenames and test snapshots stay comparable.
25 request_id = "example-multi-step-json-memory-design-001"
26 tracer = drag.Tracer(
27 enabled=True,
28 trace_dir=Path("artifacts/examples/traces"),
29 enable_jsonl=True,
30 enable_console=True,
31 )
32 db_path = Path("artifacts/examples/multi_step_json_with_memory.sqlite3")
33 db_path.parent.mkdir(parents=True, exist_ok=True)
34 # Recreate the DB per run to keep the example deterministic across repeated executions.
35 if db_path.exists():
36 db_path.unlink()
37
38 # Run the memory-backed JSON example using public runtime surfaces. Using this with statement will
39 # automatically close the tool runtime, memory store, and managed client when the example is done.
40 with (
41 drag.Toolbox() as tool_runtime,
42 SQLiteMemoryStore(db_path=db_path) as store,
43 drag.LlamaCppServerLLMClient(**_EXAMPLE_LLAMA_CLIENT_KWARGS) as llm_client,
44 ):
45 # Seed one memory item so the agent can demonstrate retrieval-conditioned behavior.
46 tool_runtime.invoke_dict(
47 "memory.write",
48 {
49 "db_path": str(db_path),
50 "namespace": "design_examples",
51 "records": [
52 {
53 "content": (
54 "Prior design note: target quick maintenance by minimizing tool changes and "
55 "favoring reusable fasteners."
56 )
57 }
58 ],
59 },
60 request_id=f"{request_id}:seed_memory",
61 dependencies={},
62 )
63 memory_agent = drag.MultiStepAgent(
64 mode="json",
65 llm_client=llm_client,
66 tool_runtime=tool_runtime,
67 max_steps=3,
68 memory_store=store,
69 memory_namespace="design_examples",
70 memory_read_top_k=1,
71 memory_write_observations=False,
72 allowed_tools=("text.word_count",),
73 tracer=tracer,
74 )
75 result = memory_agent.run(
76 (
77 "Use the retrieved design note as your input, count its words with text.word_count, "
78 "then return only the resulting word_count."
79 ),
80 request_id=request_id,
81 )
82 # Print the results
83 summary = result.summary()
84 print(json.dumps(summary, ensure_ascii=True, indent=2, sort_keys=True))
85
86
87if __name__ == "__main__":
88 main()
Expected Results#
Run Command
PYTHONPATH=src python3 examples/agents/multi_step_json_with_memory.py
Example output shape (values vary by run):
{
"success": true,
"final_output": "<example-specific payload>",
"terminated_reason": "<string-or-null>",
"error": null,
"trace": {
"request_id": "<request-id>",
"trace_dir": "artifacts/examples/traces",
"trace_path": "artifacts/examples/traces/run_<timestamp>_<request_id>.jsonl"
}
}