Skip to main content

ContextMessage

Trait ContextMessage 

Source
pub trait ContextMessage:
    Send
    + Sync
    + Clone
    + Serialize
    + DeserializeOwned {
    // Required methods
    fn role(&self) -> Role;
    fn preserve_reasoning(&self) -> bool;
    fn without_reasoning(self) -> Self;
    fn with_role(self, role: Role) -> Self;
}
Expand description

后端消息类型必须实现此 trait。

AgentContext 不感知消息的具体内容结构,仅通过此 trait 获取两个关键信息:

  • 角色:用于按角色筛选和保留
  • 推理保留策略:用于格式转换时决定是否剥离 reasoning_content

§实现要求

由于孤儿规则,你无法为外部类型直接实现此 trait。需要在你的 crate 中 创建 newtype 包装器:

#[derive(Debug, Clone, Serialize, Deserialize)]
struct MyMessage(deepseek_sdk::Message);

impl ContextMessage for MyMessage {
    fn role(&self) -> Role { /* 映射 */ }
    fn preserve_reasoning(&self) -> bool { /* 按 provider 规则 */ }
}

Required Methods§

Source

fn role(&self) -> Role

返回此消息的角色。

Source

fn preserve_reasoning(&self) -> bool

此消息的 reasoning_content 是否需要在后续请求中保留。

各 LLM provider 有不同规则。例如 DeepSeek 要求:

  • 工具调用场景中 assistant 的 reasoning_content 必须完整回传
  • 非工具调用场景中可省略
Source

fn without_reasoning(self) -> Self

返回一个剥离 reasoning_content 的副本。

用于 ContextBackend::to_request_messages 的默认实现: 对 !preserve_reasoning() 的消息剥离思维链,减少 token 消耗。

Source

fn with_role(self, role: Role) -> Self

返回一个角色被替换为新角色的副本。

用于 ContextBackend::to_system_message 的默认实现: 将消息转换为 System 角色(压缩摘要等场景)。

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§