会话
Agents SDK 提供了内置会话内存,可以自动维护多次代理运行之间的对话历史记录,无需手动处理 .to_input_list() 来进行轮次间的转换。
会话存储特定会话的对话历史记录,允许代理在无需显式手动内存管理的情况下保持上下文。这对于构建聊天应用程序或多轮对话特别有用,您希望代理记住之前的交互。
快速上手
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"
工作原理
启用会话内存时
- 每次运行前:运行器会自动检索会话的对话历史记录,并将其添加到输入项的前面。
- 每次运行后:在运行过程中生成的所有新项目(用户输入、助手回复、工具调用等)都会自动存储在会话中。
- 上下文保留:使用相同会话的每个后续运行都包含完整的对话历史记录,从而使代理能够保持上下文。
这消除了手动调用 .to_input_list() 以及在运行之间管理对话状态的需要。
内存操作
基本操作
会话支持几种管理对话历史记录的操作
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}")
会话类型
SDK 提供了几种会话实现,用于不同的用例
OpenAI Conversations API 会话
通过 OpenAIConversationsSession 使用 OpenAI 的 Conversations API。
from agents import Agent, Runner, OpenAIConversationsSession
# Create agent
agent = Agent(
name="Assistant",
instructions="Reply very concisely.",
)
# Create a new conversation
session = OpenAIConversationsSession()
# Optionally resume a previous conversation by passing a conversation ID
# session = OpenAIConversationsSession(conversation_id="conv_123")
# Start conversation
result = await Runner.run(
agent,
"What city is the Golden Gate Bridge in?",
session=session
)
print(result.final_output) # "San Francisco"
# Continue the conversation
result = await Runner.run(
agent,
"What state is it in?",
session=session
)
print(result.final_output) # "California"
SQLite 会话
默认的、轻量级的会话实现,使用 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
)
SQLAlchemy 会话
使用 SQLAlchemy 支持的任何数据库的生产就绪型会话
from agents.extensions.memory import SQLAlchemySession
# Using database URL
session = SQLAlchemySession.from_url(
"user_123",
url="postgresql+asyncpg://user:pass@localhost/db",
create_tables=True
)
# Using existing engine
from sqlalchemy.ext.asyncio import create_async_engine
engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db")
session = SQLAlchemySession("user_123", engine=engine, create_tables=True)
请参阅 SQLAlchemy 会话 以获取详细文档。
高级 SQLite 会话
具有对话分支、使用情况分析和结构化查询的增强型 SQLite 会话
from agents.extensions.memory import AdvancedSQLiteSession
# Create with advanced features
session = AdvancedSQLiteSession(
session_id="user_123",
db_path="conversations.db",
create_tables=True
)
# Automatic usage tracking
result = await Runner.run(agent, "Hello", session=session)
await session.store_run_usage(result) # Track token usage
# Conversation branching
await session.create_branch_from_turn(2) # Branch from turn 2
请参阅 高级 SQLite 会话 以获取详细文档。
加密会话
用于任何会话实现的透明加密包装器
from agents.extensions.memory import EncryptedSession, SQLAlchemySession
# Create underlying session
underlying_session = SQLAlchemySession.from_url(
"user_123",
url="sqlite+aiosqlite:///conversations.db",
create_tables=True
)
# Wrap with encryption and TTL
session = EncryptedSession(
session_id="user_123",
underlying_session=underlying_session,
encryption_key="your-secret-key",
ttl=600 # 10 minutes
)
result = await Runner.run(agent, "Hello", session=session)
请参阅 加密会话 以获取详细文档。
其他会话类型
还有一些其他的内置选项。请参阅 examples/memory/ 和 extensions/memory/ 下的源代码。
会话管理
会话 ID 命名
使用有意义的会话 ID 来帮助您组织对话
- 基于用户:
"user_12345" - 基于线程:
"thread_abc123" - 基于上下文:
"support_ticket_456"
内存持久化
- 使用内存中的 SQLite (
SQLiteSession("session_id")) 进行临时对话 - 使用基于文件的 SQLite (
SQLiteSession("session_id", "path/to/db.sqlite")) 进行持久对话 - 使用 SQLAlchemy 驱动的会话 (
SQLAlchemySession("session_id", engine=engine, create_tables=True)) 用于与 SQLAlchemy 支持的现有数据库的生产系统 - 使用 Dapr 状态存储会话 (
DaprSession.from_address("session_id", state_store_name="statestore", dapr_address="localhost:50001")) 用于支持 30 多个数据库后端、内置遥测、跟踪和数据隔离的生产云原生部署 - 当您希望将历史记录存储在 OpenAI Conversations API 中时,使用 OpenAI 托管存储 (
OpenAIConversationsSession()) - 使用加密会话 (
EncryptedSession(session_id, underlying_session, encryption_key)) 使用透明加密和基于 TTL 的过期时间来包装任何会话 - 考虑为其他生产系统(Redis、Django 等)实现自定义会话后端,以用于更高级的用例
多个会话
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,
"Help me with my account",
session=session_1
)
result2 = await Runner.run(
agent,
"What are my charges?",
session=session_2
)
会话共享
# 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
)
完整示例
这是一个完整的示例,展示了会话内存的作用
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())
自定义会话实现
您可以通过创建一个遵循 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")
)
社区会话实现
社区开发了额外的会话实现
| 包 | 描述 |
|---|---|
| openai-django-sessions | 基于 Django ORM 的会话,用于任何 Django 支持的数据库(PostgreSQL、MySQL、SQLite 等) |
如果您构建了一个会话实现,请随时提交文档 PR 以将其添加到此处!
API 参考
有关详细的 API 文档,请参阅
Session- 协议接口OpenAIConversationsSession- OpenAI Conversations API 实现SQLiteSession- 基本 SQLite 实现SQLAlchemySession- SQLAlchemy 驱动的实现DaprSession- Dapr 状态存储实现AdvancedSQLiteSession- 具有分支和分析的增强型 SQLiteEncryptedSession- 用于任何会话的加密包装器