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”Each agent.run() does not write directly to the main Tape; instead, it creates a temporary Tape fork for the Run and merges it back into the main Tape when the stream closes:
One important detail: merging happens when the stream closes, not only when the task succeeds. Even if a Run fails partway, is cancelled, or exits early, steps already recorded on the fork still merge into the main Tape by default.
To discard a Run’s records on exit (e.g., for dry runs or previews), pass merge_back=False:
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=...) or tape.fork_tape(merge_back=...).
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 forks from the history visible at start and merges back on close. 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.