deepseekClient_rs/chat/
request.rs

1use super::super::base_types::data::*;
2use serde::{Deserialize, Serialize};
3
4/// chat类型请求
5#[derive(Serialize, Deserialize, Debug, Clone)]
6pub struct ChatRequest {
7    // 对话的消息列表。
8    messages: Vec<Message>,
9    // 使用的模型的 ID。您可以使用 deepseek-chat。
10    model: String,
11    // 介于 -2.0 和 2.0 之间的数字。如果该值为正,
12    // 那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
13    #[serde(skip_serializing_if = "Option::is_none")]
14    frequency_penalty: Option<f64>,
15    // 介于 1 到 8192 间的整数,限制一次请求中模型生成 completion 的最大 token 数。
16    // 输入 token 和输出 token 的总长度受模型的上下文长度的限制。
17    // 如未指定 max_tokens参数,默认使用 4096。
18    #[serde(skip_serializing_if = "Option::is_none")]
19    max_tokens: Option<usize>,
20    // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,
21    // 从而增加模型谈论新主题的可能性。
22    #[serde(skip_serializing_if = "Option::is_none")]
23    presence_penalty: Option<f64>,
24    // 一个 object,指定模型必须输出的格式。
25    // 设置为 { "type": "json_object" } 以启用 JSON 模式,该模式保证模型生成的消息是有效的 JSON。
26    // 注意: 使用 JSON 模式时,你还必须通过系统或用户消息指示模型生成 JSON。否则,
27    // 模型可能会生成不断的空白字符,直到生成达到令牌限制,
28    // 从而导致请求长时间运行并显得“卡住”。此外,
29    // 如果 finish_reason="length",这表示生成超过了 max_tokens 
30    // 或对话超过了最大上下文长度,消息内容可能会被部分截断。
31    #[serde(skip_serializing_if = "Option::is_none")]
32    response_format: Option<RespinseFormat>,
33    // 一个 string 或最多包含 16 个 string 的 list,在遇到这些词时,API 将停止生成更多的 token。
34    #[serde(skip_serializing_if = "Option::is_none")]
35    stop: Option<Vec<String>>,
36    // 如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
37    #[serde(skip_serializing_if = "Option::is_none")]
38    stream: Option<bool>,
39    // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 
40    // 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
41    #[serde(skip_serializing_if = "Option::is_none")]
42    temperature: Option<f64>,
43    // 作为调节采样温度的替代方案,模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 
44    // 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改
45    #[serde(skip_serializing_if = "Option::is_none")]
46    top_p: Option<f64>,
47    // 模型可能会调用的 tool 的列表。目前,仅支持 function 作为工具。使用此参数来提供以 JSON 作为输入参数的 function 列表。
48    // 最多支持 128 个 function。
49    #[serde(skip_serializing_if = "Option::is_none")]
50    tools: Option<Vec<Tool>>,
51}
52
53impl ChatRequest {
54    pub fn to_json(&self) -> Result<String, serde_json::Error> {
55        serde_json::to_string(self)
56    }
57    pub fn add_message(&mut self, message: Message) {
58        self.messages.push(message);
59    }
60    pub fn add_messages(&mut self, messages: Vec<Message>) {
61        self.messages.extend(messages);
62    }
63}
64
65/// chat类型请求构建器
66#[derive(Serialize, Deserialize, Debug, Clone)]
67pub struct ChatRequestBuilder{
68    // 对话的消息列表。
69    messages: Vec<Message>,
70    // 使用的模型的 ID。您可以使用 deepseek-chat。
71    model: ModelName,
72    // 介于 -2.0 和 2.0 之间的数字。如果该值为正,
73    // 那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
74    #[serde(skip_serializing_if = "Option::is_none")]
75    frequency_penalty: Option<f64>,
76    // 介于 1 到 8192 间的整数,限制一次请求中模型生成 completion 的最大 token 数。
77    // 输入 token 和输出 token 的总长度受模型的上下文长度的限制。
78    // 如未指定 max_tokens参数,默认使用 4096。
79    #[serde(skip_serializing_if = "Option::is_none")]
80    max_tokens: Option<usize>,
81    // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,
82    // 从而增加模型谈论新主题的可能性。
83    #[serde(skip_serializing_if = "Option::is_none")]
84    presence_penalty: Option<f64>,
85    // 一个 object,指定模型必须输出的格式。
86    // 设置为 { "type": "json_object" } 以启用 JSON 模式,该模式保证模型生成的消息是有效的 JSON。
87    // 注意: 使用 JSON 模式时,你还必须通过系统或用户消息指示模型生成 JSON。否则,
88    // 模型可能会生成不断的空白字符,直到生成达到令牌限制,
89    // 从而导致请求长时间运行并显得“卡住”。此外,
90    // 如果 finish_reason="length",这表示生成超过了 max_tokens 
91    // 或对话超过了最大上下文长度,消息内容可能会被部分截断。
92    #[serde(skip_serializing_if = "Option::is_none")]
93    response_format: Option<RespinseFormat>,
94    // 一个 string 或最多包含 16 个 string 的 list,在遇到这些词时,API 将停止生成更多的 token。
95    #[serde(skip_serializing_if = "Option::is_none")]
96    stop: Option<Vec<String>>,
97    // 如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
98    #[serde(skip_serializing_if = "Option::is_none")]
99    stream: Option<bool>,
100    // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 
101    // 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
102    #[serde(skip_serializing_if = "Option::is_none")]
103    temperature: Option<f64>,
104    // 作为调节采样温度的替代方案,模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 
105    // 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改
106    #[serde(skip_serializing_if = "Option::is_none")]
107    top_p: Option<f64>,
108    // 模型可能会调用的 tool 的列表。目前,仅支持 function 作为工具。使用此参数来提供以 JSON 作为输入参数的 function 列表。
109    // 最多支持 128 个 function。
110    #[serde(skip_serializing_if = "Option::is_none")]
111    tools: Option<Vec<Tool>>,
112}
113
114impl ChatRequestBuilder {
115    pub fn new() -> Self {
116        ChatRequestBuilder {
117            messages: Vec::new(),
118            model: ModelName::DeepseekChat,
119            frequency_penalty: None,
120            max_tokens: None,
121            presence_penalty: None,
122            response_format: None,
123            stop: None,
124            stream: None,
125            temperature: None,
126            top_p: None,
127            tools: None
128        }
129    }
130    pub fn add_message(mut self, message: Message) -> Self {
131        self.messages.push(message);
132        self
133    }
134    
135    pub fn model(mut self, model: ModelName) -> Self {
136        self.model = model;
137        self
138    }
139    pub fn frequency_penalty(mut self, frequency_penalty: f64) -> Self {
140        self.frequency_penalty = Some(frequency_penalty);
141        self
142    }
143    pub fn max_tokens(mut self, max_tokens: usize) -> Self {
144        self.max_tokens = Some(max_tokens);
145        self
146    }
147    pub fn presence_penalty(mut self, presence_penalty: f64) -> Self {
148        self.presence_penalty = Some(presence_penalty);
149        self
150    }
151    pub fn response_format(mut self, response_format: RespinseFormat) -> Self {
152        self.response_format = Some(response_format);
153        self
154    }
155    pub fn stop(mut self, stop: Vec<String>) -> Self {
156        self.stop = Some(stop);
157        self
158    }
159    pub fn stream(mut self, stream: bool) -> Self {
160        self.stream = Some(stream);
161        self
162    }
163    pub fn temperature(mut self, temperature: f64) -> Self {
164        self.temperature = Some(temperature);
165        self
166    }
167    pub fn top_p(mut self, top_p: f64) -> Self {
168        self.top_p = Some(top_p);
169        self
170    }
171    pub fn tools(mut self, tools: Tool) -> Self {
172        self.tools.get_or_insert_with(Vec::new).push(tools);
173        self
174    }
175    pub fn build(self) -> (String, ChatRequest) {
176        let mut base_url = String::new();
177        if self.model == ModelName::DeepseekChat{
178            base_url = format!("{}https://api.deepseek.com/chat",base_url);
179        }else if self.model == ModelName::DeepseekReasoner{
180            base_url = format!("{}https://api.deepseek.com/chat",base_url);
181        }
182        base_url = format!("{}/completions",base_url);
183        
184        (
185            base_url,
186            ChatRequest {
187                messages: self.messages,
188                model: self.model.to_string(),
189                frequency_penalty: self.frequency_penalty,
190                max_tokens: self.max_tokens,
191                presence_penalty: self.presence_penalty,
192                response_format: self.response_format,
193                stop: self.stop,
194                stream: self.stream,
195                temperature: self.temperature,
196                top_p: self.top_p,
197                tools: self.tools,
198            }
199        )
200    }
201}
202
203/// 系统消息
204#[derive(Serialize, Deserialize, Debug, Clone)]
205pub struct Message{
206    //消息的内容
207    content: String,
208    //该消息的发起角色,其值为 `system`
209    role: String,
210    #[serde(skip_serializing_if = "Option::is_none")]
211    //可以选填的参与者的名称,为模型提供信息以区分相同角色的参与者。
212    name: Option<String>,
213    #[serde(skip_serializing_if = "Option::is_none")]
214    prefix: Option<bool>,
215    //(Beta) 用于 deepseek-reasoner 模型在对话前缀续写功能下,作为最后一条 assistant 思维链内容的输入。
216    //使用此功能时,prefix 参数必须设置为 true。
217    #[serde(skip_serializing_if = "Option::is_none")]
218    reasoning_content: Option<String>,
219    // 此消息所响应的 tool call 的 ID。
220    #[serde(skip_serializing_if = "Option::is_none")]
221    tool_call_id: Option<String>,
222}
223
224impl Message {
225    pub fn system_message(content: &str) -> Self {
226        Message {
227            content: String::from(content),
228            role: String::from("system"),
229            name: None,
230            prefix: None,
231            reasoning_content: None,
232            tool_call_id: None,
233        }
234    }
235    pub fn user_message(content: &str) -> Self {
236        Message {
237            content: String::from(content),
238            role: String::from("user"),
239            name: None,
240            prefix: None,
241            reasoning_content: None,
242            tool_call_id: None,
243        }
244    }
245    pub fn assistant_message(content: &str) -> Self {
246        Message {
247            content: String::from(content),
248            role: String::from("assistant"),
249            name: None,
250            prefix: None,
251            reasoning_content: None,
252            tool_call_id: None,
253        }
254    }
255    // 可以选填的参与者的名称,为模型提供信息以区分相同角色的参与者。
256    pub fn name(mut self, name: &str) -> Self {
257        if self.role == "system" || self.role == "user" || self.role == "assistant"{
258            self.name = Some(String::from(name));
259        }
260        self
261    }
262    // role 类型为 assistant 时,是否在消息内容前添加 “Assistant:” 前缀。
263    pub fn prefix(mut self, prefix: bool) -> Self {
264        if self.role == "assistant" {
265            self.prefix = Some(prefix);
266        }
267        self
268    }
269    // (Beta) role 类型为 assistant 时,用于 deepseek-reasoner 模型在对话前缀续写功能下,作为最后一条 assistant 思维链内容的输入。
270    pub fn reasoning_content(mut self, content: &str) -> Self {
271        if self.role == "assistant" {
272            self.reasoning_content = Some(String::from(content));
273        }
274        self
275    }
276    // 此消息所响应的 tool call 的 ID。
277    pub fn tool_call_id(mut self, id: &str) -> Self {
278        if self.role == "tool"{
279            self.tool_call_id = Some(String::from(id));
280        }
281        self
282    }
283    
284}
285
286#[derive(Serialize, Deserialize, Debug, Clone)]
287pub struct RespinseFormat{
288    // ai回复的格式,可选值为 `text` 和 `json_object`。
289    #[serde(rename = "type")]
290    format_type: String,
291}
292
293impl RespinseFormat {
294    // 设置ai回复为文本格式
295    pub fn text() -> Self {
296        RespinseFormat {
297            format_type: String::from("text"),
298        }
299    }
300    // 设置ai回复为json格式
301    pub fn json_object() -> Self {
302        RespinseFormat {
303            format_type: String::from("json_object"),
304        }
305    }
306}
307
308#[derive(Serialize, Deserialize, Debug, Clone)]
309pub struct Tool{
310    // 类型,为: “function”。
311    #[serde(rename = "type")]
312    fun_type: String,
313    // 函数的参数。
314    function: Option<Function>,
315}
316
317impl Tool {
318    pub fn function() -> Self {
319        Tool {
320            fun_type: String::from("function"),
321            function: Some(Function::new()),
322        }
323    }
324    pub fn function_description(mut self, description: &str) -> Self {
325        if self.fun_type == "function" {
326            self.function.as_mut().unwrap().description(description);
327        }
328        self
329    }
330    pub fn function_name(mut self, name: &str) -> Self {
331        if self.fun_type == "function" {
332            self.function.as_mut().unwrap().name(name);
333        }
334        self
335    }
336    pub fn function_parameters(mut self, parameters: serde_json::Value) -> Self {
337        if self.fun_type == "function" {
338            self.function.as_mut().unwrap().parameters(parameters);
339        }
340        self
341    }
342}
343
344#[derive(Serialize, Deserialize, Debug, Clone)]
345pub struct Function{
346    // function 的功能描述,供模型理解何时以及如何调用该 function。
347    description: String,
348    // 要调用的 function 名称。必须由 a-z、A-Z、0-9 字符组成,或包含下划线和连字符,最大长度为 64 个字符。
349    name: String,
350    // function 的输入参数,以 JSON Schema 对象描述。请参阅 Function Calling 指南获取示例,
351    // 并参阅JSON Schema 参考了解有关格式的文档。省略 parameters 会定义一个参数列表为空的 function。
352    parameters: serde_json::Value,
353}
354
355impl Function {
356    pub fn new() -> Self {
357        Function {
358            description: String::from("function one"),
359            name: String::from("function_one"),
360            parameters: serde_json::Value::Null,
361        }
362    }
363    pub fn description(&mut self, description: &str) {
364        self.description = description.to_string();
365    }
366    pub fn name(&mut self, name: &str) {
367        self.name = name.to_string();
368    }
369    pub fn parameters(&mut self, parameters: serde_json::Value) {
370        self.parameters = parameters;
371    }
372}