Struct openai_api_rs::v1::api::Client

source ·
pub struct Client {
    pub api_key: String,
}

Fields§

§api_key: String

Implementations§

source§

impl Client

source

pub fn new(api_key: String) -> Self

Examples found in repository?
examples/embedding.rs (line 7)
6
7
8
9
10
11
12
13
14
15
16
17
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
    let req = EmbeddingRequest {
        model: "text-embedding-ada-002".to_string(),
        input: "story time".to_string(),
        user: Option::None,
    };
    let result = client.embedding(req).await?;
    println!("{:?}", result.data);

    Ok(())
}
More examples
Hide additional examples
examples/chat_completion.rs (line 7)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
    let req = ChatCompletionRequest {
        model: chat_completion::GPT4.to_string(),
        messages: vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: Some(String::from("What is Bitcoin?")),
            name: None,
            function_call: None,
        }],
        functions: None,
        function_call: None,
    };
    let result = client.chat_completion(req).await?;
    println!("{:?}", result.choices[0].message.content);
    Ok(())
}
examples/completion.rs (line 7)
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
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
    let req = CompletionRequest {
        model: completion::GPT3_TEXT_DAVINCI_003.to_string(),
        prompt: Some(String::from("What is Bitcoin?")),
        suffix: None,
        max_tokens: Some(3000),
        temperature: Some(0.9),
        top_p: Some(1.0),
        n: None,
        stream: None,
        logprobs: None,
        echo: None,
        stop: Some(vec![String::from(" Human:"), String::from(" AI:")]),
        presence_penalty: Some(0.6),
        frequency_penalty: Some(0.0),
        best_of: None,
        logit_bias: None,
        user: None,
    };
    let result = client.completion(req).await?;
    println!("{:}", result.choices[0].text);

    Ok(())
}
examples/function_call.rs (line 18)
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
async 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 {
        model: chat_completion::GPT3_5_TURBO_0613.to_string(),
        messages: vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: Some(String::from("What is the price of Ethereum?")),
            name: None,
            function_call: None,
        }],
        functions: Some(vec![chat_completion::Function {
            name: String::from("get_coin_price"),
            description: Some(String::from("Get the price of a cryptocurrency")),
            parameters: Some(chat_completion::FunctionParameters {
                schema_type: chat_completion::JSONSchemaType::Object,
                properties: Some(properties),
                required: Some(vec![String::from("coin")]),
            }),
        }]),
        function_call: Some("auto".to_string()),
    };

    let result = client.chat_completion(req).await?;

    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).await;
                println!("{} price: {}", coin, price);
            }
        }
        chat_completion::FinishReason::content_filter => {
            println!("ContentFilter");
        }
        chat_completion::FinishReason::null => {
            println!("Null");
        }
    }
    Ok(())
}
source

pub async fn post<T: Serialize>( &self, path: &str, params: &T ) -> Result<Response, APIError>

source

pub async fn get(&self, path: &str) -> Result<Response, APIError>

source

pub async fn delete(&self, path: &str) -> Result<Response, APIError>

source

pub async fn completion( &self, req: CompletionRequest ) -> Result<CompletionResponse, APIError>

Examples found in repository?
examples/completion.rs (line 26)
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
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
    let req = CompletionRequest {
        model: completion::GPT3_TEXT_DAVINCI_003.to_string(),
        prompt: Some(String::from("What is Bitcoin?")),
        suffix: None,
        max_tokens: Some(3000),
        temperature: Some(0.9),
        top_p: Some(1.0),
        n: None,
        stream: None,
        logprobs: None,
        echo: None,
        stop: Some(vec![String::from(" Human:"), String::from(" AI:")]),
        presence_penalty: Some(0.6),
        frequency_penalty: Some(0.0),
        best_of: None,
        logit_bias: None,
        user: None,
    };
    let result = client.completion(req).await?;
    println!("{:}", result.choices[0].text);

    Ok(())
}
source

pub async fn edit(&self, req: EditRequest) -> Result<EditResponse, APIError>

source

pub async fn image_generation( &self, req: ImageGenerationRequest ) -> Result<ImageGenerationResponse, APIError>

source

