Agent Core & Cache

Prompt 缓存保护铁律与角色交替校直

解密 system_prompt.py 的字节级稳定设计与 agent_runtime_helpers.py 的角色自动对齐
缓存铁律时序
📊 图 2-2-1:系统提示词静态序列化与 LLM 缓存撞击 UML 序列图

🔒 1. 缓存前缀字节级稳定的代码实现

为了保证大模型的 Prompt 缓存命中率,系统在 agent/system_prompt.py 中实施了严格的工具定义排序:

def format_tools_for_system_message(tools_list: list) -> str:
    # 强制将工具按 name 键值字典升序排列,规避哈希随机化带来的顺序抖动
    sorted_tools = sorted(tools_list, key=lambda x: x["name"])
    # 强制去除空格和换行符,确保序列化字符串每个字符完全一致
    return json.dumps(sorted_tools, sort_keys=True, separators=(',', ':'))
缓存优化流图
📊 图 2-2-2:AIAgent 决策流与缓存优化整体时序图

🔄 2. 角色交替对齐 (Role Alternation Control)

agent/agent_runtime_helpers.pyrepair_message_sequence_with_cursor() 中,系统对消息列表进行自愈清洗:

  • 若发现两条连续的 user 消息,系统会自动在文本上通过 "\n\n" 进行合并,缩减为单条消息。
  • 若发现 tool 消息前方没有 assistanttool_calls 对齐,系统会自动塞入一条含有空白回复的合成 assistant 响应,满足厂商规范。