All Agent Engineering

OpenAI Agents SDK: manage multi-turn history with SQLiteSession

Carry history across turns with SQLiteSession, keep it apart from server-side continuation options, and check storage, pruning and cleanup.

AINavWritten / Updated
On this page

At a glance

This entry follows the Sessions page of the OpenAI Agents SDK documentation. It covers how a client-side SQLiteSession carries history between runs, where that history is stored, and how session_input_callback changes what the model sees. All product behavior comes from that page, while the checks, stopping rules and cleanup steps are editorial recommendations, not official behavior.

Runtime and applicability

Article type
Engineering practice
Verified
Applies to
  • OpenAI Agents SDK Documented openai_agents_sdk task and conditions

Execution locations and responsibilities

  • Python application definition and caller Define the configuration or request shown here and check its inputs, outputs and failure branches.

When to use

  • A Python application that already imports Agent and Runner from agents and runs inside an async function or another async context, because the excerpts use top-level await. The source also shows Runner.run_sync(...), but the supplied excerpts do not use it.

When not to use

  • The source states the SQLite trust boundary explicitly: a session ID does not authenticate a user, and the application must authorize access and protect the database file and its backups.

Prepare the input and environment

  • A Python application that already imports Agent and Runner from agents and runs inside an async function or another async context, because the excerpts use top-level await. The source also shows Runner.run_sync(...), but the supplied excerpts do not use it.
  • Editorial recommendation: confirm that the application has a usable model configuration, then check credentials and network needs for that actual model and runtime. The Sessions page does not specify these settings; a model credential is not assumed to be an unconditional requirement for every runtime.
  • A decision on whether history is client-side (a session) or server-managed (conversation_id, previous_response_id, auto_previous_response_id). In one run, a session cannot be combined with those three options.
  • For a file-backed session, a writable path for the database file, such as conversations.db, with access limited to your application.

Mechanism and data flow

Client-side memory and its exclusive options:A session lets the SDK manage conversation memory on the client side. Before each run, the runner retrieves the stored history for that session and prepends it to the input items. After the run, the new items from that run, such as user input, assistant responses and tool calls, are stored in the session. A session cannot be combined in the same run with conversation_id, previous_response_id or auto_previous_response_id. If you want OpenAI server-managed continuation, pick one of those options and leave the session out.

SQLite storage: memory or file:SQLiteSession takes a session ID as its first argument. With only that ID, as in SQLiteSession("user_123"), the database lives in memory and is lost when the process ends. With a second argument, as in SQLiteSession("user_123", "conversations.db"), the database is file-based and persistent. The source calls this class the default lightweight implementation, suited to local development and simple apps. It does not say an in-memory session survives a restart, so the one-argument form should not be read as automatic cross-process persistence.

Controlling what the model sees:By default the model input is the session history from session.get_items(...) followed by the new turn input. RunConfig.session_input_callback replaces that merge step. It receives history and new_input as copies, so mutating them is safe, and what it returns is the list sent to the model. The SDK still persists only items that belong to the new turn, so pruning or reordering old history changes the model input without deleting stored items or saving old ones again as new input. The source also describes SessionSettings(limit=N) through RunConfig.session_settings, which limits how many recent items are fetched before the run; no excerpt for it is supplied here.

Trust boundary of the SQLite file:SQLiteSession assumes the application trusts the database and its storage. It does not authenticate stored rows or detect outside edits, deletions, reordering or replay. A session ID selects a history; it does not authenticate a user or authorize access. get_items() selects rows by session_id, orders them by insertion ID and decodes each row's message_data as JSON, so direct database changes can reach the next run, and rows that fail to decode are skipped without an integrity error. Your application has to authorize each session and restrict access to the file, its storage and backups.

Workflow map

Workflow stages and responsibilities
StageWhat happens
Client-side memory and its exclusive optionsA session lets the SDK manage conversation memory on the client side.
SQLite storage: memory or fileSQLiteSession takes a session ID as its first argument.
Controlling what the model seesBy default the model input is the session history from session.get_items(...) followed by the new turn input.
Trust boundary of the SQLite fileSQLiteSession assumes the application trusts the database and its storage.

Complete the task

Choose the continuation mechanism:Decide first whether the Agent will use a client-side session or an OpenAI server-managed option. If you choose SQLiteSession, remove conversation_id, previous_response_id and auto_previous_response_id from the same run, since the source says they cannot be combined. Record the choice so that later changes do not layer one mechanism on top of the other.

Prepare the runtime and credentials:Check that the runtime can execute the excerpts. Both supplied excerpts use top-level await, so place them inside an async function of your application. The callback excerpt defines agent itself and imports what it needs. The storage excerpt imports only SQLiteSession and then uses Runner and agent without defining them, so your own code must supply both. The source page does not describe credential configuration; follow the official SDK documentation, and as an editorial precaution keep keys out of source files.

