|
| 1 | +from __future__ import annotations as _annotations |
| 2 | + |
| 3 | +import os |
| 4 | +from typing import overload |
| 5 | + |
| 6 | +from httpx import AsyncClient as AsyncHTTPClient |
| 7 | +from openai import AsyncOpenAI |
| 8 | + |
| 9 | +from pydantic_ai.exceptions import UserError |
| 10 | +from pydantic_ai.models import cached_async_http_client |
| 11 | +from pydantic_ai.providers import Provider |
| 12 | + |
| 13 | +try: |
| 14 | + from openai import AsyncOpenAI |
| 15 | +except ImportError as _import_error: # pragma: no cover |
| 16 | + raise ImportError( |
| 17 | + 'Please install the `openai` package to use the OpenRouter provider, ' |
| 18 | + 'you can use the `openai` optional group — `pip install "pydantic-ai-slim[openai]"`' |
| 19 | + ) from _import_error |
| 20 | + |
| 21 | + |
| 22 | +class OpenRouterProvider(Provider[AsyncOpenAI]): |
| 23 | + """Provider for OpenRouter API.""" |
| 24 | + |
| 25 | + @property |
| 26 | + def name(self) -> str: |
| 27 | + return 'openrouter' |
| 28 | + |
| 29 | + @property |
| 30 | + def base_url(self) -> str: |
| 31 | + return 'https://openrouter.ai/api/v1' |
| 32 | + |
| 33 | + @property |
| 34 | + def client(self) -> AsyncOpenAI: |
| 35 | + return self._client |
| 36 | + |
| 37 | + @overload |
| 38 | + def __init__(self) -> None: ... |
| 39 | + |
| 40 | + @overload |
| 41 | + def __init__(self, *, api_key: str) -> None: ... |
| 42 | + |
| 43 | + @overload |
| 44 | + def __init__(self, *, api_key: str, http_client: AsyncHTTPClient) -> None: ... |
| 45 | + |
| 46 | + @overload |
| 47 | + def __init__(self, *, openai_client: AsyncOpenAI | None = None) -> None: ... |
| 48 | + |
| 49 | + def __init__( |
| 50 | + self, |
| 51 | + *, |
| 52 | + api_key: str | None = None, |
| 53 | + openai_client: AsyncOpenAI | None = None, |
| 54 | + http_client: AsyncHTTPClient | None = None, |
| 55 | + ) -> None: |
| 56 | + api_key = api_key or os.getenv('OPENROUTER_API_KEY') |
| 57 | + if not api_key and openai_client is None: |
| 58 | + raise UserError( |
| 59 | + 'Set the `OPENROUTER_API_KEY` environment variable or pass it via `OpenRouterProvider(api_key=...)`' |
| 60 | + 'to use the OpenRouter provider.' |
| 61 | + ) |
| 62 | + |
| 63 | + if openai_client is not None: |
| 64 | + self._client = openai_client |
| 65 | + elif http_client is not None: |
| 66 | + self._client = AsyncOpenAI(base_url=self.base_url, api_key=api_key, http_client=http_client) |
| 67 | + else: |
| 68 | + http_client = cached_async_http_client(provider='openrouter') |
| 69 | + self._client = AsyncOpenAI(base_url=self.base_url, api_key=api_key, http_client=http_client) |
0 commit comments