Tape & Memory
If every request sent only the latest message to the model, an Agent could never continue a conversation. To remember what you said earlier, it needs to record the exchange and pass relevant history on the next turn. Bub uses a Tape to store messages, tool round-trips, and events so an Agent maintains memory across turns. For how the Tape relates to model context, see Tape and model context.
Multi-turn conversations
Section titled “Multi-turn conversations”To let the model continue a conversation and remember your preferences, reuse the same tape name across agent.run() calls:
import asyncioimport republicfrom bub.core import Agent
async def run_turn(agent: Agent, model, prompt: str) -> None: async with agent.run(prompt, model=model, tape="demo-user") as stream: async for event in stream: if event.kind == "text": print(event.data["delta"], end="", flush=True) print("\nDONE")
async def main() -> None: agent = Agent( system_prompt="You are a concise assistant. Remember the answer format the user asks for.", max_steps=6, )
async with republic.get_model("openai:gpt-5-mini") as model: await run_turn(agent, model, "From now on, answer with a short numbered list. Got it?") await run_turn(agent, model, "What answer format do I prefer?")
if __name__ == "__main__": asyncio.run(main())Agent defaults to InMemoryTapeStore, which lives only in the current Agent instance and process. Exiting the process or creating a new Agent per request loses in-memory history.
Persist to disk or a database
Section titled “Persist to disk or a database”To keep conversation history across process restarts, pass Bub’s built-in FileTapeStore to persist each Tape as a local .jsonl file:
from pathlib import Pathfrom bub.core import Agentfrom bub.core.store import FileTapeStore
agent = Agent( store=FileTapeStore(Path("sessions")), system_prompt="You are a concise assistant. Remember the answer format the user asks for.",)With this configuration, tape="demo-user" is saved to sessions/demo-user.jsonl.
Tape naming and isolation
Section titled “Tape naming and isolation”agent.run(..., tape="customer-42") selects a Tape by name: reusing a name continues its history, while a new name starts an isolated session. core.Agent adds no workspace or tenant prefix automatically.
Choosing a store
Section titled “Choosing a store”| Store | Lifetime | Best for |
|---|---|---|
InMemoryTapeStore (default) |
Current Agent instance and process |
Tests and one-off scripts |
FileTapeStore |
One .jsonl file per Tape |
Local CLIs, development, and single-node services |
Custom TapeStore / AsyncTapeStore |
Defined by the backend | Production SQL databases, Redis, or distributed stores |
Inspect history outside a Run
Section titled “Inspect history outside a Run”Use agent.tape(name) to read either the selected model messages or the raw Tape entries:
async def inspect_history(agent: Agent) -> None: tape = agent.tape("customer-42") messages = await tape.read_messages() # Model messages built via TapeContext entries = list(await tape.query().all()) # Raw stored TapeEntry items print(f"model messages: {len(messages)}, raw entries: {len(entries)}")Customize TapeContext
Section titled “Customize TapeContext”Every Agent is bound to a context (default_tape_context() by default):
from bub.core import Agent, default_tape_context
agent = Agent( context=default_tape_context(),)TapeContext fields
Section titled “TapeContext fields”| Field | Default | Purpose |
|---|---|---|
anchor |
LAST_ANCHOR |
Read start point: entries after the latest anchor (LAST_ANCHOR), after a named anchor string, or None for all entries |
select |
None |
Custom selector function converting Tape entries into model messages (None uses the built-in selector) |
state |
{} |
Request-scoped state dictionary (shared with agent.run(state=...) and ToolContext.state) |
Choose a different start anchor
Section titled “Choose a different start anchor”anchor value |
Entries read |
|---|---|
LAST_ANCHOR (default) |
Entries after the most recent anchor |
"order-reviewed" |
Entries after the anchor named "order-reviewed" |
None |
All entries from the beginning of the Tape |
Custom selectors (select)
Section titled “Custom selectors (select)”Pass a selector function to TapeContext(select=...) to include custom business events (kind="event") in model messages:
from collections.abc import Iterableimport republicfrom bub.core import Agent, TapeContext, default_tape_contextfrom bub.core.tape import TapeEntry, build_messages
def with_order_notes( entries: Iterable[TapeEntry], _context: TapeContext) -> list[republic.Message]: """Append order notes as a system reminder on top of the default messages.""" entries = list(entries) messages = build_messages(entries, default_tape_context()) notes = [ entry.payload.get("data", {}) for entry in entries if entry.kind == "event" and entry.payload.get("name") == "order.note" ] if notes: messages.append(republic.system(f"Known order notes: {notes}")) return messages
agent = Agent(context=TapeContext(anchor=None, select=with_order_notes))Two common gotchas to watch out for when writing a custom selector:
- Materialize
entrieswithlist(entries)first:entriesis anIterablethat may be a single-pass generator. - Pass a fresh
default_tape_context()tobuild_messages(): never pass_context(which holds your customselect) back intobuild_messages(), or it will recurse infinitely.
A custom selector replaces the default selector; entries written with context=False are filtered out before your selector runs.
Switch context for a single read
Section titled “Switch context for a single read”If you want a different view for a single read without changing the Agent’s default context (for example, bypassing the anchor to inspect the full conversation), use tape.with_context(...):
from dataclasses import replacefrom bub.core import default_tape_context
tape = agent.tape("demo-user")full_messages = await tape.with_context( replace(default_tape_context(), anchor=None)).read_messages()Anchors and handoffs
Section titled “Anchors and handoffs”For the concepts behind anchors and handoffs, see Moving the context start with anchors and handoffs. Two initialization rules apply in code:
- Starting a session via
agent.run(),agent.start(), oragent.session()writes an initialsession/startanchor automatically if the Tape has no anchors yet. - Calling
agent.tape(name)does not write an anchor. Reading a blank Tape that has no anchors with the defaultLAST_ANCHORraisesBubError [not_found](No anchors found in tape). Run once, callhandoff(), or read withanchor=None.
Perform a manual handoff
Section titled “Perform a manual handoff”Write an anchor at phase transitions to advance the default context start:
tape = agent.tape("demo-user")
await tape.handoff( name="order-reviewed", state={"summary": "Order A123 has been reviewed and approved."},)After the handoff, tape.read_messages() reads only entries after order-reviewed, while earlier history remains available via anchors() and query():
anchors = await tape.anchors()history = list(await tape.query().all())Common anchor patterns
Section titled “Common anchor patterns”| Scenario | Approach |
|---|---|
| Phase transition (e.g., shipping check to after-sales) | Call await tape.handoff(name="after-shipping") |
| Resume context from a specific checkpoint | Configure replace(default_tape_context(), anchor="checkpoint-name") |
| Read full unfiltered history | Configure replace(default_tape_context(), anchor=None) |
| Automatic recovery on context overflow | On a model context-length error, the Agent writes auto_handoff/context_overflow and retries once |
| Proactive compaction by token budget | Attach the bub-context-budget plugin and provide the tape.handoff tool |
Sidecars: keep large payloads out of main context
Section titled “Sidecars: keep large payloads out of main context”Sometimes you need to store large companion data alongside a session—such as ten-thousand-line command output or scraped web pages—without filling up the main conversation’s model context. Bub provides TapeSidecar for this: mounted beside the main Tape via Agent(sidecars=...), it forks, merges, and resets with the main Tape, while keeping its entries out of the main model context.
For example, the Bub app uses a spill sidecar for large tool outputs: when a tool result exceeds BUB_SPILL_THRESHOLD, the full output is written to the spill sidecar while the main conversation keeps only a short preview and a handle for spill.read (see Built-in tools). Plugins can register custom sidecars via provide_tape_sidecar.
Multimodal media storage boundaries
Section titled “Multimodal media storage boundaries”The Tape is designed for text and event records, not raw media storage:
- User-supplied media is stripped before writing to the Tape: when recording a user prompt, Bub strips non-text blocks and writes only plain text so large Base64 payloads do not bloat session storage. To audit or replay user media, save files to object storage or disk in your host code and record a path or URL reference in text or an event.
- Tool-returned media can be passed to the model: tools can use
content_result()to return text together with images, audio, or video (asfs.readdoes for image files). These are recorded intool_resultand reconstructed into multimodal content blocks byresult_content().
Combine temporary state with persistent events
Section titled “Combine temporary state with persistent events”Here is how a tool can combine request-scoped state (such as request_id) with a persistent business event on the Tape:
from bub.core.tools import ToolContext, tool
@tool(context=True)async def add_order_note(note: str, *, context: ToolContext) -> str: """Append an order note to the current session.""" await context.tape.append_event( "order.note", {"text": note, "request_id": context.state.get("request_id")}, ) return "Note recorded."As a reminder, custom business events written via append_event() are persisted on the Tape but do not enter the model context automatically—pair them with a custom selector if you want the model to see them. For a comparison of data lifetimes, see Where data belongs.
Tape forks and merge_back
Section titled “Tape forks and merge_back”By default agent.run() writes each entry straight to the Tape, as it is recorded. That is enough while Runs on a Tape take turns. When Runs on the same Tape overlap, pass a fork_key to each so they do not read each other’s unfinished work:
async with agent.run( prompt, model=model, tape="support-42", fork_key="thread-7",) as stream: async for event in stream: ...A Run with a fork_key works on a temporary Tape fork of the main Tape. The fork keeps the Run’s entries in memory as written, and copies each one to the main Tape as soon as it is appended. Until the Run ends, forks with a different key do not read those copies. In a Bub app, a turn gets its fork_key from the inbound message’s context["thread_id"]; messages without one write to the session’s Tape directly.
Two details follow from this:
- Records reach the main Tape during the Run, not when it succeeds, with or without a fork. If a Run fails partway, is cancelled, or the process is killed, the steps already recorded stay on the main Tape. Should the process die between a tool call and its result, the default context answers that call with an “interrupted” error result on the next Run.
- A fork’s copy on the main Tape holds only the text parts of a message. Images and other media stay in the fork, where the Run’s later steps still read them. Each copy carries the
fork_keyinmeta["fork_id"]. A Run without a fork records messages whole, media included.
A copy that fails to write does not stop the Run: the fork retries it, in order, with the next entry and once more when the stream closes, where a failure on the main Tape is raised.
To discard a Run’s records on exit (e.g., for dry runs or previews), pass merge_back=False. The Run then works on a fork that never writes to the main Tape:
async with agent.run( prompt, model=model, tape="preview-demo", merge_back=False,) as stream: async for event in stream: ...You can also control fork scope explicitly with agent.session(name, merge_back=..., fork_key=...) or tape.fork_tape(merge_back=..., key=...).
Same-session concurrency and locking
Section titled “Same-session concurrency and locking”If two concurrent requests call agent.run() with the same Tape name, each writes its entries to the main Tape as it goes, so their records interleave there. A Run does not read the entries of another Run in the same process until that Run’s stream closes; the default context then keeps each tool result next to its call. core.Agent does not queue same-session requests automatically.
In a web service where requests in the same session depend on prior turns, serialize requests per session_id with a lock. FileTapeStore includes only a per-file thread lock within one process; see the FastAPI capstone for an in-process session lock example.