Contract-driven memory for AI agents — typed schemas, explicit conflict policies, structured provenance, typed event timeline.
pip install typedmem==0.9.1 Copy PIP instructions
Agent memory stores facts. Facts change. Which one is true now?
TypedMem keeps the current truth without erasing what used to be true, or where it came from.
$ pip install "typedmem>=0.9" # Python 3.10+, no dependencies $ typedmem set alice.employer OpenAI alice.employer = OpenAI (new) $ typedmem set alice.employer Anthropic alice.employer = Anthropic (was OpenAI) $ typedmem get alice.employer Anthropic $ typedmem history alice.employer Anthropic current source: cli OpenAI previous source: cli What breaks without it: most agent memory stores both sentences and retrieves both. Your agent sees "OpenAI" and "Anthropic" with equal weight and guesses. TypedMem knows which one is current. When two sources genuinely disagree, it doesn't guess either: it keeps both and reports the conflict.
from typedmem import AgentMemory mem = AgentMemory(path="agent.db") mem.set("alice.employer", "OpenAI") mem.set("alice.employer", "Anthropic", source="email from Alice") mem.get("alice.employer") # 'Anthropic'
📦 PyPI · 📚 Docs · 🏷️ Releases · 📝 Changelog
A state is a key you name (alice.employer, order.1234.status, repo.default_branch) that holds one value at a time. Nothing is ever overwritten. Every value keeps its validity window and its source.
$ typedmem set alice.employer OpenAI --valid-from 2021-03-01 alice.employer = OpenAI (new) $ typedmem set alice.employer Anthropic --valid-from 2024-01-15 alice.employer = Anthropic (was OpenAI) $ typedmem set alice.employer Google --valid-from 2022-06-01 alice.employer: recorded Google from 2022-06-01 as a past value; current is Anthropic $ typedmem history alice.employer -v Anthropic current since 2024-01-15 source: cli Google previous 2022-06-01 → 2024-01-15 source: cli OpenAI previous 2021-03-01 → 2022-06-01 source: cli $ typedmem set alice.employer Meta --source "agent guess" --authority 0.5 alice.employer: CONFLICT: Meta disagrees with Anthropic; no current value see: typedmem history alice.employer $ typedmem get alice.employer alice.employer: CONFLICT, no current value Meta conflict source: agent guess (authority 0.5) vs Anthropic Anthropic conflict source: cli vs Meta Change is resolved. The value that became true latest is current: when it became true (--valid-from), not when TypedMem heard about it. Google arrived last but belongs in 2022, so it goes into history. Disagreement is exposed. A value that can't be ordered against the current one is a conflict: it starts at the same moment, or it's later but comes from a weaker source. A weaker source never silently overrides a stronger one. get then refuses to pick (exit code 3; StateConflict in Python) until a later value from a source at least as strong settles it. Repeating a value corroborates it. The source is added to the existing value; nothing new appears in history. Design note: design/0002-changing-facts.md.
States are the simplest part of TypedMem. Underneath is a typed memory store for agents, with profiles, conflict policies, provenance and a replayable event log.
Boundary. TypedMem is a persistent memory representation. It does not model execution provenance or semantic reasoning.
Memory you can contract against. Four explicit contracts make TypedMemory:
Built for domain apps where "the memory accepted nonsense" is a correctness bug.
AI agents start believing their own hallucinations. They:
$ pip install typedmem # Python 3.10+ $ typedmem --profile engineering_design add \ "SQLite handles our single-writer load fine" --type risk --subject storage $ typedmem --profile engineering_design add \ "SQLite blocks under concurrent writes" --type risk --subject storage $ typedmem --profile engineering_design contradictions 1 contradiction cluster(s): cluster 1 (2 memories): [risk] [storage] SQLite handles our load fine [risk] [storage] SQLite blocks under concurrent writes Two memories cross-linked by the FLAG policy. Both still in the store — no silent overwrite. Run typedmem history on either to see exactly when and why the state changed.
More demos: examples/DEMO.md for the 30-second no-flags paste · examples/agent_loop_demo.py for the before-vs-after agent story.
Most memory systems are learned — they consolidate, refine, and optimize for retrieval recall. TypedMemory is contracted — every state change is governed by rules you declare up front.
The agent's beliefs are auditable because the contracts are explicit. The whole point: when the memory got something wrong, you can prove what changed, when, why, and who did it.
If those omissions sound like features to you, you're the audience.
┌──────────────────┐ │ DomainProfile │ ← schema: which types, │ TypeSpec × N │ which policies, │ prompt + rules │ which validations └────────┬─────────┘ │ text ──► Extractor ──► Memory ──┴──► MemoryStore ──► Retriever │ ▼ Evolver (contradictions, drift, goals, non-destructive summarization) Every memory has a type (claim, decision, observation, …), a confidence, a structured source, a lifecycle policy, and a workspace — not a string in a vector database. Memories know how to update themselves on conflict, how to decay over time, and how to be summarized.
Zero runtime dependencies. Stdlib only. LLM clients, YAML profile loading, and richer embedders are optional extras.
Most "AI memory" libraries are wrappers around a vector database. That works for "remember what the user said," but it falls apart the moment you want an agent to:
TypedMemory handles these as first-class concepts, not bolt-ons.
pip install typedmem # default install, zero deps pip install 'typedmem[anthropic]' # + AnthropicClient pip install 'typedmem[openai]' # + OpenAIClient pip install 'typedmem[yaml]' # + DomainProfile.from_yaml() pip install 'typedmem[server]' # + HTTP server (FastAPI + uvicorn) pip install 'typedmem[gcp]' # + Cloud Run / Google ID-token auth pip install 'typedmem[all]' Python 3.10+.
Not a Python project? Use typedmem over HTTP:
pip install 'typedmem[server]' typedmem --store agent.db serve --api-token $(openssl rand -hex 32) REST API under /v1/, interactive docs at /docs. Same surface as the Python library — add, get, delete, list, recall, history, timeline, changed-since, reflect. Works on Cloud Run + GCS FUSE, plain Docker, or systemd. Full deploy guide: docs/server.md.
import json from typedmem import ( DomainProfile, FakeClient, LLMExtractor, SQLiteMemoryStore, ) profile = DomainProfile.builtin("engineering_design") store = SQLiteMemoryStore.for_profile(profile, "design.db") # Pretend the LLM extracted these from your design docs. extractor = LLMExtractor(client=FakeClient([ json.dumps([ {"type": "decision", "content": "Use SQLite for storage", "subject": "storage_backend", "confidence": 0.9, "source": {"document_id": "design_v1.md"}}, {"type": "risk", "content": "SQLite is single-writer", "subject": "storage_backend", "confidence": 0.8, "source": {"document_id": "design_v1.md"}}, ]), json.dumps([ {"type": "decision", "content": "Switch to PostgreSQL for concurrent writes", "subject": "storage_backend", "confidence": 0.9, "source": {"document_id": "design_v2.md"}}, {"type": "risk", "content": "Postgres adds an external service", "subject": "storage_backend", "confidence": 0.85, "source": {"document_id": "design_v2.md"}}, ]), ]), profile=profile) for snippet in ("v1 text", "v2 text"): for m in extractor.extract(snippet): store.add(m) # decision → SUPERSEDE: old preserved, new active. print(store.by_type("decision")) # → just PostgreSQL print(store.by_type("decision", include_superseded=True)) # → both # risk → FLAG: two risks on the same subject get cross-linked. for cluster in store.contradictions(): for m in cluster: print(m.content) # → both risks See examples/engineering_design_demo.py for the full version with audit trail and source provenance, or run:
typedmem profiles typedmem --profile engineering_design add "..." --document-id design_v3.md typedmem --profile engineering_design list --type decision typedmem evolve --evolver contradictions The mental model Layer What it gives you Examples Memory Typed object with content + confidence + workspace + sources + status Memory(type="claim", content=..., sources=[Source(...)]) Source Structured provenance with hashable identity (document_id, chunk_id, span) — dedup key for REINFORCE workspace Namespace on every memory One agent, multiple corpora, zero cross-contamination ConflictPolicy What to do when a new memory hits the same (workspace, type, subject) slot REPLACE · KEEP_BOTH · SUPERSEDE · REINFORCE · FLAG · IGNORE DomainProfile Schema for a domain: which types, what policy each obeys, what's required engineering_design · research_paper · legal · medical_literature · personal · … Evolver Reads memories (not text); produces audit-trailed actions ContradictionSurfacer · PreferenceDriftDetector · GoalResolver · SummaryEvolver Built-in profiles Profile Types Notable policies core fact, note, goal, task, event Shared primitives all other profiles can opt into personal + preference, observation preference → REPLACE (60d decay) child_development + observation (tagged), milestone, concern observation tags: language/motor/emotional/cognitive/social research_paper + claim, method, evidence, limitation, open_question evidence → REINFORCE (multiple papers corroborate) engineering_design + decision, constraint, risk, assumption, todo decision → SUPERSEDE, risk → FLAG legal + obligation, exception, deadline, definition, citation definition → SUPERSEDE medical_literature + finding, population, intervention, outcome, limitation outcome → REINFORCE across studies Custom profiles via Python dataclass, JSON, or YAML.
from typedmem import SQLiteMemoryStore, DomainProfile store = SQLiteMemoryStore.for_profile( DomainProfile.builtin("research_paper"), path="papers.db", ) Retrieval from typedmem import HashingEmbeddingProvider, Retriever retriever = Retriever(store, embedder=HashingEmbeddingProvider()) hits = retriever.relevant( "blood pressure reduction", types=["evidence"], workspace="cardiology", ) relevant() blends three signals: semantic (cosine), recency (exponential decay), confidence (with type-specific half-life). Without an embedder, falls back to token overlap.
Retrieval answers "what's true now?". The timeline answers "how did we get here?". Every successful add / update / delete / conflict-resolution / evolver action emits a typed MemoryEvent into an indexed event log.
from datetime import datetime, timedelta, timezone mem.remember("User prefers dark mode") mem.remember("Actually, light mode in the morning") # Everything that ever touched this memory: mid = mem.recall("color theme")[0].memory.id for e in mem.store.history(mid): print(f"{e.timestamp:%H:%M:%S} {e.source}/{e.source_name} {e.action}") # 23:58:32 agent/AgentMemory.remember added # 23:58:33 agent/AgentMemory.remember replaced # Or filter by subject / type / workspace / source: mem.store.timeline(subject="storage_backend", source="evolver") # Or pull the canonical change feed since a point in time # (for sync, replication, downstream notification): since = datetime.now(timezone.utc) - timedelta(minutes=10) for e in mem.store.changed_since(since): ship_to_downstream(e) Each event carries memory_id, workspace, type, subject, action, source (one of "store" / "evolver" / "agent" / "user" / "system"), source_name, reason, input_ids, output_ids, payload, timestamp. Delete events outlive the memory row — changed_since() surfaces deletions to consumers staying in sync.
The log is replayable. Every state-changing event carries full before / after snapshots of the memory (Memory.to_dict() values) in payload, so each event is self-contained:
state = mem.store.replay() # {memory_id: Memory}, rebuilt purely from the log assert {m.id for m in mem.store} == set(state) replay applies recorded outcomes in order — it never re-runs a ConflictPolicy — so changing a policy tomorrow does not change what yesterday's log replays to. Events written before v0.9 have no snapshots; they remain readable, and replay(strict=False) skips them.
Evolvers read stored memories and produce auditable actions.
from typedmem import ( ContradictionSurfacer, PreferenceDriftDetector, GoalResolver, SummaryEvolver, HashingEmbeddingProvider, AnthropicClient, ) # 1. Pure read: walk the FLAG graph. for cluster in store.contradictions(): print(f"{len(cluster)} memories cross-link as contradictions") # 2. Annotation: catch unstable preferences. PreferenceDriftDetector(min_replaces=3, window_days=30).evolve(store) # 3. Safe match: dry-run first, then commit. embedder = HashingEmbeddingProvider() plan = GoalResolver(embedder, threshold=0.85).evolve(store, dry_run=True) print(plan.summary()) GoalResolver(embedder, threshold=0.85).evolve(store) # commit # 4. Non-destructive summary of stale events. SummaryEvolver(AnthropicClient(), min_cluster_size=3).evolve(store) # Originals untouched; new memory links via metadata["summarizes"]. Every action emits a typed MemoryEvent into the store's indexed event log — source="evolver", source_name="goal_resolver" (etc.), plus action, input_ids, output_ids, reason, timestamp. Query with store.history(memory_id), store.timeline(subject=..., source="evolver"), or store.changed_since(t). No black-box mutations, no metadata["evolution_history"] cap to worry about.
Under the hood, every mutation now goes through one funnel. A Transition is an inert description of intent; the TransitionEngine is the only thing that writes to storage — it validates, resolves conflicts, bumps a persisted version, emits the event, and persists. Store add/delete, conflict resolution, and all three evolvers route through it.
from typedmem import Transition # Optimistic concurrency: refuse to clobber a newer state. store.apply_transition(Transition( action="update", memory_id=goal.id, expected_version=goal.version, changes={"status": "resolved"}, actor="evolver", actor_name="goal_resolver", )) # → ConcurrencyError if goal.version has moved; LifecycleError on an illegal status Behavior is injectable via three strategies, each with a default that preserves prior behavior: IdentityStrategy (slot/dedup key), ConfidenceStrategy (reinforcement + decay), LifecycleStrategy (status validation + is_active). Public API — all importable from typedmem: Transition, TransitionEngine, TransitionResult, ConcurrencyError, LifecycleError, IdentityStrategy / SlotIdentityStrategy, ConfidenceStrategy / PolicyConfidenceStrategy, LifecycleStrategy / DefaultLifecycleStrategy.
The kernel API is public but provisional until v1.0.
typedmem profiles # list built-in domain profiles typedmem --profile research_paper add "..." --document-id paper.pdf typedmem --profile engineering_design list --type decision typedmem search "blood pressure" --type evidence typedmem evolve --evolver contradictions typedmem evolve --evolver goals --apply --threshold 0.9 # dry-run by default typedmem history MEMORY_ID # per-memory event timeline typedmem timeline --subject storage_backend --source evolver # filter the event log typedmem changed-since 1h # canonical change feed (also: 5m, 2h, 1d, 1w, or ISO 8601) typedmem workspaces CLI writes (add / delete) are tagged source="user" in the event log, so typedmem timeline --source user shows exactly what a human did at the terminal vs. what an agent or evolver did.
Default store: ~/.typedmem/memories.db (override with --store path.db or --store path.jsonl).
Latest release: v0.9.0, states: set / get / history for values that change over time, with conflicts exposed rather than guessed. Before that, v0.8.0: governed state transitions (one TransitionEngine for every write). See the CHANGELOG for v0.4–v0.7 (profiles, AgentMemory, event timeline, HTTP server).
Under consideration next, only if real usage demands it:
What TypedMemory doesn't do and doesn't plan to:
Issues and PRs welcome. Please run pytest and the demos in examples/ before opening a PR; CI runs them on Python 3.10/3.11/3.12.
Also from lyr-ai: AgentSeism, regression decisions for stochastic AI systems.
test openai anthropic yaml docs server gcp all
ai memory agents llm knowledge rag anthropic openai
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 27, 2026.




