Struct ChatCompletionRequest

Source
pub struct ChatCompletionRequest {
Show 16 fields pub model: String, pub messages: Vec<ChatCompletionMessage>, pub temperature: Option<f64>, pub top_p: Option<f64>, pub n: Option<i64>, pub response_format: Option<Value>, pub stream: Option<bool>, pub stop: Option<Vec<String>>, pub max_tokens: Option<i64>, pub presence_penalty: Option<f64>, pub frequency_penalty: Option<f64>, pub logit_bias: Option<HashMap<String, i32>>, pub user: Option<String>, pub seed: Option<i64>, pub tools: Option<Vec<Tool>>, pub tool_choice: Option<ToolChoiceType>,
}
Expand description

Represents a request for chat completion.

Fields§

§model: String

Model to be used for the completion.

§messages: Vec<ChatCompletionMessage>

List of messages for the completion.

§temperature: Option<f64>

Sampling temperature.

§top_p: Option<f64>

Nucleus sampling parameter.

§n: Option<i64>

Number of completions to generate.

§response_format: Option<Value>

Format of the response.

§stream: Option<bool>

Whether to stream back partial progress.

§stop: Option<Vec<String>>

Up to 4 sequences where the API will stop generating further tokens.

§max_tokens: Option<i64>

Maximum number of tokens to generate.

§presence_penalty: Option<f64>

Positive values penalize new tokens based on their existing frequency in the text so far.

§frequency_penalty: Option<f64>

Positive values penalize new tokens based on their frequency in the text so far.

§logit_bias: Option<HashMap<String, i32>>

Modify the likelihood of specified tokens appearing in the completion.

§user: Option<String>

A unique identifier representing your end-user.

§seed: Option<i64>

Seed for random number generation.

§tools: Option<Vec<Tool>>

Tools available for the model.

§tool_choice: Option<ToolChoiceType>

Choice of tool for the request.

Implementations§

Source§

impl ChatCompletionRequest

Source

pub fn new(model: Model, message: ChatCompletionMessage) -> Self

Creates a new ChatCompletionRequest with a single message.

Source

pub fn new_multi(model: Model, messages: Vec<ChatCompletionMessage>) -> Self

Creates a new ChatCompletionRequest with multiple messages.

