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