Agent skill

Ag2 Knowledge And Memory

by ag2ai in ag2ai/build-with-ag2

Persist agent state across runs, shape what the LLM sees per turn, and cap history to fit a context window.

Apache-2.0Auto-check passedDatabases

Install Ag2 Knowledge And Memory

skills CLI
$ npx skills add ag2ai/build-with-ag2 --skill ag2-knowledge-and-memory -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install ag2ai/build-with-ag2 ag2-knowledge-and-memory --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/ag2ai/build-with-ag2.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.agents/skills/ag2-knowledge-and-memory .claude/skills/ag2-knowledge-and-memory && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
ag2-knowledge-and-memory
GitHub stars
252
Token cost
~2.9k tokens
SKILL.md length
745 words
Files
3 (incl. assets)
Skills in repo
16
Repo updated
First seen
Licence
Apache-2.0

At a glance

Persist agent state across runs, shape what the LLM sees per turn, and cap history to fit a context window.

  • The user wants the agent to remember between conversations
  • SKILL.md covers When to use what, 60-second recipe — persistent…, KnowledgeStore implementations and Assembly chain — what the LLM…, plus 5 more sections
  • Runs Python scripts from its folder
  • Manage long histories

What it does

Ag2 Knowledge And Memory is an agent skill from ag2ai/build-with-ag2. Persist agent state across runs, shape what the LLM sees per turn, and cap history to fit a context window. Covers KnowledgeStore (memory / sqlite / disk / redis), KnowledgeConfig (store=, compact=, aggregate=, bootstrap=), aggregation strategies (WorkingMemoryAggregate, ConversationSummaryAggregate), assembly policies (WorkingMemoryPolicy, EpisodicMemoryPolicy, ConversationPolicy, SlidingWindowPolicy, TokenBudgetPolicy, AlertPolicy), and compaction (TailWindowCompact, SummarizeCompact). Use when the user wants…

Its SKILL.md is about 2.9k tokens, which your agent loads only when the skill is triggered. The skill folder holds 3 other files, including assets (for example `assets/journal_companion.py` and `assets/long_doc_chat.py`).

It sits in Databases, covering Context engineering. It works with Redis and SQLite. The repository describes itself as: Sample code and application showcases to get you going with AG2 (formally AutoGen). The licence is Apache-2.0.

When your agent uses it

  • The user wants the agent to remember between conversations
  • Manage long histories
  • Control prompt assembly

Example prompts

  • “/ag2-knowledge-and-memory”

Requirements

  • Python 3

What it can do on your machine

Read from SKILL.md and the folder at commit 29eeac3. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Ships script files (Python), which the agent can run.

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Ag2 Knowledge And Memory loads about 2.9k tokens when it runs. Until then it costs about 167 tokens; SKILL.md has 745 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~167
When it runs · the whole SKILL.md, loaded when a task matches
~2.9k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from ag2ai/build-with-ag2 at commit 29eeac3, republished under its Apache-2.0 licence (© ag2ai). 745 words, ~2,879 tokens.