Examples found in repository?
examples/vision.rs (lines 12-34)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10    let client = Client::from_env().unwrap();
11
12    let req = ChatCompletionRequest::new_multi(
13        Model::GPT4(GPT4::GPT40125Preview),
14        vec![chat_completion::ChatCompletionMessage {
15            role: MessageRole::User,
16            content: chat_completion::Content::ImageUrl(vec![
17                chat_completion::ImageUrl {
18                    r#type: chat_completion::ContentType::text,
19                    text: Some(String::from("What’s in this image?")),
20                    image_url: None,
21                },
22                chat_completion::ImageUrl {
23                    r#type: chat_completion::ContentType::image_url,
24                    text: None,
25                    image_url: Some(chat_completion::ImageUrlType {
26                        url: String::from(
27                            "https://upload.wikimedia.org/wikipedia/commons/5/50/Bitcoin.png",
28                        ),
29                    }),
30                },
31            ]),
32            name: None,
33        }],
34    );
35
36    let result = client.chat_completion(req).await?;
37    println!("{:?}", result.choices[0].message.content);
38
39    Ok(())
40}
More examples
Hide additional examples
examples/function_call.rs (lines 36-43)
23async fn main() -> Result<(), Box<dyn std::error::Error>> {
24    let client = Client::from_env().unwrap();
25
26    let mut properties = HashMap::new();
27    properties.insert(
28        "coin".to_string(),
29        Box::new(JSONSchemaDefine {
30            schema_type: Some(JSONSchemaType::String),
31            description: Some("The cryptocurrency to get the price of".to_string()),
32            ..Default::default()
33        }),
34    );
35
36    let req = ChatCompletionRequest::new_multi(
37        Model::GPT3(GPT3::GPT35Turbo),
38        vec![ChatCompletionMessage {
39            role: MessageRole::User,
40            content: Content::Text(String::from("What is the price of Ethereum?")),
41            name: None,
42        }],
43    )
44    .tools(vec![Tool {
45        r#type: ToolType::Function,
46        function: Function {
47            name: String::from("get_coin_price"),
48            description: Some(String::from("Get the price of a cryptocurrency")),
49            parameters: FunctionParameters {
50                schema_type: JSONSchemaType::Object,
51                properties: Some(properties),
52                required: Some(vec![String::from("coin")]),
53            },
54        },
55    }])
56    .tool_choice(ToolChoiceType::Auto);
57
58    let result = client.chat_completion(req).await?;
59
60    match result.choices[0].finish_reason {
61        None => {
62            println!("No finish_reason");
63            println!("{:?}", result.choices[0].message.content);
64        }
65        Some(FinishReason::stop) => {
66            println!("Stop");
67            println!("{:?}", result.choices[0].message.content);
68        }
69        Some(FinishReason::length) => {
70            println!("Length");
71        }
72        Some(FinishReason::tool_calls) => {
73            println!("ToolCalls");
74            #[derive(Deserialize, Serialize)]
75            struct Currency {
76                coin: String,
77            }
78            let tool_calls = result.choices[0].message.tool_calls.as_ref().unwrap();
79            for tool_call in tool_calls {
80                let name = tool_call.function.name.clone().unwrap();
81                let arguments = tool_call.function.arguments.clone().unwrap();
82                let c: Currency = serde_json::from_str(&arguments)?;
83                let coin = c.coin;
84                if name == "get_coin_price" {
85                    let price = get_coin_price(&coin);
86                    println!("{} price: {}", coin, price);
87                }
88            }
89        }
90        Some(FinishReason::content_filter) => {
91            println!("ContentFilter");
92        }
93        Some(FinishReason::null) => {
94            println!("Null");
95        }
96    }
97    Ok(())
98}
examples/function_call_role.rs (lines 33-40)
20async fn main() -> Result<(), Box<dyn std::error::Error>> {
21    let client = Client::from_env().unwrap();
22
23    let mut properties = HashMap::new();
24    properties.insert(
25        "coin".to_string(),
26        Box::new(chat_completion::JSONSchemaDefine {
27            schema_type: Some(chat_completion::JSONSchemaType::String),
28            description: Some("The cryptocurrency to get the price of".to_string()),
29            ..Default::default()
30        }),
31    );
32
33    let req = ChatCompletionRequest::new_multi(
34        Model::GPT3(GPT3::GPT35Turbo),
35        vec![chat_completion::ChatCompletionMessage {
36            role: MessageRole::User,
37            content: chat_completion::Content::Text(String::from("What is the price of Ethereum?")),
38            name: None,
39        }],
40    )
41    .tools(vec![chat_completion::Tool {
42        r#type: chat_completion::ToolType::Function,
43        function: chat_completion::Function {
44            name: String::from("get_coin_price"),
45            description: Some(String::from("Get the price of a cryptocurrency")),
46            parameters: chat_completion::FunctionParameters {
47                schema_type: chat_completion::JSONSchemaType::Object,
48                properties: Some(properties),
49                required: Some(vec![String::from("coin")]),
50            },
51        },
52    }]);
53
54    let result = client.chat_completion(req).await?;
55
56    match result.choices[0].finish_reason {
57        None => {
58            println!("No finish_reason");
59            println!("{:?}", result.choices[0].message.content);
60        }
61        Some(chat_completion::FinishReason::stop) => {
62            println!("Stop");
63            println!("{:?}", result.choices[0].message.content);
64        }
65        Some(chat_completion::FinishReason::length) => {
66            println!("Length");
67        }
68        Some(chat_completion::FinishReason::tool_calls) => {
69            println!("ToolCalls");
70            #[derive(Deserialize, Serialize)]
71            struct Currency {
72                coin: String,
73            }
74            let tool_calls = result.choices[0].message.tool_calls.as_ref().unwrap();
75            for tool_call in tool_calls {
76                let function_call = &tool_call.function;
77                let arguments = function_call.arguments.clone().unwrap();
78                let c: Currency = serde_json::from_str(&arguments)?;
79                let coin = c.coin;
80                println!("coin: {}", coin);
81                let price = get_coin_price(&coin);
82                println!("price: {}", price);
83
84                let req = ChatCompletionRequest::new_multi(
85                    Model::GPT3(GPT3::GPT35Turbo),
86                    vec![
87                        chat_completion::ChatCompletionMessage {
88                            role: MessageRole::User,
89                            content: chat_completion::Content::Text(String::from(
90                                "What is the price of Ethereum?",
91                            )),
92                            name: None,
93                        },
94                        chat_completion::ChatCompletionMessage {
95                            role: MessageRole::Function,
96                            content: chat_completion::Content::Text({
97                                let price = get_coin_price(&coin);
98                                format!("{{\"price\": {}}}", price)
99                            }),
100                            name: Some(String::from("get_coin_price")),
101                        },
102                    ],
103                );
104
105                let result = client.chat_completion(req).await?;
106                println!("{:?}", result.choices[0].message.content);
107            }
108        }
109        Some(chat_completion::FinishReason::content_filter) => {
110            println!("ContentFilter");
111        }
112        Some(chat_completion::FinishReason::null) => {
113            println!("Null");
114        }
115    }
116    Ok(())
117}
Source§

