pub struct Client { /* private fields */ }Implementations§
Source§impl Client
impl Client
Sourcepub fn new(
base_uri: Option<String>,
token: Option<String>,
) -> Result<Client, Error>
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, orNoneto use the environment variable or default.token: The API token, orNoneto use the environment variable.
§Returns
A Result containing the new Client instance, or an Error if the configuration is invalid.
Sourcepub fn new_without_environment(
base_uri: String,
token: Option<String>,
) -> Result<Client, Error>
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, orNoneif 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.
Sourcepub fn new_from_environment() -> Result<Client, Error>
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.
Sourcepub async fn chat_completions(
&self,
request: &ChatCompletions,
) -> Result<ChatCompletionsResponse, Error>
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: TheChatCompletionsstruct 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);Sourcepub async fn chat_completions_into<F, T, E>(
&self,
request: &ChatCompletions,
max_tries: usize,
converter: F,
) -> Result<T, Error>
pub async fn chat_completions_into<F, T, E>( &self, request: &ChatCompletions, max_tries: usize, converter: F, ) -> Result<T, Error>
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);Sourcepub async fn embeddings(
&self,
request: &Embeddings,
) -> Result<EmbeddingsResponse, Error>
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: TheEmbeddingsstruct 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);