MCPcopy Index your code
hub / github.com/dongri/openai-api-rs

github.com/dongri/openai-api-rs @v10.0.1

Chat with this repo
repository ↗ · DeepWiki ↗ · release v10.0.1 ↗ · + Follow
403 symbols 571 edges 50 files 1 documented · 0%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

OpenAI API client library for Rust (unofficial)

The OpenAI API client Rust library provides convenient access to the OpenAI API from Rust applications.

Check out the docs.rs.

Installation:

Cargo.toml

[dependencies]
openai-api-rs = "10.0.1"

Usage

The library needs to be configured with your account's secret key, which is available on the website. We recommend setting it as an environment variable. Here's an example of initializing the library with the API key loaded from an environment variable and creating a completion:

Set OPENAI_API_KEY or OPENROUTER_API_KEY to environment variable

$ export OPENAI_API_KEY=sk-xxxxxxx
or
$ export OPENROUTER_API_KEY=sk-xxxxxxx

Create OpenAI client

let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;

Create OpenRouter client

let api_key = env::var("OPENROUTER_API_KEY").unwrap().to_string();
let mut client = OpenAIClient::builder()
    .with_endpoint("https://openrouter.ai/api/v1")
    .with_api_key(api_key)
    .build()?;

Create request

let req = ChatCompletionRequest::new(
    GPT4_O.to_string(),
    vec![chat_completion::ChatCompletionMessage {
        role: chat_completion::MessageRole::user,
        content: chat_completion::Content::Text(String::from("What is bitcoin?")),
        name: None,
        tool_calls: None,
        tool_call_id: None,
    }],
);

Send request

let result = client.chat_completion(req)?;
println!("Content: {:?}", result.choices[0].message.content);

for (key, value) in client.headers.unwrap().iter() {
    println!("{}: {:?}", key, value);
}

Set OPENAI_API_BASE to environment variable (optional)

$ export OPENAI_API_BASE=https://api.openai.com/v1

Example of chat completion

use openai_api_rs::v1::api::OpenAIClient;
use openai_api_rs::v1::chat_completion::{self, ChatCompletionRequest};
use openai_api_rs::v1::common::GPT4_O;
use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
    let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;

    let req = ChatCompletionRequest::new(
        GPT4_O.to_string(),
        vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: chat_completion::Content::Text(String::from("What is bitcoin?")),
            name: None,
            tool_calls: None,
            tool_call_id: None,
        }],
    );

    let result = client.chat_completion(req).await?;
    println!("Content: {:?}", result.choices[0].message.content);

    for (key, value) in client.headers.unwrap().iter() {
        println!("{}: {:?}", key, value);
    }

    Ok(())
}

Example for OpenRouter

use openai_api_rs::v1::api::OpenAIClient;
use openai_api_rs::v1::chat_completion::{self, ChatCompletionRequest};
use openai_api_rs::v1::common::GPT4_O_MINI;
use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api_key = env::var("OPENROUTER_API_KEY").unwrap().to_string();
    let mut client = OpenAIClient::builder()
        .with_endpoint("https://openrouter.ai/api/v1")
        .with_api_key(api_key)
        .build()?;

    let req = ChatCompletionRequest::new(
        GPT4_O_MINI.to_string(),
        vec![chat_completion::ChatCompletionMessage {
            role: chat_completion::MessageRole::user,
            content: chat_completion::Content::Text(String::from("What is bitcoin?")),
            name: None,
            tool_calls: None,
            tool_call_id: None,
        }],
    );

    let result = client.chat_completion(req).await?;
    println!("Content: {:?}", result.choices[0].message.content);

    for (key, value) in client.headers.unwrap().iter() {
        println!("{}: {:?}", key, value);
    }

    Ok(())
}

More Examples: examples

Check out the full API documentation for examples of all the available functions.

Supported APIs

License

This project is licensed under MIT license.

Core symbols most depended-on inside this repo

get
called by 33
src/v1/api.rs
post
called by 26
src/v1/api.rs
build
called by 19
src/v1/api.rs
with_api_key
called by 18
src/v1/api.rs
build_request
called by 9
src/v1/api.rs
chat_completion
called by 8
src/v1/api.rs
delete
called by 6
src/v1/api.rs
handle_response
called by 4
src/v1/api.rs

Shape

Class 190
Method 128
Function 48
Enum 37

Languages

Rust100%

Modules by API surface

src/v1/api.rs88 symbols
src/realtime/server_event.rs32 symbols
src/v1/chat_completion/mod.rs28 symbols
src/realtime/types.rs27 symbols
src/v1/chat_completion/chat_completion_stream.rs19 symbols
src/v1/message.rs18 symbols
src/v1/chat_completion/chat_completion.rs16 symbols
src/v1/thread.rs15 symbols
src/v1/fine_tuning.rs11 symbols
src/v1/assistant.rs11 symbols
src/realtime/client_event.rs11 symbols
src/v1/types.rs10 symbols

For agents

$ claude mcp add openai-api-rs \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact