Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ nebius = []
neosantara = []
openai = []
openrouter = []
portkey = []
portkey = ["portkey-ai"]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[minor] portkey-ai has no lower bound. The code needs portkey_ai.AsyncPortkey and 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 as portkey-ai>=2.3.4, as other extras here do.

qiniu = []
requesty = []
sambanova = []
Expand Down
54 changes: 54 additions & 0 deletions src/any_llm/providers/portkey/portkey.py
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
Expand All @@ -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."""
Expand All @@ -30,25 +42,67 @@ class PortkeyProvider(XMLReasoningOpenAIProvider):
SUPPORTS_LIST_MODELS = True

_DEFAULT_REASONING_EFFORT = None
MISSING_PACKAGES_ERROR = MISSING_PACKAGES_ERROR
client: Any

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[minor] client: Any (with AsyncPortkey: Any above) removes all type checking from every self.client... call in the base class. Import the class directly inside the try block and declare client: AsyncPortkey behind TYPE_CHECKING, the way xai and mistral do, so mypy keeps checking those calls.


@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(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The 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 timeout out of the call kwargs and passes timeout=None to its inner OpenAI client, and None means "no limit" in httpx. The old AsyncOpenAI client sent connect=5.0, read=600; AsyncPortkey sends connect=None, read=None, write=None, pool=None. A stalled gateway call now blocks forever instead of failing after 10 minutes. Client options do not help: AsyncPortkey(request_timeout=60) still yields an all-None timeout, because the per-call timeout=None wins. Set a default timeout in _convert_completion_params (and for the models.list call) to keep the old behaviour.

api_key=api_key,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[minor] The request on the wire changed. Portkey's client sends Authorization: Bearer OPENAI_API_KEY (a literal placeholder) and puts the real key in the x-portkey-api-key header, where the old client sent the key as the bearer token. That is correct for api.portkey.ai, but a user who points PORTKEY_API_BASE at a gateway expecting a bearer token loses authentication. Please confirm this against a real endpoint.

base_url=api_base or self.API_BASE,
**kwargs,
)
Comment on lines +62 to +66
Comment thread
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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nit] wrap_chunks_with_xml_reasoning is imported inside the method, but any_llm.providers.openai.xml_reasoning is already imported at the top of the file (line 8). There is no import cycle to avoid, so move this up with the other imports.


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]:
Expand Down
156 changes: 155 additions & 1 deletion tests/unit/providers/test_portkey_provider.py
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."""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The 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. AsyncPortkey.chat.completions.create() without streaming returns portkey_ai.api_resources.types.chat_complete_type.ChatCompletions, and models.list() returns portkey_ai.api_resources.types.models_type.ModelList holding portkey_ai...models_type.Model. Only the streaming chunk is the vendored OpenAI type. So the two main regression tests pass without ever touching the real shapes, and a change in those Portkey types would not be caught. portkey_ai._vendor is also a private path that can move between releases. Building a real AsyncPortkey on an httpx.MockTransport covers all three paths and avoids private modules.

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:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The 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 action_required, so unit tests, lint, and mypy never ran, and the description says pre-commit did not complete. Portkey is in the integration matrix and the client that talks to the gateway changed, so please apply the run-integration-tests label before merge.

"""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"}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved


def test_convert_completion_params_with_dataclass_response_format() -> None:
Expand All @@ -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")]