Crate oaapi

Source
Expand description

An unofficial Rust client for the OpenAI API.

§Feature flags

[!NOTE] You need to enable feature flags to use the corresponding APIs.

§Supported APIs

Beta version APIs:

§Usage

  1. Enable API feature flags that you want to use, e.g. chat.
  2. Create a Client with the API key and the other optional settings.
  3. Use the client to call the APIs, e.g. Client::chat_complete.

See also examples in documents of each feature module for more details.

§Examples

An example to call the chat completions API with the chat feature flag:

[dependencies]
oaapi = { version = "0.2.0", features = ["chat"] }

and setting the API key to the environment variable :OPENAI_API_KEY

OPENAI_API_KEY={your-openai-api-key}

is as follows:

use oaapi::Client;
use oaapi::chat::CompletionsRequestBody;
use oaapi::chat::SystemMessage;
use oaapi::chat::UserMessage;
use oaapi::chat::ChatModel;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // 1. Create a client with the API key from the environment variable: "OPENAI_API_KEY"
    let client = Client::from_env()?;
    // or specify the API key directly.
    // let client = Client::new(oaapi::ApiKey::new("OPENAI_API_KEY"), None, None);

    // 2. Create a request body parameters.
    let request_body = CompletionsRequestBody {
        messages: vec![
            SystemMessage::new("Prompt.", None).into(),
            UserMessage::new("Chat message from user.".into(), None).into(),
        ],
        model: ChatModel::Gpt35Turbo,
        ..Default::default()
    };

    // 3. Call the API.
    let response = client
        .chat_complete(request_body)
        .await?;

    // 4. Use the response.
    println!("Result:\n{}", response);

    Ok(())
}

See also examples in documents of each feature module for more details.

Re-exports§

pub use reqwest;
pub use serde_json;
pub use subtp;

Modules§

audio
The audio API of the OpenAI API.
chat
The chat APIs of the OpenAI API.

Structs§

ApiError
The error of an API.
ApiErrorBody
The error body of an API error response.
ApiKey
The API key of the OpenAI API.
Client
The client of the OpenAI API.
ErrorResponse
The error response of an API calling.
OrganizationId
The organization ID of the OpenAI API.
Prompt
The prompt for generations.
Temperature
The temperature for generations.
ValidationError
The error of a validation.

Enums§

ClientError
The error of the client API calling.

Type Aliases§

ValidationResult
The result of a validation.