Client

Struct Client 

Source
pub struct Client { /* private fields */ }

Implementations§

Source§

impl Client

Source

pub fn new(key: &str) -> Client

Creates a new client with the given api key.

Examples found in repository?
examples/image.rs (line 16)
6async fn main() {
7    let mut prompt = String::new();
8
9    print!("Enter a prompt: ");
10    let _ = stdout().flush();
11
12    stdin().read_line(&mut prompt).unwrap();
13
14    println!("Generating image...\n");
15
16    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().as_str());
17
18    let resp = client
19        .create_image(|args| args.prompt(prompt).size(ImageSize::Medium).n(1))
20        .await
21        .unwrap();
22
23    let url = resp.get_content(0).unwrap();
24
25    println!("Url: {}", url);
26}
More examples
Hide additional examples
examples/completion.rs (line 15)
7async fn main() {
8    let mut prompt = String::new();
9
10    print!("Enter a prompt: ");
11    let _ = stdout().flush();
12
13    stdin().read_line(&mut prompt).unwrap();
14
15    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().as_str());
16
17    let resp = client
18        .create_completion(|args| {
19            args.prompt(prompt)
20                .model(CompletionModels::TextDavinci3)
21                .max_tokens(32)
22                .n(1)
23                .temperature(1.0)
24        })
25        .await
26        .unwrap();
27
28    let completion = resp.get_content(0).unwrap();
29
30    println!("{}", completion);
31}
examples/edit.rs (line 21)
7async fn main() {
8    let mut prompt = String::new();
9    let mut instruction = String::new();
10
11    print!("Enter a prompt: ");
12    let _ = stdout().flush();
13
14    stdin().read_line(&mut prompt).unwrap();
15
16    print!("Enter the instruction: ");
17    let _ = stdout().flush();
18
19    stdin().read_line(&mut instruction).unwrap();
20
21    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().as_str());
22
23    let resp = client
24        .create_edit(|args| {
25            args.input(prompt)
26                .instruction(instruction)
27                .model(EditModels::TextDavinciEdit1)
28                .n(1)
29                .temperature(1.0)
30        })
31        .await
32        .unwrap();
33
34    let text = resp.get_content(0).unwrap();
35
36    println!("{}", text);
37}
examples/chat.rs (line 8)
7async fn main() {
8    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().as_str());
9
10    let mut role: String;
11    let mut message = String::new();
12
13    let mut index = String::new();
14
15    print!("    1: system\n    2: assistant\n    3: user\nSelect a role: ");
16    let _ = stdout().flush();
17
18    stdin().read_line(&mut index).unwrap();
19
20    if index.trim() == "1" {
21        role = "system".to_string();
22    } else if index.trim() == "2" {
23        role = "assistant".to_string();
24    } else if index.trim() == "3" {
25        role = "user".to_string();
26    } else {
27        panic!("Invalid role!");
28    }
29
30    role = role.trim().to_string();
31
32    print!("Enter a message: ");
33    let _ = stdout().flush();
34
35    stdin().read_line(&mut message).unwrap();
36
37    let content = message.trim().to_string();
38
39    let message = Message { role, content };
40
41    let message = vec![message];
42
43    let resp = client
44        .create_chat_completion(|args| args.messages(message))
45        .await
46        .unwrap();
47
48    let content = resp.get_content(0).unwrap();
49
50    println!("Response: {}", content);
51}
Source

pub async fn create_completion<T>( &self, f: T, ) -> Result<CompletionResp, ResponseError>
where T: FnOnce(&mut CompletionArgs) -> &mut CompletionArgs,

Makes an api call to OpenAI Completion API and returns the response.

§Arguments
  • f - A closure that takes a mutable reference to CompletionArgs and returns it.
§Example
use openai_gpt_rs::{args::CompletionArgs, client::Client, response::{CompletionResp, Content}, models::CompletionModels};
use std::env;

#[tokio::main]
async fn main() {
    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().as_str());

    let resp = client.create_completion(|args| {
                    args.prompt("This is a test")
                        .model(CompletionModels::TextDavinci3)
                        .max_tokens(32)
                        .n(5)
               })
           .await
          .unwrap();

    let text = resp.get_contents(0..5);

    for val in text {
       assert!(!val.is_empty());
   }
}
§Panics

This function will panic if the request to OpenAI fails.

Examples found in repository?
examples/completion.rs (lines 18-24)
7async fn main() {
8    let mut prompt = String::new();
9
10    print!("Enter a prompt: ");
11    let _ = stdout().flush();
12
13    stdin().read_line(&mut prompt).unwrap();
14
15    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().as_str());
16
17    let resp = client
18        .create_completion(|args| {
19            args.prompt(prompt)
20                .model(CompletionModels::TextDavinci3)
21                .max_tokens(32)
22                .n(1)
23                .temperature(1.0)
24        })
25        .await
26        .unwrap();
27
28    let completion = resp.get_content(0).unwrap();
29
30    println!("{}", completion);
31}
Source

pub async fn create_edit<T>(&self, f: T) -> Result<EditResp, ResponseError>
where T: FnOnce(&mut EditArgs) -> &mut EditArgs,

Makes an api call to OpenAI Edit API and returns the response.

§Arguments
  • f - A closure that takes a mutable reference to EditArgs and returns it.
§Example
use openai_gpt_rs::{args::EditArgs, client::Client, response::{EditResp, Content}, models::EditModels};
use std::env;

