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(&crate::rest::default_client(), QWEN_URL, &api_key)
325 .await?;
326 println!("{}", result);
327
328 Ok(())
329 }
330
331 #[tokio::test]
332 async fn test_qwen_completions_stream() -> Result<(), anyhow::Error> {
333 let Some(api_key) = qwen_api_key() else {
334 println!("Skipping: set QWEN_API_KEY to run this test");
335 return Ok(());
336 };
337
338 let request_body = CompletionRequest {
339 model: QWEN_MODEL.to_string(),
340 prompt: Prompt::PromptString(
341 r#"
342 package main
343
344 import (
345 "fmt"
346 "strings"
347 "net/http"
348 "io/ioutil"
349 )
350
351 func main() {
352
353 url := "https://api.deepseek.com/chat/completions"
354 method := "POST"
355
356 payload := strings.NewReader(`{
357 "messages": [
358 {
359 "content": "You are a helpful assistant",
360 "role": "system"
361 },
362 {
363 "content": "Hi",
364 "role": "user"
365 }
366 ],
367 "model": "deepseek-chat",
368 "frequency_penalty": 0,
369 "max_tokens": 4096,
370 "presence_penalty": 0,
371 "response_format": {
372 "type": "text"
373 },
374 "stop": null,
375 "stream": true,
376 "stream_options": null,
377 "temperature": 1,
378 "top_p": 1,
379 "tools": null,
380 "tool_choice": "none",
381 "logprobs": false,
382 "top_logprobs": null
383 }`)
384
385 client := &http.Client {
386 }
387 req, err := http.NewRequest(method, url, payload)
388
389 if err != nil {
390 fmt.Println(err)
391 return
392 }
393 req.Header.Add("Content-Type", "application/json")
394 req.Header.Add("Accept", "application/json")
395 req.Header.Add("Authorization", "Bearer <TOKEN>")
396
397 res, err := client.Do(req)
398 if err != nil {
399 fmt.Println(err)
400 return
401 }
402 defer res.Body.Close()
403 "#
404 .to_string(),
405 ),
406 suffix: Some(
407 r#"
408 if err != nil {
409 fmt.Println(err)
410 return
411 }
412 fmt.Println(string(body))
413 }
414 "#
415 .to_string(),
416 ),
417 stream: Some(true),
418 ..Default::default()
419 };
420
421 let mut stream = request_body
422 .get_stream_response_string(&crate::rest::default_client(), QWEN_URL, &api_key)
423 .await?;
424
425 while let Some(chunk) = stream.next().await {
426 match chunk {
427 Ok(data) => {
428 println!("Received chunk: {:?}", data);
429 }
430 Err(e) => {
431 eprintln!("Error receiving chunk: {:?}", e);
432 break;
433 }
434 }
435 }
436
437 Ok(())
438 }
439}