Movatterモバイル変換


[0]ホーム

URL:


跳转至

加密会话

EncryptedSession 为任意会话实现提供透明加密,通过自动过期机制保护会话数据中已过期的条目。

特性

  • 透明加密: 使用 Fernet 加密封装任意会话
  • 会话级密钥: 使用 HKDF 密钥派生为每个会话生成唯一加密密钥
  • 自动过期: 达到 TTL 的旧条目在读取时会被静默跳过
  • 即插即用: 适用于任何现有的会话实现

安装

加密会话需要安装encrypt extra:

pipinstallopenai-agents[encrypt]

快速开始

importasynciofromagentsimportAgent,Runnerfromagents.extensions.memoryimportEncryptedSession,SQLAlchemySessionasyncdefmain():agent=Agent("Assistant")# Create underlying sessionunderlying_session=SQLAlchemySession.from_url("user-123",url="sqlite+aiosqlite:///:memory:",create_tables=True)# Wrap with encryptionsession=EncryptedSession(session_id="user-123",underlying_session=underlying_session,encryption_key="your-secret-key-here",ttl=600# 10 minutes)result=awaitRunner.run(agent,"Hello",session=session)print(result.final_output)if__name__=="__main__":asyncio.run(main())

配置

加密密钥

加密密钥可以是 Fernet 密钥或任意字符串:

fromagents.extensions.memoryimportEncryptedSession# Using a Fernet key (base64-encoded)session=EncryptedSession(session_id="user-123",underlying_session=underlying_session,encryption_key="your-fernet-key-here",ttl=600)# Using a raw string (will be derived to a key)session=EncryptedSession(session_id="user-123",underlying_session=underlying_session,encryption_key="my-secret-password",ttl=600)

TTL(存活时间)

设置加密条目的有效时长:

# Items expire after 1 hoursession=EncryptedSession(session_id="user-123",underlying_session=underlying_session,encryption_key="secret",ttl=3600# 1 hour in seconds)# Items expire after 1 daysession=EncryptedSession(session_id="user-123",underlying_session=underlying_session,encryption_key="secret",ttl=86400# 24 hours in seconds)

与不同会话类型配合使用

与 SQLite 会话配合使用

fromagentsimportSQLiteSessionfromagents.extensions.memoryimportEncryptedSession# Create encrypted SQLite sessionunderlying=SQLiteSession("user-123","conversations.db")session=EncryptedSession(session_id="user-123",underlying_session=underlying,encryption_key="secret-key")

与 SQLAlchemy 会话配合使用

fromagents.extensions.memoryimportEncryptedSession,SQLAlchemySession# Create encrypted SQLAlchemy sessionunderlying=SQLAlchemySession.from_url("user-123",url="postgresql+asyncpg://user:pass@localhost/db",create_tables=True)session=EncryptedSession(session_id="user-123",underlying_session=underlying,encryption_key="secret-key")

高级会话功能

EncryptedSession 与诸如AdvancedSQLiteSession 等高级会话实现一起使用时,请注意:

  • 由于消息内容被加密,find_turns_by_content() 等方法将无法有效工作
  • 基于内容的搜索会作用在加密数据上,因此效果受限

密钥派生

EncryptedSession 使用 HKDF(基于 HMAC 的密钥派生函数)为每个会话派生唯一的加密密钥:

  • 主密钥: 你提供的加密密钥
  • 会话盐值: 会话 ID
  • Info 字符串:"agents.session-store.hkdf.v1"
  • 输出: 32 字节的 Fernet 密钥

这确保:- 每个会话都有唯一的加密密钥- 没有主密钥无法派生出会话密钥- 不同会话之间的数据无法相互解密

自动过期

当条目超过 TTL 时,在读取时会被自动跳过:

# Items older than TTL are silently ignoreditems=awaitsession.get_items()# Only returns non-expired items# Expired items don't affect session behaviorresult=awaitRunner.run(agent,"Continue conversation",session=session)

API 参考


[8]ページ先頭

©2009-2025 Movatter.jp