Expand description
支持自定义历史记录管理的聊天客户端模块
提供灵活的聊天客户端实现,允许用户自定义对话历史记录的存储和管理方式。
§主要特性
- 自定义历史记录: 通过实现
Historytrait 来自定义历史记录存储 - 聊天功能: 支持基本的聊天交互
- JSON 响应: 支持 JSON 格式的响应
- 异步处理: 基于
tokio的异步实现
§示例
§基本使用
use ds_api::{NormalChatter, History, Message, Role};
#[tokio::main]
async fn main() -> ds_api::error::Result<()> {
let token = "your_deepseek_api_token".to_string();
let mut chatter = NormalChatter::new(token);
let mut history: Vec<Message> = vec![];
let response = chatter.chat("Hello, how are you?", &mut history).await?;
println!("Assistant: {}", response);
Ok(())
}§自定义历史记录实现
use ds_api::{NormalChatter, History, Message, Role};
struct LimitedHistory {
messages: Vec<Message>,
max_messages: usize,
}
impl History for LimitedHistory {
fn add_message(&mut self, message: Message) {
self.messages.push(message);
if self.messages.len() > self.max_messages {
self.messages.remove(0); // 移除最旧的消息
}
}
fn get_history(&self) -> Vec<Message> {
self.messages.clone()
}
}
#[tokio::main]
async fn main() -> ds_api::error::Result<()> {
let token = "your_deepseek_api_token".to_string();
let mut chatter = NormalChatter::new(token);
let mut history = LimitedHistory {
messages: vec![],
max_messages: 10,
};
let response = chatter.chat("What is Rust?", &mut history).await?;
println!("Assistant: {}", response);
Ok(())
}§使用 JSON 响应
use ds_api::{NormalChatter, History, Message, Role};
use serde_json::Value;
#[tokio::main]
async fn main() -> ds_api::error::Result<()> {
let token = "your_deepseek_api_token".to_string();
let mut chatter = NormalChatter::new(token);
let mut history: Vec<Message> = vec![
Message::new(Role::System, "You are a helpful assistant that responds in JSON format.")
];
let json_response = chatter.chat_json("Give me information about Paris in JSON format", &mut history).await?;
println!("JSON response: {}", serde_json::to_string_pretty(&json_response)?);
Ok(())
}§注意事项
- 当前实现不支持流式响应
- 需要手动管理上下文长度,避免超过模型限制
- 历史记录中的第一条消息通常是系统提示词
Structs§
- Normal
Chatter - 支持自定义历史记录管理的聊天客户端
Traits§
- History
- 历史记录管理 trait