|
| 1 | +from __future__ import 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.profiles import ModelProfile |
| 12 | +from pydantic_ai.profiles.openai import openai_model_profile |
| 13 | +from pydantic_ai.providers import Provider |
| 14 | + |
| 15 | + |
| 16 | +class AIMLAPIProvider(Provider[AsyncOpenAI]): |
| 17 | + """Provider for the AI/ML API.""" |
| 18 | + |
| 19 | + @property |
| 20 | + def name(self) -> str: # pragma: no cover - simple property |
| 21 | + return "aimlapi" |
| 22 | + |
| 23 | + @property |
| 24 | + def base_url(self) -> str: # pragma: no cover - simple property |
| 25 | + return "https://api.aimlapi.com/v1" |
| 26 | + |
| 27 | + @property |
| 28 | + def client(self) -> AsyncOpenAI: |
| 29 | + return self._client |
| 30 | + |
| 31 | + def model_profile(self, model_name: str) -> ModelProfile | None: # pragma: no cover - thin wrapper |
| 32 | + return openai_model_profile(model_name) |
| 33 | + |
| 34 | + @overload |
| 35 | + def __init__(self) -> None: ... |
| 36 | + |
| 37 | + @overload |
| 38 | + def __init__(self, *, api_key: str) -> None: ... |
| 39 | + |
| 40 | + @overload |
| 41 | + def __init__(self, *, api_key: str, http_client: AsyncHTTPClient) -> None: ... |
| 42 | + |
| 43 | + @overload |
| 44 | + def __init__(self, *, openai_client: AsyncOpenAI | None = None) -> None: ... |
| 45 | + |
| 46 | + def __init__( |
| 47 | + self, |
| 48 | + *, |
| 49 | + api_key: str | None = None, |
| 50 | + openai_client: AsyncOpenAI | None = None, |
| 51 | + http_client: AsyncHTTPClient | None = None, |
| 52 | + ) -> None: |
| 53 | + api_key = api_key or os.getenv("AIML_API_KEY") |
| 54 | + if not api_key and openai_client is None: |
| 55 | + raise UserError( |
| 56 | + "Set the `AIML_API_KEY` environment variable or pass it via `AIMLAPIProvider(api_key=...)` " |
| 57 | + "to use the AI/ML API provider." |
| 58 | + ) |
| 59 | + |
| 60 | + if openai_client is not None: |
| 61 | + self._client = openai_client |
| 62 | + elif http_client is not None: |
| 63 | + self._client = AsyncOpenAI(base_url=self.base_url, api_key=api_key, http_client=http_client) |
| 64 | + else: |
| 65 | + http_client = cached_async_http_client(provider="aimlapi") |
| 66 | + self._client = AsyncOpenAI(base_url=self.base_url, api_key=api_key, http_client=http_client) |
0 commit comments