-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathany_llm.py
More file actions
1485 lines (1267 loc) · 59 KB
/
Copy pathany_llm.py
File metadata and controls
1485 lines (1267 loc) · 59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Inspired by https://github.com/andrewyng/aisuite/tree/main/aisuite
from __future__ import annotations
import importlib
import os
import warnings
from abc import ABC, abstractmethod
from typing import IO, TYPE_CHECKING, Any, ClassVar, Literal, TypeVar, cast, overload
from openresponses_types import ResponseResource
from pydantic import BaseModel
from any_llm.constants import INSIDE_NOTEBOOK, LLMProvider
from any_llm.exceptions import (
ContentFilterFinishReasonError,
LengthFinishReasonError,
MissingApiKeyError,
UnsupportedProviderError,
)
from any_llm.tools import prepare_tools
from any_llm.types.audio import AudioSpeechParams, AudioTranscriptionParams, Transcription
from any_llm.types.completion import (
ChatCompletion,
ChatCompletionMessage,
CompletionParams,
ParsedChatCompletion,
ReasoningEffort,
)
from any_llm.types.image import ImageGenerationParams, ImagesResponse
from any_llm.types.messages import (
ContentBlockStopEvent,
MessageDelta,
MessageDeltaEvent,
MessageDeltaUsage,
MessageResponse,
MessagesParams,
MessageStopEvent,
MessageStreamEvent,
ParsedMessage,
StopReason,
)
from any_llm.types.provider import ProviderMetadata
from any_llm.types.responses import (
ParsedResponse,
Response,
ResponseInputParam,
ResponsesParams,
ResponseStreamEvent,
)
from any_llm.utils.aio import async_coro_to_sync_iter, async_iter_to_sync_iter, run_async_in_sync
from any_llm.utils.exception_handler import handle_exceptions
from any_llm.utils.structured_output import (
build_parsed_message,
is_structured_output_type,
parse_json_content,
parse_responses_output,
)
ResponseFormatT = TypeVar("ResponseFormatT", bound=BaseModel)
if TYPE_CHECKING:
from collections.abc import AsyncIterator, Callable, Coroutine, Iterator, Sequence
from any_llm.types.batch import Batch, BatchResult
from any_llm.types.completion import ChatCompletionChunk, CreateEmbeddingResponse
from any_llm.types.model import Model
from any_llm.types.moderation import ModerationResponse
from any_llm.types.rerank import RerankResponse
class AnyLLM(ABC):
"""Provider for the LLM."""
# === Provider-specific configuration (to be overridden by subclasses) ===
PROVIDER_NAME: str
"""Must match the name of the provider directory (case sensitive)"""
PROVIDER_DOCUMENTATION_URL: str
"""Link to the provider's documentation"""
ENV_API_KEY_NAME: str
"""Environment variable name for the API key"""
ENV_API_BASE_NAME: str | None = None
"""Environment variable name for the API base URL. Optional."""
# === Feature support flags (to be set by subclasses) ===
SUPPORTS_COMPLETION_STREAMING: bool
"""OpenAI Streaming Completion API"""
SUPPORTS_COMPLETION: bool
"""OpenAI Completion API"""
SUPPORTS_COMPLETION_REASONING: bool
"""Reasoning Content attached to Completion API Response"""
SUPPORTS_COMPLETION_IMAGE: bool
"""Image Support for Completion API"""
SUPPORTS_COMPLETION_PDF: bool
"""PDF Support for Completion API"""
SUPPORTS_EMBEDDING: bool
"""OpenAI Embedding API"""
SUPPORTS_MODERATION: bool = False
"""OpenAI-compatible moderation API."""
SUPPORTS_RESPONSES: bool
"""OpenAI Responses API"""
SUPPORTS_LIST_MODELS: bool
"""OpenAI Models API"""
SUPPORTS_BATCH: bool
"""OpenAI Batch Completion API"""
SUPPORTS_IMAGE_GENERATION: bool = False
"""Image Generation API (e.g., OpenAI DALL-E)"""
SUPPORTS_AUDIO_TRANSCRIPTION: bool = False
"""Audio Transcription API (e.g., OpenAI Whisper)"""
SUPPORTS_AUDIO_SPEECH: bool = False
"""Audio Speech / TTS API (e.g., OpenAI TTS)"""
SUPPORTS_RERANK: bool = False
"""Rerank API - reorder documents by relevance to a query."""
SUPPORTS_MESSAGES: bool = True
"""Anthropic Messages API (all providers support it via conversion)"""
API_BASE: str | None = None
"""This is used to set the API base for the provider.
It is not required but may prove useful for providers that have overridable api bases.
"""
# === Internal Flag Checks ===
MISSING_PACKAGES_ERROR: ImportError | None = None
"""Some providers use SDKs that are not installed by default.
This flag is used to check if the packages are installed before instantiating the provider.
"""
BUILT_IN_TOOLS: ClassVar[list[Any] | None] = None
"""Some providers have built-in tools that can be used as-is without conversion.
This should be a list of the allowed built-in tool instances.
For example, in `gemini` provider, this could include `google.genai.types.Tool`.
"""
def __init__(self, api_key: str | None = None, api_base: str | None = None, **kwargs: Any) -> None:
self._verify_no_missing_packages()
self._init_client(
api_key=self._verify_and_set_api_key(api_key),
api_base=self._resolve_api_base(api_base),
**kwargs,
)
def _verify_no_missing_packages(self) -> None:
if self.MISSING_PACKAGES_ERROR is not None:
msg = f"{self.PROVIDER_NAME} required packages are not installed. Please install them with `pip install any-llm-sdk[{self.PROVIDER_NAME}]`. Specific error message: {self.MISSING_PACKAGES_ERROR}"
raise ImportError(msg) from self.MISSING_PACKAGES_ERROR
def _verify_and_set_api_key(self, api_key: str | None = None) -> str | None:
# Standardized API key handling. Splitting into its own function so that providers
# can easily override this method if they don't want verification (for instance, LMStudio)
if not api_key:
api_key = os.getenv(self.ENV_API_KEY_NAME)
if not api_key:
raise MissingApiKeyError(self.PROVIDER_NAME, self.ENV_API_KEY_NAME)
return api_key
def _resolve_api_base(self, api_base: str | None = None) -> str | None:
"""Resolve API base URL from parameter or environment variable.
Resolution order:
1. Explicit api_base parameter (if provided)
2. Environment variable (if ENV_API_BASE_NAME is defined and set)
3. None (allowing _init_client to use API_BASE class default)
"""
if api_base:
return api_base
if self.ENV_API_BASE_NAME:
return os.getenv(self.ENV_API_BASE_NAME)
return None
@classmethod
def create(
cls, provider: str | LLMProvider, api_key: str | None = None, api_base: str | None = None, **kwargs: Any
) -> AnyLLM:
"""Create a provider instance using the given provider name and config.
Args:
provider: The provider name (e.g., 'openai', 'anthropic')
api_key: API key for the provider
api_base: Base URL for the provider API
**kwargs: Additional provider-specific arguments
Returns:
Provider instance for the specified provider
"""
return cls._create_provider(provider, api_key=api_key, api_base=api_base, **kwargs)
@classmethod
def _create_provider(
cls, provider_key: str | LLMProvider, api_key: str | None = None, api_base: str | None = None, **kwargs: Any
) -> AnyLLM:
"""Dynamically load and create an instance of a provider based on the naming convention."""
provider_key = LLMProvider.from_string(provider_key).value
provider_class_name = f"{provider_key.capitalize()}Provider"
provider_module_name = f"{provider_key}"
module_path = f"any_llm.providers.{provider_module_name}"
try:
module = importlib.import_module(module_path)
except ImportError as e:
msg = f"Could not import module {module_path}: {e!s}. Please ensure the provider is supported by doing AnyLLM.get_supported_providers()"
raise ImportError(msg) from e
provider_class: type[AnyLLM] = getattr(module, provider_class_name)
return provider_class(api_key=api_key, api_base=api_base, **kwargs)
@classmethod
def get_provider_class(cls, provider_key: str | LLMProvider) -> type[AnyLLM]:
"""Get the provider class without instantiating it.
Args:
provider_key: The provider key (e.g., 'anthropic', 'openai')
Returns:
The provider class
"""
provider_key = LLMProvider.from_string(provider_key).value
provider_class_name = f"{provider_key.capitalize()}Provider"
provider_module_name = f"{provider_key}"
module_path = f"any_llm.providers.{provider_module_name}"
try:
module = importlib.import_module(module_path)
except ImportError as e:
msg = f"Could not import module {module_path}: {e!s}. Please ensure the provider is supported by doing AnyLLM.get_supported_providers()"
raise ImportError(msg) from e
provider_class: type[AnyLLM] = getattr(module, provider_class_name)
return provider_class
@classmethod
def get_supported_providers(cls) -> list[str]:
"""Get a list of supported provider keys."""
return [provider.value for provider in LLMProvider]
@classmethod
def get_all_provider_metadata(cls) -> list[ProviderMetadata]:
"""Get metadata for all supported providers.
Returns:
List of dictionaries containing provider metadata
"""
providers: list[ProviderMetadata] = []
for provider_key in cls.get_supported_providers():
provider_class = cls.get_provider_class(provider_key)
metadata = provider_class.get_provider_metadata()
providers.append(metadata)
# Sort providers by name
providers.sort(key=lambda x: x.name)
return providers
@classmethod
def get_provider_enum(cls, provider_key: str) -> LLMProvider:
"""Convert a string provider key to a ProviderName enum."""
try:
return LLMProvider(provider_key)
except ValueError as e:
supported = [provider.value for provider in LLMProvider]
raise UnsupportedProviderError(provider_key, supported) from e
@classmethod
def split_model_provider(cls, model: str) -> tuple[LLMProvider, str]:
"""Extract the provider key from the model identifier.
Supports both new format 'provider:model' (e.g., 'mistral:mistral-small')
and legacy format 'provider/model' (e.g., 'mistral/mistral-small').
The legacy format will be deprecated in version 1.0.
"""
colon_index = model.find(":")
slash_index = model.find("/")
# Determine which delimiter comes first
if colon_index != -1 and (slash_index == -1 or colon_index < slash_index):
# The colon came first, so it's using the new syntax.
provider, model_name = model.split(":", 1)
elif slash_index != -1:
# Slash comes first, so it's the legacy syntax
warnings.warn(
f"Model format 'provider/model' is deprecated and will be removed in version 1.0. "
f"Please use 'provider:model' format instead. Got: '{model}'",
DeprecationWarning,
stacklevel=3,
)
provider, model_name = model.split("/", 1)
else:
msg = f"Invalid model format. Expected 'provider:model' or 'provider/model', got '{model}'"
raise ValueError(msg)
if not provider or not model_name:
msg = f"Invalid model format. Expected 'provider:model' or 'provider/model', got '{model}'"
raise ValueError(msg)
return cls.get_provider_enum(provider), model_name
@staticmethod
@abstractmethod
def _convert_completion_params(params: CompletionParams, **kwargs: Any) -> dict[str, Any]:
msg = "Subclasses must implement this method"
raise NotImplementedError(msg)
@staticmethod
@abstractmethod
def _convert_completion_response(response: Any) -> ChatCompletion:
msg = "Subclasses must implement this method"
raise NotImplementedError(msg)
@staticmethod
@abstractmethod
def _convert_completion_chunk_response(response: Any, **kwargs: Any) -> ChatCompletionChunk:
msg = "Subclasses must implement this method"
raise NotImplementedError(msg)
@staticmethod
@abstractmethod
def _convert_embedding_params(params: Any, **kwargs: Any) -> dict[str, Any]:
msg = "Subclasses must implement this method"
raise NotImplementedError(msg)
@staticmethod
@abstractmethod
def _convert_embedding_response(response: Any) -> CreateEmbeddingResponse:
msg = "Subclasses must implement this method"
raise NotImplementedError(msg)
@staticmethod
@abstractmethod
def _convert_list_models_response(response: Any) -> Sequence[Model]:
msg = "Subclasses must implement this method"
raise NotImplementedError(msg)
@staticmethod
def _convert_rerank_params(model: str, query: str, documents: list[str], **kwargs: Any) -> dict[str, Any]:
msg = "Subclasses must implement this method"
raise NotImplementedError(msg)
@staticmethod
def _convert_rerank_response(response: Any) -> RerankResponse:
msg = "Subclasses must implement this method"
raise NotImplementedError(msg)
@classmethod
def get_provider_metadata(cls) -> ProviderMetadata:
"""Get provider metadata without requiring instantiation.
Returns:
Dictionary containing provider metadata including name, environment variable,
documentation URL, and class name.
"""
return ProviderMetadata(
name=cls.PROVIDER_NAME,
env_key=cls.ENV_API_KEY_NAME,
env_api_base=cls.ENV_API_BASE_NAME,
doc_url=cls.PROVIDER_DOCUMENTATION_URL,
streaming=cls.SUPPORTS_COMPLETION_STREAMING,
reasoning=cls.SUPPORTS_COMPLETION_REASONING,
completion=cls.SUPPORTS_COMPLETION,
image=cls.SUPPORTS_COMPLETION_IMAGE,
pdf=cls.SUPPORTS_COMPLETION_PDF,
embedding=cls.SUPPORTS_EMBEDDING,
moderation=cls.SUPPORTS_MODERATION,
responses=cls.SUPPORTS_RESPONSES,
list_models=cls.SUPPORTS_LIST_MODELS,
batch_completion=cls.SUPPORTS_BATCH,
image_generation=cls.SUPPORTS_IMAGE_GENERATION,
audio_transcription=cls.SUPPORTS_AUDIO_TRANSCRIPTION,
audio_speech=cls.SUPPORTS_AUDIO_SPEECH,
rerank=cls.SUPPORTS_RERANK,
messages=cls.SUPPORTS_MESSAGES,
class_name=cls.__name__,
)
@abstractmethod
def _init_client(self, api_key: str | None = None, api_base: str | None = None, **kwargs: Any) -> None:
msg = "Subclasses must implement this method"
raise NotImplementedError(msg)
# Overloads let type checkers narrow the return type based on response_format and stream.
# The implementation only declares these discriminating params; everything else
# passes through via **kwargs to acompletion().
@overload
def completion(
self,
model: str,
messages: list[dict[str, Any] | ChatCompletionMessage],
*,
response_format: type[ResponseFormatT],
stream: Literal[False] | None = ...,
**kwargs: Any,
) -> ParsedChatCompletion[ResponseFormatT]: ...
@overload
def completion(
self,
model: str,
messages: list[dict[str, Any] | ChatCompletionMessage],
*,
stream: Literal[True],
**kwargs: Any,
) -> Iterator[ChatCompletionChunk]: ...
@overload
def completion(
self,
model: str,
messages: list[dict[str, Any] | ChatCompletionMessage],
*,
response_format: dict[str, Any] | None = ...,
stream: Literal[False] | None = ...,
**kwargs: Any,
) -> ChatCompletion: ...
@overload
def completion(
self,
model: str,
messages: list[dict[str, Any] | ChatCompletionMessage],
*,
response_format: dict[str, Any] | type | None = ...,
stream: bool | None = ...,
**kwargs: Any,
) -> ChatCompletion | Iterator[ChatCompletionChunk] | ParsedChatCompletion[Any]: ...
def completion(
self,
model: str,
messages: list[dict[str, Any] | ChatCompletionMessage],
*,
response_format: dict[str, Any] | type | None = None,
stream: bool | None = None,
allow_running_loop: bool | None = None,
**kwargs: Any,
) -> ChatCompletion | Iterator[ChatCompletionChunk] | ParsedChatCompletion[Any]:
"""Create a chat completion synchronously.
See [AnyLLM.acompletion][any_llm.any_llm.AnyLLM.acompletion]
"""
if allow_running_loop is None:
allow_running_loop = INSIDE_NOTEBOOK
if stream:
return async_coro_to_sync_iter(
self.acompletion(
model=model,
messages=messages,
response_format=response_format,
stream=stream,
**kwargs,
),
allow_running_loop=allow_running_loop,
)
response = run_async_in_sync(
self.acompletion(model=model, messages=messages, response_format=response_format, stream=stream, **kwargs),
allow_running_loop=allow_running_loop,
)
if isinstance(response, ChatCompletion):
return response
return async_iter_to_sync_iter(response, allow_running_loop=allow_running_loop)
# Overloads let type checkers narrow the return type based on response_format and stream.
@overload
async def acompletion(
self,
model: str,
messages: list[dict[str, Any] | ChatCompletionMessage],
*,
response_format: type[ResponseFormatT],
stream: Literal[False] | None = ...,
**kwargs: Any,
) -> ParsedChatCompletion[ResponseFormatT]: ...
@overload
async def acompletion(
self,
model: str,
messages: list[dict[str, Any] | ChatCompletionMessage],
*,
stream: Literal[True],
**kwargs: Any,
) -> AsyncIterator[ChatCompletionChunk]: ...
@overload
async def acompletion(
self,
model: str,
messages: list[dict[str, Any] | ChatCompletionMessage],
*,
response_format: dict[str, Any] | None = ...,
stream: Literal[False] | None = ...,
**kwargs: Any,
) -> ChatCompletion: ...
@overload
async def acompletion(
self,
model: str,
messages: list[dict[str, Any] | ChatCompletionMessage],
*,
response_format: dict[str, Any] | type | None = ...,
stream: bool | None = ...,
**kwargs: Any,
) -> ChatCompletion | AsyncIterator[ChatCompletionChunk] | ParsedChatCompletion[Any]: ...
@handle_exceptions(wrap_streaming=True)
async def acompletion(
self,
model: str,
messages: list[dict[str, Any] | ChatCompletionMessage],
*,
tools: list[dict[str, Any] | Callable[..., Any]] | Any | None = None,
tool_choice: str | dict[str, Any] | None = None,
temperature: float | None = None,
top_p: float | None = None,
max_tokens: int | None = None,
response_format: dict[str, Any] | type | None = None,
stream: bool | None = None,
n: int | None = None,
stop: str | list[str] | None = None,
presence_penalty: float | None = None,
frequency_penalty: float | None = None,
seed: int | None = None,
user: str | None = None,
session_label: str | None = None,
parallel_tool_calls: bool | None = None,
logprobs: bool | None = None,
top_logprobs: int | None = None,
logit_bias: dict[str, float] | None = None,
stream_options: dict[str, Any] | None = None,
max_completion_tokens: int | None = None,
reasoning_effort: ReasoningEffort | None = "auto",
**kwargs: Any,
) -> ChatCompletion | AsyncIterator[ChatCompletionChunk] | ParsedChatCompletion[Any]:
"""Create a chat completion asynchronously.
Args:
model: Model identifier for the chosen provider (e.g., model='gpt-4.1-mini' for LLMProvider.OPENAI).
messages: List of messages for the conversation
tools: List of tools for tool calling. Can be Python callables or OpenAI tool format dicts
tool_choice: Controls which tools the model can call
temperature: Controls randomness in the response (0.0 to 2.0)
top_p: Controls diversity via nucleus sampling (0.0 to 1.0)
max_tokens: Maximum number of tokens to generate
response_format: Format specification for the response
stream: Whether to stream the response
n: Number of completions to generate
stop: Stop sequences for generation
presence_penalty: Penalize new tokens based on presence in text
frequency_penalty: Penalize new tokens based on frequency in text
seed: Random seed for reproducible results
user: Unique identifier for the end user
session_label: Deprecated, no longer used. Previously used for platform traces.
parallel_tool_calls: Whether to allow parallel tool calls
logprobs: Include token-level log probabilities in the response
top_logprobs: Number of alternatives to return when logprobs are requested
logit_bias: Bias the likelihood of specified tokens during generation
stream_options: Additional options controlling streaming behavior
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.
**kwargs: Additional provider-specific arguments that will be passed to the provider's API call.
Returns:
The completion response from the provider
"""
prepared_tools = None
if tools:
prepared_tools = prepare_tools(tools, built_in_tools=self.BUILT_IN_TOOLS)
processed_messages: list[dict[str, Any]] = []
for message in messages:
if isinstance(message, ChatCompletionMessage):
# Dump the message but exclude the extra field that we extend from OpenAI Spec
processed_messages.append(message.model_dump(exclude_none=True, exclude={"reasoning"}))
else:
processed_messages.append(message)
params = CompletionParams(
model_id=model,
messages=processed_messages,
tools=prepared_tools,
tool_choice=tool_choice,
temperature=temperature,
top_p=top_p,
max_tokens=max_tokens,
response_format=response_format,
stream=stream,
n=n,
stop=stop,
presence_penalty=presence_penalty,
frequency_penalty=frequency_penalty,
seed=seed,
user=user,
parallel_tool_calls=parallel_tool_calls,
logprobs=logprobs,
top_logprobs=top_logprobs,
logit_bias=logit_bias,
stream_options=stream_options,
max_completion_tokens=max_completion_tokens,
reasoning_effort=reasoning_effort,
)
result = await self._acompletion(params, **kwargs)
if is_structured_output_type(response_format):
if isinstance(result, ParsedChatCompletion):
parsed_completion = result
elif isinstance(result, ChatCompletion):
parsed_completion = ParsedChatCompletion.model_validate(result, from_attributes=True)
else:
return result
for choice in parsed_completion.choices:
if choice.message.parsed is not None:
continue
if choice.finish_reason == "length":
raise LengthFinishReasonError(completion=parsed_completion)
if choice.finish_reason == "content_filter":
raise ContentFilterFinishReasonError(completion=parsed_completion)
if choice.message.content and not choice.message.refusal:
choice.message.parsed = parse_json_content(response_format, choice.message.content)
return parsed_completion
return result
async def _acompletion(
self, params: CompletionParams, **kwargs: Any
) -> ChatCompletion | AsyncIterator[ChatCompletionChunk]:
if not self.SUPPORTS_COMPLETION:
msg = "Provider doesn't support completion."
raise NotImplementedError(msg)
msg = "Subclasses must implement _acompletion method"
raise NotImplementedError(msg)
def messages(
self,
*,
allow_running_loop: bool | None = None,
**kwargs: Any,
) -> MessageResponse | ParsedMessage[Any] | Iterator[MessageStreamEvent]:
"""Create a message using the Anthropic Messages API synchronously.
See [AnyLLM.amessages][any_llm.any_llm.AnyLLM.amessages]
"""
if allow_running_loop is None:
allow_running_loop = INSIDE_NOTEBOOK
response = run_async_in_sync(self.amessages(**kwargs), allow_running_loop=allow_running_loop)
if isinstance(response, (MessageResponse, ParsedMessage)):
return response
return async_iter_to_sync_iter(response)
@handle_exceptions(wrap_streaming=True)
async def amessages(
self,
model: str,
messages: list[dict[str, Any]],
max_tokens: int,
*,
system: str | list[dict[str, Any]] | None = None,
temperature: float | None = None,
top_p: float | None = None,
top_k: int | None = None,
stream: bool | None = None,
stop_sequences: list[str] | None = None,
tools: list[dict[str, Any]] | None = None,
tool_choice: dict[str, Any] | None = None,
metadata: dict[str, Any] | None = None,
thinking: dict[str, Any] | None = None,
cache_control: dict[str, Any] | None = None,
output_format: type | dict[str, Any] | None = None,
**kwargs: Any,
) -> MessageResponse | ParsedMessage[Any] | AsyncIterator[MessageStreamEvent]:
"""Create a message using the Anthropic Messages API asynchronously.
All providers support this via automatic conversion to/from Chat Completions.
The Anthropic provider uses a native pass-through for efficiency.
Args:
model: Model identifier for the chosen provider.
messages: List of messages in Anthropic format.
max_tokens: Maximum number of tokens to generate.
system: System prompt (string or list of content blocks with optional cache_control).
temperature: Controls randomness (0.0 to 1.0).
top_p: Controls diversity via nucleus sampling.
top_k: Only sample from the top K options.
stream: Whether to stream the response.
stop_sequences: Custom stop sequences.
tools: List of tools in Anthropic format.
tool_choice: Controls which tool the model uses.
metadata: Request metadata.
thinking: Thinking/reasoning configuration.
cache_control: Cache control configuration for prompt caching.
output_format: Structured output, mirroring Anthropic's ``messages.parse``/
``output_config``. Either a Pydantic ``BaseModel``/dataclass **type** (typed
``parsed_output``) or a raw Anthropic ``output_config`` **dict** for non-Pydantic
JSON schemas (``parsed_output`` holds the parsed JSON). The call returns
Anthropic's ``ParsedMessage``. Not supported with ``stream=True``.
**kwargs: Additional provider-specific arguments.
Returns:
MessageResponse (or ParsedMessage when `output_format` is given), or an async
iterator of MessageStreamEvent (if streaming).
Raises:
ValueError: If `output_format` is combined with `stream=True`.
"""
if output_format is not None and stream:
msg = "stream is not supported for output_format"
raise ValueError(msg)
params = MessagesParams(
model=model,
messages=messages,
max_tokens=max_tokens,
system=system,
temperature=temperature,
top_p=top_p,
top_k=top_k,
stream=stream,
stop_sequences=stop_sequences,
tools=tools,
tool_choice=tool_choice,
metadata=metadata,
thinking=thinking,
cache_control=cache_control,
output_format=output_format,
)
result = await self._amessages(params, **kwargs)
# The Anthropic provider already returns a ParsedMessage via native messages.parse (typed
# case); for the raw-dict case and for all bridged providers it returns a MessageResponse,
# so build the same ParsedMessage shape from the response's JSON text here.
if output_format is not None and isinstance(result, MessageResponse):
return build_parsed_message(result, output_format)
return result
async def _amessages(
self, params: MessagesParams, **kwargs: Any
) -> MessageResponse | ParsedMessage[Any] | AsyncIterator[MessageStreamEvent]:
"""Default implementation: converts Messages ↔ Completions format.
Providers with native Messages API support (e.g., Anthropic) override this
for direct pass-through.
"""
from any_llm.types.completion import CompletionParams
from any_llm.utils.messages_compat import (
StreamingState,
chat_completion_chunk_to_message_stream_events,
chat_completion_to_message_response,
messages_params_to_completion_params,
)
completion_kwargs = messages_params_to_completion_params(params)
completion_params = CompletionParams(**completion_kwargs)
result = await self._acompletion(completion_params, **kwargs)
if isinstance(result, ChatCompletion):
return chat_completion_to_message_response(result)
async def convert_stream() -> AsyncIterator[MessageStreamEvent]:
state = StreamingState()
def usage_delta(stop_reason: StopReason | None) -> MessageDeltaEvent:
return MessageDeltaEvent(
type="message_delta",
delta=MessageDelta(stop_reason=stop_reason),
usage=MessageDeltaUsage(
output_tokens=state.output_tokens,
input_tokens=state.input_tokens,
cache_read_input_tokens=state.cache_read_input_tokens or None,
),
)
try:
async for chunk in result:
for event in chat_completion_chunk_to_message_stream_events(chunk, state):
yield event
except Exception:
# Flush the usage accumulated so far before re-raising, so a mid-stream failure still reports tokens.
if state.started:
yield usage_delta(state.stop_reason)
raise
# Emit the closing events after the full stream is consumed so trailing-chunk usage is included.
if state.started:
if state.current_block_type is not None:
yield ContentBlockStopEvent(
type="content_block_stop",
index=state.current_block_index,
)
yield usage_delta(state.stop_reason or "end_turn")
yield MessageStopEvent(type="message_stop")
return convert_stream()
# Overloads let type checkers narrow the return type based on response_format and stream.
@overload
def responses(
self,
model: str,
input_data: str | ResponseInputParam,
*,
response_format: type[ResponseFormatT],
stream: Literal[False] | None = ...,
**kwargs: Any,
) -> ParsedResponse[ResponseFormatT]: ...
@overload
def responses(
self,
model: str,
input_data: str | ResponseInputParam,
*,
stream: Literal[True],
**kwargs: Any,
) -> Iterator[ResponseStreamEvent]: ...
@overload
def responses(
self,
model: str,
input_data: str | ResponseInputParam,
*,
response_format: dict[str, Any] | None = ...,
stream: Literal[False] | None = ...,
**kwargs: Any,
) -> ResponseResource | Response: ...
@overload
def responses(
self,
model: str,
input_data: str | ResponseInputParam,
*,
response_format: dict[str, Any] | type | None = ...,
stream: bool | None = ...,
**kwargs: Any,
) -> ResponseResource | Response | Iterator[ResponseStreamEvent] | ParsedResponse[Any]: ...
def responses(
self, model: str, input_data: str | ResponseInputParam, **kwargs: Any
) -> ResponseResource | Response | Iterator[ResponseStreamEvent] | ParsedResponse[Any]:
"""Create a response synchronously.
See [AnyLLM.aresponses][any_llm.any_llm.AnyLLM.aresponses]
"""
allow_running_loop = kwargs.pop("allow_running_loop", INSIDE_NOTEBOOK)
if kwargs.get("stream"):
return async_coro_to_sync_iter(
cast(
"Coroutine[Any, Any, AsyncIterator[ResponseStreamEvent]]",
self.aresponses(model, input_data, **kwargs),
),
allow_running_loop=allow_running_loop,
)
response = run_async_in_sync(
self.aresponses(model, input_data, **kwargs), allow_running_loop=allow_running_loop
)
# ParsedResponse (structured output) is a subclass of Response, so it is covered here.
if isinstance(response, (ResponseResource, Response)):
return response
return async_iter_to_sync_iter(response, allow_running_loop=allow_running_loop)
# Overloads let type checkers narrow the return type based on response_format and stream.
@overload
async def aresponses(
self,
model: str,
input_data: str | ResponseInputParam,
*,
response_format: type[ResponseFormatT],
stream: Literal[False] | None = ...,
**kwargs: Any,
) -> ParsedResponse[ResponseFormatT]: ...
@overload
async def aresponses(
self,
model: str,
input_data: str | ResponseInputParam,
*,
stream: Literal[True],
**kwargs: Any,
) -> AsyncIterator[ResponseStreamEvent]: ...
@overload
async def aresponses(
self,
model: str,
input_data: str | ResponseInputParam,
*,
response_format: dict[str, Any] | None = ...,
stream: Literal[False] | None = ...,
**kwargs: Any,
) -> ResponseResource | Response: ...
@overload
async def aresponses(
self,
model: str,
input_data: str | ResponseInputParam,
*,
response_format: dict[str, Any] | type | None = ...,
stream: bool | None = ...,
**kwargs: Any,
) -> ResponseResource | Response | AsyncIterator[ResponseStreamEvent] | ParsedResponse[Any]: ...
@handle_exceptions(wrap_streaming=True)
async def aresponses(
self,
model: str,
input_data: str | ResponseInputParam,
*,
tools: list[dict[str, Any] | Callable[..., Any]] | Any | None = None,
tool_choice: str | dict[str, Any] | None = None,
max_output_tokens: int | None = None,
temperature: float | None = None,
top_p: float | None = None,
stream: bool | None = None,
instructions: str | None = None,
max_tool_calls: int | None = None,
parallel_tool_calls: bool | None = None,
reasoning: Any | None = None,
text: Any | None = None,
response_format: dict[str, Any] | type | None = None,
presence_penalty: float | None = None,
frequency_penalty: float | None = None,
truncation: str | None = None,
store: bool | None = None,
service_tier: str | None = None,
user: str | None = None,
metadata: dict[str, str] | None = None,
previous_response_id: str | None = None,
include: list[str] | None = None,
background: bool | None = None,
safety_identifier: str | None = None,
prompt_cache_key: str | None = None,
prompt_cache_retention: str | None = None,
conversation: str | dict[str, Any] | None = None,
**kwargs: Any,
) -> ResponseResource | Response | AsyncIterator[ResponseStreamEvent] | ParsedResponse[Any]:
"""Create a response using the OpenResponses API.
This implements the OpenResponses specification and returns either
`openresponses_types.ResponseResource` (for OpenResponses-compliant providers)
or `openai.types.responses.Response` (for providers using OpenAI's native API).
If `stream=True`, an iterator of streaming event dicts is returned.
Args:
model: Model identifier for the chosen provider (e.g., model='gpt-4.1-mini' for LLMProvider.OPENAI).
input_data: The input payload accepted by provider's Responses API.
For OpenAI-compatible providers, this is typically a list mixing
text, images, and tool instructions, or a dict per OpenAI spec.
tools: Optional tools for tool calling (Python callables or OpenAI tool dicts)
tool_choice: Controls which tools the model can call
max_output_tokens: Maximum number of output tokens to generate
temperature: Controls randomness in the response (0.0 to 2.0)
top_p: Controls diversity via nucleus sampling (0.0 to 1.0)
stream: Whether to stream response events
instructions: A system (or developer) message inserted into the model's context.
max_tool_calls: The maximum number of total calls to built-in tools that can be processed in a response. This maximum number applies across all built-in tool calls, not per individual tool. Any further attempts to call a tool by the model will be ignored.
parallel_tool_calls: Whether to allow the model to run tool calls in parallel.
reasoning: Configuration options for reasoning models.
text: Configuration options for a text response from the model. Can be plain text or structured JSON data.
response_format: Structured-output type. When a Pydantic ``BaseModel`` or dataclass is passed, the
response is parsed and returned as a ``ParsedResponse`` whose ``output_parsed`` holds the typed
object (the Responses-API analogue of ``client.responses.parse``). A raw OpenAI ``text.format``
dict is also accepted and passed through unparsed.
presence_penalty: Penalizes new tokens based on whether they appear in the text so far.
frequency_penalty: Penalizes new tokens based on their frequency in the text so far.
truncation: Controls how the service truncates input when it exceeds the model context window.
store: Whether to store the response so it can be retrieved later.
service_tier: The service tier to use for this request.