pub struct ChatCompletionRequest {
Show 14 fields pub model: String, pub messages: Vec<ChatCompletionMessage>, pub functions: Option<Vec<Function>>, pub function_call: Option<FunctionCallType>, pub temperature: Option<f64>, pub top_p: Option<f64>, pub n: Option<i64>, 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>,
}

Fields§

§model: String§messages: Vec<ChatCompletionMessage>§functions: Option<Vec<Function>>§function_call: Option<FunctionCallType>§temperature: Option<f64>§top_p: Option<f64>§n: Option<i64>§stream: Option<bool>§stop: Option<Vec<String>>§max_tokens: Option<i64>§presence_penalty: Option<f64>§frequency_penalty: Option<f64>§logit_bias: Option<HashMap<String, i32>>§user: Option<String>

Implementations§

source§

impl ChatCompletionRequest

source

pub fn new(model: String, messages: Vec<ChatCompletionMessage>) -> Self

Examples found in repository?
examples/chat_completion.rs (lines 8-16)
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let req = ChatCompletionRequest::new(
        chat_completion::GPT4.to_string(),
        vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: String::from("What is Bitcoin?"),
            name: None,
            function_call: None,
        }],
    );

    let result = client.chat_completion(req)?;
    println!("{:?}", result.choices[0].message.content);

    Ok(())
}
More examples
Hide additional examples
examples/function_call.rs (lines 32-40)
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
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let mut properties = HashMap::new();
    properties.insert(
        "coin".to_string(),
        Box::new(chat_completion::JSONSchemaDefine {
            schema_type: Some(chat_completion::JSONSchemaType::String),
            description: Some("The cryptocurrency to get the price of".to_string()),
            enum_values: None,
            properties: None,
            required: None,
            items: None,
        }),
    );

    let req = ChatCompletionRequest::new(
        chat_completion::GPT3_5_TURBO_0613.to_string(),
        vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: String::from("What is the price of Ethereum?"),
            name: None,
            function_call: None,
        }],
    )
    .functions(vec![chat_completion::Function {
        name: String::from("get_coin_price"),
        description: Some(String::from("Get the price of a cryptocurrency")),
        parameters: chat_completion::FunctionParameters {
            schema_type: chat_completion::JSONSchemaType::Object,
            properties: Some(properties),
            required: Some(vec![String::from("coin")]),
        },
    }])
    .function_call(FunctionCallType::Auto);

    // debug reuqest json
    // let serialized = serde_json::to_string(&req).unwrap();
    // println!("{}", serialized);

    let result = client.chat_completion(req)?;

    match result.choices[0].finish_reason {
        chat_completion::FinishReason::stop => {
            println!("Stop");
            println!("{:?}", result.choices[0].message.content);
        }
        chat_completion::FinishReason::length => {
            println!("Length");
        }
        chat_completion::FinishReason::function_call => {
            println!("FunctionCall");
            #[derive(Serialize, Deserialize)]
            struct Currency {
                coin: String,
            }
            let function_call = result.choices[0].message.function_call.as_ref().unwrap();
            let name = function_call.name.clone().unwrap();
            let arguments = function_call.arguments.clone().unwrap();
            let c: Currency = serde_json::from_str(&arguments)?;
            let coin = c.coin;
            if name == "get_coin_price" {
                let price = get_coin_price(&coin);
                println!("{} price: {}", coin, price);
            }
        }
        chat_completion::FinishReason::content_filter => {
            println!("ContentFilter");
        }
        chat_completion::FinishReason::null => {
            println!("Null");
        }
    }
    Ok(())
}
examples/function_call_role.rs (lines 32-40)
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
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let mut properties = HashMap::new();
    properties.insert(
        "coin".to_string(),
        Box::new(chat_completion::JSONSchemaDefine {
            schema_type: Some(chat_completion::JSONSchemaType::String),
            description: Some("The cryptocurrency to get the price of".to_string()),
            enum_values: None,
            properties: None,
            required: None,
            items: None,
        }),
    );

    let req = ChatCompletionRequest::new(
        chat_completion::GPT3_5_TURBO_0613.to_string(),
        vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: String::from("What is the price of Ethereum?"),
            name: None,
            function_call: None,
        }],
    )
    .functions(vec![chat_completion::Function {
        name: String::from("get_coin_price"),
        description: Some(String::from("Get the price of a cryptocurrency")),
        parameters: chat_completion::FunctionParameters {
            schema_type: chat_completion::JSONSchemaType::Object,
            properties: Some(properties),
            required: Some(vec![String::from("coin")]),
        },
    }]);

    let result = client.chat_completion(req)?;

    match result.choices[0].finish_reason {
        chat_completion::FinishReason::stop => {
            println!("Stop");
            println!("{:?}", result.choices[0].message.content);
        }
        chat_completion::FinishReason::length => {
            println!("Length");
        }
        chat_completion::FinishReason::function_call => {
            println!("FunctionCall");
            #[derive(Serialize, Deserialize)]
            struct Currency {
                coin: String,
            }
            let function_call = result.choices[0].message.function_call.as_ref().unwrap();
            let arguments = function_call.arguments.clone().unwrap();
            let c: Currency = serde_json::from_str(&arguments)?;
            let coin = c.coin;

            let req = ChatCompletionRequest::new(
                chat_completion::GPT3_5_TURBO_0613.to_string(),
                vec![
                    chat_completion::ChatCompletionMessage {
                        role: chat_completion::MessageRole::user,
                        content: String::from("What is the price of Ethereum?"),
                        name: None,
                        function_call: None,
                    },
                    chat_completion::ChatCompletionMessage {
                        role: chat_completion::MessageRole::function,
                        content: {
                            let price = get_coin_price(&coin);
                            format!("{{\"price\": {}}}", price)
                        },
                        name: Some(String::from("get_coin_price")),
                        function_call: None,
                    },
                ],
            );

            let result = client.chat_completion(req)?;
            println!("{:?}", result.choices[0].message.content);
        }
        chat_completion::FinishReason::content_filter => {
            println!("ContentFilter");
        }
        chat_completion::FinishReason::null => {
            println!("Null");
        }
    }
    Ok(())
}
source§

