К содержимому

Rust LLM API: SDK, запрос и обработка ошибок

Rust-клиент async-openai.

Установка

Установите клиент в проекте и передайте ключ через переменную RELAY_API_KEY среды.

text
[dependencies]
async-openai = { version = "0.42", features = ["chat-completion"] }
futures = "0.3"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

Первый запрос

Задайте адрес, ключ и идентификатор модели, затем прочитайте текст ответа.

ts
use async_openai::{
    config::OpenAIConfig,
    types::chat::{ChatCompletionRequestUserMessage, CreateChatCompletionRequestArgs},
    Client,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = OpenAIConfig::new()
        .with_api_base("https://relay-llm.ru/v1")
        .with_api_key(std::env::var("RELAY_API_KEY")?);
    let client = Client::with_config(config);

    let request = CreateChatCompletionRequestArgs::default()
        .model("gpt-5.6-luna")
        .messages([ChatCompletionRequestUserMessage::from("Say hello in one sentence.").into()])
        .build()?;

    let reply = client.chat().create(request).await?;
    println!("{}", reply.choices[0].message.content.clone().unwrap_or_default());
    Ok(())
}

Потоковый ответ

Поток показывает текст по мере генерации и сохраняет usage, если протокол его отдаёт.

ts
use futures::StreamExt;
use async_openai::{
    config::OpenAIConfig,
    types::chat::{ChatCompletionRequestUserMessage, CreateChatCompletionRequestArgs},
    Client,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = OpenAIConfig::new()
        .with_api_base("https://relay-llm.ru/v1")
        .with_api_key(std::env::var("RELAY_API_KEY")?);
    let client = Client::with_config(config);

    let request = CreateChatCompletionRequestArgs::default()
        .model("gpt-5.6-luna")
        .stream(true)
        .messages([ChatCompletionRequestUserMessage::from("Say hello in one sentence.").into()])
        .build()?;

    let mut stream = client.chat().create_stream(request).await?;
    while let Some(chunk) = stream.next().await {
        for choice in chunk?.choices {
            if let Some(text) = choice.delta.content {
                print!("{text}");
            }
        }
    }
    println!();
    Ok(())
}

Ошибки и повторы

Клиент использует ограниченное число повторов и выводит идентификатор запроса при ошибке.

ts
use async_openai::error::OpenAIError;
use async_openai::{
    config::OpenAIConfig,
    types::chat::{ChatCompletionRequestUserMessage, CreateChatCompletionRequestArgs},
    Client,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = OpenAIConfig::new()
        .with_api_base("https://relay-llm.ru/v1")
        .with_api_key(std::env::var("RELAY_API_KEY")?);
    let client = Client::with_config(config);

    let request = CreateChatCompletionRequestArgs::default()
        .model("gpt-5.6-luna")
        .messages([ChatCompletionRequestUserMessage::from("Say hello in one sentence.").into()])
        .build()?;

    match client.chat().create(request).await {
        Ok(reply) => {
            println!("{}", reply.choices[0].message.content.clone().unwrap_or_default());
        }
        Err(OpenAIError::ApiError(error)) => {
            eprintln!("{error}");
            std::process::exit(1);
        }
        Err(error) => return Err(error.into()),
    }
    Ok(())
}
Исполняемые варианты: 3 из 4.
Готовы? Три шага, чтобы начатьВойдите в консоль · пополните баланс · создайте API Key