Skip to content

Procedural Memory

Semantic cache of error-to-fix code patterns. When the agent makes a code error, similar past errors are retrieved from a SemanticCache backed by HyperBinder, and their fixes are surfaced as hints.

flowchart LR
    Fail["Code fails"] --> Record["record_failure()"]
    Record --> Lookup["Semantic lookup:<br/>similar past errors"]
    Lookup --> Hints["Reactive hints<br/>surfaced to LLM"]
    Hints --> Fix["Agent retries<br/>with fix"]
    Fix --> Success["record_success()"]
    Success --> Cache["Fix stored in<br/>SemanticCache"]
    Cache -.->|"next failure"| Lookup

How It Works

  1. Agent code fails in the sandbox -- record_failure(code, error) stores the pending failure and searches the cache for similar past errors
  2. If similar errors are found, their fixes are surfaced as reactive hints (WRONG/CORRECT code blocks)
  3. Agent retries with corrected code -- record_success(code, output) stores the error-to-fix pair in the semantic cache
  4. On future errors, semantic matching retrieves relevant fixes even if the error messages are not identical

Cross-session learning: patterns persist in HyperBinder and are available to all future sessions.

Usage

from hybi import HyperBinder
from hybi.semantic_cache import SemanticCache
from hybi.agent.procedural import ProceduralMemory

hb = HyperBinder(local=True)
cache = SemanticCache(hb, collection="procedural_patterns", threshold=0.55)
pm = ProceduralMemory(cache)

# Record a failure (called by post-hook on execute_code error)
pm.record_failure(
    code='print(drugs["mechanism"])',
    error="TypeError: string indices must be integers"
)

# Reactive hints are immediately available (if similar past errors exist)
for hint in pm.select_hints():
    print(f"Similar error: {hint.error_key}")
    print(f"  Fix: {hint.working_code}")

# Record the subsequent success (stores fix in cache)
pm.record_success(
    code='for row in await drugs.search("kinase"): print(row["mechanism"])',
    output="ALK inhibitor\nBRAF inhibitor\n..."
)

Session Integration

Procedural memory is enabled via a flag on AgentSession.create():

session = AgentSession.create(hb, procedural_memory=True)

This creates a SemanticCache internally, registers a post-hook on the tool registry that captures execute_code outcomes, and injects hints into the context via ContextRenderer.render_blocks().

Reactive Hints

When record_failure() is called, the cache is searched for similar past errors. Matches are stored as PatternHint objects:

Field Type Description
error_key str Normalized error string from the cached pattern
failing_code str Code that produced the original error
working_code str Code that fixed it
success_output str Truncated output from the fix
score float Similarity score (0-1) from cache lookup

select_hints(max_hints=5) returns the current reactive hints. render_hints() formats them as:

CODE HINTS (learned from prior errors -- use these patterns):

  ERROR: TypeError: string indices must be integers
  WRONG:
    print(drugs["mechanism"])
  CORRECT:
    for row in await drugs.search("kinase"): print(row["mechanism"])

Pitfall Rules

As patterns are captured during a session, error-class rules accumulate:

Error Pattern Rule
NameError: name 'x' not defined Variables do NOT persist between execute_code calls. Always re-query data you need.
globals()/locals()/eval() not available Use collection methods (.filter, .search, .key_values, .fields) instead.
Code rejected...import json, defaultdict, Counter, OrderedDict, and math are pre-loaded -- do not import.
KeyError Check field names with aggregate() to verify exact names before accessing.

render_pitfalls(max_rules=8) formats the session's accumulated rules.

Persistence

The semantic cache persists via HyperBinder -- patterns survive across sessions automatically. Session-local state (pitfall rules) is saved with the session:

# Session save/restore handles everything
session.save("session.json")
restored = AgentSession.restore(hb, "session.json")
# restored.procedural_memory has the same cache + restored rules

Schema Mapping

Internally, SemanticCache stores patterns as:

Cache Field Encoding Content
query SEMANTIC (weight 2.0) Normalized error message
context EXACT Fixed "procedural" context key
response SEMANTIC (weight 0.1) JSON: {failing_code, working_code, success_output}