Skip to main content

agent_context/
role.rs

1use serde::{Deserialize, Serialize};
2
3/// LLM 对话消息角色,对应 OpenAI/DeepSeek/智谱等 API 的标准消息角色。
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, derive_more::Display)]
5pub enum Role {
6    /// 系统提示词
7    #[display("system")]
8    System,
9    /// 用户消息
10    #[display("user")]
11    User,
12    /// 模型回复
13    #[display("assistant")]
14    Assistant,
15    /// 工具调用结果
16    #[display("tool")]
17    Tool,
18}
19
20impl Role {
21    /// 返回角色对应的 JSON 字段值(小写字符串)。
22    pub fn as_str(&self) -> &'static str {
23        match self {
24            Self::System => "system",
25            Self::User => "user",
26            Self::Assistant => "assistant",
27            Self::Tool => "tool",
28        }
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35
36    #[test]
37    fn display() {
38        assert_eq!(Role::System.to_string(), "system");
39        assert_eq!(Role::User.to_string(), "user");
40        assert_eq!(Role::Assistant.to_string(), "assistant");
41        assert_eq!(Role::Tool.to_string(), "tool");
42    }
43
44    #[test]
45    fn as_str_matches_display() {
46        assert_eq!(Role::System.as_str(), Role::System.to_string());
47    }
48
49    #[test]
50    fn serde_roundtrip() {
51        let json = serde_json::to_string(&Role::Assistant).unwrap();
52        assert_eq!(json, "\"Assistant\"");
53        let role: Role = serde_json::from_str(&json).unwrap();
54        assert_eq!(role, Role::Assistant);
55    }
56}