Repository navigation
fix: use Portkey native Python SDK #1307
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 6 commits
c68d532
30f5e05
1c43648
29f4574
a05f9d5
328ba4f
5ba45f9
eb973e7
4e8b123
9cbdbcd
ad949c1
60f203a
ffcb420
aee3e4d
e3e597c
3c0d193
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| from collections.abc import AsyncIterator, Sequence | ||
| from typing import Any | ||
|
|
||
| from openai.types.chat.chat_completion import ChatCompletion as OpenAIChatCompletion | ||
|
|
@@ -10,8 +11,19 @@ | |
| convert_chat_completion_with_xml_reasoning, | ||
| ) | ||
| from any_llm.types.completion import ChatCompletion, ChatCompletionChunk, CompletionParams | ||
| from any_llm.types.model import Model | ||
| from any_llm.utils.structured_output import get_json_schema, is_structured_output_type | ||
|
|
||
| try: | ||
| import portkey_ai | ||
|
|
||
| AsyncPortkey: Any = portkey_ai.AsyncPortkey | ||
| except ImportError as e: # pragma: no cover - exercised by the package guard | ||
| AsyncPortkey = None | ||
| MISSING_PACKAGES_ERROR: ImportError | None = e | ||
| else: | ||
| MISSING_PACKAGES_ERROR = None | ||
|
|
||
|
|
||
| class PortkeyProvider(XMLReasoningOpenAIProvider): | ||
| """Portkey provider for accessing 200+ LLMs through Portkey's AI Gateway.""" | ||
|
|
@@ -30,25 +42,67 @@ class PortkeyProvider(XMLReasoningOpenAIProvider): | |
| SUPPORTS_LIST_MODELS = True | ||
|
|
||
| _DEFAULT_REASONING_EFFORT = None | ||
| MISSING_PACKAGES_ERROR = MISSING_PACKAGES_ERROR | ||
| client: Any | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [minor] |
||
|
|
||
| @override | ||
| def _init_client(self, api_key: str | None = None, api_base: str | None = None, **kwargs: Any) -> None: | ||
| """Initialize Portkey's native async client.""" | ||
| self.client = AsyncPortkey( | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [major] Requests now go out with no timeout at all. Portkey's SDK pops |
||
| api_key=api_key, | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [minor] The request on the wire changed. Portkey's client sends |
||
| base_url=api_base or self.API_BASE, | ||
| **kwargs, | ||
| ) | ||
|
Comment on lines
+62
to
+66
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| @staticmethod | ||
| @override | ||
| def _convert_completion_response(response: Any) -> ChatCompletion: | ||
| """Convert a Portkey completion response and extract XML reasoning.""" | ||
| if isinstance(response, OpenAIChatCompletion): | ||
| return convert_chat_completion_with_xml_reasoning(response) | ||
| if isinstance(response, ChatCompletion): | ||
| return response | ||
| if hasattr(response, "model_dump"): | ||
| return convert_chat_completion_with_xml_reasoning(response) | ||
| return ChatCompletion.model_validate(response) | ||
|
|
||
| @staticmethod | ||
| @override | ||
| def _convert_completion_chunk_response(response: Any, **kwargs: Any) -> ChatCompletionChunk: | ||
| """Convert a Portkey completion chunk and extract XML reasoning.""" | ||
| if isinstance(response, OpenAIChatCompletionChunk): | ||
| return convert_chat_completion_chunk_with_xml_reasoning(response) | ||
| if isinstance(response, ChatCompletionChunk): | ||
| return response | ||
| if hasattr(response, "model_dump"): | ||
| return convert_chat_completion_chunk_with_xml_reasoning(response) | ||
| return ChatCompletionChunk.model_validate(response) | ||
|
|
||
| @override | ||
| def _convert_completion_response_async(self, response: Any) -> ChatCompletion | AsyncIterator[ChatCompletionChunk]: | ||
| """Convert native Portkey completion objects and streams. | ||
|
|
||
| Portkey returns Pydantic models from its vendored OpenAI SDK, so they do | ||
| not satisfy the OpenAI SDK ``isinstance`` checks in the shared base. | ||
| """ | ||
| if not hasattr(response, "__aiter__"): | ||
| return self._convert_completion_response(response) | ||
|
|
||
| async def chunk_iterator() -> AsyncIterator[ChatCompletionChunk]: | ||
| async for chunk in response: | ||
| yield self._convert_completion_chunk_response(chunk) | ||
|
|
||
| from any_llm.providers.openai.xml_reasoning import wrap_chunks_with_xml_reasoning | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [nit] |
||
|
|
||
| return wrap_chunks_with_xml_reasoning(chunk_iterator()) | ||
|
|
||
| @staticmethod | ||
| @override | ||
| def _convert_list_models_response(response: Any) -> Sequence[Model]: | ||
| """Convert Portkey's vendored OpenAI model objects to AnyLLM models.""" | ||
| models = response.data if hasattr(response, "data") else response | ||
| return [Model.model_validate(model.model_dump() if hasattr(model, "model_dump") else model) for model in models] | ||
|
|
||
| @staticmethod | ||
| @override | ||
| def _convert_completion_params(params: CompletionParams, **kwargs: Any) -> dict[str, Any]: | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,116 @@ | ||
| from collections.abc import AsyncIterator | ||
| from dataclasses import dataclass | ||
| from typing import Any, cast | ||
|
|
||
| import pytest | ||
|
|
||
| from any_llm.providers.portkey.portkey import PortkeyProvider | ||
| from any_llm.types.completion import CompletionParams | ||
| from any_llm.types.completion import ChatCompletion, CompletionParams | ||
|
|
||
|
|
||
| def _native_portkey_model(data: dict[str, Any]) -> Any: | ||
| """Build the actual vendored Pydantic model returned by portkey-ai.""" | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [major] This helper says it builds "the actual vendored Pydantic model returned by portkey-ai", but that is not the type the SDK returns for two of the three paths. |
||
| if data["object"] == "chat.completion": | ||
| from portkey_ai._vendor.openai.types.chat.chat_completion import ChatCompletion as NativeChatCompletion | ||
|
|
||
| return NativeChatCompletion.model_validate(data) | ||
| if data["object"] == "chat.completion.chunk": | ||
| from portkey_ai._vendor.openai.types.chat.chat_completion_chunk import ( | ||
| ChatCompletionChunk as NativeChatCompletionChunk, | ||
| ) | ||
|
|
||
| return NativeChatCompletionChunk.model_validate(data) | ||
|
|
||
| from portkey_ai._vendor.openai.types.model import Model as NativeModel | ||
|
|
||
| return NativeModel.model_validate(data) | ||
|
|
||
|
|
||
| class _NativePortkeyStream: | ||
| """Async iterator matching the stream returned by AsyncPortkey.""" | ||
|
|
||
| def __init__(self, chunks: list[Any]) -> None: | ||
| self._chunks = iter(chunks) | ||
|
|
||
| def __aiter__(self) -> AsyncIterator[Any]: | ||
| return self | ||
|
|
||
| async def __anext__(self) -> Any: | ||
| try: | ||
| return next(self._chunks) | ||
| except StopIteration: | ||
| raise StopAsyncIteration from None | ||
|
|
||
|
|
||
| class _NativePortkeyClient: | ||
| """Minimal AsyncPortkey-shaped client with deterministic native SDK responses.""" | ||
|
|
||
| def __init__(self) -> None: | ||
| self.chat = self | ||
| self.completions = self | ||
| self.models = self | ||
|
|
||
| async def create(self, **kwargs: Any) -> Any: | ||
| if kwargs.get("stream"): | ||
| return _NativePortkeyStream( | ||
| [ | ||
| _native_portkey_model( | ||
| { | ||
| "id": "chunk-1", | ||
| "object": "chat.completion.chunk", | ||
| "created": 0, | ||
| "model": "test-model", | ||
| "choices": [ | ||
| { | ||
| "index": 0, | ||
| "delta": {"role": "assistant", "content": "<think>because</think>answer"}, | ||
| "finish_reason": "stop", | ||
| } | ||
| ], | ||
| } | ||
| ) | ||
| ] | ||
| ) | ||
| return _native_portkey_model( | ||
| { | ||
| "id": "completion-1", | ||
| "object": "chat.completion", | ||
| "created": 0, | ||
| "model": "test-model", | ||
| "choices": [ | ||
| { | ||
| "index": 0, | ||
| "message": {"role": "assistant", "content": "<think>because</think>answer"}, | ||
| "finish_reason": "stop", | ||
| } | ||
| ], | ||
| } | ||
| ) | ||
|
|
||
| async def list(self, **_kwargs: object) -> Any: | ||
| return type( | ||
| "NativeModelList", | ||
| (), | ||
| { | ||
| "data": [ | ||
| _native_portkey_model({"id": "test-model", "object": "model", "created": 0, "owned_by": "portkey"}) | ||
| ] | ||
| }, | ||
| )() | ||
|
|
||
|
|
||
| def test_portkey_uses_native_async_client(monkeypatch: pytest.MonkeyPatch) -> None: | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [minor] This change has no CI signal. Every workflow run on the branch is |
||
| """The provider initializes Portkey's native SDK instead of OpenAI's client.""" | ||
| calls: dict[str, Any] = {} | ||
|
|
||
| class FakeAsyncPortkey: | ||
| def __init__(self, **kwargs: Any) -> None: | ||
| calls.update(kwargs) | ||
|
|
||
| monkeypatch.setattr("any_llm.providers.portkey.portkey.AsyncPortkey", FakeAsyncPortkey) | ||
| PortkeyProvider(api_key="test-key", api_base="https://example.test/v1") | ||
|
|
||
| assert calls == {"api_key": "test-key", "base_url": "https://example.test/v1"} | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
|
|
||
| def test_convert_completion_params_with_dataclass_response_format() -> None: | ||
|
|
@@ -26,3 +135,48 @@ class TestOutput: | |
| assert "properties" in result["response_format"]["json_schema"]["schema"] | ||
| assert "name" in result["response_format"]["json_schema"]["schema"]["properties"] | ||
| assert "value" in result["response_format"]["json_schema"]["schema"]["properties"] | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_native_portkey_completion_converts_vendored_model_and_xml_reasoning() -> None: | ||
| provider = PortkeyProvider(api_key="test-key") | ||
| provider.client = _NativePortkeyClient() | ||
|
|
||
| result = await provider._acompletion( | ||
| CompletionParams(model_id="test-model", messages=[{"role": "user", "content": "Hello"}]) | ||
| ) | ||
|
|
||
| completion = cast("ChatCompletion", result) | ||
| assert completion.choices[0].message.content == "answer" | ||
| assert completion.choices[0].message.reasoning is not None | ||
| assert completion.choices[0].message.reasoning.content == "because" | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_native_portkey_stream_converts_vendored_chunks_and_xml_reasoning() -> None: | ||
| provider = PortkeyProvider(api_key="test-key") | ||
| provider.client = _NativePortkeyClient() | ||
|
|
||
| result = await provider._acompletion( | ||
| CompletionParams( | ||
| model_id="test-model", | ||
| messages=[{"role": "user", "content": "Hello"}], | ||
| stream=True, | ||
| ) | ||
| ) | ||
|
|
||
| chunks = [chunk async for chunk in cast("AsyncIterator[Any]", result)] | ||
|
|
||
| assert chunks[0].choices[0].delta.content == "answer" | ||
| assert chunks[0].choices[0].delta.reasoning is not None | ||
| assert chunks[0].choices[0].delta.reasoning.content == "because" | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_native_portkey_list_models_converts_vendored_models() -> None: | ||
| provider = PortkeyProvider(api_key="test-key") | ||
| provider.client = _NativePortkeyClient() | ||
|
|
||
| models = await provider._alist_models() | ||
|
|
||
| assert [(model.id, model.owned_by) for model in models] == [("test-model", "portkey")] | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[minor]
portkey-aihas no lower bound. The code needsportkey_ai.AsyncPortkeyand the response shapes of a recent release, so a resolver that picks an old version would fail in a confusing way. Add a floor such asportkey-ai>=2.3.4, as other extras here do.