Session 快速开始
适用版本:4.0.8+
本页用完整流程介绍新版 Session:
- 开关会话
- 多会话隔离
- 定制记录字段
- 导出恢复
- 自定义窗口与 memo
1. 开关会话(最常用)
python
from agently import Agently
agent = Agently.create_agent()
# 开启会话后,后续请求会自动带 chat_history
agent.activate_session(session_id="demo_on_off")
agent.input("记住:我明天要买鸡蛋").streaming_print()
agent.input("我明天要买什么?").streaming_print()
# 关闭会话后,不再使用该会话上下文
agent.deactivate_session()
agent.input("我明天要买什么?").streaming_print()说明:
activate_session()不传session_id时自动生成 id- 同 id 会复用历史,不同 id 会隔离历史
2. 会话隔离(多用户/多任务)
python
agent.activate_session(session_id="trip_a")
agent.input("记住:A 行程目的地是东京").streaming_print()
agent.activate_session(session_id="trip_b")
agent.input("记住:B 行程目的地是巴黎").streaming_print()
agent.input("我的目的地是?").streaming_print() # 读取 trip_b
agent.activate_session(session_id="trip_a")
agent.input("我的目的地是?").streaming_print() # 读取 trip_a建议:Web 场景直接用 user_id 或 tenant_id:user_id 作为 session_id。
3. 选择性记录输入与输出
默认会记录完整请求文本与回复。若你只想保存关键字段,可设置:
session.input_keyssession.reply_keys
python
agent.activate_session(session_id="record_demo")
agent.set_settings("session.input_keys", ["info.task", "input.lang"])
agent.set_settings("session.reply_keys", ["summary", "keywords"])
result = (
agent
.info({"task": "Summarize Agently", "style": "technical"})
.input({"lang": "en", "noise": "ignored"})
.output({"summary": (str,), "keywords": [(str,)]})
.get_data()
)
print(result)
print(agent.activated_session.full_context)
# 用完建议恢复默认
agent.set_settings("session.input_keys", None)
agent.set_settings("session.reply_keys", None)4. 导出与恢复
python
from agently.core import Session
agent.activate_session(session_id="export_demo")
agent.input("记住恢复码:X-2025-ABCD").streaming_print()
exported = agent.activated_session.get_json_session()
restored = Session(settings=agent.settings)
restored.load_json_session(exported)
restored.id = "export_demo_restored"
agent.sessions[restored.id] = restored
agent.activate_session(session_id=restored.id)
agent.input("我让你记住的恢复码是什么?").streaming_print()5. 自定义窗口策略与 memo
新版 Session 的 memo 由你定义。推荐做法:
register_analysis_handler()决定何时触发策略register_execution_handlers()执行裁剪并更新 memo
python
def analysis_handler(full_context, context_window, memo, session_settings):
if len(context_window) > 4:
return "keep_last_four"
return None
async def keep_last_four(full_context, context_window, memo, session_settings):
kept = list(context_window[-4:])
# 你可以在这里做 LLM 摘要,生成新 memo
new_memo = {"kept_count": len(kept)}
return None, kept, new_memo
agent.activate_session(session_id="memo_demo")
session = agent.activated_session
session.register_analysis_handler(analysis_handler)
session.register_execution_handlers("keep_last_four", keep_last_four)下一步建议阅读: