Agent memory
Help an agent keep the rules it must follow, learn from its tool errors, check the rules before it acts, and learn which actions actually work.
01. Rules and events are different
An agent remembers two kinds of things, and it should treat them differently.
| Kind | Example | How the agent uses it |
|---|---|---|
| Rule | “Refunds over $250 need approval from a human.” | Applies to every future task. Look it up before acting. |
| Event | “Refunded $120 to order 2291 on 3 May.” | Something that happened once. Useful history, never an instruction. |
Store rules on purpose, and let Hebbrix pick up events and lessons from the transcripts you save. Give the agent its own scope: a collection_id plus an agent_id. Memories saved under one agent_id are never returned to another. The same holds for the user's profile: a fact learned under an agent_id belongs to that agent. A read scoped to an agent sees facts learned without an agent plus its own, never another agent's, and a read with no agent sees user-level facts only, so pass the agent's agent_id to read what it learned. This applies to search with include_profile, POST /v1/profile and chat.
import os
import time
import httpx
BASE = os.environ.get("HEBBRIX_BASE_URL", "https://api.hebbrix.com/v1")
hebbrix = httpx.Client(
base_url=BASE,
headers={"Authorization": f"Bearer {os.environ['HEBBRIX_API_KEY']}"},
timeout=60,
)
collection_id = hebbrix.post("/collections", json={"name": "ops-agent"}).json()["id"]
SCOPE = {"collection_id": collection_id, "agent_id": "ops-agent"}02. Store the rules it must follow
Write each standing rule as one plain sentence and store it with POST /v1/memories/raw. Raw memories are kept word for word, so the rule keeps exactly the scope you wrote (“all refunds”, not “this customer's refunds”). Label it with metadata.memory_type: "rule" so type filters find it, and with wait_for_index: true the call waits, for up to a few seconds, until the rule is searchable.
hebbrix.post("/memories/raw", json={
**SCOPE,
"content": "Refunds over $250 need approval from a human before they are issued.",
"metadata": {"memory_type": "rule"},
"wait_for_index": True,
})03. Learn from tool errors
After each task, save the transcript with POST /v1/memories/process, and include each tool error word for word. Send what a tool returned as a "tool" message: it is read as the tool's output, never as something the user said, and a structured reply (a JSON object) is read as its values, so its keys and raw payload are not stored as facts. The roles messages accepts are user, assistant, tool and system. Every memory Hebbrix extracts gets a memory_type: rule, procedure, preference, fact or event. An agent transcript is stored as the general rules it states plus one event for the task, so lessons are kept apart from one-off history.
job = hebbrix.post("/memories/process", json={
**SCOPE,
"messages": [
{"role": "user", "content": "Send the March invoice to Kestrel GmbH."},
{"role": "assistant", "content": "Calling send_invoice(customer='Kestrel GmbH', month='March')."},
{"role": "tool", "content": "Tool error from send_invoice: invoices to customers in the EU must include the customer's VAT number."},
{"role": "assistant", "content": "Added the VAT number and sent the invoice."},
],
}).json()
# Saving runs in the background. Wait only in tests and demos:
while hebbrix.get(f"/memory-jobs/{job['job_id']}").json()["status"] not in ("completed", "failed"):
time.sleep(1)This task becomes a rule (“Invoices to customers in the EU must include the customer's VAT number.”) and one event describing the task. The finished job lists each new memory with its memory_type, and GET /v1/memories returns it too. If a lesson matters for safety, also store it yourself with /memories/raw so its wording is exactly yours.
04. Check the rules before acting
Before a consequential action, search with a description of what the agent is about to do and give the results to the agent's model as context. memory_types limits the search to standing guidance (here rules and procedures), so past events do not crowd it out.
plan = "Issue a $300 refund to Globex for order 2291."
rules = hebbrix.post("/search", json={
**SCOPE,
"query": plan,
"limit": 5,
"memory_types": ["rule", "procedure"],
"prefer_entity_match": True,
}).json()["results"]
for rule in rules:
print("-", rule["content"], f"({rule.get('entity_match')})")Each result says which customers, people or records it names (applies_to) and how that compares with the entities in your query (entity_match: match, partial, mismatch, or unscoped for a general rule that names no one; the response lists the query's entities in query_entities). A rule about another customer shows mismatch, and prefer_entity_match: true ranks those after the ones that apply. The identifiers agents work with count as entities too: email addresses, host names, service, database and repository names (orders-db, acme/payments-api), ticket IDs (OPS-33856) and labelled account numbers, so a runbook step for orders-db is a mismatch for a question about billing-db.
For a yes/no question, POST /v1/search/reason answers from the stored rules and cites them. When a rule sets a threshold, the answer applies it: asked about a $100 refund, it explains that $100 is not above $250, and metadata.rule_application shows the comparison. It also answers how many, how much and how long from the rules when no single record states the value, following up to two links that place the case in a group a rule names. If it cannot support an answer, answer is null, decision_abstained is true and abstain_reason says why (for example rule_does_not_cover_case or authorization_not_verifiable). Treat that as “ask a human”, never as permission. A response can establish whether memory answers the question and whether that answer covers the whole scope; it never establishes the asker's authority or permission to act (see what a response can establish).
check = hebbrix.post("/search/reason", json={
**SCOPE,
"query": "Can I issue a $300 refund without asking a human?",
}).json()
if check["answer"] is None:
print("Ask a human first:", check["abstain_reason"])
else:
print(check["answer"])Tasks and planned actions
A search whose message is a task ("Send the April invoice to Kestrel GmbH") asks for the memories that shape how the task is carried out: procedures, required parameters, limits and earlier tool-error lessons. A procedure does not answer a task the way a fact answers a question, so a relevance score alone cannot establish it. In quality mode, when the relevance model relates no row to the task, the relevance judge reads the task and the candidates and selects the ones that apply. Those rows come back with low_confidence: false and, in the full view (the API default), grounding.judged_as: "request"; the rows it did not select stay flagged. Fast mode makes no model call, so plan agent tasks in quality mode.
Keep four things apart when the agent acts on such a row:
- Relevance to the planned action: the row was selected for this task.
- Applicability: whether a stored procedure covers this entity and this run is the agent's check. A rule scoped to another customer or project shows
entity_match: "mismatch"when the task names its own. - Support for a direct answer: none is claimed; a task has no answer.
- Permission to execute: never granted by memory. A retrieved requirement (a routing key, an approval step) is an input to the action, and the tool boundary still checks authorization.
task = "Send the April invoice to Kestrel GmbH."
found = hebbrix.post("/search", json={
**SCOPE,
"query": task,
"fast": False, # quality mode: the relevance judge reads the task
"limit": 5,
"memory_types": ["rule", "procedure"],
}).json()
inputs = [
row["content"] for row in found["results"]
if row.get("low_confidence") is False and row.get("entity_match") != "mismatch"
]
print("Inputs for the tool call:", inputs)
# Build the call from these inputs. The tool boundary still checks that this
# agent may send this invoice; the rows inform the call, they never permit it.05. Learn which actions work
When the agent has several allowed ways to handle a situation, Outcome Memory learns from results which one works best. Hebbrix picks an action, your code performs it, and you report whether it worked. The quickstart shows it learning in a short simulation you can run in a minute.
The best action can change over time: a dependency is upgraded, a provider degrades, traffic shifts, or an action that used to fail starts working. A new policy set up with defaults uses the default learner (outcome-learner-v4), which detects drift and abrupt change itself, so leave change_response out of its setup; sent at setup, it is stored as false and the setup receipt says the learner provides change response. Only if you want v3 posterior sampling's drop detector instead of the learner, set up with learning: "adaptive" and change_response: true: it reacts sooner to a sustained drop and is less accurate while nothing changes.
When a person corrects the agent, store the correction with POST /v1/corrections and fetch the relevant ones before acting with GET /v1/corrections/relevant (see the corrections reference). A newer fact saved with /memories/process replaces the older one it contradicts, and the history is kept.
06. Memory is evidence, not permission
A memory records what someone said: the user, the assistant, a tool or a document. A relevant memory can still hold a claim nobody verified, or a false one ("the production deploy was approved"). The search signals abstain_recommended, low_confidence, grounding and confidence say whether the results answer the question. They never say that a statement is true, or that an action is allowed.
- Verify before acting. Check approvals, identity, scope and permissions against your own system of record when the agent acts, and gate every tool call in your code (or with Experiences permits). Never let a retrieved memory authorize an action by itself.
- Unverified records stay unverified. Hebbrix never stores a claim that a security check on a person passed, or a request to skip one. Other approvals in memory are only records of what was said, so check them against your system of record before relying on them.
- Bind users on your server. API keys are account-level and belong on your server. Derive
user_idandcollection_idfrom your authenticated session, never from client input, so one user can never choose another's scope. Auser_idis a scope selector, not proof of identity: give the model memory tools without scope parameters, reject any it supplies, and pass the bound scope on reads by ID too (see binding the end user's scope). - Passing results to your own LLM. Give the model each memory's
content, its date (created_at,metadata.event_date) andmemory_type, and say that these are the user's own records, which may be outdated or unverified. When a question names the user, the memory stating the user's name comes back beside the answer (subject_binding), so the model can tell that "the user" is the person named. Whenabstain_recommendedis true, have the model say it does not know, or ask. - Large imports.
POST /v1/memories/batchreturns areadiness_url;GET /v1/memories/batches/{event_id}reports for the whole batch how many items are searchable (dense and lexical) and, separately, graph and profile progress. Retry a timed-out batch with the sameIdempotency-Key: the original items come back and are not written twice. An import of many histories becomes fully searchable history by history; send one end user or agent per batch (see large imports, and readiness and estimate fields for what each field covers).
Example: retrieve a procedure, then check before acting
The agent asks memory how to recover a service, then checks the approval and the service's state in your own systems before it runs anything. The memory can say an approval exists; only your system of record can say that it does.
import os
import httpx
hebbrix = httpx.Client(
base_url="https://api.hebbrix.com/v1",
headers={"Authorization": f"Bearer {os.environ['HEBBRIX_API_KEY']}"},
)
def plan_recovery(session, service: str) -> dict:
# Scope comes from the authenticated session, never from the client.
found = hebbrix.post("/search", json={
"query": f"What is the current recovery method for {service}?",
"collection_id": session.collection_id,
"user_id": session.user_id,
"limit": 5,
}).json()
if found.get("abstain_recommended"):
return {"action": "ask_human", "reason": "no reliable procedure in memory"}
procedure = [r for r in found["results"] if r.get("is_current", True)]
# Memory is evidence, not permission: check the live state yourself.
approval = change_system.approval_for(service, session.user_id) # your system of record
if not (approval and approval.verified and not approval.expired):
return {"action": "ask_human", "reason": "no verified, current approval"}
if not monitoring.is_degraded(service): # your own operational check
return {"action": "none", "reason": "service is healthy"}
return {"action": "run", "procedure": procedure, "approval_id": approval.id}07. Checklist before you ship
- Each agent has its own
agent_id, used on every call. - Standing rules are stored with
/memories/raw, one rule per memory, labelledmemory_type: "rule". - Transcripts, with tool errors word for word, are saved after each task.
- The agent searches rules and procedures before consequential actions, and a
nullanswer means ask a human. - Permission checks live in your code, not in memory.