async_llm/request/chat.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
use std::{collections::HashMap, pin::Pin};
use futures::Stream;
use serde::{Deserialize, Serialize};
use crate::{
error::Error,
types::{
AssistantContent, ChatAudio, ChatFunction, ChatFunctionCall, ChatResponseFormat, ChatTool,
ChatToolChoice, Content, Modalities, PredictionContent, ReasoningEffort, ServiceTier, Stop,
StreamOptions,
},
ChatResponse, ChatResponseStream, Client, Printable,
};
use super::{ChatMessage, Requestable};
/// https://platform.openai.com/docs/api-reference/chat/create
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct ChatRequest {
/// A list of messages comprising the conversation so far. Depending on the [model](https://platform.openai.com/docs/models) you use, different message types (modalities) are supported, like [text](https://platform.openai.com/docs/guides/text-generation), [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio).
pub(crate) messages: Vec<ChatMessage>,
/// ID of the model to use. See the [model endpoint compatibility](https://platform.openai.com/docs/models#model-endpoint-compatibility) table for details on which models work with the Chat API.
pub(crate) model: String,
/// Whether or not to store the output of this chat completion request for use in our [model distillation](https://platform.openai.com/docs/guides/distillation) or [evals](https://platform.openai.com/docs/guides/evals) products.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) store: Option<bool>,
/// Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) reasoning_effort: Option<ReasoningEffort>,
/// Developer-defined tags and values used for filtering completions in the dashboard.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) metadata: Option<serde_json::Value>,
/// Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) frequency_penalty: Option<f32>, // min: -2.0, max: 2.0, default: 0
/// Modify the likelihood of specified tokens appearing in the completion.
///
/// Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this tokenizer tool to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.
///
/// As an example, you can pass {"50256": -100} to prevent the <|endoftext|> token from being generated.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) logit_bias: Option<HashMap<String, serde_json::Value>>, // default: null
/// Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) logprobs: Option<bool>,
/// An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. logprobs must be set to true if this parameter is used.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) top_logprobs: Option<u8>,
/// The maximum number of [tokens](https://platform.openai.com/tokenizer) that can be generated in the chat completion. This value can be used to control [costs](https://openai.com/api/pricing/) for text generated via API.
///
/// This value is now deprecated in favor of `max_completion_tokens`, and is not compatible with [o1 series models](https://platform.openai.com/docs/guides/reasoning).
#[deprecated]
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) max_tokens: Option<u32>,
/// An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and [reasoning tokens](https://platform.openai.com/docs/guides/reasoning).
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) max_completion_tokens: Option<u32>,
/// How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep n as 1 to minimize costs.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) n: Option<u8>, // min:1, max: 128, default: 1
/// Output types that you would like the model to generate for this request. Most models are capable of generating text, which is the default:
/// ["text"]
/// The gpt-4o-audio-preview model can also be used to generate audio. To request that this model generate both text and audio responses, you can use:
/// ["text", "audio"]
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) modalities: Option<Vec<Modalities>>,
/// Configuration for a [Predicted Output](https://platform.openai.com/docs/guides/predicted-outputs), which can greatly improve response times when large parts of the model response are known ahead of time. This is most common when you are regenerating a file with only minor changes to most of the content.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) prediction: Option<PredictionContent>,
/// Parameters for audio output. Required when audio output is requested with modalities: ["audio"]. [Learn more](https://platform.openai.com/docs/guides/audio).
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) audio: Option<ChatAudio>,
/// Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.
///
/// [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details)
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) presence_penalty: Option<f32>, // min: -2.0, max: 2.0, default 0
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) response_format: Option<ChatResponseFormat>,
/// This feature is in Beta.
/// If specified, our system will make a best effort to sample deterministically, such that repeated requests
/// with the same `seed` and parameters should return the same result.
/// Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) seed: Option<i64>,
/// Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service:
/// - If set to 'auto', the system will utilize scale tier credits until they are exhausted.
/// - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee.
/// - When not set, the default behavior is 'auto'.
///
/// When this parameter is set, the response body will include the `service_tier` utilized.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) service_tier: Option<ServiceTier>,
/// Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) stop: Option<Stop>,
/// If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a data: [DONE] message. Example [Python code](https://cookbook.openai.com/examples/how_to_stream_completions).
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) stream: Option<bool>,
/// Options for streaming response. Only set this when you set stream: true.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) stream_options: Option<StreamOptions>,
/// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
///
/// We generally recommend altering this or top_p but not both.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) temperature: Option<f32>, // min: 0, max: 2, default: 1,
/// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.
///
/// We generally recommend altering this or temperature but not both.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) top_p: Option<f32>, // min: 0, max: 1, default: 1
/// A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) tools: Option<Vec<ChatTool>>,
/// Controls which (if any) tool is called by the model.
/// - `none` means the model will not call any tool and instead generates a message.
/// - `auto` means the model can pick between generating a message or calling one or more tools.
/// - `required` means the model must call one or more tools.
/// - Specifying a particular tool via {"type": "function", "function": {"name": "my_function"}} forces the model to call that tool.
/// `none` is the default when no tools are present. `auto` is the default if tools are present.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) tool_choice: Option<ChatToolChoice>,
/// Whether to enable [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) parallel_tool_calls: Option<bool>,
/// A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) user: Option<String>,
/// Deprecated in favor of `tool_choice`.
///
/// Controls which (if any) function is called by the model.
/// - `none` means the model will not call a function and instead generates a message.
/// - `auto` means the model can pick between generating a message or calling a function.
/// - Specifying a particular function via `{"name": "my_function"}` forces the model to call that function.
///
/// `none` is the default when no functions are present. `auto` is the default if functions are present.
#[deprecated]
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) function_call: Option<ChatFunctionCall>,
/// Deprecated in favor of `tools`.
///
/// A list of functions the model may generate JSON inputs for.
#[deprecated]
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) functions: Option<Vec<ChatFunction>>,
}
impl ChatRequest {
pub fn new(model: impl Into<String>, messages: Vec<ChatMessage>) -> Self {
Self {
messages,
model: model.into(),
..Default::default()
}
}
pub fn from_system(message: impl Into<Content>) -> Self {
Self {
messages: vec![ChatMessage::system(message.into())],
..Default::default()
}
}
pub fn from_model(model: impl Into<String>) -> Self {
Self::new(model, vec![])
}
pub fn iter_messages(&self) -> impl Iterator<Item = &ChatMessage> {
self.messages.iter()
}
pub async fn send(self) -> Result<ChatResponse, Error> {
Client::new().chat().create(self).await
}
pub async fn send_stream(
self,
) -> Result<Pin<Box<dyn Stream<Item = Result<ChatResponseStream, Error>> + Send>>, Error> {
Client::new().chat().create_stream(self).await
}
}
/// Chainable setters
impl ChatRequest {
pub fn system(mut self, message: impl Into<Content>) -> Self {
self.messages.push(ChatMessage::system(message));
self
}
pub fn user(mut self, message: impl Into<String>) -> Self {
self.messages.push(ChatMessage::user(message));
self
}
pub fn developer(mut self, message: impl Into<Content>) -> Self {
self.messages.push(ChatMessage::developer(message));
self
}
pub fn assistant(mut self, message: impl Into<AssistantContent>) -> Self {
self.messages.push(ChatMessage::assistant(message));
self
}
pub fn tool(mut self, message: impl Into<Content>, tool_call_id: impl Into<String>) -> Self {
self.messages.push(ChatMessage::tool(message, tool_call_id));
self
}
pub fn tool_choice(mut self, tool_choice: ChatToolChoice) -> Self {
self.tool_choice = Some(tool_choice);
self
}
pub fn model(mut self, model: impl Into<String>) -> Self {
self.model = model.into();
self
}
pub fn stream(mut self) -> Self {
self.stream = Some(true);
self
}
pub fn tools(mut self, tools: Vec<impl Into<ChatTool>>) -> Self {
self.tools = Some(tools.into_iter().map(Into::into).collect::<Vec<ChatTool>>());
self
}
pub fn response_format(mut self, response_format: impl Into<ChatResponseFormat>) -> Self {
self.response_format = Some(response_format.into());
self
}
}
impl ChatRequest {
pub fn to_string_pretty(&self) -> Result<String, Error> {
Ok(serde_json::to_string_pretty(&self)?)
}
}
impl Requestable for ChatRequest {
fn stream(&self) -> bool {
self.stream.unwrap_or(false)
}
}
impl Printable for ChatRequest {
fn to_string_pretty(&self) -> Result<String, Error> {
Ok(serde_json::to_string_pretty(self)?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn chat_request_works() {
let request = ChatRequest::new(
"gpt-4o-mini",
vec![
ChatMessage::system("You are a helpful assistant"),
ChatMessage::user("Who are you?"),
],
)
.user("1 + 1 =");
assert!(request.to_string_pretty().is_ok());
}
}