#openai-api #openai #api-key

openai_api_rust

A very simple Rust library for OpenAI API, free from complex async operations and redundant dependencies

9 releases

0.1.9 May 29, 2024
0.1.8 Apr 4, 2023
0.1.5 Mar 31, 2023

#6 in #openai-api

Download history 87/week @ 2024-04-01 39/week @ 2024-04-08 56/week @ 2024-04-15 97/week @ 2024-04-22 115/week @ 2024-04-29 75/week @ 2024-05-06 79/week @ 2024-05-13 108/week @ 2024-05-20 269/week @ 2024-05-27 102/week @ 2024-06-03 55/week @ 2024-06-10 201/week @ 2024-06-17 323/week @ 2024-06-24 109/week @ 2024-07-01 54/week @ 2024-07-08 103/week @ 2024-07-15

674 downloads per month
Used in 4 crates

MIT license

535KB
979 lines

OpenAI API for Rust

GitHub Workflow Status Crates.io Crates.io GitHub

A community-maintained library provides a simple and convenient way to interact with the OpenAI API. No complex async and redundant dependencies.

API

check official API reference

API Support
Models ✔️
Completions ✔️
Chat ✔️
Images ✔️
Embeddings ✔️
Audio ✔️
Files
Fine-tunes
Moderations
Engines

Usage

Add the following to your Cargo.toml file:

openai_api_rust = "0.1.9"

Export your API key into the environment variables

export OPENAI_API_KEY=<your_api_key>

Then use the crate in your Rust code:

use openai_api_rust::*;
use openai_api_rust::chat::*;
use openai_api_rust::completions::*;

fn main() {
    // Load API key from environment OPENAI_API_KEY.
    // You can also hadcode through `Auth::new(<your_api_key>)`, but it is not recommended.
    let auth = Auth::from_env().unwrap();
    let openai = OpenAI::new(auth, "https://api.openai.com/v1/");
    let body = ChatBody {
        model: "gpt-3.5-turbo".to_string(),
        max_tokens: Some(7),
        temperature: Some(0_f32),
        top_p: Some(0_f32),
        n: Some(2),
        stream: Some(false),
        stop: None,
        presence_penalty: None,
        frequency_penalty: None,
        logit_bias: None,
        user: None,
        messages: vec![Message { role: Role::User, content: "Hello!".to_string() }],
    };
    let rs = openai.chat_completion_create(&body);
    let choice = rs.unwrap().choices;
    let message = &choice[0].message.as_ref().unwrap();
    assert!(message.content.contains("Hello"));
}

Use proxy

Load proxy from env

let openai = OpenAI::new(auth, "https://api.openai.com/v1/")
        .use_env_proxy();

Set the proxy manually

let openai = OpenAI::new(auth, "https://api.openai.com/v1/")
        .set_proxy("http://127.0.0.1:1080");

License

This library is distributed under the terms of the MIT license. See LICENSE for details.

Dependencies

~2.5–3.5MB
~99K SLoC