#[tokio::main]
async fn main() {
    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().as_str());

    let resp = client.create_edit(|args| {
                    args.model(EditModels::TextDavinciEdit1)
                        .input("How is you dae")
                        .instruction("Fix the spelling mistakes")
                        .n(5)
                })
               .await
               .unwrap();

    let text = resp.get_contents(0..5);

    for val in text {
        assert!(!val.is_empty());
    }
}
§Panics

This function will panic if the request to OpenAI fails.

Examples found in repository?
examples/edit.rs (lines 24-30)
7async fn main() {
8    let mut prompt = String::new();
9    let mut instruction = String::new();
10
11    print!("Enter a prompt: ");
12    let _ = stdout().flush();
13
14    stdin().read_line(&mut prompt).unwrap();
15
16    print!("Enter the instruction: ");
17    let _ = stdout().flush();
18
19    stdin().read_line(&mut instruction).unwrap();
20
21    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().as_str());
22
23    let resp = client
24        .create_edit(|args| {
25            args.input(prompt)
26                .instruction(instruction)
27                .model(EditModels::TextDavinciEdit1)
28                .n(1)
29                .temperature(1.0)
30        })
31        .await
32        .unwrap();
33
34    let text = resp.get_content(0).unwrap();
35
36    println!("{}", text);
37}
Source

pub async fn create_image<T>(&self, f: T) -> Result<ImageResp, ResponseError>
where T: FnOnce(&mut ImageArgs) -> &mut ImageArgs,

Makes an api call to OpenAI Image API and returns the response.

§Arguments
  • f - A closure that takes a mutable reference to ImageArgs and returns it.
§Example
use openai_gpt_rs::{args::{ImageArgs, ImageSize}, client::Client, response::{ImageResp, Content}};
use std::env;

#[tokio::main]
async fn main() {
    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().as_str());
     
    let resp = client.create_image(|args| {
                        args.prompt("Kitty")
                            .size(ImageSize::Small)
                            .n(2)
                    })
                    .await
                    .unwrap();

    let urls = resp.get_contents(0..2);

    for val in urls {
        assert!(!val.is_empty());
    }
}
§Panics

This function will panic if the request to OpenAI fails.

Examples found in repository?
examples/image.rs (line 19)
6async fn main() {
7    let mut prompt = String::new();
8
9    print!("Enter a prompt: ");
10    let _ = stdout().flush();
11
12    stdin().read_line(&mut prompt).unwrap();
13
14    println!("Generating image...\n");
15
16    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().as_str());
17
18    let resp = client
19        .create_image(|args| args.prompt(prompt).size(ImageSize::Medium).n(1))
20        .await
21        .unwrap();
22
23    let url = resp.get_content(0).unwrap();
24
25    println!("Url: {}", url);
26}
Source

pub fn get_key(&self) -> &String

Returns the client’s api key.

Source

pub fn set_key(&mut self, new_key: &str)

Sets the client’s api key to the value of given key.

Source

pub async fn get_models(&self) -> Result<Value, Error>

Returns a json listing all the models

Source

pub async fn create_chat_completion<T>( &self, f: T, ) -> Result<ChatResp, ResponseError>
where T: FnOnce(&mut ChatArgs) -> &mut ChatArgs,

Makes an api call to OpenAI Chat Completion API and returns the response.

§Arguments
  • f - A closure that takes a mutable reference to ChatArgs and returns it.
§Example
use openai_gpt_rs::{args::ChatArgs, client::Client, response::{ChatResp, Content}, models::ChatModels, chat::Message};
use std::env;
use std::collections::HashMap;

#[tokio::main]
async fn main() {
    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().as_str());

    let message1 = Message {
        role: "user".to_string(),
        content: "Who won the world series in 2020?".to_string(),
    };

    let message2 = Message {
        role: "system".to_string(),
        content: "You are a helpful assistant.".to_string(),
    };

    let messages = vec![message1, message2];

    let resp = client
        .create_chat_completion(|args| args.messages(messages.clone()))
        .await
        .unwrap();

    let contents = resp.get_content(0).unwrap();

    assert!(!contents.is_empty());
}
§Errors

This function will return an error if the api call fails. The error will be of type reqwest::Error.

Examples found in repository?
examples/chat.rs (line 44)
7async fn main() {
8    let client = Client::new(env::var("OPENAI_API_KEY").unwrap().as_str());
9
10    let mut role: String;
11    let mut message = String::new();
12
13    let mut index = String::new();
14
15    print!("    1: system\n    2: assistant\n    3: user\nSelect a role: ");
16    let _ = stdout().flush();
17
18    stdin().read_line(&mut index).unwrap();
19
20    if index.trim() == "1" {
21        role = "system".to_string();
22    } else if index.trim() == "2" {
23        role = "assistant".to_string();
24    } else if index.trim() == "3" {
25        role = "user".to_string();
26    } else {
27        panic!("Invalid role!");
28    }
29
30    role = role.trim().to_string();
31
32    print!("Enter a message: ");
33    let _ = stdout().flush();
34
35    stdin().read_line(&mut message).unwrap();
36
37    let content = message.trim().to_string();
38
39    let message = Message { role, content };
40
41    let message = vec![message];
42
43    let resp = client
44        .create_chat_completion(|args| args.messages(message))
45        .await
46        .unwrap();
47
48    let content = resp.get_content(0).unwrap();
49
50    println!("Response: {}", content);
51}

Auto Trait Implementations§

§

impl Freeze for Client

§

impl !RefUnwindSafe for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl !UnwindSafe for Client

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> 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, 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> ErasedDestructor for T
where T: 'static,