Skip to main content

openai_interface/completions/
request.rs

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