Skip to content

Sessions

Agents SDK 提供內建的 session 記憶,可自動在多次代理運行之間維護對話歷史,無需手動處理 .to_input_list() 於每個回合之間。

Sessions 會針對特定 session 儲存對話歷史,讓代理能夠維持上下文,而不需要顯式地進行手動記憶管理。這對於建立聊天應用程式或多回合對話特別有用,因為你希望代理能記住先前的互動內容。

快速開始

from agents import Agent, Runner, SQLiteSession

# Create agent
agent = Agent(
    name="Assistant",
    instructions="Reply very concisely.",
)

# Create a session instance with a session ID
session = SQLiteSession("conversation_123")

# First turn
result = await Runner.run(
    agent,
    "What city is the Golden Gate Bridge in?",
    session=session
)
print(result.final_output)  # "San Francisco"

# Second turn - agent automatically remembers previous context
result = await Runner.run(
    agent,
    "What state is it in?",
    session=session
)
print(result.final_output)  # "California"

# Also works with synchronous runner
result = Runner.run_sync(
    agent,
    "What's the population?",
    session=session
)
print(result.final_output)  # "Approximately 39 million"

運作方式

當啟用 session 記憶時:

  1. 每次執行前:runner 會自動擷取該 session 的對話歷史,並將其加到輸入項目前方。
  2. 每次執行後:執行期間產生的所有新項目(使用者輸入、助理回應、工具呼叫等)都會自動儲存到 session 中。
  3. 上下文保留:每次以相同 session 執行時,皆會包含完整的對話歷史,讓代理能夠維持上下文。

這樣即可省去手動呼叫 .to_input_list() 及在多次執行間自行管理對話狀態的需求。

記憶操作

基本操作

Sessions 支援多種操作來管理對話歷史:

from agents import SQLiteSession

session = SQLiteSession("user_123", "conversations.db")

# Get all items in a session
items = await session.get_items()

# Add new items to a session
new_items = [
    {"role": "user", "content": "Hello"},
    {"role": "assistant", "content": "Hi there!"}
]
await session.add_items(new_items)

# Remove and return the most recent item
last_item = await session.pop_item()
print(last_item)  # {"role": "assistant", "content": "Hi there!"}

# Clear all items from a session
await session.clear_session()

使用 pop_item 進行修正

pop_item 方法在你想要撤銷或修改對話中最後一個項目時特別有用:

from agents import Agent, Runner, SQLiteSession

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

# Initial conversation
result = await Runner.run(
    agent,
    "What's 2 + 2?",
    session=session
)
print(f"Agent: {result.final_output}")

# User wants to correct their question
assistant_item = await session.pop_item()  # Remove agent's response
user_item = await session.pop_item()  # Remove user's question

# Ask a corrected question
result = await Runner.run(
    agent,
    "What's 2 + 3?",
    session=session
)
print(f"Agent: {result.final_output}")

記憶選項

無記憶(預設)

# Default behavior - no session memory
result = await Runner.run(agent, "Hello")

OpenAI Conversations API 記憶

使用 OpenAI Conversations API 來持久化對話狀態,無需自行管理資料庫。當你已經依賴 OpenAI 所託管的基礎設施來儲存對話歷史時,這會特別有幫助。

from agents import OpenAIConversationsSession

session = OpenAIConversationsSession()

# Optionally resume a previous conversation by passing a conversation ID
# session = OpenAIConversationsSession(conversation_id="conv_123")

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

SQLite 記憶

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
)

多重工作階段 (Multiple sessions)

from agents import Agent, Runner, SQLiteSession

agent = Agent(name="Assistant")

# Different sessions maintain separate conversation histories
session_1 = SQLiteSession("user_123", "conversations.db")
session_2 = SQLiteSession("user_456", "conversations.db")

result1 = await Runner.run(
    agent,
    "Hello",
    session=session_1
)
result2 = await Runner.run(
    agent,
    "Hello",
    session=session_2
)

由 SQLAlchemy 驅動的 sessions

對於更進階的使用情境,你可以使用由 SQLAlchemy 驅動的 session 後端。這讓你能夠使用任何 SQLAlchemy 支援的資料庫(如 PostgreSQL、MySQL、SQLite 等)來儲存 session。

範例 1:使用 from_url 搭配記憶內的 SQLite

這是最簡單的入門方式,非常適合開發與測試用途。

import asyncio
from agents import Agent, Runner
from agents.extensions.memory.sqlalchemy_session import SQLAlchemySession

async def main():
    agent = Agent("Assistant")
    session = SQLAlchemySession.from_url(
        "user-123",
        url="sqlite+aiosqlite:///:memory:",
        create_tables=True,  # Auto-create tables for the demo
    )

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

if __name__ == "__main__":
    asyncio.run(main())

範例 2:使用現有的 SQLAlchemy AsyncEngine

在正式環境的應用程式中,你很可能已經有一個 SQLAlchemy AsyncEngine 實例。你可以直接將它傳遞給 session 使用。

