|
| 1 | +import asyncio |
| 2 | + |
| 3 | +import openai |
| 4 | + |
| 5 | +from ifixai.core.types import ChatMessage, ProviderConfig |
| 6 | +from ifixai.providers.base import ( |
| 7 | + ChatProvider, |
| 8 | + ProviderAuthError, |
| 9 | + ProviderConnectionError, |
| 10 | + ProviderEmptyContentError, |
| 11 | + ProviderRateLimitError, |
| 12 | + ProviderResponseError, |
| 13 | + ProviderTimeoutError, |
| 14 | + create_chat_completion_json_fallback, |
| 15 | +) |
| 16 | + |
| 17 | +DEFAULT_MODEL = "qwen/qwen3.5-flash" |
| 18 | +DEFAULT_BASE_URL = "https://api.atlascloud.ai/v1" |
| 19 | +MAX_TOKENS_CEILING: int = 8192 |
| 20 | + |
| 21 | +ClientCacheKey = tuple[str, str | None, float, int] |
| 22 | + |
| 23 | + |
| 24 | +class AtlasCloudProvider(ChatProvider): |
| 25 | + |
| 26 | + def __init__(self) -> None: |
| 27 | + self._clients: dict[ClientCacheKey, openai.AsyncOpenAI] = {} |
| 28 | + self._client_lock = asyncio.Lock() |
| 29 | + |
| 30 | + async def get_client(self, config: ProviderConfig) -> openai.AsyncOpenAI: |
| 31 | + """Return a long-lived AsyncOpenAI client keyed on connection params.""" |
| 32 | + base_url = config.endpoint or DEFAULT_BASE_URL |
| 33 | + key: ClientCacheKey = ( |
| 34 | + base_url, |
| 35 | + config.api_key, |
| 36 | + float(config.timeout), |
| 37 | + config.max_retries, |
| 38 | + ) |
| 39 | + cached = self._clients.get(key) |
| 40 | + if cached is not None: |
| 41 | + return cached |
| 42 | + async with self._client_lock: |
| 43 | + cached = self._clients.get(key) |
| 44 | + if cached is not None: |
| 45 | + return cached |
| 46 | + client = openai.AsyncOpenAI( |
| 47 | + api_key=config.api_key, |
| 48 | + base_url=base_url, |
| 49 | + timeout=float(config.timeout), |
| 50 | + max_retries=config.max_retries, |
| 51 | + ) |
| 52 | + self._clients[key] = client |
| 53 | + return client |
| 54 | + |
| 55 | + async def aclose(self) -> None: |
| 56 | + for client in self._clients.values(): |
| 57 | + await client.close() |
| 58 | + self._clients.clear() |
| 59 | + |
| 60 | + async def send_message( |
| 61 | + self, |
| 62 | + messages: list[ChatMessage], |
| 63 | + config: ProviderConfig, |
| 64 | + ) -> str: |
| 65 | + base_url = config.endpoint or DEFAULT_BASE_URL |
| 66 | + model = config.model or DEFAULT_MODEL |
| 67 | + formatted = [{"role": m.role, "content": m.content} for m in messages] |
| 68 | + |
| 69 | + client = await self.get_client(config) |
| 70 | + try: |
| 71 | + effective_max_tokens = ( |
| 72 | + min(config.max_tokens, MAX_TOKENS_CEILING) |
| 73 | + if config.max_tokens is not None |
| 74 | + else MAX_TOKENS_CEILING |
| 75 | + ) |
| 76 | + create_kwargs: dict = { |
| 77 | + "model": model, |
| 78 | + "messages": formatted, # type: ignore[arg-type] |
| 79 | + "max_tokens": effective_max_tokens, |
| 80 | + "temperature": config.temperature, |
| 81 | + } |
| 82 | + if config.seed is not None: |
| 83 | + create_kwargs["seed"] = config.seed |
| 84 | + if config.json_output: |
| 85 | + create_kwargs["response_format"] = {"type": "json_object"} |
| 86 | + response = await create_chat_completion_json_fallback(client, **create_kwargs) |
| 87 | + choices = response.choices |
| 88 | + if not choices: |
| 89 | + raise ProviderResponseError( |
| 90 | + provider="atlascloud", |
| 91 | + endpoint=base_url, |
| 92 | + details=f"No choices in response (id={response.id})", |
| 93 | + ) |
| 94 | + choice = choices[0] |
| 95 | + finish_reason = choice.finish_reason or "unknown" |
| 96 | + if choice.message is None: |
| 97 | + raise ProviderResponseError( |
| 98 | + provider="atlascloud", |
| 99 | + endpoint=base_url, |
| 100 | + details=f"Missing message in choice (finish_reason={finish_reason})", |
| 101 | + ) |
| 102 | + content = choice.message.content |
| 103 | + if not content: |
| 104 | + raise ProviderEmptyContentError( |
| 105 | + provider="atlascloud", |
| 106 | + endpoint=base_url, |
| 107 | + details=f"Empty content in response (finish_reason={finish_reason})", |
| 108 | + ) |
| 109 | + except openai.AuthenticationError as exc: |
| 110 | + raise ProviderAuthError( |
| 111 | + provider="atlascloud", endpoint=base_url, details=str(exc) |
| 112 | + ) from exc |
| 113 | + except openai.RateLimitError as exc: |
| 114 | + raise ProviderRateLimitError( |
| 115 | + provider="atlascloud", endpoint=base_url, details=str(exc) |
| 116 | + ) from exc |
| 117 | + except openai.APITimeoutError as exc: |
| 118 | + raise ProviderTimeoutError( |
| 119 | + provider="atlascloud", endpoint=base_url, details=str(exc) |
| 120 | + ) from exc |
| 121 | + except openai.APIConnectionError as exc: |
| 122 | + raise ProviderConnectionError( |
| 123 | + provider="atlascloud", endpoint=base_url, details=str(exc) |
| 124 | + ) from exc |
| 125 | + except openai.APIError as exc: |
| 126 | + raise ProviderResponseError( |
| 127 | + provider="atlascloud", endpoint=base_url, details=str(exc) |
| 128 | + ) from exc |
| 129 | + else: |
| 130 | + return content |
0 commit comments