impl ChatCompletionRequest

Source

pub fn temperature(self, temperature: f64) -> Self

Sets the value of the specified field.

Source

pub fn top_p(self, top_p: f64) -> Self

Sets the value of the specified field.

Source

pub fn n(self, n: i64) -> Self

Sets the value of the specified field.

Source

pub fn response_format(self, response_format: Value) -> Self

Sets the value of the specified field.

Source

pub fn stream(self, stream: bool) -> Self

Sets the value of the specified field.

Source

pub fn stop(self, stop: Vec<String>) -> Self

Sets the value of the specified field.

Source

pub fn max_tokens(self, max_tokens: i64) -> Self

Sets the value of the specified field.

Source

pub fn presence_penalty(self, presence_penalty: f64) -> Self

Sets the value of the specified field.

Source

pub fn frequency_penalty(self, frequency_penalty: f64) -> Self

Sets the value of the specified field.

Source

pub fn logit_bias(self, logit_bias: HashMap<String, i32>) -> Self

Sets the value of the specified field.

Source

pub fn user(self, user: String) -> Self

Sets the value of the specified field.

Source

pub fn seed(self, seed: i64) -> Self

Sets the value of the specified field.

Source

pub fn tools(self, tools: Vec<Tool>) -> Self

Sets the value of the specified field.