import asyncio
from agents import Agent, Runner
from agents.extensions.memory.sqlalchemy_session import SQLAlchemySession
from sqlalchemy.ext.asyncio import create_async_engine

async def main():
    # In your application, you would use your existing engine
    engine = create_async_engine("sqlite+aiosqlite:///conversations.db")

    agent = Agent("Assistant")
    session = SQLAlchemySession(
        "user-456",
        engine=engine,
        create_tables=True,  # Auto-create tables for the demo
    )

    result = await Runner.run(agent, "Hello", session=session)
    print(result.final_output)

    await engine.dispose()

if __name__ == "__main__":
    asyncio.run(main())

自訂記憶實作

你可以透過建立一個遵循 [Session][agents.memory.session.Session] 協定的類別,來實作你自己的 session 記憶:

from agents.memory.session import SessionABC
from agents.items import TResponseInputItem
from typing import List

class MyCustomSession(SessionABC):
    """Custom session implementation following the Session protocol."""

    def __init__(self, session_id: str):
        self.session_id = session_id
        # Your initialization here

    async def get_items(self, limit: int | None = None) -> List[TResponseInputItem]:
        """Retrieve conversation history for this session."""
        # Your implementation here
        pass

    async def add_items(self, items: List[TResponseInputItem]) -> None:
        """Store new items for this session."""
        # Your implementation here
        pass

    async def pop_item(self) -> TResponseInputItem | None:
        """Remove and return the most recent item from this session."""
        # Your implementation here
        pass

    async def clear_session(self) -> None:
        """Clear all items for this session."""
        # Your implementation here
        pass

# Use your custom session
agent = Agent(name="Assistant")
result = await Runner.run(
    agent,
    "Hello",
    session=MyCustomSession("my_session")
)

工作階段管理

工作階段 ID 命名

請使用有意義的工作階段 ID,以便於組織對話:

  • 以使用者為基礎:"user_12345"
  • 以討論串為基礎:"thread_abc123"
  • 以情境為基礎:"support_ticket_456"

記憶持久化

  • 對於暫時性的對話,請使用記憶內的 SQLite(SQLiteSession("session_id")
  • 對於需持久保存的對話,請使用檔案型 SQLite(SQLiteSession("session_id", "path/to/db.sqlite")
  • 若為已經有 SQLAlchemy 支援的資料庫之正式環境,請使用 SQLAlchemy 驅動的工作階段(SQLAlchemySession("session_id", engine=engine, create_tables=True)
  • 若希望將歷史記錄儲存於 OpenAI Conversations API,請使用 OpenAI 託管的儲存空間(OpenAIConversationsSession()
  • 若有更進階的需求,可考慮為其他正式環境(如 Redis、Django 等)實作自訂的工作階段後端

工作階段管理

# Clear a session when conversation should start fresh
await session.clear_session()

# Different agents can share the same session
support_agent = Agent(name="Support")
billing_agent = Agent(name="Billing")
session = SQLiteSession("user_123")

# Both agents will see the same conversation history
result1 = await Runner.run(
    support_agent,
    "Help me with my account",
    session=session
)
result2 = await Runner.run(
    billing_agent,
    "What are my charges?",
    session=session
)

完整範例

以下是一個完整範例,展示 session 記憶的實際運作方式:

import asyncio
from agents import Agent, Runner, SQLiteSession


async def main():
    # Create an agent
    agent = Agent(
        name="Assistant",
        instructions="Reply very concisely.",
    )

    # Create a session instance that will persist across runs
    session = SQLiteSession("conversation_123", "conversation_history.db")

    print("=== Sessions Example ===")
    print("The agent will remember previous messages automatically.\n")

    # First turn
    print("First turn:")
    print("User: What city is the Golden Gate Bridge in?")
    result = await Runner.run(
        agent,
        "What city is the Golden Gate Bridge in?",
        session=session
    )
    print(f"Assistant: {result.final_output}")
    print()

    # Second turn - the agent will remember the previous conversation
    print("Second turn:")
    print("User: What state is it in?")
    result = await Runner.run(
        agent,
        "What state is it in?",
        session=session
    )
    print(f"Assistant: {result.final_output}")
    print()

    # Third turn - continuing the conversation
    print("Third turn:")
    print("User: What's the population of that state?")
    result = await Runner.run(
        agent,
        "What's the population of that state?",
        session=session
    )
    print(f"Assistant: {result.final_output}")
    print()

    print("=== Conversation Complete ===")
    print("Notice how the agent remembered the context from previous turns!")
    print("Sessions automatically handles conversation history.")


if __name__ == "__main__":
    asyncio.run(main())

API 參考

如需詳細的 API 文件,請參閱:

  • [Session][agents.memory.Session] - 協定介面
  • [SQLiteSession][agents.memory.SQLiteSession] - SQLite 實作
  • OpenAIConversationsSession - OpenAI Conversations API 實作
  • [SQLAlchemySession][agents.extensions.memory.sqlalchemy_session.SQLAlchemySession] - 基於 SQLAlchemy 的實作