AiClient API(Python)
AiClient API
Section titled “AiClient API”クライアントの作成
Section titled “クライアントの作成”モデル識別子から
Section titled “モデル識別子から”from ai_lib_python import AiClient
client = await AiClient.create("anthropic/claude-3-5-sonnet")ビルダーを使用
Section titled “ビルダーを使用”client = await AiClient.builder() \ .model("openai/gpt-4o") \ .protocol_dir("./ai-protocol") \ .timeout(60) \ .build()耐障害性付き
Section titled “耐障害性付き”from ai_lib_python.resilience import ResilientConfig
config = ResilientConfig( max_retries=3, rate_limit_rps=10, circuit_breaker_threshold=5, max_inflight=50,)
client = await AiClient.builder() \ .model("openai/gpt-4o") \ .resilience(config) \ .build()ChatRequestBuilder
Section titled “ChatRequestBuilder”リクエスト構築のための fluent API:
response = await client.chat() \ .system("You are a helpful assistant") \ .user("Hello!") \ .messages([Message.user("Follow-up")]) \ .temperature(0.7) \ .max_tokens(1000) \ .top_p(0.9) \ .tools([tool_definition]) \ .execute()レスポンス型
Section titled “レスポンス型”ChatResponse
Section titled “ChatResponse”class ChatResponse: content: str # レスポンステキスト tool_calls: list[ToolCall] # 関数呼び出し finish_reason: str # 完了理由 usage: Usage # トークン数StreamingEvent
Section titled “StreamingEvent”class StreamingEvent: # 型チェック is_content_delta: bool is_tool_call_started: bool is_partial_tool_call: bool is_stream_end: bool
# 型安全アクセサー as_content_delta -> ContentDelta as_tool_call_started -> ToolCallStarted as_partial_tool_call -> PartialToolCall as_stream_end -> StreamEndCallStats
Section titled “CallStats”class CallStats: total_tokens: int prompt_tokens: int completion_tokens: int latency_ms: float model: str provider: str非ストリーミング
Section titled “非ストリーミング”# シンプルなレスポンスresponse = await client.chat().user("Hello").execute()
# 統計付きresponse, stats = await client.chat().user("Hello").execute_with_stats()ストリーミング
Section titled “ストリーミング”async for event in client.chat().user("Hello").stream(): if event.is_content_delta: print(event.as_content_delta.text, end="")キャンセル可能なストリーム
Section titled “キャンセル可能なストリーム”from ai_lib_python import CancelToken
token = CancelToken()
async for event in client.chat().user("Long task...").stream(cancel_token=token): if event.is_content_delta: print(event.as_content_delta.text, end="") if should_cancel: token.cancel() breakエラーハンドリング
Section titled “エラーハンドリング”すべてのエラーは standard_code プロパティで V2 標準エラーコードを公開します(ai-lib-python v0.6.0+):
from ai_lib_python.errors import ( AiLibError, ProtocolError, TransportError, RemoteError)
try: response = await client.chat().user("Hello").execute()except RemoteError as e: print(f"Provider error: {e.error_type}") # 標準エラークラス print(f"Standard code: {e.standard_code}") # V2 StandardErrorCode(例:E1001) print(f"HTTP status: {e.status_code}")except TransportError as e: print(f"Network error: {e}")except ProtocolError as e: print(f"Protocol error: {e}")except AiLibError as e: print(f"Other error: {e}")次のステップ
Section titled “次のステップ”- ストリーミングパイプライン — パイプラインの内部
- 耐障害性 — 信頼性パターン
- 高度な機能 — テレメトリ、ルーティング、プラグイン