impl ChatCompletionRequest

source

pub fn functions(self, functions: Vec<Function>) -> Self

Examples found in repository?
examples/function_call.rs (lines 41-49)
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
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let mut properties = HashMap::new();
    properties.insert(
        "coin".to_string(),
        Box::new(chat_completion::JSONSchemaDefine {
            schema_type: Some(chat_completion::JSONSchemaType::String),
            description: Some("The cryptocurrency to get the price of".to_string()),
            enum_values: None,
            properties: None,
            required: None,
            items: None,
        }),
    );

    let req = ChatCompletionRequest::new(
        chat_completion::GPT3_5_TURBO_0613.to_string(),
        vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: String::from("What is the price of Ethereum?"),
            name: None,
            function_call: None,
        }],
    )
    .functions(vec![chat_completion::Function {
        name: String::from("get_coin_price"),
        description: Some(String::from("Get the price of a cryptocurrency")),
        parameters: chat_completion::FunctionParameters {
            schema_type: chat_completion::JSONSchemaType::Object,
            properties: Some(properties),
            required: Some(vec![String::from("coin")]),
        },
    }])
    .function_call(FunctionCallType::Auto);

    // debug reuqest json
    // let serialized = serde_json::to_string(&req).unwrap();
    // println!("{}", serialized);

    let result = client.chat_completion(req)?;

    match result.choices[0].finish_reason {
        chat_completion::FinishReason::stop => {
            println!("Stop");
            println!("{:?}", result.choices[0].message.content);
        }
        chat_completion::FinishReason::length => {
            println!("Length");
        }
        chat_completion::FinishReason::function_call => {
            println!("FunctionCall");
            #[derive(Serialize, Deserialize)]
            struct Currency {
                coin: String,
            }
            let function_call = result.choices[0].message.function_call.as_ref().unwrap();
            let name = function_call.name.clone().unwrap();
            let arguments = function_call.arguments.clone().unwrap();
            let c: Currency = serde_json::from_str(&arguments)?;
            let coin = c.coin;
            if name == "get_coin_price" {
                let price = get_coin_price(&coin);
                println!("{} price: {}", coin, price);
            }
        }
        chat_completion::FinishReason::content_filter => {
            println!("ContentFilter");
        }
        chat_completion::FinishReason::null => {
            println!("Null");
        }
    }
    Ok(())
}
More examples
Hide additional examples
examples/function_call_role.rs (lines 41-49)
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
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let mut properties = HashMap::new();
    properties.insert(
        "coin".to_string(),
        Box::new(chat_completion::JSONSchemaDefine {
            schema_type: Some(chat_completion::JSONSchemaType::String),
            description: Some("The cryptocurrency to get the price of".to_string()),
            enum_values: None,
            properties: None,
            required: None,
            items: None,
        }),
    );

    let req = ChatCompletionRequest::new(
        chat_completion::GPT3_5_TURBO_0613.to_string(),
        vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: String::from("What is the price of Ethereum?"),
            name: None,
            function_call: None,
        }],
    )
    .functions(vec![chat_completion::Function {
        name: String::from("get_coin_price"),
        description: Some(String::from("Get the price of a cryptocurrency")),
        parameters: chat_completion::FunctionParameters {
            schema_type: chat_completion::JSONSchemaType::Object,
            properties: Some(properties),
            required: Some(vec![String::from("coin")]),
        },
    }]);

    let result = client.chat_completion(req)?;

    match result.choices[0].finish_reason {
        chat_completion::FinishReason::stop => {
            println!("Stop");
            println!("{:?}", result.choices[0].message.content);
        }
        chat_completion::FinishReason::length => {
            println!("Length");
        }
        chat_completion::FinishReason::function_call => {
            println!("FunctionCall");
            #[derive(Serialize, Deserialize)]
            struct Currency {
                coin: String,
            }
            let function_call = result.choices[0].message.function_call.as_ref().unwrap();
            let arguments = function_call.arguments.clone().unwrap();
            let c: Currency = serde_json::from_str(&arguments)?;
            let coin = c.coin;

            let req = ChatCompletionRequest::new(
                chat_completion::GPT3_5_TURBO_0613.to_string(),
                vec![
                    chat_completion::ChatCompletionMessage {
                        role: chat_completion::MessageRole::user,
                        content: String::from("What is the price of Ethereum?"),
                        name: None,
                        function_call: None,
                    },
                    chat_completion::ChatCompletionMessage {
                        role: chat_completion::MessageRole::function,
                        content: {
                            let price = get_coin_price(&coin);
                            format!("{{\"price\": {}}}", price)
                        },
                        name: Some(String::from("get_coin_price")),
                        function_call: None,
                    },
                ],
            );

            let result = client.chat_completion(req)?;
            println!("{:?}", result.choices[0].message.content);
        }
        chat_completion::FinishReason::content_filter => {
            println!("ContentFilter");
        }
        chat_completion::FinishReason::null => {
            println!("Null");
        }
    }
    Ok(())
}
source

