Skip to main content

ds_api/
response.rs

1//! 响应 trait 模块
2//!
3//! 提供统一的响应处理接口,简化对 DeepSeek API 响应的访问。
4//!
5//! # 主要特性
6//!
7//! - [`Response`] trait: 定义响应对象的通用接口
8//! - 为原始响应类型提供标准实现
9//!
10//! # 示例
11//!
12//! ```rust
13//! use ds_api::{Response, ChatCompletionResponse};
14//! use std::time::SystemTime;
15//!
16//! // 假设有一个 ChatCompletionResponse 实例
17//! # let response = ChatCompletionResponse {
18//! #     id: "test".to_string(),
19//! #     object: ds_api::ObjectType::ChatCompletion,
20//! #     created: 1234567890,
21//! #     model: ds_api::Model::DeepseekChat,
22//! #     system_fingerprint: "test_fingerprint".to_string(),
23//! #     choices: vec![ds_api::Choice {
24//! #         index: 0,
25//! #         message: ds_api::Message {
26//! #             role: ds_api::Role::Assistant,
27//! #             content: Some("Hello!".to_string()),
28//! #             ..Default::default()
29//! #         },
30//! #         finish_reason: ds_api::FinishReason::Stop,
31//! #         logprobs: None,
32//! #     }],
33//! #     usage: ds_api::Usage {
34//! #         prompt_tokens: 10,
35//! #         completion_tokens: 5,
36//! #         total_tokens: 15,
37//! #         prompt_cache_hit_tokens: None,
38//! #         prompt_cache_miss_tokens: None,
39//! #         completion_tokens_details: None,
40//! #     },
41//! # };
42//!
43//! // 获取响应内容
44//! let content = response.content().unwrap();
45//! println!("Response content: {}", content);
46//!
47//! // 获取响应创建时间
48//! let created_time: SystemTime = response.created();
49//! println!("Response created at: {:?}", created_time);
50//! ```
51//!
52//! # 实现说明
53//!
54//! [`Response`] trait 提供了对 API 响应的统一访问方式,无论底层响应结构如何变化,
55//! 用户都可以通过相同的接口获取响应内容和创建时间。
56
57use std::{
58    ops::Add,
59    time::{Duration, SystemTime, UNIX_EPOCH},
60};
61
62use crate::{
63    error::{ApiError, Result},
64    raw::ChatCompletionResponse,
65};
66
67/// 响应 trait,为 DeepSeek API 响应提供统一的访问接口
68///
69/// 这个 trait 定义了所有响应类型都应该实现的基本操作,
70/// 使得用户可以以一致的方式处理不同类型的响应。
71pub trait Response {
72    /// 获取响应的文本内容
73    ///
74    /// # 返回
75    ///
76    /// 返回响应内容的字符串切片。对于聊天补全响应,这通常是助手的回复文本。
77    fn content(&self) -> Result<&str>;
78
79    /// 获取响应的创建时间
80    ///
81    /// # 返回
82    ///
83    /// 返回响应创建的系统时间,可以用于日志记录、缓存控制等场景。
84    fn created(&self) -> SystemTime;
85}
86
87impl Response for ChatCompletionResponse {
88    fn content(&self) -> Result<&str> {
89        self.choices
90            .get(0)
91            .and_then(|c| c.message.content.as_deref())
92            .ok_or_else(|| ApiError::Other("empty choices or missing content".to_string()))
93    }
94
95    fn created(&self) -> SystemTime {
96        UNIX_EPOCH.add(Duration::from_secs(self.created))
97    }
98}