Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
12 changes: 12 additions & 0 deletions src/any_llm/any_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,7 @@ def completion(
response_format: dict[str, Any] | type | None = None,
stream: bool | None = None,
prompt_cache_key: str | None = None,
timeout: float | None = None,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
allow_running_loop: bool | None = None,
**kwargs: Any,
) -> ChatCompletion | Iterator[ChatCompletionChunk] | ParsedChatCompletion[Any]:
Expand All @@ -594,6 +595,7 @@ def completion(
response_format=response_format,
stream=stream,
prompt_cache_key=prompt_cache_key,
timeout=timeout,
**kwargs,
),
allow_running_loop=allow_running_loop,
Expand All @@ -606,6 +608,7 @@ def completion(
response_format=response_format,
stream=stream,
prompt_cache_key=prompt_cache_key,
timeout=timeout,
**kwargs,
),
allow_running_loop=allow_running_loop,
Expand Down Expand Up @@ -687,6 +690,7 @@ async def acompletion(
max_completion_tokens: int | None = None,
reasoning_effort: ReasoningEffort | None = "auto",
prompt_cache_key: str | None = None,
timeout: float | None = None, # noqa: ASYNC109 # forwarded to the provider SDK, which owns the timeout
**kwargs: Any,
) -> ChatCompletion | AsyncIterator[ChatCompletionChunk] | ParsedChatCompletion[Any]:
"""Create a chat completion asynchronously.
Expand Down Expand Up @@ -716,6 +720,9 @@ async def acompletion(
max_completion_tokens: Maximum number of tokens for the completion
reasoning_effort: Reasoning effort level for models that support it. "auto" will map to each provider's default.
prompt_cache_key: A key to use when reading from or writing to a provider's prompt cache.
timeout: Per-request timeout in seconds, passed through to the provider's client/SDK.
An explicit ``None`` is treated the same as omitting it (the provider's default
applies), so it cannot request an unbounded timeout.
**kwargs: Additional provider-specific arguments that will be passed to the provider's API call.

Returns:
Expand Down Expand Up @@ -761,6 +768,11 @@ async def acompletion(
)

self._validate_prompt_cache_key(prompt_cache_key)
# timeout is forwarded through kwargs rather than carried on CompletionParams: providers
# apply it differently (per-request vs client-level), so each consumes it from kwargs.
# Forward it only when set, so the default path (and its provider behavior) is unchanged.
if timeout is not None:
kwargs["timeout"] = timeout
result = await self._acompletion(params, **kwargs)

if is_structured_output_type(response_format):
Expand Down
10 changes: 10 additions & 0 deletions src/any_llm/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ def completion(
max_completion_tokens: int | None = None,
reasoning_effort: ReasoningEffort | None = "auto",
prompt_cache_key: str | None = None,
timeout: float | None = None,
client_args: dict[str, Any] | None = None,
**kwargs: Any,
) -> ChatCompletion | Iterator[ChatCompletionChunk]:
Expand Down Expand Up @@ -87,6 +88,9 @@ def completion(
max_completion_tokens: Maximum number of tokens for the completion
reasoning_effort: Reasoning effort level for models that support it. "auto" will map to each provider's default.
prompt_cache_key: A key to use when reading from or writing to a provider's prompt cache.
timeout: Per-request timeout in seconds, passed through to the provider's client/SDK.
An explicit ``None`` is treated the same as omitting it (the provider's default
applies), so it cannot request an unbounded timeout.
client_args: Additional provider-specific arguments that will be passed to the provider's client instantiation.
**kwargs: Additional provider-specific arguments that will be passed to the provider's API call.

Expand Down Expand Up @@ -130,6 +134,7 @@ def completion(
max_completion_tokens=max_completion_tokens,
reasoning_effort=reasoning_effort,
prompt_cache_key=prompt_cache_key,
timeout=timeout,
**kwargs,
)

Expand Down Expand Up @@ -163,6 +168,7 @@ async def acompletion(
max_completion_tokens: int | None = None,
reasoning_effort: ReasoningEffort | None = "auto",
prompt_cache_key: str | None = None,
timeout: float | None = None, # noqa: ASYNC109 # forwarded to the provider SDK, which owns the timeout
client_args: dict[str, Any] | None = None,
**kwargs: Any,
) -> ChatCompletion | AsyncIterator[ChatCompletionChunk]:
Expand Down Expand Up @@ -199,6 +205,9 @@ async def acompletion(
max_completion_tokens: Maximum number of tokens for the completion
reasoning_effort: Reasoning effort level for models that support it. "auto" will map to each provider's default.
prompt_cache_key: A key to use when reading from or writing to a provider's prompt cache.
timeout: Per-request timeout in seconds, passed through to the provider's client/SDK.
An explicit ``None`` is treated the same as omitting it (the provider's default
applies), so it cannot request an unbounded timeout.
client_args: Additional provider-specific arguments that will be passed to the provider's client instantiation.
**kwargs: Additional provider-specific arguments that will be passed to the provider's API call.

Expand Down Expand Up @@ -242,6 +251,7 @@ async def acompletion(
max_completion_tokens=max_completion_tokens,
reasoning_effort=reasoning_effort,
prompt_cache_key=prompt_cache_key,
timeout=timeout,
**kwargs,
)

Expand Down
47 changes: 41 additions & 6 deletions src/any_llm/providers/anthropic/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
import json
from abc import ABC, abstractmethod
from collections.abc import Mapping
from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast

from typing_extensions import override

from any_llm.any_llm import AnyLLM
from any_llm.exceptions import BatchNotCompleteError
from any_llm.exceptions import BatchNotCompleteError, InvalidRequestError
from any_llm.logging import logger
from any_llm.types.batch import Batch, BatchRequestCounts, BatchResult, BatchResultError, BatchResultItem
from any_llm.types.messages import (
Expand Down Expand Up @@ -40,7 +41,7 @@
MISSING_PACKAGES_ERROR = e

if TYPE_CHECKING:
from collections.abc import AsyncIterator, Sequence
from collections.abc import AsyncIterator, Iterator, Sequence

from anthropic import AsyncAnthropic, AsyncAnthropicVertex
from anthropic.types import Message
Expand All @@ -57,6 +58,34 @@
_COMPACTION_MIN_TRIGGER_TOKENS = 50_000
_CONTEXT_MANAGEMENT_BETA = "context-management-2025-06-27"

# The SDK's client-side non-streaming guard raises a bare ValueError beginning with this text. It
# is the only signal the SDK exposes for that condition (no error code or dedicated subtype), and
# it has stayed stable across SDK versions. Kept as a single named constant so this is the one
# documented point of coupling to the SDK's wording; the real-client test surfaces any future reword.
_NONSTREAMING_TIMEOUT_GUARD_MARKER = "Streaming is required"


@contextmanager
def _translating_nonstreaming_guard(provider: AnyLLM, max_tokens: int | None) -> Iterator[None]:
"""Translate the SDK's client-side non-streaming guard into an actionable any-llm error.

