ag2-knowledge-and-memory
Skill12 starsChanged 8 days agoApache-2.0View on GitHub
Persist agent memory across runs, shape per-turn LLM context, cap history in AG2. Covers `KnowledgePlugin` (`plugins=[KnowledgePlugin(store, expose_tool=, aggregate=, compact=, ...)]`), stores `MemoryKnowledgeStore`, `SqliteKnowledgeStore`, `DiskKnowledgeStore` (needs watchdog), `RedisKnowledgeStore` (ag2[redis]), `LockedKnowledgeStore`; assembly policies via `Middleware(AssemblerMiddleware, policies=[...])` (`WorkingMemoryPolicy`, `EpisodicMemoryPolicy`, `ConversationPolicy`, `SlidingWindowPolicy`, `TokenBudgetPolicy`, `AlertPolicy` + `HaltCheckMiddleware`); aggregation (`WorkingMemoryAggregate`, `ConversationSummaryAggregate`, `AggregateTrigger`); compaction (`TailWindowCompact`, `SummarizeCompact`, `CompactTrigger`); `EventLogWriter`; `AggregationCompleted`/`CompactionCompleted`/`*Failed` events. Use for remembering between conversations, long histories, or prompt assembly; replaces deprecated `knowledge=`/`assembly=`. See `ag2-middleware`, `ag2-observers-and-alerts`.
- Installs packages
1 other project uses a version of this.
Adopted by
Most recently taken up by
- ag2ai/build-with-ag2their own version, first seen Oct 9, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- ag2ai/build-with-ag2★ 252same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository27 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- ag2-a2aSkill
- ag2-acpSkill
- ag2-add-custom-toolSkill
- ag2-ag-uiSkill
- ag2-eval-comparisonSkill
- ag2-evaluationSkill
- ag2-hitlSkill
- ag2-liveSkill
- ag2-mcpSkill
- ag2-middlewareSkill
- ag2-multimodal-inputSkill
- ag2-network-discussionSkill
- ag2-network-governanceSkill
- ag2-network-quickstartSkill
- ag2-network-tools-and-viewsSkill
- ag2-network-workflowSkill
- ag2-observers-and-alertsSkill
- ag2-overviewSkill
- ag2-quickstartSkill
- ag2-shell-toolSkill
- ag2-structured-outputSkill
- ag2-subagent-delegationSkill
- ag2-telemetrySkill
- ag2-testingSkill
- ag2-use-builtin-toolsSkill
The file
We split this skill into the rules it gives an agent
2 rules. About 0 are common, 0 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 75
All methods are async: read, write, list, delete, exists, append (returns byte offset), read_range(path, start, end=None), on_change(path, …
- Very specific: line 83
Only one KnowledgePlugin per invocation.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Knowledge, memory, and context assembly
| Primitive | Import | Role |
KnowledgeStore | ag2.knowledge | Path-based async persistent storage |
KnowledgePlugin | ag2.knowledge | Puts a store on an Agent + optional knowledge tool, bootstrap, /log/ dump, aggregation, compaction |
| Assembly policies | ag2.policies (+ AssemblerMiddleware from ag2.assembly) | Shape (prompts, events) before each LLM call |
| Aggregation / compaction | ag2.aggregate / ag2.compact | Write memory into the store / trim stream history |
When to use what
| Goal | Reach for |
| Remember user facts between conversations | WorkingMemoryAggregate (writes) + WorkingMemoryPolicy (reads) + persistent store |
| Summarise each session for next time | ConversationSummaryAggregate + EpisodicMemoryPolicy |
| Cap what the LLM sees | SlidingWindowPolicy(max_events=N) / TokenBudgetPolicy(max_tokens=N) |
| Hide lifecycle/observer noise from the LLM | ConversationPolicy() |
| Trim the stream history itself | TailWindowCompact (free) / SummarizeCompact (1 LLM call) |
| Let the model read/write files itself | KnowledgePlugin(store) (default expose_tool=True) |
Recipe — persistent working memory
from ag2 import Agent
from ag2.aggregate import AggregateTrigger, WorkingMemoryAggregate
from ag2.assembly import AssemblerMiddleware
from ag2.config import OpenAIResponsesConfig
from ag2.knowledge import KnowledgePlugin, SqliteKnowledgeStore
from ag2.middleware import Middleware
from ag2.policies import ConversationPolicy, WorkingMemoryPolicy
config = OpenAIResponsesConfig(model="gpt-4.1-mini")
store = SqliteKnowledgeStore("./journal.db") # no extra install needed
agent = Agent(
"journal",
prompt="You are a daily journal companion.",
config=config,
plugins=[KnowledgePlugin(
store,
expose_tool=False, # memory is policy-driven; no `knowledge` tool
write_event_log=False, # no /log/{stream_id}.jsonl dumps
aggregate=WorkingMemoryAggregate(config=config), # cheaper model is fine
aggregate_trigger=AggregateTrigger(on_end=True),
)],
middleware=[Middleware(AssemblerMiddleware, policies=[
WorkingMemoryPolicy(), # injection first: reads /memory/working.md
ConversationPolicy(), # then reduction
])],
)
reply = await agent.ask("I'm choosing between a Silvia Pro and a Linea Mini.")
print(await store.read("/memory/working.md")) # written when ask() returnedon_end aggregation fires when each ask() / reply.ask() finishes. A new Agent (even a new process) on the same DB gets the memory injected. Runnable: assets/journal_companion.py; assembly + compaction demo: assets/long_doc_chat.py.
Store backends and installs
| Store | Install | Notes |
MemoryKnowledgeStore() | core | Tests / ephemeral |
SqliteKnowledgeStore(path, *, poll_interval_s=0.5) | core | Pragmatic durable default |
DiskKnowledgeStore(root) | pip install "watchdog>=4.0,<7" (no ag2 extra) | Human-readable files. Import works without watchdog, constructing raises ImportError with that hint |
RedisKnowledgeStore(url_or_client, ..., poll_interval_s=0.5) | pip install "ag2[redis]" | Multi-process / cross-host |
LockedKnowledgeStore(store, lock) | core | Serialises write/delete/append via your acquire(name, ttl)/release(name) lock |
All methods are async: read, write, list, delete, exists, append (returns byte offset), read_range(path, start, end=None), on_change(path, cb). Import KnowledgeStore from ag2.knowledge (not top-level ag2).
KnowledgePlugin(store, *, ...) defaults
expose_tool=True— adds aknowledge(action="read"|"write"|"list"|"delete", path, content)tool.write_event_log=True— dumps the stream to/log/{stream_id}.jsonlafter eachask().bootstrap=None— seeds/SKILL.md,/log/,/memory/,/artifacts/on first use (DefaultBootstrap(mention_tool=expose_tool)); pass your ownStoreBootstrapto change/disable.aggregate+aggregate_trigger,compact+compact_trigger— give them in pairs:compactwithout a trigger, or an active trigger withoutaggregate, raisesValueErrorat construction;aggregatewithout a trigger (orAggregateTrigger()with nothing enabled) silently never fires. On turn end aggregation runs before compaction.- Only one
KnowledgePluginper invocation.dependencies={KnowledgeStore: other}overrides the plugin's store for tools, policies and maintenance. - Bare minimum without a plugin:
Agent(..., dependencies={KnowledgeStore: store})— policies can read the store; no tool, no bootstrap, no logs, no maintenance.
Assembly policies
Register via middleware=[Middleware(AssemblerMiddleware, policies=[...]), Middleware(HaltCheckMiddleware)]. Injection before reduction: WorkingMemoryPolicy, EpisodicMemoryPolicy(max_episodes=5), AlertPolicy() → ConversationPolicy(), SlidingWindowPolicy(max_events=N, transparent=False), TokenBudgetPolicy(max_tokens=N, chars_per_token=4). Add Middleware(HaltCheckMiddleware) right after the assembler when using AlertPolicy so FATAL alerts stop the call. AssemblerMiddleware.validate_order(policies) returns warnings for bad orderings. Window limits are targets: orphaned tool results are dropped, so the sent window can be smaller (or larger) than asked.
Migration (deprecated in 1.3, removed in 1.4)
Agent(knowledge=KnowledgeConfig(...)) → plugins=[KnowledgePlugin(store, ...)] (same kwargs). Agent(assembly=[...]) → middleware=[Middleware(AssemblerMiddleware, policies=[...]), Middleware(HaltCheckMiddleware)] (the old form added the halt check automatically; drop it and FATAL alerts stop halting). Mixing knowledge= with a KnowledgePlugin raises ValueError.
Reference
references/details.md— full wiring example, aggregation/compaction strategies, custom policies/strategies, lifecycle events,EventLogWriter, pitfalls.- Upstream:
website/docs/user-guide/agent_harness.mdx,advanced/knowledge_store.mdx,advanced/assembly.mdx,advanced/aggregation.mdx,advanced/compaction.mdx; ADRdocs/adr/0033-knowledge-is-a-plugin-with-scoped-maintenance.md.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

