@aemeath/openrouter
v1.0.7
Published
OpenRouter API client for TypeScript
Downloads
544
Maintainers
Readme
🚀 @aemeath/openrouter
OpenRouter API用のTypeScriptクライアントライブラリです。
リポジトリ: https://codeberg.org/aemeath/openrouter
OpenRouterの言語モデルとシンプルで柔軟なインターフェースを通じて対話できます。 ストリーミング、ツール/ファンクション呼び出し、プロバイダー選択に対応しています。
📦 インストール
npm install @aemeath/openrouter🎯 機能
- 🔄 ストリーミング対応: リアルタイムレスポンスストリーミングでユーザー体験を向上
- 🛠️ ツール/ファンクション呼び出し: カスタムツールを定義して実行可能
- 🔀 プロバイダー選択: プロバイダーの順序、包含、除外を設定可能
- 📋 レスポンスフォーマット: テキスト、JSONオブジェクト、JSONスキーマをサポート
- 🔗 チェーン実行: マルチターン会話でのツール呼び出しを自動的に処理
- 🧠 推論: 設定可能な effort を伴う推論モデルをサポート
- 🔌 プラグイン: Web検索プラグインをサポート
📖 使い方
💻 基本的な使い方
import { OpenRouter, userMessage, systemMessage } from '@aemeath/openrouter';
const client = new OpenRouter({
apiKey: 'your-api-key',
model: 'anthropic/claude-3-5-sonnet',
});
const resp = await client.completion([
systemMessage('You are a helpful assistant.'),
userMessage('Hello! How are you?'),
]);
console.log(resp.choices[0].message.content);🌊 ストリーミング
const streamFn = async (chunk: string) => {
const { content } = JSON.parse(chunk);
process.stdout.write(content);
};
const resp = await client.stream(messages, streamFn);🛠️ ツール / ファンクション呼び出し
Tool インターフェースを実装します:
import type { Tool } from '@aemeath/openrouter';
class WeatherTool implements Tool {
name() { return 'get_weather'; }
description() { return 'Get the current weather in a location'; }
parameters() {
return {
type: 'object',
properties: {
location: {
type: 'string',
description: 'The city and state, e.g. San Francisco, CA',
},
},
required: ['location'],
};
}
strict() { return false; }
async call(args: string): Promise<string> {
const { location } = JSON.parse(args);
return 'Sunny, 72°F';
}
}
client.setTools([new WeatherTool()]);🔗 チェーン実行(ツール呼び出しの自動処理)
chainCompletion と chainStream メソッドは、マルチターン会話でのツール呼び出しを自動的に処理します:
const resp = await client.chainCompletion(messages);🔀 プロバイダー選択
client.setProviderOrder(['Google', 'Anthropic', 'OpenAI']);
client.setProviderIgnore(['DeepSeek']);🧠 推論
import { ReasoningEffort } from '@aemeath/openrouter';
client.setReasoning({
enabled: true,
effort: ReasoningEffort.Low,
});📚 APIリファレンス
OpenRouter APIの詳細については公式ドキュメントを参照してください。
📝 型
Message: ロール、コンテント、推論、ツール呼び出しを含むチャットメッセージを表します。Tool: カスタムツールを定義するインターフェース。Provider: プロバイダー選択の設定。ChatCompletionRequest: APIリクエスト構造。ChatCompletionResponse: APIレスポンス構造。
⚙️ メソッド
new OpenRouter(options): クライアントを作成。setModel(model): モデルを設定。setTemperature(temperature): 温度を設定。setTools(tools): カスタムツールを設定。setProviderOrder(order): プロバイダーの順序を設定。setProviderIgnore(ignore): 除外するプロバイダーを設定。setResponseFormat(format): レスポンスフォーマットを設定。setReasoning(reasoning): 推論設定。completion(messages): ノンストリーミングレスポンスを取得。stream(messages, streamFn): ストリーミングレスポンスを取得。chainCompletion(messages): ツール呼び出しを自動処理して取得。chainStream(messages, streamFn): ツール呼び出しを自動処理してストリーミング。fetchCredits(): アカウントのクレジットを取得。fetchKeyInfo(): キーの使用情報を取得。
⚙️ 環境変数
OPENROUTER_API_URLを設定すると、APIベースURLを設定できます(デフォルト:https://openrouter.ai/api/v1)OPENROUTER_API_KEYを設定すると、APIキーを設定できます
📄 ライセンス
MIT License