pub fn function_call(self, function_call: FunctionCallType) -> Self

Examples found in repository?
examples/function_call.rs (line 50)
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
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());

    let mut properties = HashMap::new();
    properties.insert(
        "coin".to_string(),
        Box::new(chat_completion::JSONSchemaDefine {
            schema_type: Some(chat_completion::JSONSchemaType::String),
            description: Some("The cryptocurrency to get the price of".to_string()),
            enum_values: None,
            properties: None,
            required: None,
            items: None,
        }),
    );

    let req = ChatCompletionRequest::new(
        chat_completion::GPT3_5_TURBO_0613.to_string(),
        vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: String::from("What is the price of Ethereum?"),
            name: None,
            function_call: None,
        }],
    )
    .functions(vec![chat_completion::Function {
        name: String::from("get_coin_price"),
        description: Some(String::from("Get the price of a cryptocurrency")),
        parameters: chat_completion::FunctionParameters {
            schema_type: chat_completion::JSONSchemaType::Object,
            properties: Some(properties),
            required: Some(vec![String::from("coin")]),
        },
    }])
    .function_call(FunctionCallType::Auto);

    // debug reuqest json
    // let serialized = serde_json::to_string(&req).unwrap();
    // println!("{}", serialized);

    let result = client.chat_completion(req)?;

    match result.choices[0].finish_reason {
        chat_completion::FinishReason::stop => {
            println!("Stop");
            println!("{:?}", result.choices[0].message.content);
        }
        chat_completion::FinishReason::length => {
            println!("Length");
        }
        chat_completion::FinishReason::function_call => {
            println!("FunctionCall");
            #[derive(Serialize, Deserialize)]
            struct Currency {
                coin: String,
            }
            let function_call = result.choices[0].message.function_call.as_ref().unwrap();
            let name = function_call.name.clone().unwrap();
            let arguments = function_call.arguments.clone().unwrap();
            let c: Currency = serde_json::from_str(&arguments)?;
            let coin = c.coin;
            if name == "get_coin_price" {
                let price = get_coin_price(&coin);
                println!("{} price: {}", coin, price);
            }
        }
        chat_completion::FinishReason::content_filter => {
            println!("ContentFilter");
        }
        chat_completion::FinishReason::null => {
            println!("Null");
        }
    }
    Ok(())
}
source

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

source

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

source

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

source

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

source

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

source

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

source

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

source

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

source

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

source

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

Trait Implementations§

source§

impl Debug for ChatCompletionRequest

source§

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

Formats the value using the given formatter. Read more
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 Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere 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, U> TryFrom<U> for Twhere U: Into<T>,

§

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 Twhere U: TryFrom<T>,

§

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.