|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import TYPE_CHECKING, Any, cast |
| 4 | + |
| 5 | +from httpx import AsyncClient |
| 6 | + |
| 7 | +from any_llm.any_llm import AnyLLM |
| 8 | +from any_llm.logging import logger |
| 9 | +from any_llm.types.completion import ( |
| 10 | + ChatCompletion, |
| 11 | + ChatCompletionChunk, |
| 12 | + CompletionParams, |
| 13 | + CompletionUsage, |
| 14 | + CreateEmbeddingResponse, |
| 15 | +) |
| 16 | + |
| 17 | +from .utils import get_provider_key, post_completion_usage_event |
| 18 | + |
| 19 | +if TYPE_CHECKING: |
| 20 | + from collections.abc import AsyncIterator, Sequence |
| 21 | + |
| 22 | + from any_llm.types.model import Model |
| 23 | + |
| 24 | + |
| 25 | +class PlatformProvider(AnyLLM): |
| 26 | + PROVIDER_NAME = "platform" |
| 27 | + ENV_API_KEY_NAME = "ANY_LLM_KEY" |
| 28 | + PROVIDER_DOCUMENTATION_URL = "https://github.com/mozilla-ai/any-llm" |
| 29 | + |
| 30 | + # All features are marked as supported, but depending on which provider you call inside the gateway, they may not all work. |
| 31 | + SUPPORTS_COMPLETION_STREAMING = True |
| 32 | + SUPPORTS_COMPLETION = True |
| 33 | + SUPPORTS_RESPONSES = True |
| 34 | + SUPPORTS_COMPLETION_REASONING = True |
| 35 | + SUPPORTS_COMPLETION_IMAGE = True |
| 36 | + SUPPORTS_COMPLETION_PDF = True |
| 37 | + SUPPORTS_EMBEDDING = True |
| 38 | + SUPPORTS_LIST_MODELS = True |
| 39 | + SUPPORTS_BATCH = True |
| 40 | + |
| 41 | + def __init__(self, api_key: str | None = None, api_base: str | None = None, **kwargs: Any): |
| 42 | + self.any_llm_key = self._verify_and_set_api_key(api_key) |
| 43 | + self.api_base = api_base |
| 44 | + self.kwargs = kwargs |
| 45 | + |
| 46 | + self._init_client(api_key=api_key, api_base=api_base, **kwargs) |
| 47 | + |
| 48 | + def _init_client(self, api_key: str | None = None, api_base: str | None = None, **kwargs: Any) -> None: |
| 49 | + self.client = AsyncClient(**kwargs) |
| 50 | + |
| 51 | + @staticmethod |
| 52 | + def _convert_completion_params(params: CompletionParams, **kwargs: Any) -> dict[str, Any]: |
| 53 | + raise NotImplementedError |
| 54 | + |
| 55 | + @staticmethod |
| 56 | + def _convert_completion_response(response: Any) -> ChatCompletion: |
| 57 | + raise NotImplementedError |
| 58 | + |
| 59 | + @staticmethod |
| 60 | + def _convert_completion_chunk_response(response: Any, **kwargs: Any) -> ChatCompletionChunk: |
| 61 | + raise NotImplementedError |
| 62 | + |
| 63 | + @staticmethod |
| 64 | + def _convert_embedding_params(params: Any, **kwargs: Any) -> dict[str, Any]: |
| 65 | + raise NotImplementedError |
| 66 | + |
| 67 | + @staticmethod |
| 68 | + def _convert_embedding_response(response: Any) -> CreateEmbeddingResponse: |
| 69 | + raise NotImplementedError |
| 70 | + |
| 71 | + @staticmethod |
| 72 | + def _convert_list_models_response(response: Any) -> Sequence[Model]: |
| 73 | + raise NotImplementedError |
| 74 | + |
| 75 | + async def _acompletion( |
| 76 | + self, |
| 77 | + params: CompletionParams, |
| 78 | + **kwargs: Any, |
| 79 | + ) -> ChatCompletion | AsyncIterator[ChatCompletionChunk]: |
| 80 | + completion = await self.provider._acompletion(params=params, **kwargs) |
| 81 | + |
| 82 | + if not params.stream: |
| 83 | + await post_completion_usage_event( |
| 84 | + client=self.client, |
| 85 | + any_llm_key=self.any_llm_key, # type: ignore[arg-type] |
| 86 | + provider=self.provider.PROVIDER_NAME, |
| 87 | + completion=cast("ChatCompletion", completion), |
| 88 | + ) |
| 89 | + return completion |
| 90 | + |
| 91 | + # For streaming, wrap the iterator to collect usage info |
| 92 | + return self._stream_with_usage_tracking(cast("AsyncIterator[ChatCompletionChunk]", completion)) |
| 93 | + |
| 94 | + async def _stream_with_usage_tracking( |
| 95 | + self, stream: AsyncIterator[ChatCompletionChunk] |
| 96 | + ) -> AsyncIterator[ChatCompletionChunk]: |
| 97 | + """Wrap the stream to track usage after completion.""" |
| 98 | + chunks: list[ChatCompletionChunk] = [] |
| 99 | + |
| 100 | + async for chunk in stream: |
| 101 | + chunks.append(chunk) |
| 102 | + yield chunk |
| 103 | + |
| 104 | + # After stream completes, reconstruct completion for usage tracking |
| 105 | + if chunks: |
| 106 | + # Combine chunks into a single ChatCompletion-like object |
| 107 | + final_completion = self._combine_chunks(chunks) |
| 108 | + await post_completion_usage_event( |
| 109 | + client=self.client, |
| 110 | + any_llm_key=self.any_llm_key, # type: ignore [arg-type] |
| 111 | + provider=self.provider.PROVIDER_NAME, |
| 112 | + completion=final_completion, |
| 113 | + ) |
| 114 | + |
| 115 | + def _combine_chunks(self, chunks: list[ChatCompletionChunk]) -> ChatCompletion: |
| 116 | + """Combine streaming chunks into a ChatCompletion for usage tracking.""" |
| 117 | + # Get the last chunk which typically has the full usage info |
| 118 | + last_chunk = chunks[-1] |
| 119 | + |
| 120 | + if not last_chunk.usage: |
| 121 | + msg = ( |
| 122 | + "The last chunk of your streaming response does not contain usage data. " |
| 123 | + "Consult your provider documentation on how to retrieve it." |
| 124 | + ) |
| 125 | + logger.error(msg) |
| 126 | + |
| 127 | + return ChatCompletion( |
| 128 | + id=last_chunk.id, |
| 129 | + model=last_chunk.model, |
| 130 | + created=last_chunk.created, |
| 131 | + object="chat.completion", |
| 132 | + usage=CompletionUsage( |
| 133 | + completion_tokens=0, |
| 134 | + prompt_tokens=0, |
| 135 | + total_tokens=0, |
| 136 | + ), |
| 137 | + choices=[], |
| 138 | + ) |
| 139 | + |
| 140 | + # Create a minimal ChatCompletion object with the data needed for usage tracking |
| 141 | + # We only need id, model, created, usage, and object type |
| 142 | + return ChatCompletion( |
| 143 | + id=last_chunk.id, |
| 144 | + model=last_chunk.model, |
| 145 | + created=last_chunk.created, |
| 146 | + object="chat.completion", |
| 147 | + usage=last_chunk.usage if hasattr(last_chunk, "usage") and last_chunk.usage else None, |
| 148 | + choices=[], |
| 149 | + ) |
| 150 | + |
| 151 | + @property |
| 152 | + def provider(self) -> AnyLLM: |
| 153 | + return self._provider |
| 154 | + |
| 155 | + @provider.setter |
| 156 | + def provider(self, provider_class: type[AnyLLM]) -> None: |
| 157 | + provider_key = get_provider_key(any_llm_key=self.any_llm_key, provider=provider_class) # type: ignore[arg-type] |
| 158 | + self._provider = provider_class(api_key=provider_key, api_base=self.api_base, **self.kwargs) |
0 commit comments