The guard rejects a non-streaming request whose max_tokens could exceed the default
per-request time limit, raising a bare ValueError before anything is sent. Any unrelated
ValueError is left untouched.
"""
try:
yield
except ValueError as exc:
if not str(exc).startswith(_NONSTREAMING_TIMEOUT_GUARD_MARKER):
raise
msg = (
f"A non-streaming request with max_tokens={max_tokens} can exceed the default "
"per-request time limit, so it needs an explicit timeout. "
"Pass a `timeout` (in seconds) or use `stream=True`."
)
raise InvalidRequestError(msg, original_exception=exc, provider_name=provider.PROVIDER_NAME) from exc


_ANTHROPIC_TO_OPENAI_STATUS_MAP: dict[str, str] = {
"in_progress": "in_progress",
"canceling": "cancelling",
Expand Down Expand Up @@ -275,7 +304,8 @@ async def _acompletion(
if converted_kwargs.pop("stream", False):
return self._stream_completion_async(**converted_kwargs)

message = await self.client.messages.create(**converted_kwargs)
with _translating_nonstreaming_guard(self, converted_kwargs.get("max_tokens")):
message = await self.client.messages.create(**converted_kwargs)

return self._convert_completion_response(message)

Expand Down Expand Up @@ -303,9 +333,13 @@ async def _amessages(
native_kwargs["betas"] = betas
native_kwargs.update(kwargs)
if is_structured_output_type(params.output_format):
parsed = await messages_resource.parse(output_format=params.output_format, **native_kwargs)
with _translating_nonstreaming_guard(self, params.max_tokens):
parsed = await messages_resource.parse(output_format=params.output_format, **native_kwargs)
return cast("ParsedMessage[Any] | ParsedBetaMessage[Any]", parsed)
message = await messages_resource.create(output_config=cast("Any", params.output_format), **native_kwargs)
with _translating_nonstreaming_guard(self, params.max_tokens):
message = await messages_resource.create(
output_config=cast("Any", params.output_format), **native_kwargs
)
return self._convert_native_message_to_response(message)

api_kwargs = params.model_dump(exclude_none=True, exclude={"betas"})
Expand All @@ -318,7 +352,8 @@ async def _amessages(
return self._stream_messages_async(use_beta=use_beta, **api_kwargs)

messages_resource = self.client.beta.messages if use_beta else self.client.messages
response: Message = await messages_resource.create(**api_kwargs)
with _translating_nonstreaming_guard(self, params.max_tokens):
response: Message = await messages_resource.create(**api_kwargs)
return self._convert_native_message_to_response(response)

async def _stream_messages_async(
Expand Down
8 changes: 8 additions & 0 deletions src/any_llm/providers/cohere/cohere.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,14 @@ def _convert_completion_params(params: CompletionParams, **kwargs: Any) -> dict[
"token_budget": REASONING_EFFORT_TO_THINKING_BUDGETS[params.reasoning_effort],
}
converted_params.update(kwargs)

# Cohere's SDK carries a per-request timeout inside `request_options` rather than as a
# top-level keyword, so the seconds-based any-llm parameter has to be folded in there.
if (timeout := converted_params.pop("timeout", None)) is not None:
request_options = dict(converted_params.get("request_options") or {})
request_options.setdefault("timeout", timeout)
converted_params["request_options"] = request_options

return converted_params

@staticmethod
Expand Down
9 changes: 9 additions & 0 deletions src/any_llm/providers/lmstudio/lmstudio.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from typing_extensions import override

from any_llm.any_llm import AnyLLM
from any_llm.logging import logger
from any_llm.utils.structured_output import get_json_schema, is_structured_output_type

MISSING_PACKAGES_ERROR = None
Expand Down Expand Up @@ -139,6 +140,14 @@ def _convert_completion_params(params: CompletionParams, **kwargs: Any) -> dict[
if params.stop is not None:
config["stopStrings"] = [params.stop] if isinstance(params.stop, str) else params.stop
config.update(kwargs)

# LM Studio folds this dict into the prediction config, which has no per-request timeout,
# so a `timeout` cannot be honored here.
if config.pop("timeout", None) is not None:
logger.warning(
"LM Studio does not support a per-request 'timeout'; ignoring it. "
"Set it on the client via client_args instead."
)
return config

@staticmethod
Expand Down
6 changes: 6 additions & 0 deletions src/any_llm/providers/mistral/mistral.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,12 @@ def _convert_completion_params(params: CompletionParams, **kwargs: Any) -> dict[
converted_params["reasoning_effort"] = _MISTRAL_REASONING_EFFORT

converted_params.update(kwargs)

# Mistral's SDK names its per-request timeout `timeout_ms`, so the seconds-based any-llm
# parameter has to be translated; forwarding it as `timeout` is an unexpected keyword.
if (timeout := converted_params.pop("timeout", None)) is not None:
converted_params["timeout_ms"] = int(timeout * 1000)

return converted_params

@staticmethod
Expand Down
8 changes: 8 additions & 0 deletions src/any_llm/providers/ollama/ollama.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,14 @@ def _convert_completion_params(params: CompletionParams, **kwargs: Any) -> dict[
converted_params["think"] = REASONING_EFFORT_TO_OLLAMA_THINK[params.reasoning_effort]
converted_params.update(kwargs)

# The Ollama client only accepts a timeout at construction, so a per-request `timeout`
# cannot be honored here and would reach the SDK as an unexpected keyword.
if converted_params.pop("timeout", None) is not None:
logger.warning(
"Ollama does not support a per-request 'timeout'; ignoring it. "
"Set it on the client via client_args instead."
)

max_tokens = converted_params.pop("max_tokens", None)
max_completion_tokens = converted_params.pop("max_completion_tokens", None)
requested_max_tokens = max_completion_tokens if max_completion_tokens is not None else max_tokens
Expand Down
7 changes: 7 additions & 0 deletions src/any_llm/providers/sagemaker/sagemaker.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ class SagemakerProvider(AnyLLM):
@override
def _convert_completion_params(params: CompletionParams, **kwargs: Any) -> dict[str, Any]:
"""Convert CompletionParams to kwargs for SageMaker API."""
# SageMaker serializes these kwargs into the request body, so a per-request `timeout`
# cannot be honored here and would be sent as a payload field.
if kwargs.pop("timeout", None) is not None:
logger.warning(
"SageMaker does not support a per-request 'timeout'; ignoring it. "
"Set it on the client via client_args instead."
)
return _convert_params(params, kwargs)

@staticmethod
Expand Down
9 changes: 9 additions & 0 deletions src/any_llm/providers/watsonx/watsonx.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from typing_extensions import override

from any_llm.any_llm import AnyLLM
from any_llm.logging import logger
from any_llm.utils.structured_output import is_structured_output_type

MISSING_PACKAGES_ERROR: ImportError | None = None
Expand Down Expand Up @@ -77,6 +78,14 @@ def _convert_completion_params(params: CompletionParams, **kwargs: Any) -> dict[
if converted_params.get("reasoning_effort") in ("auto", "none"):
converted_params.pop("reasoning_effort")
converted_params.update(kwargs)

# watsonx merges this dict straight into its chat payload as generation parameters, so a
# per-request `timeout` cannot be honored here and would be sent as an invalid model field.
if converted_params.pop("timeout", None) is not None:
logger.warning(
"watsonx does not support a per-request 'timeout'; ignoring it. "
"Set it on the client via client_args instead."
)
return converted_params

@staticmethod
Expand Down
10 changes: 10 additions & 0 deletions src/any_llm/providers/xai/xai.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from typing_extensions import override

from any_llm.any_llm import AnyLLM
from any_llm.logging import logger
from any_llm.utils.structured_output import get_json_schema

MISSING_PACKAGES_ERROR = None
Expand Down Expand Up @@ -77,6 +78,15 @@ def _convert_completion_params(params: CompletionParams, **kwargs: Any) -> dict[
if converted_params.get("reasoning_effort") in ("auto", "none"):
converted_params.pop("reasoning_effort")
converted_params.update(kwargs)

# The xAI SDK sets timeouts on the gRPC client, not per request, so a per-request
# `timeout` cannot be honored here and would reach the SDK as an unexpected keyword.
if converted_params.pop("timeout", None) is not None:
logger.warning(
"xAI does not support a per-request 'timeout'; ignoring it. "
"Pass client_args={'timeout': seconds} to set it on the client instead."
)

return converted_params

@staticmethod
Expand Down
31 changes: 29 additions & 2 deletions tests/unit/providers/test_anthropic_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@
from collections.abc import AsyncIterator
from dataclasses import dataclass
from typing import Any, Self, cast
from unittest.mock import AsyncMock, MagicMock, Mock
from unittest.mock import AsyncMock, MagicMock, Mock, patch

import httpx
import pytest
from anthropic.types import Message, TextBlock, ThinkingBlock, ToolUseBlock, Usage
from anthropic.types.beta import BetaMCPToolUseBlock, BetaMessage, BetaThinkingBlock, BetaUsage
from pydantic import BaseModel

from any_llm.exceptions import UnsupportedParameterError
from any_llm.exceptions import InvalidRequestError, UnsupportedParameterError
from any_llm.providers.anthropic.anthropic import AnthropicProvider
from any_llm.providers.anthropic.base import BaseAnthropicProvider, _messages_betas, _pop_anthropic_beta_header
from any_llm.types.messages import (
Expand Down Expand Up @@ -1339,3 +1339,30 @@ async def test_amessages_system_list_form() -> None:

call_kwargs = mock_client.messages.create.call_args.kwargs
assert call_kwargs["system"] == system_blocks


@pytest.mark.asyncio
async def test_amessages_without_timeout_translates_nonstreaming_guard() -> None:
"""The messages API surfaces the same actionable error as completions for the pre-flight guard.

Uses a real ``AsyncAnthropic`` client so the SDK guard runs; the transport is patched to fail
fast so the test stays hermetic if the guard ever changes.
"""
provider = AnthropicProvider(api_key="sk-test")

with (
patch.object(
provider.client, "post", new=AsyncMock(side_effect=AssertionError("network should not be reached"))
),
pytest.raises(InvalidRequestError) as exc_info,
):
await provider.amessages(
model="claude-opus-5",
messages=[{"role": "user", "content": "Hi"}],
max_tokens=65536,
stream=False,
)

message = str(exc_info.value)
assert "timeout" in message
assert "stream=True" in message
Loading