async-dashscope 0.12.0

A Rust client for DashScope API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
use std::{fmt::Debug, pin::Pin};

use async_stream::try_stream;
use bytes::Bytes;
use reqwest_eventsource::{Event, EventSource, RequestBuilderExt as _};
use serde::{Serialize, de::DeserializeOwned};
use tokio_stream::{Stream, StreamExt as _};

use crate::{
    config::Config,
    error::{ApiError, DashScopeError, map_deserialization_error},
};

#[derive(Debug, Default, Clone)]
pub struct Client {
    pub(crate) http_client: reqwest::Client,
    pub(crate) config: Config,
    pub(crate) backoff: backoff::ExponentialBackoff,
}

impl Client {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_config(config: Config) -> Self {
        Self {
            http_client: reqwest::Client::new(),
            config,
            backoff: backoff::ExponentialBackoff::default(),
        }
    }
    pub fn with_api_key(mut self, api_key: String) -> Self {
        self.config.set_api_key(api_key.into());
        self
    }

    pub fn build(
        http_client: reqwest::Client,
        config: Config,
        backoff: backoff::ExponentialBackoff,
    ) -> Self {
        Self {
            http_client,
            config,
            backoff,
        }
    }

    pub fn files(&self) -> crate::operation::file::File<'_> {
        crate::operation::file::File::new(self)
    }

    /// 获取当前实例的生成(Generation)信息
    ///
    /// 此方法属于操作级别,用于创建一个`Generation`对象,
    /// 该对象表示当前实例的某一特定生成(代)信息
    ///
    /// # Returns
    ///
    /// 返回一个`Generation`对象,用于表示当前实例的生成信息
    pub fn generation(&self) -> crate::operation::generation::Generation<'_> {
        crate::operation::generation::Generation::new(self)
    }

    /// 启发多模态对话的功能
    ///
    /// 该函数提供了与多模态对话相关的操作入口
    /// 它创建并返回一个MultiModalConversation实例,用于执行多模态对话操作
    ///
    /// 返回一个`MultiModalConversation`实例,用于进行多模态对话操作
    pub fn multi_modal_conversation(
        &self,
    ) -> crate::operation::multi_modal_conversation::MultiModalConversation<'_> {
        crate::operation::multi_modal_conversation::MultiModalConversation::new(self)
    }

    /// 获取音频处理功能
    pub fn audio(&self) -> crate::operation::audio::Audio<'_> {
        crate::operation::audio::Audio::new(self)
    }

    /// 创建一个新的 Image2Image 操作实例
    ///
    /// 返回一个可用于执行图像到图像转换操作的 Image2Image 构建器
    ///
    /// # Examples
    /// ```
    /// let client = Client::new();
    /// let image2image = client.image2image();
    /// ```
    ///
    /// # Errors
    /// 此方法本身不会返回错误,但后续操作可能会返回错误
    pub fn image2image(&self) -> crate::operation::image2image::Image2Image<'_> {
        crate::operation::image2image::Image2Image::new(self)
    }

    /// 创建一个新的文本转图像操作实例
    ///
    /// # 返回
    /// 返回一个 `Text2Image` 操作构建器,用于配置和执行文本转图像请求
    ///
    /// # 示例
    /// ```
    /// let client = Client::new();
    /// let text2image = client.text2image();
    /// ```
    pub fn text2image(&self) -> crate::operation::text2image::Text2Image<'_> {
        crate::operation::text2image::Text2Image::new(self)
    }

    /// 创建一个新的文件操作实例
    ///
    /// # 返回
    /// 返回一个可用于执行文件操作的 File 实例
    ///
    /// # 示例
    /// ```
    /// let client = Client::new();
    /// let file = client.file();
    /// ```
    pub fn file(&self) -> crate::operation::file::File<'_> {
        crate::operation::file::File::new(self)
    }

    pub fn http_client(&self) -> reqwest::Client {
        self.http_client.clone()
    }

    /// 创建一个新的任务操作实例
    ///
    /// # 返回
    /// 返回一个绑定到当前客户端的 `Task` 实例,用于执行任务相关操作
    pub fn task(&self) -> crate::operation::task::Task<'_> {
        crate::operation::task::Task::new(self)
    }

    /// 获取文本嵌入表示
    ///
    /// 此函数提供了一个接口,用于将文本转换为嵌入表示
    /// 它利用当前实例的上下文来生成文本的嵌入表示
    ///
    /// 返回一个`Embeddings`实例,该实例封装了文本嵌入相关的操作和数据
    /// `Embeddings`类型提供了进一步处理文本数据的能力,如计算文本相似度或进行文本分类等
    pub fn text_embeddings(&self) -> crate::operation::embeddings::Embeddings<'_> {
        crate::operation::embeddings::Embeddings::new(self)
    }

    pub(crate) async fn post_stream<I, O>(
        &self,
        path: &str,
        request: I,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<O, DashScopeError>> + Send>>, DashScopeError>
    where
        I: Serialize + Debug,
        O: DeserializeOwned + std::marker::Send + 'static,
    {
        self.post_stream_with_headers(path, request, self.config.headers())
            .await
    }

    pub(crate) async fn post_stream_with_headers<I, O>(
        &self,
        path: &str,
        request: I,
        headers: reqwest::header::HeaderMap,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<O, DashScopeError>> + Send>>, DashScopeError>
    where
        I: Serialize + Debug,
        O: DeserializeOwned + std::marker::Send + 'static,
    {
        let event_source = self
            .http_client
            .post(self.config.url(path))
            .headers(headers)
            .json(&request)
            .eventsource()?;

        Ok(stream(event_source).await)
    }

    pub(crate) async fn post<I, O>(&self, path: &str, request: I) -> Result<O, DashScopeError>
    where
        I: Serialize + Debug,
        O: DeserializeOwned,
    {
        self.post_with_headers(path, request, self.config().headers())
            .await
    }

    /// 发送带有自定义请求头的 POST 请求
    ///
    /// # 参数
    /// * `path` - API 路径
    /// * `request` - 要发送的请求体,需要实现 Serialize 和 Debug trait
    /// * `headers` - 自定义请求头
    ///
    /// # 返回值
    /// 返回解析后的响应数据,类型由调用方指定
    ///
    /// # Errors
    /// 返回 DashScopeError 如果请求失败或响应解析失败
    ///
    /// # 注意事项
    /// 此函数是 crate 内部使用的工具函数,不对外公开
    pub(crate) async fn post_with_headers<I, O>(
        &self,
        path: &str,
        request: I,
        headers: reqwest::header::HeaderMap,
    ) -> Result<O, DashScopeError>
    where
        I: Serialize + Debug,
        O: DeserializeOwned,
    {
        let request_maker = || async {
            Ok(self
                .http_client
                .post(self.config.url(path))
                .headers(headers.clone())
                .json(&request)
                .build()?)
        };

        self.execute(request_maker).await
    }

    async fn execute<O, M, Fut>(&self, request_maker: M) -> Result<O, DashScopeError>
    where
        O: DeserializeOwned,
        M: Fn() -> Fut,
        Fut: core::future::Future<Output = Result<reqwest::Request, DashScopeError>>,
    {
        let bytes = self.execute_raw(request_maker).await?;

        let response: O = serde_json::from_slice(bytes.as_ref())
            .map_err(|e| map_deserialization_error(e, bytes.as_ref()))?;

        Ok(response)
    }

    async fn execute_raw<M, Fut>(&self, request_maker: M) -> Result<Bytes, DashScopeError>
    where
        M: Fn() -> Fut,
        Fut: core::future::Future<Output = Result<reqwest::Request, DashScopeError>>,
    {
        let client = self.http_client.clone();

        backoff::future::retry(self.backoff.clone(), || async {
            let request = request_maker().await.map_err(backoff::Error::Permanent)?;
            let response = client
                .execute(request)
                .await
                .map_err(DashScopeError::Reqwest)
                .map_err(backoff::Error::Permanent)?;

            let status = response.status();
            let bytes = response
                .bytes()
                .await
                .map_err(DashScopeError::Reqwest)
                .map_err(backoff::Error::Permanent)?;

            // Deserialize response body from either error object or actual response object
            if !status.is_success() {
                let api_error: ApiError = serde_json::from_slice(bytes.as_ref())
                    .map_err(|e| map_deserialization_error(e, bytes.as_ref()))
                    .map_err(backoff::Error::Permanent)?;

                if status.as_u16() == 429 {
                    // Rate limited retry...
                    tracing::warn!("Rate limited: {}", api_error.message);
                    return Err(backoff::Error::Transient {
                        err: DashScopeError::ApiError(api_error),
                        retry_after: None,
                    });
                } else {
                    return Err(backoff::Error::Permanent(DashScopeError::ApiError(
                        api_error,
                    )));
                }
            }

            Ok(bytes)
        })
        .await
    }

    pub fn config(&self) -> &Config {
        &self.config
    }
    
    /// 发送 multipart 表单 POST 请求
    ///
    /// # 参数
    /// * `path` - API 路径
    /// * `form_fn` - 返回 multipart 表单数据的函数
    ///
    /// # 返回值
    /// 返回响应结果,类型由调用方指定
    ///
    /// # 错误
    /// 返回 DashScopeError 如果请求失败或响应解析失败
    ///
    /// # 注意事项
    /// 此函数是 crate 内部使用的工具函数,不对外公开
    pub(crate) async fn post_multipart<O, F>(
        &self,
        path: &str,
        form_fn: F,
    ) -> Result<O, DashScopeError>
    where
        O: DeserializeOwned,
        F: Fn() -> reqwest::multipart::Form,
    {
        let request_maker = || async {
            let mut headers = self.config.headers();
            headers.remove("Content-Type");
            headers.remove("X-DashScope-OssResourceResolve");
            Ok(self
                .http_client
                .post(self.config.url(path))
                .headers(headers)
                .multipart(form_fn())
                .build()?)
        };

        self.execute(request_maker).await
    }

    /// 发送带查询参数的 GET 请求
    ///
    /// # 参数
    /// * `path` - API 路径
    /// * `params` - 查询参数
    ///
    /// # 返回值
    /// 返回响应结果,类型由调用方指定
    ///
    /// # 错误
    /// 返回 DashScopeError 如果请求失败或响应解析失败
    ///
    /// # 注意事项
    /// 此函数是 crate 内部使用的工具函数,不对外公开
    pub(crate) async fn get_with_params<O, P>(&self, path: &str, params: &P) -> Result<O, DashScopeError>
    where
        O: DeserializeOwned,
        P: serde::Serialize + ?Sized,
    {
        let request_maker = || async {
            Ok(self
                .http_client
                .get(self.config.url(path))
                .headers(self.config.headers())
                .query(params)
                .build()?)
        };

        self.execute(request_maker).await
    }

    /// 发送 DELETE 请求
    ///
    /// # 参数
    /// * `path` - API 路径
    ///
    /// # 返回值
    /// 返回响应结果,类型由调用方指定
    ///
    /// # 错误
    /// 返回 DashScopeError 如果请求失败或响应解析失败
    ///
    /// # 注意事项
    /// 此函数是 crate 内部使用的工具函数,不对外公开
    pub(crate) async fn delete<O>(&self, path: &str) -> Result<O, DashScopeError>
    where
        O: DeserializeOwned,
    {
        let request_maker = || async {
            Ok(self
                .http_client
                .delete(self.config.url(path))
                .headers(self.config.headers())
                .build()?)
        };

        self.execute(request_maker).await
    }
}

pub(crate) async fn stream<O>(
    mut event_source: EventSource,
) -> Pin<Box<dyn Stream<Item = Result<O, DashScopeError>> + Send>>
where
    O: DeserializeOwned + std::marker::Send + 'static,
{
    let stream = try_stream! {
        while let Some(ev) = event_source.next().await {
            match ev {
                Err(e) => {
                    Err(DashScopeError::StreamError(e.to_string()))?;
                }
                Ok(Event::Open) => continue,
                Ok(Event::Message(message)) => {
                    // First, deserialize to a generic JSON Value to inspect it without failing.
                    let json_value: serde_json::Value = match serde_json::from_str(&message.data) {
                        Ok(val) => val,
                        Err(e) => {
                            Err(map_deserialization_error(e, message.data.as_bytes()))?;
                            continue;
                        }
                    };

                    // Now, deserialize from the `Value` to the target type `O`.
                    let response = serde_json::from_value::<O>(json_value.clone())
                        .map_err(|e| map_deserialization_error(e, message.data.as_bytes()))?;

                    // Yield the successful message
                    yield response;

                    // Check for finish reason after sending the message.
                    // This ensures the final message with "stop" is delivered.
                    let finish_reason = json_value
                        .pointer("/output/choices/0/finish_reason")
                        .and_then(|v| v.as_str());

                    if let Some("stop") = finish_reason {
                        break;
                    }
                }
            }
        }
        event_source.close();
    };

    Box::pin(stream)
}

#[cfg(test)]
mod tests {
    use crate::config::ConfigBuilder;

    use super::*;

    #[test]
    pub fn test_config() {
        let config = ConfigBuilder::default()
            .api_key("test key")
            .build()
            .unwrap();
        let client = Client::with_config(config);

        for header in client.config.headers().iter() {
            if header.0 == "authorization" {
                assert_eq!(header.1, "Bearer test key");
            }
        }
    }
}