हम cookies इस्तेमाल करते हैं. Cookies और ब्राउज़र स्टोरेज आपको साइन इन रखते हैं और आपकी प्राथमिकताएं याद रखते हैं। आपकी अनुमति से हम यह भी मापते हैं कि साइट कैसे इस्तेमाल होती है। आप कभी भी । हमारी cookie नीति देखें।

Rust

SDK गाइड

Rust

api14 के साथ async-openai इस्तेमाल करें: API बेस सेट करें, चैट, स्ट्रीमिंग, टूल कॉलिंग, स्ट्रक्चर्ड आउटपुट, त्रुटियाँ और टाइमआउट के Rust उदाहरण।

api14 के साथ async-openai इस्तेमाल करें। API बेस को OpenAIConfig::with_api_base से कॉन्फ़िगर करें और openai/gpt-5-mini जैसे मॉडल id पास करें।

इंस्टॉल करें

cargo add async-openai futures serde_json
cargo add tokio --features full
export API14_API_KEY="sk-api14-..."

कॉन्फ़िगर करें

use async_openai::{config::OpenAIConfig, Client};

let config = OpenAIConfig::new()
    .with_api_base("https://api14.com/api/v1")
    .with_api_key(std::env::var("API14_API_KEY")?);
let client = Client::with_config(config);

कुंजी को हार्ड-कोड करने के बजाय ऊपर की तरह एनवायरनमेंट से पढ़ें। staging और production के बीच बदलने के लिए बेस URL भी इसी तरह पढ़ें, उदाहरण के लिए std::env::var("API14_BASE_URL").unwrap_or("https://api14.com/api/v1".into())।

चैट

use async_openai::{
    config::OpenAIConfig,
    types::{ChatCompletionRequestUserMessageArgs, CreateChatCompletionRequestArgs},
    Client,
};

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

    let request = CreateChatCompletionRequestArgs::default()
        .model("openai/gpt-5-mini")
        .messages([ChatCompletionRequestUserMessageArgs::default()
            .content("Explain vector databases in two sentences.")
            .build()?
            .into()])
        .build()?;

    let response = client.chat().create(request).await?;
    if let Some(content) = &response.choices[0].message.content {
        println!("{content}");
    }
    Ok(())
}

स्ट्रीमिंग

use futures::StreamExt;

let request = CreateChatCompletionRequestArgs::default()
    .model("anthropic/claude-sonnet-4.5")
    .messages([ChatCompletionRequestUserMessageArgs::default()
        .content("Write a haiku about APIs.")
        .build()?
        .into()])
    .build()?;

let mut stream = client.chat().create_stream(request).await?;
while let Some(result) = stream.next().await {
    match result {
        Ok(chunk) => {
            for choice in chunk.choices {
                if let Some(text) = choice.delta.content {
                    print!("{text}");
                }
            }
        }
        Err(err) => eprintln!("stream error: {err}"),
    }
}

देखें स्ट्रीमिंग।

टूल कॉलिंग

use async_openai::types::{
    ChatCompletionRequestAssistantMessageArgs, ChatCompletionRequestMessage,
    ChatCompletionRequestToolMessageArgs, ChatCompletionToolArgs, ChatCompletionToolType,
    FunctionObjectArgs,
};
use serde_json::{json, Value};

let tools = vec![ChatCompletionToolArgs::default()
    .r#type(ChatCompletionToolType::Function)
    .function(FunctionObjectArgs::default()
        .name("get_weather")
        .description("Current weather for a city")
        .parameters(json!({
            "type": "object",
            "properties": { "city": { "type": "string" } },
            "required": ["city"]
        }))
        .build()?)
    .build()?];

let mut messages: Vec<ChatCompletionRequestMessage> = vec![ChatCompletionRequestUserMessageArgs::default()
    .content("What's the weather in Istanbul?")
    .build()?
    .into()];

loop {
    let request = CreateChatCompletionRequestArgs::default()
        .model("openai/gpt-5-mini")
        .messages(messages.clone())
        .tools(tools.clone())
        .build()?;
    let message = client.chat().create(request).await?.choices.remove(0).message;

    let Some(calls) = message.tool_calls else {
        println!("{}", message.content.unwrap_or_default());
        break;
    };
    messages.push(ChatCompletionRequestAssistantMessageArgs::default()
        .tool_calls(calls.clone())
        .build()?
        .into());
    for call in calls {
        let args: Value = serde_json::from_str(&call.function.arguments)?;
        let result = get_weather(args["city"].as_str().unwrap_or_default()); // आपका फ़ंक्शन
        messages.push(ChatCompletionRequestToolMessageArgs::default()
            .tool_call_id(call.id)
            .content(result)
            .build()?
            .into());
    }
}

