Lingara Lingara ドキュメント 学習ガイド API ライブラリ アプリ 作成 ウェブ版
言語: 日本語

Rust

このページは英語から翻訳されています。内容に相違がある場合は、英語のページが正しい内容です。 英語のページを読む

Rust ライブラリは crates.io の lingara クレートです。Rust 1.87 以降が必要で、Tokio ランタイム上で動作します。TLS はデフォルトで rustls を使い、フィーチャーを有効にするとプラットフォーム自身の TLS も使えます。

使い方

  • すべての呼び出しは async fn で、Result を返します。呼び出しをキャンセルするにはその future を破棄し、ストリームをキャンセルするにはストリームを破棄します。
  • ストリームはレスポンスヘッダーが届いた時点で、結果の Stream として届きます。.next().await で読み取ります。
  • エラーは 4 つのバリアントを持つ単一の Error 列挙型です。API が待機時間を示した場合、Error::retry_after はその時間を返します。
  • クライアントは Client::builder() で構築します。コネクションプールを共有するには独自の reqwest::Client を渡しますが、そのクライアントには全体のタイムアウトを設定しないでください。設定すると長いストリームが途中で切れてしまいます。1 回の呼び出しに期限を設けるには、tokio::time::timeout で包みます。

以下のサンプルでは、クレートのインストール、クライアントの作成、語彙リストのストリーミング、エラー処理を行います。

Rust

cargo add lingara@0.1.0-alpha.6
cargo add tokio --features macros,rt-multi-thread

Rust

use lingara::Client;

let client = Client::builder()
    .client_credentials(std::env::var("LINGARA_CLIENT_ID")?, std::env::var("LINGARA_CLIENT_SECRET")?)
    .build()?;

Rust

use lingara::models::{GenerateVocabularyEvent, VocabRequest};
use std::num::NonZeroU8;

let request = VocabRequest { level: 2, source_lang: "en".into(), target_lang: "zh".into(), count: NonZeroU8::new(8) };
let mut stream = client.generate_vocabulary(&request).await?;
while let Some(event) = stream.next().await {
    if let GenerateVocabularyEvent::Item(item) = event? {
        println!("{} {}", item.word, item.translation);
    }
}

Rust

use lingara::Error;

let result = client.get_usage().await;
if let Some(wait) = result.as_ref().err().and_then(Error::retry_after) {
    eprintln!("the API asks you to retry after {wait:?}");
}
match result {
    Ok(usage) => println!("{} allowance rows", usage.allowance.len()),
    // A refusal from the API: status, code (stable) and message (localised).
    Err(Error::Api(e)) => eprintln!("{} {} {}", e.status, e.code, e.message),
    // The token endpoint refused the credentials or the scopes.
    Err(Error::OAuth(e)) => eprintln!("{} {} {}", e.status, e.error, e.description.unwrap_or_default()),
    Err(Error::Maintenance(_)) => eprintln!("the API is under maintenance"),
    // No usable answer: connect, tls, reset, timeout, and so on.
    Err(Error::Transport(e)) => eprintln!("transport: {}", e.kind),
    Err(other) => return Err(other.into()),
}

このページがラップするもの