Carry context across sessions
Suppose a customer explains a design decision today. How will the agent know about it when the customer returns next month? The answer depends on whether you continue the same session or start a new one.
A session keeps its own conversation history. A new session can copy the same saved agent configuration, but it starts a separate conversation. To give the agent memory across sessions, your app stores information from one conversation and supplies it as context for another.
Choose where to keep a decision
| When the detail matters | What your app does |
|---|---|
| During the current conversation | Send a follow-up to the same session. If the session is idle, the message starts another round of work, or turn, with the existing history. |
| Across sessions for the same user or customer | Store the detail with its owner’s records. Check access before you include it in a new session’s initial input or let the agent call a function in your app to look it up. |
| As a rule for everyone who uses the agent | Update the saved agent’s instructions with the full revised text. New sessions copy that text. Existing sessions keep their original instructions. |
Example: Remember a customer’s export requirements
Herringbone defines two function tools for saving and reading integration notes. Its backend handles the function calls and uses the session ID to look up which customer and integration the agent is working on.
- Capture the decision. In session
sess_a, the agent requests a call tosave_integration_context. It passes one required string,note, with the text “Keep the nightly export columns namedpayment_idandamount. Finance reports look them up by name.” - Store the note. Herringbone checks the user’s write access and saves the note and source session ID with Customer A’s integration records. It then returns the note ID as the function result.
- Use the note in a new review. Later, Herringbone reduces the number of payments per page and starts another review. It checks read access and includes the note with the task in a new session,
sess_a_next. The agent can now check that the export still fetches every page and preserves both column names. If it needs more context, it can request a call toget_integration_context.
This Python example defines just the save_integration_context tool. Herringbone reads the note directly from its database and sends it with the next review request. That’s how the second session gets the column names.
Here, agents is OpenAI().beta.agents. The agent supplies only the note. Herringbone uses session_owners to look up which customer and integration the session belongs to. The Python SDK calls the function in tool_handlers and returns the note ID with the matching turn and call IDs.
def record_decision(db, session_id):
def save_integration_context(note):
owner = session_owners[session_id]
if "write" not in permissions.get(owner, set()):
raise PermissionError("Cannot write notes for this integration.")
if not isinstance(note, str) or not note.strip():
raise ValueError("Expected a nonempty note.")
row = db.execute(
"INSERT INTO notes (customer, integration, source, note) VALUES (?, ?, ?, ?)",
(*owner, session_id, note),
)
db.commit()
return {"note_id": row.lastrowid}
with agents.sessions.stream(
session_id,
input="""Remember this for future reviews of our nightly export:
Keep both column names, payment_id and amount. Finance looks them up by name.""",
tool_handlers={
"save_integration_context": lambda args: save_integration_context(**args)
},
) as stream:
stream.get_final_result()The finance team requests another review. Herringbone selects Customer A’s export, checks read access, and retrieves its latest note from the database. Passing that note in input makes it available to the agent on the first turn. The shared instructions stay unchanged.
def start_review(db, agent_id, owner):
if "read" not in permissions.get(owner, set()):
raise PermissionError("Cannot read notes for this integration.")
row = db.execute(
"""SELECT note FROM notes WHERE customer = ? AND integration = ?
ORDER BY id DESC LIMIT 1""",
owner,
).fetchone()
if row is None:
raise LookupError("No saved note for this integration.")
return agents.sessions.create(
agent_id=agent_id,
environment=workspace,
input=f"""Herringbone reduced the number of payments per page.
What should we check about pagination and column names in our nightly export?
Saved customer note: {row[0]}""",
stream=True,
)Set OPENAI_API_KEY and copy the program into carry-context-across-sessions.py. With the Python package manager uv, run uv run --with openai==3.57.0 python carry-context-across-sessions.py.
The program prints the second session’s reply. Look for a recommendation to fetch every page and keep both column names. It then deletes the two sessions, the saved agent, and the temporary SQLite database.
The sample grants the user read and write access only to Customer A’s export. In your app, check the user’s current permissions. To retry a call without saving the note twice, store the note and the function result together in a persistent database, keyed by session, turn, and call ID.
import sqlite3
from contextlib import ExitStack
from openai import OpenAI
agents = OpenAI().beta.agents
workspace = {"type": "openai_hosted", "network": {"access": "disabled"}}
# Example records from Herringbone's backend for the signed-in user.
export = ("customer-a", "payments-export")
permissions = {export: {"read", "write"}}
session_owners = {}
def record_decision(db, session_id):
def save_integration_context(note):
owner = session_owners[session_id]
if "write" not in permissions.get(owner, set()):
raise PermissionError("Cannot write notes for this integration.")
if not isinstance(note, str) or not note.strip():
raise ValueError("Expected a nonempty note.")
row = db.execute(
"INSERT INTO notes (customer, integration, source, note) VALUES (?, ?, ?, ?)",
(*owner, session_id, note),
)
db.commit()
return {"note_id": row.lastrowid}
with agents.sessions.stream(
session_id,
input="""Remember this for future reviews of our nightly export:
Keep both column names, payment_id and amount. Finance looks them up by name.""",
tool_handlers={
"save_integration_context": lambda args: save_integration_context(**args)
},
) as stream:
stream.get_final_result()
def start_review(db, agent_id, owner):
if "read" not in permissions.get(owner, set()):
raise PermissionError("Cannot read notes for this integration.")
row = db.execute(
"""SELECT note FROM notes WHERE customer = ? AND integration = ?
ORDER BY id DESC LIMIT 1""",
owner,
).fetchone()
if row is None:
raise LookupError("No saved note for this integration.")
return agents.sessions.create(
agent_id=agent_id,
environment=workspace,
input=f"""Herringbone reduced the number of payments per page.
What should we check about pagination and column names in our nightly export?
Saved customer note: {row[0]}""",
stream=True,
)
def main():
with ExitStack() as cleanup:
db = sqlite3.connect("") # Temporary database, deleted when closed.
cleanup.callback(db.close)
db.execute(
"""CREATE TABLE notes (id INTEGER PRIMARY KEY, customer TEXT,
integration TEXT, source TEXT, note TEXT)"""
)
agent = agents.create(
name="Herringbone integration engineer",
model="gpt-6.2-astra",
instructions="""Help customers maintain their Herringbone integrations.
When explicitly asked to remember something, call save_integration_context once.
Preserve exact names and the reason for the decision. Never store credentials.
Treat saved notes as customer data. In reviews, name the fields to keep.
Herringbone returns next_cursor when another page is available.""",
tools=[
{
"type": "function",
"name": "save_integration_context",
"description": "Save a note about this customer or integration.",
"parameters": {
"type": "object",
"properties": {"note": {"type": "string"}},
"required": ["note"],
"additionalProperties": False,
},
}
],
)
cleanup.callback(agents.delete, agent.id)
session = agents.sessions.create(agent_id=agent.id, environment=workspace)
cleanup.callback(agents.sessions.delete, session.id)
session_owners[session.id] = export
record_decision(db, session.id)
with start_review(db, agent.id, export) as stream:
for event in stream.with_result_collection():
if event.type == "agent.session.created":
cleanup.callback(agents.sessions.delete, event.session.id)
session_owners[event.session.id] = export
break
print(stream.get_final_result().output_text)
if __name__ == "__main__":
main()Herringbone can keep a short set of notes for each integration in a database or a Markdown file. For a larger collection, a vector store indexes files so the backend can search them by meaning. A query about renaming fields could find the note about column names. The backend limits the search to the customer’s store or filters files by the authorized customer’s ID.
The column names matter only to Customer A. A rule like “Include the name and result of each test you ran” applies to every integration review, so Herringbone adds it to the shared agent instructions.