Examples found in repository?
examples/function_call.rs (lines 44-55)
23async fn main() -> Result<(), Box<dyn std::error::Error>> {
24    let client = Client::from_env().unwrap();
25
26    let mut properties = HashMap::new();
27    properties.insert(
28        "coin".to_string(),
29        Box::new(JSONSchemaDefine {
30            schema_type: Some(JSONSchemaType::String),
31            description: Some("The cryptocurrency to get the price of".to_string()),
32            ..Default::default()
33        }),
34    );
35
36    let req = ChatCompletionRequest::new_multi(
37        Model::GPT3(GPT3::GPT35Turbo),
38        vec![ChatCompletionMessage {
39            role: MessageRole::User,
40            content: Content::Text(String::from("What is the price of Ethereum?")),
41            name: None,
42        }],
43    )
44    .tools(vec![Tool {
45        r#type: ToolType::Function,
46        function: Function {
47            name: String::from("get_coin_price"),
48            description: Some(String::from("Get the price of a cryptocurrency")),
49            parameters: FunctionParameters {
50                schema_type: JSONSchemaType::Object,
51                properties: Some(properties),
52                required: Some(vec![String::from("coin")]),
53            },
54        },
55    }])
56    .tool_choice(ToolChoiceType::Auto);
57
58    let result = client.chat_completion(req).await?;
59
60    match result.choices[0].finish_reason {
61        None => {
62            println!("No finish_reason");
63            println!("{:?}", result.choices[0].message.content);
64        }
65        Some(FinishReason::stop) => {
66            println!("Stop");
67            println!("{:?}", result.choices[0].message.content);
68        }
69        Some(FinishReason::length) => {
70            println!("Length");
71        }
72        Some(FinishReason::tool_calls) => {
73            println!("ToolCalls");
74            #[derive(Deserialize, Serialize)]
75            struct Currency {
76                coin: String,
77            }
78            let tool_calls = result.choices[0].message.tool_calls.as_ref().unwrap();
79            for tool_call in tool_calls {
80                let name = tool_call.function.name.clone().unwrap();
81                let arguments = tool_call.function.arguments.clone().unwrap();
82                let c: Currency = serde_json::from_str(&arguments)?;
83                let coin = c.coin;
84                if name == "get_coin_price" {
85                    let price = get_coin_price(&coin);
86                    println!("{} price: {}", coin, price);
87                }
88            }
89        }
90        Some(FinishReason::content_filter) => {
91            println!("ContentFilter");
92        }
93        Some(FinishReason::null) => {
94            println!("Null");
95        }
96    }
97    Ok(())
98}
More examples
Hide additional examples
examples/function_call_role.rs (lines 41-52)
20async fn main() -> Result<(), Box<dyn std::error::Error>> {
21    let client = Client::from_env().unwrap();
22
23    let mut properties = HashMap::new();
24    properties.insert(
25        "coin".to_string(),
26        Box::new(chat_completion::JSONSchemaDefine {
27            schema_type: Some(chat_completion::JSONSchemaType::String),
28            description: Some("The cryptocurrency to get the price of".to_string()),
29            ..Default::default()
30        }),
31    );
32
33    let req = ChatCompletionRequest::new_multi(
34        Model::GPT3(GPT3::GPT35Turbo),
35        vec![chat_completion::ChatCompletionMessage {
36            role: MessageRole::User,
37            content: chat_completion::Content::Text(String::from("What is the price of Ethereum?")),
38            name: None,
39        }],
40    )
41    .tools(vec![chat_completion::Tool {
42        r#type: chat_completion::ToolType::Function,
43        function: chat_completion::Function {
44            name: String::from("get_coin_price"),
45            description: Some(String::from("Get the price of a cryptocurrency")),
46            parameters: chat_completion::FunctionParameters {
47                schema_type: chat_completion::JSONSchemaType::Object,
48                properties: Some(properties),
49                required: Some(vec![String::from("coin")]),
50            },
51        },
52    }]);
53
54    let result = client.chat_completion(req).await?;
55
56    match result.choices[0].finish_reason {
57        None => {
58            println!("No finish_reason");
59            println!("{:?}", result.choices[0].message.content);
60        }
61        Some(chat_completion::FinishReason::stop) => {
62            println!("Stop");
63            println!("{:?}", result.choices[0].message.content);
64        }
65        Some(chat_completion::FinishReason::length) => {
66            println!("Length");
67        }
68        Some(chat_completion::FinishReason::tool_calls) => {
69            println!("ToolCalls");
70            #[derive(Deserialize, Serialize)]
71            struct Currency {
72                coin: String,
73            }
74            let tool_calls = result.choices[0].message.tool_calls.as_ref().unwrap();
75            for tool_call in tool_calls {
76                let function_call = &tool_call.function;
77                let arguments = function_call.arguments.clone().unwrap();
78                let c: Currency = serde_json::from_str(&arguments)?;
79                let coin = c.coin;
80                println!("coin: {}", coin);
81                let price = get_coin_price(&coin);
82                println!("price: {}", price);
83
84                let req = ChatCompletionRequest::new_multi(
85                    Model::GPT3(GPT3::GPT35Turbo),
86                    vec![
87                        chat_completion::ChatCompletionMessage {
88                            role: MessageRole::User,
89                            content: chat_completion::Content::Text(String::from(
90                                "What is the price of Ethereum?",
91                            )),
92                            name: None,
93                        },
94                        chat_completion::ChatCompletionMessage {
95                            role: MessageRole::Function,
96                            content: chat_completion::Content::Text({
97                                let price = get_coin_price(&coin);
98                                format!("{{\"price\": {}}}", price)
99                            }),
100                            name: Some(String::from("get_coin_price")),
101                        },
102                    ],
103                );
104
105                let result = client.chat_completion(req).await?;
106                println!("{:?}", result.choices[0].message.content);
107            }
108        }
109        Some(chat_completion::FinishReason::content_filter) => {
110            println!("ContentFilter");
111        }
112        Some(chat_completion::FinishReason::null) => {
113            println!("Null");
114        }
115    }
116    Ok(())
117}
Source

