チャット補完
チャット補完
Section titled “チャット補完”チャット補完は AI モデルとやり取りする主要な API です。両ランタイムは 35 以上のプロバイダーすべてで動作する統一インターフェースを提供します。
let client = AiClient::new("openai/gpt-4o").await?;
let response = client.chat() .user("Hello, world!") .execute() .await?;
println!("{}", response.content);Python
Section titled “Python”client = await AiClient.create("openai/gpt-4o")
response = await client.chat() \ .user("Hello, world!") \ .execute()
print(response.content)システムメッセージ
Section titled “システムメッセージ”モデルの振る舞いを設定します:
// Rustclient.chat() .system("You are a helpful coding assistant. Always include code examples.") .user("Explain closures") .execute().await?;# Pythonawait client.chat() \ .system("You are a helpful coding assistant.") \ .user("Explain closures") \ .execute()マルチターン会話
Section titled “マルチターン会話”会話履歴を渡します:
// Rustuse ai_lib::{Message, MessageRole};
let messages = vec![ Message::system("You are a tutor."), Message::user("What is recursion?"), Message::assistant("Recursion is when a function calls itself..."), Message::user("Can you show an example?"),];
client.chat().messages(messages).execute().await?;# Pythonfrom ai_lib_python import Message
messages = [ Message.system("You are a tutor."), Message.user("What is recursion?"), Message.assistant("Recursion is when a function calls itself..."), Message.user("Can you show an example?"),]
await client.chat().messages(messages).execute()| パラメータ | 型 | 説明 |
|---|---|---|
temperature | float | ランダム性(0.0 = 決定論的、2.0 = 創造的) |
max_tokens | int | 最大レスポンス長 |
top_p | float | ヌクレアスサンプリング(temperature の代替) |
stop | string[] | 生成を停止するシーケンス |
// Rustclient.chat() .user("Write a poem") .temperature(0.9) .max_tokens(200) .top_p(0.95) .execute().await?;ストリーミング
Section titled “ストリーミング”リアルタイム出力にはストリーミングを使用します:
// Rustlet mut stream = client.chat() .user("Tell me a story") .stream() .execute_stream() .await?;
while let Some(event) = stream.next().await { if let StreamingEvent::ContentDelta { text, .. } = event? { print!("{text}"); std::io::stdout().flush()?; }}# Pythonasync for event in client.chat() \ .user("Tell me a story") \ .stream(): if event.is_content_delta: print(event.as_content_delta.text, end="", flush=True)レスポンス統計
Section titled “レスポンス統計”コスト管理のための使用量を追跡します:
// Rustlet (response, stats) = client.chat() .user("Hello") .execute_with_stats() .await?;
println!("Prompt tokens: {}", stats.prompt_tokens);println!("Completion tokens: {}", stats.completion_tokens);println!("Latency: {}ms", stats.latency_ms);# Pythonresponse, stats = await client.chat() \ .user("Hello") \ .execute_with_stats()
print(f"Tokens: {stats.total_tokens}")print(f"Latency: {stats.latency_ms}ms")プロバイダーの切り替え
Section titled “プロバイダーの切り替え”同じコードがすべてのプロバイダーで動作します:
// モデル識別子を変更するだけlet client = AiClient::new("anthropic/claude-3-5-sonnet").await?;let client = AiClient::new("deepseek/deepseek-chat").await?;let client = AiClient::new("gemini/gemini-2.0-flash").await?;プロトコルマニフェストが、エンドポイント URL、認証、パラメータマッピング、ストリーミング形式の違いを自動的に処理します。