Skip to content

Agent 集成

Agently 默认 Agent 已集成 SessionExtension,你可以直接调用下列方法。

绑定与解绑

python
agent.attach_session(session)
agent.detach_session()

便捷启用

python
agent.enable_session_lite(chars=12000, messages=8)
agent.enable_session_memo(chars=6000, messages=12)
agent.enable_quick_session()
agent.disable_quick_session()

chat_history API 会自动代理

当 Session 已绑定时,以下方法会写入 Session:

  • set_chat_history(...)
  • add_chat_history(...)
  • reset_chat_history()

请求前会自动把 session.current_chat_history 注入 prompt。

记录输入/输出(record)

SessionExtension 默认会在请求结束后把 input/output 写入 Session。 你可以通过设置控制记录字段:

python
agent.settings.set("session.record.input.paths", ["input", ["input", "user.id"]])
agent.settings.set("session.record.input.mode", "all")

agent.settings.set("session.record.output.paths", ["reply", "data.result"])
agent.settings.set("session.record.output.mode", "first")

自定义记录逻辑

python
def my_record_handler(result):
    return [
        {"role": "user", "content": "custom input"},
        {"role": "assistant", "content": "custom output"},
    ]

agent.set_record_handler(my_record_handler)

实际场景:多轮对话后触发整理(不同整理)

目标是“多轮后触发不同类型的整理”,并能在下一轮对话中自动生效。

1) 完整设置 + 自动触发(lite / deep)

python
from agently import Agently
from agently.core import Session

agent = Agently.create_agent()

session = Session(agent=agent).configure(
    mode="memo",
    limit={"chars": 6000, "messages": 12},
    every_n_turns=4,  # 到点就触发 lite
)
agent.attach_session(session)

默认策略会按以下优先级触发:

  • 超出字符上限 → deep
  • 超出消息数上限 → lite
  • every_n_turns → lite

2) 手动触发不同整理

python
# 强制 deep(更强的整理)
agent.session.resize(force="deep")

# 强制 lite
agent.session.resize(force="lite")

3) 自定义“不同整理”的实现

你可以为 lite / deep 分别设置不同的处理器:

python
def lite_resize_handler(full_history, current_history, memo, settings):
    # 轻量整理:只做增量 memo
    return full_history, current_history[-6:], memo

def deep_resize_handler(full_history, current_history, memo, settings):
    # 深度整理:可调用更强模型/更长指令
    return full_history, current_history[-4:], memo

session.set_resize_handlers("lite", lite_resize_handler)
session.set_resize_handlers("deep", deep_resize_handler)

整理如何自动回流到下一轮对话(长对话记忆)

关键点

  1. SessionExtension 会在请求前自动注入 current_chat_history
  2. memo 不会自动注入 prompt,需要你显式注入(或统一加一个前置钩子)

方案 A:每次请求前自动注入 memo

python
async def inject_memo(prompt, settings):
    memo = agent.session.memo
    if memo:
        prompt.set("info.memo", memo)

agent.extension_handlers.append("request_prefixes", inject_memo)

方案 B:手动注入 memo

python
agent.info({"memo": agent.session.memo})
agent.input("继续对话...").get_text()

这样形成完整闭环:

  • 对话中触发 resize → memo 被更新
  • 下次请求前把 memo 注入 prompt
  • 模型在新一轮中“记住”稳定信息