pub fn tool_choice(self, tool_choice: ToolChoiceType) -> Self

Sets the value of the specified field.

Examples found in repository?
examples/function_call.rs (line 56)
23async fn main() -> Result<(), Box<dyn std::error::Error>> {
24    let client = Client::from_env().unwrap();
25
26    let mut properties = HashMap::new();
27    properties.insert(
28        "coin".to_string(),
29        Box::new(JSONSchemaDefine {
30            schema_type: Some(JSONSchemaType::String),
31            description: Some("The cryptocurrency to get the price of".to_string()),
32            ..Default::default()
33        }),
34    );
35
36    let req = ChatCompletionRequest::new_multi(
37        Model::GPT3(GPT3::GPT35Turbo),
38        vec![ChatCompletionMessage {
39            role: MessageRole::User,
40            content: Content::Text(String::from("What is the price of Ethereum?")),
41            name: None,
42        }],
43    )
44    .tools(vec![Tool {
45        r#type: ToolType::Function,
46        function: Function {
47            name: String::from("get_coin_price"),
48            description: Some(String::from("Get the price of a cryptocurrency")),
49            parameters: FunctionParameters {
50                schema_type: JSONSchemaType::Object,
51                properties: Some(properties),
52                required: Some(vec![String::from("coin")]),
53            },
54        },
55    }])
56    .tool_choice(ToolChoiceType::Auto);
57
58    let result = client.chat_completion(req).await?;
59
60    match result.choices[0].finish_reason {
61        None => {
62            println!("No finish_reason");
63            println!("{:?}", result.choices[0].message.content);
64        }
65        Some(FinishReason::stop) => {
66            println!("Stop");
67            println!("{:?}", result.choices[0].message.content);
68        }
69        Some(FinishReason::length) => {
70            println!("Length");
71        }
72        Some(FinishReason::tool_calls) => {
73            println!("ToolCalls");
74            #[derive(Deserialize, Serialize)]
75            struct Currency {
76                coin: String,
77            }
78            let tool_calls = result.choices[0].message.tool_calls.as_ref().unwrap();
79            for tool_call in tool_calls {
80                let name = tool_call.function.name.clone().unwrap();
81                let arguments = tool_call.function.arguments.clone().unwrap();
82                let c: Currency = serde_json::from_str(&arguments)?;
83                let coin = c.coin;
84                if name == "get_coin_price" {
85                    let price = get_coin_price(&coin);
86                    println!("{} price: {}", coin, price);
87                }
88            }
89        }
90        Some(FinishReason::content_filter) => {
91            println!("ContentFilter");
92        }
93        Some(FinishReason::null) => {
94            println!("Null");
95        }
96    }
97    Ok(())
98}

Trait Implementations§

Source§

impl Clone for ChatCompletionRequest

Source§

fn clone(&self) -> ChatCompletionRequest

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ChatCompletionRequest

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for ChatCompletionRequest

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<&str> for ChatCompletionRequest

Source§

fn from(text: &str) -> Self

Converts a string into a ChatCompletionRequest.

Source§

impl Serialize for ChatCompletionRequest

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,