Download SKILL.mdSave it as .claude/skills/ag2-knowledge-and-memory/SKILL.md (or your agent's skills folder). This skill also uses 2 other files; get the full folder from GitHub.
name
ag2-knowledge-and-memory
description
Persist agent state across runs, shape what the LLM sees per turn, and cap history to fit a context window. Covers `KnowledgeStore` (memory / sqlite / disk / redis), `KnowledgeConfig` (`store=`, `compact=`, `aggregate=`, `bootstrap=`), aggregation strategies (`WorkingMemoryAggregate`, `ConversationSummaryAggregate`), assembly policies (`WorkingMemoryPolicy`, `EpisodicMemoryPolicy`, `ConversationPolicy`, `SlidingWindowPolicy`, `TokenBudgetPolicy`, `AlertPolicy`), and compaction (`TailWindowCompact`, `SummarizeCompact`). Use when the user wants the agent to remember between conversations, manage long histories, or control prompt assembly.
license
Apache-2.0

Knowledge, memory, and context assembly

This skill covers three related primitives that work together:

PrimitiveLives inRole
KnowledgeStoreautogen.beta.knowledgePath-based persistent storage (memory / sqlite / disk / redis)
Assembly policiesautogen.beta.policiesShape (prompts, events) per turn before the LLM call
Aggregation / Compactionautogen.beta.aggregate / .compactWrite structured knowledge to the store / trim event history

KnowledgeConfig wires all three onto an Agent via the knowledge= constructor parameter; assembly policies go via assembly=.

When to use what

User intentReach for
Remember user preferences / state between conversationsWorkingMemoryAggregate + WorkingMemoryPolicy (and a persistent store)
Summarise each session for next timeConversationSummaryAggregate + EpisodicMemoryPolicy
Hard-cap event history sent to the LLMSlidingWindowPolicy(max_events=N)
Cap by approximate token countTokenBudgetPolicy(max_tokens=N)
Drop lifecycle / observer events from the LLM's viewConversationPolicy()
Trim stream history (not just LLM view)TailWindowCompact or SummarizeCompact
Route observer alerts to the LLMAlertPolicy()

60-second recipe — persistent working memory

python
from autogen.beta import Agent, KnowledgeConfig
from autogen.beta.aggregate import AggregateTrigger, WorkingMemoryAggregate
from autogen.beta.config import OpenAIConfig
from autogen.beta.knowledge import DiskKnowledgeStore
from autogen.beta.policies import ConversationPolicy, WorkingMemoryPolicy

store = DiskKnowledgeStore("./journal-state")
config = OpenAIConfig(model="gpt-5")

agent = Agent(
    "journal",
    prompt="You are a daily journal companion.",
    config=config,
    knowledge=KnowledgeConfig(
        store=store,
        aggregate=WorkingMemoryAggregate(config=config),
        aggregate_trigger=AggregateTrigger(on_end=True),
    ),
    assembly=[
        WorkingMemoryPolicy(),  # injects /memory/working.md on every LLM call
        ConversationPolicy(),
    ],
)

After each conversation the aggregate writes /memory/working.md. The next time you build an Agent against the same store, WorkingMemoryPolicy reads that file in and injects it as prompt context. The agent "remembers" without replaying chat history. Full runnable example: assets/journal_companion.py.

KnowledgeStore implementations

ImplementationUse when
MemoryKnowledgeStore()Tests, ephemeral sessions
SqliteKnowledgeStore(path)Single-process durability — pragmatic default
DiskKnowledgeStore(path)Files should be human-readable on disk
RedisKnowledgeStore(url)Multi-process / cross-host sharing
LockedKnowledgeStore(inner, lock=...)Wrap any store to serialize concurrent writers

API (all async):

python
await store.write("/artifacts/report.md", "# Q3...")
text = await store.read("/artifacts/report.md")
children = await store.list("/")            # immediate children, dirs end in '/'
await store.delete("/artifacts/old.md")
exists = await store.exists("/artifacts/report.md")

off = await store.append("/log/events.jsonl", '{"t":1}\n')   # WAL-style
new_slice = await store.read_range("/log/events.jsonl", off)  # only new bytes
sub = await store.on_change("/log/", on_change_callback)

Assembly chain — what the LLM actually sees

Pass AssemblyPolicy instances via assembly=[...]. The Agent wires an internal AssemblerMiddleware at the outermost middleware position. Each policy transforms (prompts, events) and pipes into the next.

Two kinds of policy — order matters: injection before reduction.

KindPurposeBuilt-ins
InjectionAdd to promptsWorkingMemoryPolicy, EpisodicMemoryPolicy, AlertPolicy
ReductionTrim eventsConversationPolicy, SlidingWindowPolicy, TokenBudgetPolicy

Validate ordering manually:

python
from autogen.beta.assembly import AssemblerMiddleware
warnings = AssemblerMiddleware.validate_order(policies)  # returns list of warnings on known bad orderings

(AssemblerMiddleware and the AssemblyPolicy protocol live in autogen.beta.assembly for advanced/manual harness wiring; you don't need to import them when just passing built-in policies via assembly=[...].)

Built-in policies
python
from autogen.beta.policies import (
    AlertPolicy,
    ConversationPolicy,
    EpisodicMemoryPolicy,
    SlidingWindowPolicy,
    TokenBudgetPolicy,
    WorkingMemoryPolicy,
)

# Injection
WorkingMemoryPolicy()                                 # reads /memory/working.md
EpisodicMemoryPolicy(max_episodes=5, transparent=True) # reads recent /memory/conversations/
AlertPolicy()                                          # delivers ObserverAlerts to LLM, halts on FATAL

# Reduction
ConversationPolicy()                                  # drops non-conversation events
SlidingWindowPolicy(max_events=50, transparent=True)  # last N events
TokenBudgetPolicy(max_tokens=32_000, chars_per_token=4, transparent=True)

transparent=True appends a [policy_name] Showing X of Y events. note to the prompt — useful while tuning. Realistic chain:

python
assembly=[
    WorkingMemoryPolicy(),
    EpisodicMemoryPolicy(max_episodes=3),
    AlertPolicy(),
    SlidingWindowPolicy(max_events=80),
]

Aggregation — writing knowledge to the store

AggregateStrategy.aggregate(events, ctx, store) → None extracts and persists. Two built-ins, both take a ModelConfig for a summarisation call (use a cheaper model than the agent's main one):

StrategyWritesPairs with
WorkingMemoryAggregate(config=...)/memory/working.md (single rolling file)WorkingMemoryPolicy
ConversationSummaryAggregate(config=...)/memory/conversations/{ts}_{stream_id}.mdEpisodicMemoryPolicy

AggregateTrigger controls cadence — every_n_turns, every_n_events, on_end. AggregateTrigger() alone fires nothing; opt in to at least one. on_end=True defaults off because each fire is an LLM call.

Compaction — trimming stream history

CompactStrategy.compact(events, ctx, store) → list[BaseEvent]. Replaces the stream's history. Two built-ins:

StrategyBehaviourCost
TailWindowCompact(target=N)Keep last N events; drop the rest (optionally persist to /log/)Zero LLM calls
SummarizeCompact(target=N, config=...)Summarise dropped events into one CompactionSummary; insert at headOne LLM call per fire

CompactTrigger(max_events=N, max_tokens=M, chars_per_token=4) — fires when any threshold is crossed.

python
from autogen.beta.compact import CompactTrigger, TailWindowCompact, SummarizeCompact

SummarizeCompact inserts a CompactionSummary event at the head; ConversationPolicy allows it through so the LLM still gets that context.

Show full SKILL.md (273 more words)Show less

Wiring it all on the Agent

KnowledgeConfig is the bundle:

python
from dataclasses import dataclass

@dataclass
class KnowledgeConfig:
    store: KnowledgeStore
    compact: CompactStrategy | None = None
    compact_trigger: CompactTrigger | None = None
    aggregate: AggregateStrategy | None = None
    aggregate_trigger: AggregateTrigger | None = None
    bootstrap: StoreBootstrap | None = None    # e.g. DefaultBootstrap()

Full shape:

python
agent = Agent(
    "assistant",
    config=main_config,
    knowledge=KnowledgeConfig(
        store=DiskKnowledgeStore("./state"),
        compact=TailWindowCompact(target=100),
        compact_trigger=CompactTrigger(max_events=200),
        aggregate=ConversationSummaryAggregate(config=summarizer_config),
        aggregate_trigger=AggregateTrigger(every_n_turns=10, on_end=True),
        bootstrap=DefaultBootstrap(),  # seeds /SKILL.md, /artifacts/, /log/, /memory/
    ),
    assembly=[
        WorkingMemoryPolicy(),
        EpisodicMemoryPolicy(max_episodes=3),
        AlertPolicy(),
        SlidingWindowPolicy(max_events=80),
    ],
)

The harness wires internal middleware conditionally — _AssemblerMiddleware, _HaltCheckMiddleware, _CompactionMiddleware, _AggregationMiddleware. You only pay for what you turn on.

Lifecycle events emitted: CompactionCompleted (with events_before / events_after / usage), AggregationCompleted (with strategy / usage), HaltEvent (when AlertPolicy sees a FATAL alert). Subscribe via ag2-observers-and-alerts.

Going deeper

  • assets/journal_companion.py — runnable end-to-end working-memory demo (mirrors code_examples/06).
  • assets/long_doc_chat.py — assembly + compaction stress test (mirrors code_examples/07).
  • Source docs:
    • website/docs/beta/advanced/knowledge_store.mdx — store API, EventLogWriter, LockedKnowledgeStore.
    • website/docs/beta/advanced/assembly.mdx — full policy reference and ordering rules.
    • website/docs/beta/advanced/aggregation.mdx — aggregate strategies and custom strategies.
    • website/docs/beta/advanced/compaction.mdx — compact strategies and custom strategies.
    • website/docs/beta/agent_harness.mdx — KnowledgeConfig constructor reference, turn-lifecycle middleware order.

Common pitfalls

  • Reduction before injection — SlidingWindowPolicy before WorkingMemoryPolicy means the working memory injection isn't counted against the budget. Always: injections first, then AlertPolicy, then reductions.
  • Forgetting KnowledgeStore dependency for memory policies — WorkingMemoryPolicy and EpisodicMemoryPolicy look up the store via context.dependencies.get(KnowledgeStore). KnowledgeConfig(store=...) registers it for you; if you wire the policy manually, register the store in dependencies too.
  • Aggregation costs an LLM call per fire — on_end=True on every conversation can add up. Pair WorkingMemoryAggregate and ConversationSummaryAggregate thoughtfully; consider every_n_turns=N for high-volume agents.
  • Mixing HistoryLimiter middleware with assembly reduction policies — they both trim. Pick one mechanism. Assembly is more flexible (rich shaping, transparency notes); HistoryLimiter is simpler.
  • read_range operates on byte offsets, not character offsets — multi-byte UTF-8 sequences need careful alignment.
  • Forgetting that WorkingMemoryAggregate is destructive — it overwrites /memory/working.md each fire. That's intentional (rolling state, not log) but expect prior content to merge or disappear.
  • Expecting AlertPolicy to render alerts to the LLM without being in assembly= — alerts sit on the stream as ObserverAlert events but only reach the LLM when AlertPolicy injects them.

© ag2ai, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 2 other files (assets) in .agents/skills/ag2-knowledge-and-memory of ag2ai/build-with-ag2.

  • SKILL.md
  • assets/journal_companion.py
  • assets/long_doc_chat.py

Open the folder on GitHubat commit 29eeac3

Compare with similar skills

Ag2 Knowledge And Memory next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Ag2 Knowledge And Memory compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Ag2 Knowledge And Memory this skillag2ai/build-with-ag2252—~2.9kAutomated safety check: PassApache-2.0
Cognee Session Memory and Improvetopoteretes/cognee32k—~3.2kAutomated safety check: PassApache-2.0
Frontmcp Setupagentfront/frontmcp146—~5.8kAutomated safety check: PassApache-2.0
Add Memory KindEverMind-AI/EverOS13k—~2.6kAutomated safety check: PassApache-2.0
Extend Commands APIredis/lettuce5.8k—~7.7kAutomated safety check: NotesMIT
Extend Commands APIredis/jedis12k—~7.2kAutomated safety check: WarnMIT

Similar skills

  • Explains how cognee stores session memory by session_id and bridges it into the permanent graph with improve(), including the stages, results and settings.

    32k GitHub stars~3.2k tokensUpdated today
    Agent WorkflowsAuto-check passed
  • Frontmcp Setup

    agentfront/frontmcp

    A skill your agent uses when starting, scaffolding, or organizing a FrontMCP project.

    146 GitHub stars~5.8k tokensUpdated yesterday
    DatabasesAuto-check passed
  • Add Memory Kind

    EverMind-AI/EverOS

    Walks through adding a new persisted memory kind to EverOS: choose storage among Markdown, SQLite and LanceDB, pick a Markdown strategy, then wire schemas, repos and writers.

    13k GitHub stars~2.6k tokensUpdated yesterday
    DatabasesAuto-check passed
  • Extend Commands API

    redis/lettuce

    Official

    Add or extend Redis commands in the Lettuce client API end-to-end — a new core command, a family of new commands, an extension to an existing command's options, or a module/area command…

    5.8k GitHub stars~7.7k tokensUpdated today
    DatabasesAuto-check: notes
  • Official

    Add or extend Redis commands in the Jedis client API — a new core command, a family of new commands, an extension to an existing command's options, or a module command (Search/TimeSeries/JSON/Bloom).

    12k GitHub stars~7.2k tokensUpdated today
    DatabasesAuto-check: warnings
  • Pp Authentik

    mvanhorn/printing-press-library

    Agent-native admin CLI for authentik identity provider with offline SQLite cache and an MCP server for Claude Desktop.

    2.1k GitHub stars~23k tokensUpdated yesterday
    DatabasesAuto-check: notes

More from ag2ai/build-with-ag2

All 16 skills in this repo
  • Ag2 Add Custom Tool

    ag2ai/build-with-ag2

    Add a custom Python tool to an AG2 beta Agent using the @tool decorator.

    252 GitHub stars~1.9k tokensUpdated 1 mo ago
    Auto-check passed
  • Ag2 Middleware

    ag2ai/build-with-ag2

    Intercept the AG2 beta agent loop with BaseMiddleware — wrap full turns (onturn), each LLM call (onllmcall), each tool execution (ontoolexecution), or each human-input request (onhumaninput).

    252 GitHub stars~1.9k tokensUpdated 1 mo ago
    Auto-check passed
  • Ag2 Use Builtin Tools

    ag2ai/build-with-ag2

    Wire AG2 beta's shipped tools into an Agent — both provider-native server-side tools (web search, web fetch, code execution, MCP, image generation, memory) and locally-executed common toolkits…

    252 GitHub stars~1.3k tokensUpdated 1 mo ago
    Auto-check passed
  • Ag2 Observers And Alerts

    ag2ai/build-with-ag2

    Monitor an AG2 beta agent's stream — log events, detect repeated tool calls, track token spend, build trigger-driven observers, route observer alerts to the model, and halt on FATAL conditions.

    252 GitHub stars~2.5k tokensUpdated 1 mo ago
    Auto-check passed
  • Ag2 Quickstart

    ag2ai/build-with-ag2

    Build a minimal AG2 beta Agent end to end — pick a model provider, set a prompt, call agent.ask(), then continue the conversation with reply.ask() (multi-turn).

    252 GitHub stars~1.7k tokensUpdated 1 mo ago
    Auto-check: notes
  • Ag2 Structured Output

    ag2ai/build-with-ag2

    Get a typed Python value back from an AG2 beta Agent instead of free text.

    252 GitHub stars~1.8k tokensUpdated 1 mo ago
    Auto-check passed

Works with

Questions about Ag2 Knowledge And Memory

What does Ag2 Knowledge And Memory do?

Persist agent state across runs, shape what the LLM sees per turn, and cap history to fit a context window. Ag2 Knowledge And Memory is an agent skill from ag2ai/build-with-ag2. Persist agent state across runs, shape what the LLM sees per turn, and cap history to fit a context window.

When should I use Ag2 Knowledge And Memory?

Ag2 Knowledge And Memory fits situations like: the user wants the agent to remember between conversations; manage long histories; control prompt assembly.

How do I install Ag2 Knowledge And Memory in Claude Code?

Run `npx skills add ag2ai/build-with-ag2 --skill ag2-knowledge-and-memory -a claude-code`. Or copy the skill folder (.agents/skills/ag2-knowledge-and-memory in ag2ai/build-with-ag2) into .claude/skills/ag2-knowledge-and-memory in your project. Claude Code loads it when a task matches its description.

How do I install Ag2 Knowledge And Memory in Codex?

Run `npx skills add ag2ai/build-with-ag2 --skill ag2-knowledge-and-memory -a codex`. Or copy the skill folder (.agents/skills/ag2-knowledge-and-memory in ag2ai/build-with-ag2) into .agents/skills/ag2-knowledge-and-memory in your project. Codex loads it when a task matches its description.

Can I use Ag2 Knowledge And Memory in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add ag2ai/build-with-ag2 --skill ag2-knowledge-and-memory -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/ag2-knowledge-and-memory, .gemini/skills/ag2-knowledge-and-memory, .github/skills/ag2-knowledge-and-memory and .opencode/skills/ag2-knowledge-and-memory in your project.

What does Ag2 Knowledge And Memory need to run?

Going by SKILL.md and its folder, Ag2 Knowledge And Memory needs Python for the scripts in its folder. Our summary lists: Python 3.

Does Ag2 Knowledge And Memory access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Ag2 Knowledge And Memory safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Ag2 Knowledge And Memory use?

Ag2 Knowledge And Memory is published under the Apache-2.0 licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Ag2 Knowledge And Memory use?

About 2.9k tokens (SKILL.md is roughly 12k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Ag2 Knowledge And Memory?

Skills that share tags, products or a category with Ag2 Knowledge And Memory: Cognee Session Memory and Improve (topoteretes/cognee, 32k stars), Frontmcp Setup (agentfront/frontmcp, 146 stars), Add Memory Kind (EverMind-AI/EverOS, 13k stars) and Extend Commands API (redis/lettuce, 5.8k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Ag2 Knowledge And Memory?

ag2ai (a GitHub organization) maintains it in ag2ai/build-with-ag2, which has 252 GitHub stars. The repository holds 16 skills in this directory. The repository was last updated on September 6, 2026.

Source: ag2ai/build-with-ag2 on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.