देखें टूल कॉलिंग।

स्ट्रक्चर्ड आउटपुट

use async_openai::types::{ResponseFormat, ResponseFormatJsonSchema};

let request = CreateChatCompletionRequestArgs::default()
    .model("openai/gpt-5-mini")
    .messages([ChatCompletionRequestUserMessageArgs::default()
        .content("Extract: Ada Lovelace, born 1815.")
        .build()?
        .into()])
    .response_format(ResponseFormat::JsonSchema {
        json_schema: ResponseFormatJsonSchema {
            name: "person".into(),
            description: None,
            strict: Some(true),
            schema: Some(json!({
                "type": "object",
                "properties": { "name": { "type": "string" }, "born": { "type": "integer" } },
                "required": ["name", "born"],
                "additionalProperties": false
            })),
        },
    })
    .build()?;

let response = client.chat().create(request).await?;
let person: Value = serde_json::from_str(response.choices[0].message.content.as_deref().unwrap_or("{}"))?;

देखें स्ट्रक्चर्ड आउटपुट।

इमेज इनपुट

use async_openai::types::{
    ChatCompletionRequestMessageContentPartImageArgs, ChatCompletionRequestMessageContentPartTextArgs,
    ImageUrlArgs,
};

let message = ChatCompletionRequestUserMessageArgs::default()
    .content(vec![
        ChatCompletionRequestMessageContentPartTextArgs::default()
            .text("What is in this picture?")
            .build()?
            .into(),
        ChatCompletionRequestMessageContentPartImageArgs::default()
            .image_url(ImageUrlArgs::default().url("https://example.com/photo.jpg").build()?)
            .build()?
            .into(),
    ])
    .build()?;

इसे google/gemini-2.5-flash या image इनपुट वाले किसी अन्य मॉडल के साथ भेजें। देखें विज़न और फ़ाइलें।

एम्बेडिंग

use async_openai::types::CreateEmbeddingRequestArgs;

let request = CreateEmbeddingRequestArgs::default()
    .model("openai/text-embedding-3-small")
    .input(["The quick brown fox", "Lorem ipsum"])
    .build()?;
let response = client.embeddings().create(request).await?;
println!("{}", response.data[0].embedding.len());

जिन एंडपॉइंट के लिए क्रेट में टाइप नहीं हैं (वीडियो जॉब, rerank) उन्हें reqwest से कॉल किया जा सकता है; नीचे के कोड ब्लॉक में HTTP उदाहरण देखें।

त्रुटियाँ

गेटवे की त्रुटियाँ OpenAIError::ApiError में पार्स होती हैं; मशीन code पर शाखा बनाएँ:

use async_openai::error::OpenAIError;

match client.chat().create(request).await {
    Ok(response) => println!("{:?}", response.choices[0].message.content),
    Err(OpenAIError::ApiError(err)) => match err.code.as_deref() {
        Some("insufficient_balance") => eprintln!("Balance too low, add funds"),
        Some("rate_limited") | Some("daily_limit_reached") => eprintln!("Slow down: {}", err.message),
        _ => eprintln!("API error: {}", err.message),
    },
    Err(other) => eprintln!("{other}"),
}

देखें त्रुटियाँ।

टाइमआउट और रीट्राई

async-openai पहले से 429 rate_limited प्रतिक्रियाओं पर बैकऑफ़ और रीट्राई करता है। इसका डिफ़ॉल्ट बैकऑफ़ 15 मिनट तक कोशिश करता रहता है, जो अधिकतर ऐप के लिए बहुत लंबा है और daily_limit_reached के लिए बेमतलब। इसे सीमित करें, और HTTP क्लाइंट को टाइमआउट दें (cargo add backoff reqwest, उन्हीं संस्करणों के साथ जो async-openai इस्तेमाल करता है):

use std::time::Duration;

let http = reqwest::Client::builder()
    .timeout(Duration::from_secs(120))
    .build()?;

let client = Client::with_config(config)
    .with_http_client(http)
    .with_backoff(backoff::ExponentialBackoffBuilder::new()
        .with_max_elapsed_time(Some(Duration::from_secs(90)))
        .build());

देखें रेट लिमिट।

सभी क्षमताएँ

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api14.com/api/v1",
  apiKey: process.env.API14_API_KEY,
});

const result = await client.chat.completions.create({
  "model": "openai/gpt-5-mini",
  "messages": [
    {
      "role": "user",
      "content": "Explain vector databases in two sentences."
    }
  ]
});
console.log(result.choices[0].message.content);