Struct Client

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

Implementations§

Source§

impl Client

Source

pub fn new( base_uri: Option<String>, token: Option<String>, ) -> Result<Client, Error>

Creates a new Client instance.

This function will first check for environment variables OPENAI_API_BASE and OPENAI_API_KEY. If they are not set, it will use the provided base_uri and token parameters. If neither are set, it will use the default API base URI.

If a token is not provided and base_uri is set to the OpenAI API base URI, an error will be returned.

§Arguments
  • base_uri: The base URI of the API, or None to use the environment variable or default.
  • token: The API token, or None to use the environment variable.
§Returns

A Result containing the new Client instance, or an Error if the configuration is invalid.

Source

pub fn new_without_environment( base_uri: String, token: Option<String>, ) -> Result<Client, Error>

Creates a new Client instance without checking environment variables.

This function is used internally by new to create a client without checking for environment variables.

§Arguments
  • base_uri: The base URI of the API.
  • token: The API token, or None if not required.
§Returns

If base_uri is empty, an error will be returned. If base_uri is set to the OpenAI API base URI and token is None, an error will be returned. A Result containing the new Client instance, or an Error if the configuration is invalid.

Source

pub fn new_from_environment() -> Result<Client, Error>

Creates a new Client instance from environment variables.

This function will read the OPENAI_API_BASE and OPENAI_API_KEY environment variables and use them to create a client.

§Returns

A Result containing the new Client instance, or an Error if the environment variables are not set.

Source

pub async fn chat_completions( &self, request: &ChatCompletions, ) -> Result<ChatCompletionsResponse, Error>

Sends a request to the OpenAI API to generate a completion for a chat conversation.

This function takes a ChatCompletions struct as input, which defines the parameters of the completion request, including the chat history, model to use, and desired response format.

The function returns a ChatCompletionsResponse struct, which contains the generated completion.

§Arguments
  • request: The ChatCompletions struct containing the request parameters.
§Returns

A Result containing the ChatCompletionsResponse struct, or an Error if the request fails.

§Example
use mini_openai::{Client, ChatCompletions, Message, ROLE_USER};

let client = Client::new(None, None).unwrap();

// Create a new chat completion request
let mut request = ChatCompletions::default();

// Add a message to the chat history
request.messages.push(Message {
    content: "Hello!".to_string(),
    role: ROLE_USER.to_string(),
});

// Send the request to the OpenAI API
let response = client.chat_completions(&request).await.unwrap();

// Print the generated completion
println!("{}", response.choices[0].message.content);
Source

pub async fn chat_completions_into<F, T, E>( &self, request: &ChatCompletions, max_tries: usize, converter: F, ) -> Result<T, Error>
where F: Fn(String) -> Result<T, E>, E: ToString,

Attempts to retrieve a chat completion and deserializes the response into a custom type.

This function makes multiple attempts to retrieve a chat completion, up to a specified maximum number of tries. If a successful response is received, it will attempt to deserialize the response into the desired type using a provided converter function. If an error is caused anywhere the whole chain is retried up to max_tries times.

If all attempts fail, the error that was last received will be returned.

§Arguments
  • request: The chat completion request to send.
  • max_tries: The maximum number of attempts to make.
  • converter: A function that takes the content of the chat completion response and attempts to deserialize it into the desired type.
§Returns
  • Result<T, Error>: The deserialized result if successful, or the final error if all attempts fail.
§Errors
  • Any errors that occur during the network request itself.
  • Any errors that occur during deserialization.
§Example

For the likely case that you want to parse JSON, you can use the parse_json_lenient helper function. Here’s how to use it:

#[derive(Debug, serde::Deserialize)]
struct Hello {
    hello: String,
}

let client = mini_openai::Client::new(None, None).unwrap();
let request = mini_openai::ChatCompletions {
    messages: vec![
        mini_openai::Message {
            content: r#"Respond with {"hello": "world"}"#.into(),
            role: mini_openai::ROLE_SYSTEM.into(),
        }
    ],
    ..Default::default()
};

let hello: Hello = client.chat_completions_into(&request, 3, mini_openai::parse_json_lenient).await.unwrap();
println!("Result: {:?}", hello);
Source

pub async fn embeddings( &self, request: &Embeddings, ) -> Result<EmbeddingsResponse, Error>

Sends a request to the OpenAI API to generate embeddings of text.

This function takes a Embeddings struct as input..

The function returns a EmbeddingsResponse struct, which contains the generated embeddings.

§Arguments
  • request: The Embeddings struct containing the request parameters.
§Returns

A Result containing the EmbeddingsResponse struct, or an Error if the request fails.

§Example
use mini_openai::{Client, Embeddings, Message, ROLE_USER};

let client = Client::new(None, None).unwrap();

// Create a new chat completion request
let request = Embeddings { input: "Hello".into(), ..Default::default() };

// Send the request to the OpenAI API
let response = client.embeddings(&request).await.unwrap();

// Print the generated completion
println!("{}", response.data[0].embedding);

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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. 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> ErasedDestructor for T
where T: 'static,