openai_interface/completions/request.rs
1use std::collections::HashMap;
2
3use serde::Serialize;
4
5use crate::rest::post::NoStream;
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 NoStream for CompletionRequest {}
184
185#[cfg(test)]
186mod tests {
187 use std::sync::LazyLock;
188
189 use super::*;
190
191 const QWEN_MODEL: &str = "qwen-coder-turbo-latest";
192 const QWEN_URL: &str = "https://dashscope.aliyuncs.com/compatible-mode/v1/completions";
193 const QWEN_API_KEY: LazyLock<&'static str> =
194 LazyLock::new(|| include_str!("../../keys/modelstudio_domestic_key").trim());
195
196 #[tokio::test]
197 async fn test_qwen_completions() -> Result<(), anyhow::Error> {
198 let request_body = CompletionRequest {
199 model: QWEN_MODEL.to_string(),
200 prompt: Prompt::PromptString(
201 r#"
202 package main
203
204 import (
205 "fmt"
206 "strings"
207 "net/http"
208 "io/ioutil"
209 )
210
211 func main() {
212
213 url := "https://api.deepseek.com/chat/completions"
214 method := "POST"
215
216 payload := strings.NewReader(`{
217 "messages": [
218 {
219 "content": "You are a helpful assistant",
220 "role": "system"
221 },
222 {
223 "content": "Hi",
224 "role": "user"
225 }
226 ],
227 "model": "deepseek-chat",
228 "frequency_penalty": 0,
229 "max_tokens": 4096,
230 "presence_penalty": 0,
231 "response_format": {
232 "type": "text"
233 },
234 "stop": null,
235 "stream": false,
236 "stream_options": null,
237 "temperature": 1,
238 "top_p": 1,
239 "tools": null,
240 "tool_choice": "none",
241 "logprobs": false,
242 "top_logprobs": null
243 }`)
244
245 client := &http.Client {
246 }
247 req, err := http.NewRequest(method, url, payload)
248
249 if err != nil {
250 fmt.Println(err)
251 return
252 }
253 req.Header.Add("Content-Type", "application/json")
254 req.Header.Add("Accept", "application/json")
255 req.Header.Add("Authorization", "Bearer <TOKEN>")
256
257 res, err := client.Do(req)
258 if err != nil {
259 fmt.Println(err)
260 return
261 }
262 defer res.Body.Close()
263"#
264 .to_string(),
265 ),
266 suffix: Some(
267 r#"
268 if err != nil {
269 fmt.Println(err)
270 return
271 }
272 fmt.Println(string(body))
273}
274"#
275 .to_string(),
276 ),
277 stream: false,
278 ..Default::default()
279 };
280
281 let result = request_body.get_response(QWEN_URL, *QWEN_API_KEY).await?;
282 println!("{}", result);
283
284 Ok(())
285 }
286}