pub async fn image_edit( &self, req: ImageEditRequest ) -> Result<ImageEditResponse, APIError>

source

pub async fn image_variation( &self, req: ImageVariationRequest ) -> Result<ImageVariationResponse, APIError>

source

pub async fn embedding( &self, req: EmbeddingRequest ) -> Result<EmbeddingResponse, APIError>

Examples found in repository?
examples/embedding.rs (line 13)
6
7
8
9
10
11
12
13
14
15
16
17
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
    let req = EmbeddingRequest {
        model: "text-embedding-ada-002".to_string(),
        input: "story time".to_string(),
        user: Option::None,
    };
    let result = client.embedding(req).await?;
    println!("{:?}", result.data);

    Ok(())
}
source

pub async fn file_list(&self) -> Result<FileListResponse, APIError>

source

pub async fn file_upload( &self, req: FileUploadRequest ) -> Result<FileUploadResponse, APIError>

source

pub async fn file_delete( &self, req: FileDeleteRequest ) -> Result<FileDeleteResponse, APIError>

source

pub async fn file_retrieve( &self, req: FileRetrieveRequest ) -> Result<FileRetrieveResponse, APIError>

source

pub async fn file_retrieve_content( &self, req: FileRetrieveContentRequest ) -> Result<FileRetrieveContentResponse, APIError>

source

pub async fn chat_completion( &self, req: ChatCompletionRequest ) -> Result<ChatCompletionResponse, APIError>

Examples found in repository?
examples/chat_completion.rs (line 19)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
    let req = ChatCompletionRequest {
        model: chat_completion::GPT4.to_string(),
        messages: vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: Some(String::from("What is Bitcoin?")),
            name: None,
            function_call: None,
        }],
        functions: None,
        function_call: None,
    };
    let result = client.chat_completion(req).await?;
    println!("{:?}", result.choices[0].message.content);
    Ok(())
}
More examples
Hide additional examples
examples/function_call.rs (line 53)
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
async 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 {
        model: chat_completion::GPT3_5_TURBO_0613.to_string(),
        messages: vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: Some(String::from("What is the price of Ethereum?")),
            name: None,
            function_call: None,
        }],
        functions: Some(vec![chat_completion::Function {
            name: String::from("get_coin_price"),
            description: Some(String::from("Get the price of a cryptocurrency")),
            parameters: Some(chat_completion::FunctionParameters {
                schema_type: chat_completion::JSONSchemaType::Object,
                properties: Some(properties),
                required: Some(vec![String::from("coin")]),
            }),
        }]),
        function_call: Some("auto".to_string()),
    };

    let result = client.chat_completion(req).await?;

    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).await;
                println!("{} price: {}", coin, price);
            }
        }
        chat_completion::FinishReason::content_filter => {
            println!("ContentFilter");
        }
        chat_completion::FinishReason::null => {
            println!("Null");
        }
    }
    Ok(())
}
source

pub async fn audio_transcription( &self, req: AudioTranscriptionRequest ) -> Result<AudioTranscriptionResponse, APIError>

source

pub async fn audio_translation( &self, req: AudioTranslationRequest ) -> Result<AudioTranslationResponse, APIError>

source

pub async fn create_fine_tune( &self, req: CreateFineTuneRequest ) -> Result<CreateFineTuneResponse, APIError>

source

pub async fn list_fine_tune(&self) -> Result<ListFineTuneResponse, APIError>

source

pub async fn retrieve_fine_tune( &self, req: RetrieveFineTuneRequest ) -> Result<RetrieveFineTuneResponse, APIError>

source

pub async fn cancel_fine_tune( &self, req: CancelFineTuneRequest ) -> Result<CancelFineTuneResponse, APIError>

source

pub async fn list_fine_tune_events( &self, req: ListFineTuneEventsRequest ) -> Result<ListFineTuneEventsResponse, APIError>

source

pub async fn delete_fine_tune( &self, req: DeleteFineTuneModelRequest ) -> Result<DeleteFineTuneModelResponse, APIError>

source

pub async fn create_moderation( &self, req: CreateModerationRequest ) -> Result<CreateModerationResponse, APIError>

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> 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 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.
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