Pick the storage form and session ID:For a throwaway conversation, SQLiteSession("user_123") keeps history in memory only. For a conversation you want to continue later, pass a database path as the second argument, as in SQLiteSession("user_123", "conversations.db"). Choose session IDs that organize conversations; the source lists user-based, thread-based and context-based names. Because the ID does not authenticate anyone, your application must decide who may use it.

Run a turn and read the result:Call Runner.run(agent, "Hello", session=session) as the storage excerpt does. The source reports that the runner prepends stored history before the run and stores the new items afterward. The excerpt only assigns the return value to result, so decide in your own code how to read it; the source's quick start reads result.final_output. A run that returns without an exception meets only one condition for success, and the answer still needs checking.

Add the history callback if needed:When a long history should not all reach the model, use the callback excerpt. keep_recent_history(history, new_input) returns history[-10:] + new_input, so the model gets the last 10 history items plus the new turn, and it is passed through RunConfig(session_input_callback=keep_recent_history). Note that this excerpt creates SQLiteSession("conversation_123") with one argument, so its history is in memory; change it to include a file path yourself if you need persistence, and treat that combination as editor composition, not an official excerpt. Pruning does not delete stored items.

Resume with the same session ID and backend:To continue a conversation, reuse the same session instance, or create another instance with the same session ID and the same underlying storage. The source gives this rule when describing how to resume a run that paused for approval, and says the resumed turn then continues the same stored history. For the SQLite forms shown, that points to the same database file as well as the same ID; per the source, an in-memory history is lost when the process ends and cannot be reopened.

Apply the completion checks and stop rules:These completion checks are editorial recommendations, not official behavior. Success: the run returns, the output is non-empty, and the answer to the new turn uses earlier context. Failure: any exception, a missing original database when resuming existing history, or an unreadable database, or output that ignores earlier context. Empty output: record it as a failed check, not as success. User stopping: if the person running the check interrupts it, record the check as not completed. This page documents no cancellation API, so use your own application's controls. On the first creation of a file-based session, the database need not already exist; a missing original file is a failure check only when you expect to resume existing history.

Clean up on every exit path:Clean up after success, failure, empty output and user stop alike. If you created a credential for this check, remove it from the shell environment or secrets store. After confirming the path is your own, delete any conversations.db or similar file you created for the check, because it holds conversation content. The source documents clear_session() to clear all items from a session and pop_item() to remove the most recent item. Close any resources your own application opened.

Worked example

Take the source's callback excerpt. The Agent is named Assistant, the session ID is conversation_123, and the run sends Continue from the latest updates only. with keep_recent_history, so the model receives at most the last 10 history items followed by that new message. The stored history does not get shorter. As written, the session is in memory, so everything is gone when the process ends. To keep the history, a reader could adapt the session line to the two-argument form from the storage excerpt with a conversations.db path; that adaptation is an editorial suggestion and was not run. Neither excerpt was executed in this batch, so no output is reported here.

Example: Official documentation excerpt: read under the stated prerequisites; not run in this batch
python
from agents import Agent, RunConfig, Runner, SQLiteSession


def keep_recent_history(history, new_input):
    # Keep only the last 10 history items, then append the new turn.
    return history[-10:] + new_input


agent = Agent(name="Assistant")
session = SQLiteSession("conversation_123")

result = await Runner.run(
    agent,
    "Continue from the latest updates only.",
    session=session,
    run_config=RunConfig(session_input_callback=keep_recent_history),
)
Example: Official documentation excerpt: read under the stated prerequisites; not run in this batch
python
from agents import SQLiteSession

# In-memory database (lost when process ends)
session = SQLiteSession("user_123")

# Persistent file-based database
session = SQLiteSession("user_123", "conversations.db")

# Use the session
result = await Runner.run(agent, "Hello", session=session)

Check the result and failure paths

  • Static check (editorial recommendation): confirm the run uses session and does not also pass conversation_id, previous_response_id or auto_previous_response_id.
  • Static check (editorial recommendation): confirm the code sits in an async context and that agent and Runner are defined or imported.
  • Semantic check (editorial recommendation): after a second turn, confirm the answer depends on earlier context; if you used the callback, also confirm that the dropped older items are still returned by get_items(). The code alone does not prove semantic correctness.
  • Failure, empty output and stop check (editorial recommendation): an exception, empty output or a user stop is never recorded as success, and cleanup still runs.
  • Cleanup check (editorial recommendation): confirm temporary credentials are removed and that any database file created for the check has been handled.

Scope and limits

  • Neither code excerpt is a complete standalone program. They need an async environment for top-level await, and the storage excerpt also lacks agent and Runner. The source gives no credential setup, base-package install command, version support or pricing, and this entry infers none.
  • This entry does not claim any cancellation API; the stopping rules are editorial recommendations.

No product or API was called, installed or run in this batch. This entry only restates the s1 documentation; no outputs, versions, pricing or login state were observed, and the completion checks and stopping rules are editorial recommendations.

Sources

All links are official pages; verification dates are listed per source, and links point to the version checked.

  1. OpenAI · Sessions
    91fb508

Found an error? Tell us →