openai_interface/completions/
request.rs

1use std::collections::HashMap;
2
3use serde::Serialize;
4
5use crate::rest::post::{NoStream, Post, Stream};
6
7#[derive(Debug, Serialize, Default)]
8pub struct CompletionRequest {
9    /// ID of the model to use. Note that not all models are supported for completion.
10    pub model: String,
11    /// The prompt(s) to generate completions for, encoded as a string, array of
12    /// strings, array of tokens, or array of token arrays.
13    /// Note that <|endoftext|> is the document separator that the model sees during
14    /// training, so if a prompt is not specified the model will generate as if from the
15    /// beginning of a new document.
16    pub prompt: Prompt,
17    /// Generates `best_of` completions server-side and returns the "best" (the one with
18    /// the highest log probability per token). Results cannot be streamed.
19    ///
20    /// When used with `n`, `best_of` controls the number of candidate completions and
21    /// `n` specifies how many to return – `best_of` must be greater than `n`.
22    ///
23    /// **Note:** Because this parameter generates many completions, it can quickly
24    /// consume your token quota. Use carefully and ensure that you have reasonable
25    /// settings for `max_tokens` and `stop`.
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub best_of: Option<usize>,
28    /// Echo back the prompt in addition to the completion
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub echo: Option<bool>,
31    /// Number between -2.0 and 2.0. Positive values penalize new tokens based on their
32    /// existing frequency in the text so far, decreasing the model's likelihood to
33    /// repeat the same line verbatim.
34    ///
35    /// [more info about frequency/presence penalties](https://platform.openai.com/docs/guides/text-generation)
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub frequency_penalty: Option<f32>,
38    /// Modify the likelihood of specified tokens appearing in the completion.
39    ///
40    /// Accepts a JSON object that maps tokens (specified by their token ID in the GPT
41    /// tokenizer) to an associated bias value from -100 to 100. You can use this
42    /// [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs.
43    /// Mathematically, the bias is added to the logits generated by the model prior to
44    /// sampling. The exact effect will vary per model, but values between -1 and 1
45    /// should decrease or increase likelihood of selection; values like -100 or 100
46    /// should result in a ban or exclusive selection of the relevant token.
47    ///
48    /// As an example, you can pass `{"50256": -100}` to prevent the <|end-of-stream|> token
49    /// from being generated.
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub logit_bias: Option<HashMap<String, isize>>,
52    /// Include the log probabilities on the `logprobs` most likely output tokens, as
53    /// well the chosen tokens. For example, if `logprobs` is 5, the API will return a
54    /// list of the 5 most likely tokens. The API will always return the `logprob` of
55    /// the sampled token, so there may be up to `logprobs+1` elements in the response.
56    ///
57    /// The maximum value for `logprobs` is 5.
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub logprobs: Option<usize>,
60    /// The maximum number of [tokens](/tokenizer) that can be generated in the
61    /// completion.
62    ///
63    /// The token count of your prompt plus `max_tokens` cannot exceed the model's
64    /// context length.
65    /// [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken)
66    /// for counting tokens.
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub max_tokens: Option<usize>,
69    /// How many completions to generate for each prompt.
70    ///
71    /// **Note:** Because this parameter generates many completions, it can quickly
72    /// consume your token quota. Use carefully and ensure that you have reasonable
73    /// settings for `max_tokens` and `stop`.
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub n: Option<usize>,
76    /// Number between -2.0 and 2.0. Positive values penalize new tokens based on
77    /// whether they appear in the text so far, increasing the model's likelihood to
78    /// talk about new topics.
79    ///
80    /// [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub presence_penalty: Option<f32>,
83    /// If specified, our system will make a best effort to sample deterministically,
84    /// such that repeated requests with the same `seed` and parameters should return
85    /// the same result.
86    ///
87    /// Determinism is not guaranteed, and you should refer to the `system_fingerprint`
88    /// response parameter to monitor changes in the backend.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub seed: Option<usize>,
91    /// Up to 4 sequences where the API will stop generating further tokens. The
92    /// returned text will not contain the stop sequence.
93    ///
94    /// Note: Not supported with latest reasoning models `o3` and `o4-mini`.
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub stop: Option<StopKeywords>,
97    /// Whether to stream back partial progress. If set, tokens will be sent as
98    /// data-only
99    /// [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format)
100    /// as they become available, with the stream terminated by a `data: [DONE]`
101    /// message.
102    /// [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).
103    pub stream: bool,
104    /// Options for streaming response. Only set this when you set `stream: true`.
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub stream_options: Option<StreamOptions>,
107    /// The suffix that comes after a completion of inserted text.
108    ///
109    /// This parameter is only supported for `gpt-3.5-turbo-instruct`.
110    #[serde(skip_serializing_if = "Option::is_none")]
111    pub suffix: Option<String>,
112    /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will
113    /// make the output more random, while lower values like 0.2 will make it more
114    /// focused and deterministic.
115    ///
116    /// It is generally recommended to alter this or `top_p` but not both.
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub temperature: Option<f32>,
119    /// An alternative to sampling with temperature, called nucleus sampling,
120    /// where the model considers the results of the tokens with `top_p`
121    /// probability mass. So 0.1 means only the tokens comprising the top 10%
122    /// probability mass are considered.
123    ///
124    /// It is generally recommended to alter this or `temperature` but not both.
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub top_p: Option<f32>,
127    /// A unique identifier representing your end-user, which can help OpenAI to monitor
128    /// and detect abuse.
129    /// [Learn more from OpenAI](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub user: Option<String>,
132    /// Add additional JSON properties to the request
133    pub extra_body: serde_json::Map<String, serde_json::Value>,
134}
135
136#[derive(Debug, Serialize)]
137#[serde(untagged)]
138pub enum Prompt {
139    /// String
140    PromptString(String),
141    /// Array of strings
142    PromptStringArray(Vec<String>),
143    /// Array of tokens
144    TokensArray(Vec<usize>),
145    /// Array of arrays of tokens
146    TokenArraysArray(Vec<Vec<usize>>),
147}
148impl Default for Prompt {
149    fn default() -> Self {
150        Self::PromptString("".to_string())
151    }
152}
153
154#[derive(Debug, Serialize)]
155pub struct StreamOptions {
156    /// When true, stream obfuscation will be enabled.
157    ///
158    /// Stream obfuscation adds random characters to an `obfuscation` field on streaming
159    /// delta events to normalize payload sizes as a mitigation to certain side-channel
160    /// attacks. These obfuscation fields are included by default, but add a small
161    /// amount of overhead to the data stream. You can set `include_obfuscation` to
162    /// false to optimize for bandwidth if you trust the network links between your
163    /// application and the OpenAI API.
164    pub include_obfuscation: bool,
165    /// If set, an additional chunk will be streamed before the `data: [DONE]` message.
166    ///
167    /// The `usage` field on this chunk shows the token usage statistics for the entire
168    /// request, and the `choices` field will always be an empty array.
169    ///
170    /// All other chunks will also include a `usage` field, but with a null value.
171    /// **NOTE:** If the stream is interrupted, you may not receive the final usage
172    /// chunk which contains the total token usage for the request.
173    pub include_usage: bool,
174}
175
176#[derive(Debug, Serialize)]
177#[serde(untagged)]
178pub enum StopKeywords {
179    Word(String),
180    Words(Vec<String>),
181}
182
183impl Post for CompletionRequest {
184    fn is_streaming(&self) -> bool {
185        self.stream
186    }
187}
188
189impl NoStream for CompletionRequest {}
190
191impl Stream for CompletionRequest {}
192
193#[cfg(test)]
194mod tests {
195    use std::sync::LazyLock;
196
197    use futures_util::StreamExt;
198
199    use super::*;
200
201    const QWEN_MODEL: &str = "qwen-coder-turbo-latest";
202    const QWEN_URL: &str = "https://dashscope.aliyuncs.com/compatible-mode/v1/completions";
203    const QWEN_API_KEY: LazyLock<&'static str> =
204        LazyLock::new(|| include_str!("../../keys/modelstudio_domestic_key").trim());
205
206    #[tokio::test]
207    async fn test_qwen_completions_no_stream() -> Result<(), anyhow::Error> {
208        let request_body = CompletionRequest {
209            model: QWEN_MODEL.to_string(),
210            prompt: Prompt::PromptString(
211                r#"
212    package main
213
214    import (
215      "fmt"
216      "strings"
217      "net/http"
218      "io/ioutil"
219    )
220
221    func main() {
222
223      url := "https://api.deepseek.com/chat/completions"
224      method := "POST"
225
226      payload := strings.NewReader(`{
227      "messages": [
228        {
229          "content": "You are a helpful assistant",
230          "role": "system"
231        },
232        {
233          "content": "Hi",
234          "role": "user"
235        }
236      ],
237      "model": "deepseek-chat",
238      "frequency_penalty": 0,
239      "max_tokens": 4096,
240      "presence_penalty": 0,
241      "response_format": {
242        "type": "text"
243      },
244      "stop": null,
245      "stream": false,
246      "stream_options": null,
247      "temperature": 1,
248      "top_p": 1,
249      "tools": null,
250      "tool_choice": "none",
251      "logprobs": false,
252      "top_logprobs": null
253    }`)
254
255      client := &http.Client {
256      }
257      req, err := http.NewRequest(method, url, payload)
258
259      if err != nil {
260        fmt.Println(err)
261        return
262      }
263      req.Header.Add("Content-Type", "application/json")
264      req.Header.Add("Accept", "application/json")
265      req.Header.Add("Authorization", "Bearer <TOKEN>")
266
267      res, err := client.Do(req)
268      if err != nil {
269        fmt.Println(err)
270        return
271      }
272      defer res.Body.Close()
273"#
274                .to_string(),
275            ),
276            suffix: Some(
277                r#"
278    if err != nil {
279        fmt.Println(err)
280        return
281    }
282    fmt.Println(string(body))
283}
284"#
285                .to_string(),
286            ),
287            stream: false,
288            ..Default::default()
289        };
290
291        let result = request_body.get_response(QWEN_URL, *QWEN_API_KEY).await?;
292        println!("{}", result);
293
294        Ok(())
295    }
296
297    #[tokio::test]
298    async fn test_qwen_completions_stream() -> Result<(), anyhow::Error> {
299        let request_body = CompletionRequest {
300            model: QWEN_MODEL.to_string(),
301            prompt: Prompt::PromptString(
302                r#"
303        package main
304
305        import (
306          "fmt"
307          "strings"
308          "net/http"
309          "io/ioutil"
310        )
311
312        func main() {
313
314          url := "https://api.deepseek.com/chat/completions"
315          method := "POST"
316
317          payload := strings.NewReader(`{
318          "messages": [
319            {
320              "content": "You are a helpful assistant",
321              "role": "system"
322            },
323            {
324              "content": "Hi",
325              "role": "user"
326            }
327          ],
328          "model": "deepseek-chat",
329          "frequency_penalty": 0,
330          "max_tokens": 4096,
331          "presence_penalty": 0,
332          "response_format": {
333            "type": "text"
334          },
335          "stop": null,
336          "stream": true,
337          "stream_options": null,
338          "temperature": 1,
339          "top_p": 1,
340          "tools": null,
341          "tool_choice": "none",
342          "logprobs": false,
343          "top_logprobs": null
344        }`)
345
346          client := &http.Client {
347          }
348          req, err := http.NewRequest(method, url, payload)
349
350          if err != nil {
351            fmt.Println(err)
352            return
353          }
354          req.Header.Add("Content-Type", "application/json")
355          req.Header.Add("Accept", "application/json")
356          req.Header.Add("Authorization", "Bearer <TOKEN>")
357
358          res, err := client.Do(req)
359          if err != nil {
360            fmt.Println(err)
361            return
362          }
363          defer res.Body.Close()
364    "#
365                .to_string(),
366            ),
367            suffix: Some(
368                r#"
369        if err != nil {
370            fmt.Println(err)
371            return
372        }
373        fmt.Println(string(body))
374    }
375    "#
376                .to_string(),
377            ),
378            stream: true,
379            ..Default::default()
380        };
381
382        let mut stream = request_body
383            .get_stream_response(QWEN_URL, *QWEN_API_KEY)
384            .await?;
385
386        while let Some(chunk) = stream.next().await {
387            match chunk {
388                Ok(data) => {
389                    println!("Received chunk: {:?}", data);
390                }
391                Err(e) => {
392                    eprintln!("Error receiving chunk: {:?}", e);
393                    break;
394                }
395            }
396        }
397
398        Ok(())
399    }
400}