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    ///
139    /// Flattened into the JSON body, matching the official SDK's `extra_body`
140    /// semantics: the entries are sent as top-level request parameters.
141    #[serde(flatten, skip_serializing_if = "Option::is_none")]
142    pub extra_body: Option<serde_json::Map<String, serde_json::Value>>,
143}
144
145#[derive(Debug, Serialize, Clone)]
146#[serde(untagged)]
147pub enum Prompt {
148    /// String
149    PromptString(String),
150    /// Array of strings
151    PromptStringArray(Vec<String>),
152    /// Array of tokens
153    TokensArray(Vec<usize>),
154    /// Array of arrays of tokens
155    TokenArraysArray(Vec<Vec<usize>>),
156}
157impl Default for Prompt {
158    fn default() -> Self {
159        Self::PromptString("".to_string())
160    }
161}
162
163#[derive(Debug, Serialize, Clone)]
164pub struct StreamOptions {
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, Clone)]
177#[serde(untagged)]
178pub enum StopKeywords {
179    Word(String),
180    Words(Vec<String>),
181}
182
183impl CompletionRequest {
184    /// Whether this request asks for a streamed response. Defaults to
185    /// `false` when [`CompletionRequest::stream`] is `None`.
186    pub fn is_streaming(&self) -> bool {
187        self.stream.unwrap_or(false)
188    }
189}
190
191impl Post for CompletionRequest {
192    fn is_streaming(&self) -> bool {
193        CompletionRequest::is_streaming(self)
194    }
195
196    /// Builds the URL for the request.
197    ///
198    /// `base_url` should be like <https://api.openai.com/v1>
199    fn build_url(&self, base_url: &str) -> Result<String, OapiError> {
200        let mut url = Url::parse(base_url.trim_end_matches('/')).map_err(OapiError::UrlError)?;
201        url.path_segments_mut()
202            .map_err(|_| OapiError::UrlCannotBeBase(base_url.to_string()))?
203            .push("completions");
204
205        Ok(url.to_string())
206    }
207}
208
209impl PostNoStream for CompletionRequest {
210    type Response = super::response::Completion;
211}
212
213impl PostStream for CompletionRequest {
214    type Response = super::response::Completion;
215}
216
217#[cfg(test)]
218mod tests {
219    use futures_util::StreamExt;
220
221    use super::*;
222
223    const QWEN_MODEL: &str = "qwen-coder-turbo";
224    const QWEN_URL: &str = "https://dashscope.aliyuncs.com/compatible-mode/v1";
225
226    fn qwen_api_key() -> Option<String> {
227        std::env::var("QWEN_API_KEY")
228            .ok()
229            .map(|key| key.trim().to_string())
230            .filter(|key| !key.is_empty())
231    }
232
233    #[tokio::test]
234    async fn test_qwen_completions_no_stream() -> Result<(), anyhow::Error> {
235        let Some(api_key) = qwen_api_key() else {
236            println!("Skipping: set QWEN_API_KEY to run this test");
237            return Ok(());
238        };
239
240        let request_body = CompletionRequest {
241            model: QWEN_MODEL.to_string(),
242            prompt: Prompt::PromptString(
243                r#"
244    package main
245
246    import (
247      "fmt"
248      "strings"
249      "net/http"
250      "io/ioutil"
251    )
252
253    func main() {
254
255      url := "https://api.deepseek.com/chat/completions"
256      method := "POST"
257
258      payload := strings.NewReader(`{
259      "messages": [
260        {
261          "content": "You are a helpful assistant",
262          "role": "system"
263        },
264        {
265          "content": "Hi",
266          "role": "user"
267        }
268      ],
269      "model": "deepseek-chat",
270      "frequency_penalty": 0,
271      "max_tokens": 4096,
272      "presence_penalty": 0,
273      "response_format": {
274        "type": "text"
275      },
276      "stop": null,
277      "stream": false,
278      "stream_options": null,
279      "temperature": 1,
280      "top_p": 1,
281      "tools": null,
282      "tool_choice": "none",
283      "logprobs": false,
284      "top_logprobs": null
285    }`)
286
287      client := &http.Client {
288      }
289      req, err := http.NewRequest(method, url, payload)
290
291      if err != nil {
292        fmt.Println(err)
293        return
294      }
295      req.Header.Add("Content-Type", "application/json")
296      req.Header.Add("Accept", "application/json")
297      req.Header.Add("Authorization", "Bearer <TOKEN>")
298
299      res, err := client.Do(req)
300      if err != nil {
301        fmt.Println(err)
302        return
303      }
304      defer res.Body.Close()
305"#
306                .to_string(),
307            ),
308            suffix: Some(
309                r#"
310    if err != nil {
311        fmt.Println(err)
312        return
313    }
314    fmt.Println(string(body))
315}
316"#
317                .to_string(),
318            ),
319            stream: Some(false),
320            ..Default::default()
321        };
322
323        let result = request_body
324            .get_response_string(
325                &crate::rest::default_client(),
326                QWEN_URL,
327                &crate::rest::RequestOptions::bearer(&api_key),
328            )
329            .await?;
330        println!("{}", result);
331
332        Ok(())
333    }
334
335    #[tokio::test]
336    async fn test_qwen_completions_stream() -> Result<(), anyhow::Error> {
337        let Some(api_key) = qwen_api_key() else {
338            println!("Skipping: set QWEN_API_KEY to run this test");
339            return Ok(());
340        };
341
342        let request_body = CompletionRequest {
343            model: QWEN_MODEL.to_string(),
344            prompt: Prompt::PromptString(
345                r#"
346        package main
347
348        import (
349          "fmt"
350          "strings"
351          "net/http"
352          "io/ioutil"
353        )
354
355        func main() {
356
357          url := "https://api.deepseek.com/chat/completions"
358          method := "POST"
359
360          payload := strings.NewReader(`{
361          "messages": [
362            {
363              "content": "You are a helpful assistant",
364              "role": "system"
365            },
366            {
367              "content": "Hi",
368              "role": "user"
369            }
370          ],
371          "model": "deepseek-chat",
372          "frequency_penalty": 0,
373          "max_tokens": 4096,
374          "presence_penalty": 0,
375          "response_format": {
376            "type": "text"
377          },
378          "stop": null,
379          "stream": true,
380          "stream_options": null,
381          "temperature": 1,
382          "top_p": 1,
383          "tools": null,
384          "tool_choice": "none",
385          "logprobs": false,
386          "top_logprobs": null
387        }`)
388
389          client := &http.Client {
390          }
391          req, err := http.NewRequest(method, url, payload)
392
393          if err != nil {
394            fmt.Println(err)
395            return
396          }
397          req.Header.Add("Content-Type", "application/json")
398          req.Header.Add("Accept", "application/json")
399          req.Header.Add("Authorization", "Bearer <TOKEN>")
400
401          res, err := client.Do(req)
402          if err != nil {
403            fmt.Println(err)
404            return
405          }
406          defer res.Body.Close()
407    "#
408                .to_string(),
409            ),
410            suffix: Some(
411                r#"
412        if err != nil {
413            fmt.Println(err)
414            return
415        }
416        fmt.Println(string(body))
417    }
418    "#
419                .to_string(),
420            ),
421            stream: Some(true),
422            ..Default::default()
423        };
424
425        let mut stream = request_body
426            .get_stream_response_string(
427                &crate::rest::default_client(),
428                QWEN_URL,
429                &crate::rest::RequestOptions::bearer(&api_key),
430            )
431            .await?;
432
433        while let Some(chunk) = stream.next().await {
434            match chunk {
435                Ok(data) => {
436                    println!("Received chunk: {:?}", data);
437                }
438                Err(e) => {
439                    eprintln!("Error receiving chunk: {:?}", e);
440                    break;
441                }
442            }
443        }
444
445        Ok(())
446    }
447}