async_dashscope/operation/
generation.rs

1pub use super::common::*;
2use crate::error::Result;
3use crate::{client::Client, error::DashScopeError};
4pub use output::*;
5pub use param::{GenerationParam, GenerationParamBuilder, InputBuilder, MessageBuilder};
6
7mod output;
8mod param;
9
10pub struct Generation<'a> {
11    client: &'a Client,
12}
13
14impl<'a> Generation<'a> {
15    pub fn new(client: &'a Client) -> Self {
16        Self { client }
17    }
18
19    /// 异步调用生成服务
20    ///
21    /// 此函数用于当请求参数中的stream设置为false时,发送一次性生成请求
22    /// 如果stream参数为true,则会返回错误,提示用户使用call_stream方法
23    ///
24    /// # 参数
25    /// * `request`: 包含生成参数的请求对象
26    ///
27    /// # 返回
28    /// 返回生成输出的结果,如果请求配置了stream且为true,则返回错误
29    pub async fn call(&self, request: GenerationParam) -> Result<GenerationOutput> {
30        // 检查请求是否启用了流式生成,如果是,则返回错误
31        if request.stream.is_some() && request.stream.unwrap() {
32            return Err(DashScopeError::InvalidArgument(
33                "When stream is true, use Generation::call_stream".into(),
34            ));
35        }
36        // 发送POST请求到生成服务,并等待结果
37        self.client
38            .post("/services/aigc/text-generation/generation", request)
39            .await
40    }
41
42    /// 异步调用生成流函数
43    ///
44    /// 此函数用于处理文本生成的流式请求。流式请求意味着响应会随着时间的推移逐步返回,
45    /// 而不是一次性返回所有内容。这对于需要实时处理生成内容的场景特别有用。
46    ///
47    /// # 参数
48    /// * `request`: 一个可变的 `GenerationParam` 类型对象,包含了生成文本所需的参数。
49    ///
50    /// # 返回
51    /// 返回一个 `Result` 类型,包含一个 `GenerationOutputStream` 对象,用于接收生成的文本流。
52    /// 如果 `request` 中的 `stream` 字段为 `Some(false)`,则返回一个 `DashScopeError::InvalidArgument` 错误,
53    /// 提示用户应使用 `Generation::call` 函数而不是 `call_stream`。
54    ///
55    /// # 错误处理
56    /// 如果 `request` 参数中的 `stream` 属性为 `Some(false)`,表示用户不希望使用流式处理,
57    /// 函数将返回一个错误,提示用户应使用非流式处理的 `call` 方法。
58    ///
59    /// # 注意
60    /// 该函数自动将 `request` 的 `stream` 属性设置为 `Some(true)`,确保总是以流式处理方式执行生成任务。
61    pub async fn call_stream(
62        &self,
63        mut request: GenerationParam,
64    ) -> Result<GenerationOutputStream> {
65        // 检查 `request` 中的 `stream` 属性,如果明确为 `false`,则返回错误
66        if request.stream.is_some() && !request.stream.unwrap() {
67            return Err(DashScopeError::InvalidArgument(
68                "When stream is false, use Generation::call".into(),
69            ));
70        }
71
72        // 确保 `stream` 属性被设置为 `true`,即使它之前是 `None`
73        request.stream = Some(true);
74
75        // 通过客户端发起 POST 请求,使用修改后的 `request` 对象,并等待异步响应
76        Ok(self
77            .client
78            .post_stream("/services/aigc/text-generation/generation", request)
79            .await)
80    }
81}