byteplussdk-arkruntime 3.0.64__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- byteplussdk_arkruntime-3.0.64.dist-info/METADATA +36 -0
- byteplussdk_arkruntime-3.0.64.dist-info/RECORD +240 -0
- byteplussdk_arkruntime-3.0.64.dist-info/WHEEL +5 -0
- byteplussdk_arkruntime-3.0.64.dist-info/licenses/LICENSE.txt +203 -0
- byteplussdk_arkruntime-3.0.64.dist-info/top_level.txt +1 -0
- byteplussdkarkruntime/__init__.py +7 -0
- byteplussdkarkruntime/_base_client.py +1439 -0
- byteplussdkarkruntime/_client.py +570 -0
- byteplussdkarkruntime/_compat.py +245 -0
- byteplussdkarkruntime/_constants.py +43 -0
- byteplussdkarkruntime/_exceptions.py +202 -0
- byteplussdkarkruntime/_files.py +149 -0
- byteplussdkarkruntime/_legacy_response.py +451 -0
- byteplussdkarkruntime/_models.py +734 -0
- byteplussdkarkruntime/_qs.py +168 -0
- byteplussdkarkruntime/_request_options.py +117 -0
- byteplussdkarkruntime/_resource.py +47 -0
- byteplussdkarkruntime/_response.py +615 -0
- byteplussdkarkruntime/_streaming.py +470 -0
- byteplussdkarkruntime/_types.py +210 -0
- byteplussdkarkruntime/_utils/__init__.py +58 -0
- byteplussdkarkruntime/_utils/_key_agreement.py +207 -0
- byteplussdkarkruntime/_utils/_logs.py +24 -0
- byteplussdkarkruntime/_utils/_model_breaker.py +83 -0
- byteplussdkarkruntime/_utils/_streams.py +12 -0
- byteplussdkarkruntime/_utils/_transform.py +489 -0
- byteplussdkarkruntime/_utils/_typing.py +171 -0
- byteplussdkarkruntime/_utils/_utils.py +497 -0
- byteplussdkarkruntime/common/__init__.py +14 -0
- byteplussdkarkruntime/common/_parsing/__init__.py +22 -0
- byteplussdkarkruntime/common/_parsing/_completions.py +290 -0
- byteplussdkarkruntime/common/_parsing/_responses.py +189 -0
- byteplussdkarkruntime/common/_pydantic.py +192 -0
- byteplussdkarkruntime/common/_tools.py +67 -0
- byteplussdkarkruntime/common/streaming/__init__.py +12 -0
- byteplussdkarkruntime/common/streaming/_deltas.py +86 -0
- byteplussdkarkruntime/common/streaming/chat/__init__.py +33 -0
- byteplussdkarkruntime/common/streaming/chat/_completions.py +772 -0
- byteplussdkarkruntime/common/streaming/chat/_events.py +103 -0
- byteplussdkarkruntime/common/streaming/chat/_types.py +36 -0
- byteplussdkarkruntime/pagination.py +134 -0
- byteplussdkarkruntime/resources/__init__.py +48 -0
- byteplussdkarkruntime/resources/batch/__init__.py +3 -0
- byteplussdkarkruntime/resources/batch/_utils.py +155 -0
- byteplussdkarkruntime/resources/batch/batch.py +37 -0
- byteplussdkarkruntime/resources/batch/chat/__init__.py +3 -0
- byteplussdkarkruntime/resources/batch/chat/chat.py +19 -0
- byteplussdkarkruntime/resources/batch/chat/completions.py +329 -0
- byteplussdkarkruntime/resources/batch/embeddings.py +105 -0
- byteplussdkarkruntime/resources/batch/multimodal_embeddings.py +111 -0
- byteplussdkarkruntime/resources/batch_chat/__init__.py +3 -0
- byteplussdkarkruntime/resources/batch_chat/chat.py +21 -0
- byteplussdkarkruntime/resources/batch_chat/completions.py +328 -0
- byteplussdkarkruntime/resources/beta/__init__.py +12 -0
- byteplussdkarkruntime/resources/beta/beta.py +81 -0
- byteplussdkarkruntime/resources/beta/chat/__init__.py +21 -0
- byteplussdkarkruntime/resources/beta/chat/chat.py +31 -0
- byteplussdkarkruntime/resources/beta/chat/completions.py +454 -0
- byteplussdkarkruntime/resources/chat/__init__.py +3 -0
- byteplussdkarkruntime/resources/chat/chat.py +21 -0
- byteplussdkarkruntime/resources/chat/completions.py +258 -0
- byteplussdkarkruntime/resources/content_generation/__init__.py +6 -0
- byteplussdkarkruntime/resources/content_generation/content_generation.py +17 -0
- byteplussdkarkruntime/resources/content_generation/tasks.py +348 -0
- byteplussdkarkruntime/resources/context/__init__.py +3 -0
- byteplussdkarkruntime/resources/context/completions.py +221 -0
- byteplussdkarkruntime/resources/context/context.py +98 -0
- byteplussdkarkruntime/resources/embeddings.py +110 -0
- byteplussdkarkruntime/resources/encryption.py +215 -0
- byteplussdkarkruntime/resources/files.py +592 -0
- byteplussdkarkruntime/resources/images/__init__.py +6 -0
- byteplussdkarkruntime/resources/images/images.py +335 -0
- byteplussdkarkruntime/resources/multimodal_embeddings.py +113 -0
- byteplussdkarkruntime/resources/responses/__init__.py +16 -0
- byteplussdkarkruntime/resources/responses/input_items.py +248 -0
- byteplussdkarkruntime/resources/responses/responses.py +417 -0
- byteplussdkarkruntime/types/__init__.py +28 -0
- byteplussdkarkruntime/types/chat/__init__.py +78 -0
- byteplussdkarkruntime/types/chat/chat_completion.py +93 -0
- byteplussdkarkruntime/types/chat/chat_completion_assistant_message_param.py +61 -0
- byteplussdkarkruntime/types/chat/chat_completion_audio.py +22 -0
- byteplussdkarkruntime/types/chat/chat_completion_chunk.py +165 -0
- byteplussdkarkruntime/types/chat/chat_completion_content_part_image_param.py +20 -0
- byteplussdkarkruntime/types/chat/chat_completion_content_part_param.py +30 -0
- byteplussdkarkruntime/types/chat/chat_completion_content_part_text_param.py +13 -0
- byteplussdkarkruntime/types/chat/chat_completion_content_part_video_param.py +32 -0
- byteplussdkarkruntime/types/chat/chat_completion_function_call_option_param.py +10 -0
- byteplussdkarkruntime/types/chat/chat_completion_function_message_param.py +17 -0
- byteplussdkarkruntime/types/chat/chat_completion_message.py +56 -0
- byteplussdkarkruntime/types/chat/chat_completion_message_param.py +19 -0
- byteplussdkarkruntime/types/chat/chat_completion_message_tool_call.py +29 -0
- byteplussdkarkruntime/types/chat/chat_completion_message_tool_call_param.py +29 -0
- byteplussdkarkruntime/types/chat/chat_completion_named_tool_choice_param.py +17 -0
- byteplussdkarkruntime/types/chat/chat_completion_role.py +5 -0
- byteplussdkarkruntime/types/chat/chat_completion_stream_options_param.py +19 -0
- byteplussdkarkruntime/types/chat/chat_completion_system_message_param.py +34 -0
- byteplussdkarkruntime/types/chat/chat_completion_token_logprob.py +55 -0
- byteplussdkarkruntime/types/chat/chat_completion_tool_choice_option_param.py +12 -0
- byteplussdkarkruntime/types/chat/chat_completion_tool_message_param.py +37 -0
- byteplussdkarkruntime/types/chat/chat_completion_tool_param.py +14 -0
- byteplussdkarkruntime/types/chat/chat_completion_user_message_param.py +34 -0
- byteplussdkarkruntime/types/chat/completion_create_params.py +258 -0
- byteplussdkarkruntime/types/chat/parsed_chat_completion.py +52 -0
- byteplussdkarkruntime/types/chat/parsed_function_tool_call.py +34 -0
- byteplussdkarkruntime/types/completion_usage.py +33 -0
- byteplussdkarkruntime/types/content_generation/__init__.py +0 -0
- byteplussdkarkruntime/types/content_generation/content_generation_task.py +106 -0
- byteplussdkarkruntime/types/content_generation/content_generation_task_id.py +11 -0
- byteplussdkarkruntime/types/content_generation/create_task_content_param.py +72 -0
- byteplussdkarkruntime/types/content_generation/list_content_generation_tasks_response.py +24 -0
- byteplussdkarkruntime/types/context/__init__.py +8 -0
- byteplussdkarkruntime/types/context/context_chat_completion.py +33 -0
- byteplussdkarkruntime/types/context/context_chat_completion_chunk.py +41 -0
- byteplussdkarkruntime/types/context/context_create_params.py +37 -0
- byteplussdkarkruntime/types/context/create_context_response.py +25 -0
- byteplussdkarkruntime/types/context/truncation_strategy.py +13 -0
- byteplussdkarkruntime/types/create_embedding_response.py +36 -0
- byteplussdkarkruntime/types/embedding.py +21 -0
- byteplussdkarkruntime/types/file_create_params.py +49 -0
- byteplussdkarkruntime/types/file_deleted.py +24 -0
- byteplussdkarkruntime/types/file_list_params.py +43 -0
- byteplussdkarkruntime/types/file_object.py +69 -0
- byteplussdkarkruntime/types/file_purpose.py +16 -0
- byteplussdkarkruntime/types/images/__init__.py +3 -0
- byteplussdkarkruntime/types/images/image_gen_completed_event.py +59 -0
- byteplussdkarkruntime/types/images/image_gen_generating_event.py +53 -0
- byteplussdkarkruntime/types/images/image_gen_stream_event.py +24 -0
- byteplussdkarkruntime/types/images/images.py +99 -0
- byteplussdkarkruntime/types/multimodal_embedding/__init__.py +15 -0
- byteplussdkarkruntime/types/multimodal_embedding/embedding_content_part_image_param.py +17 -0
- byteplussdkarkruntime/types/multimodal_embedding/embedding_content_part_text_param.py +13 -0
- byteplussdkarkruntime/types/multimodal_embedding/embedding_data.py +15 -0
- byteplussdkarkruntime/types/multimodal_embedding/embedding_input.py +12 -0
- byteplussdkarkruntime/types/multimodal_embedding/embedding_response.py +29 -0
- byteplussdkarkruntime/types/multimodal_embedding/embedding_usage.py +23 -0
- byteplussdkarkruntime/types/responses/__init__.py +133 -0
- byteplussdkarkruntime/types/responses/easy_input_message.py +36 -0
- byteplussdkarkruntime/types/responses/easy_input_message_param.py +37 -0
- byteplussdkarkruntime/types/responses/function_tool.py +35 -0
- byteplussdkarkruntime/types/responses/function_tool_param.py +35 -0
- byteplussdkarkruntime/types/responses/input_item_list_params.py +47 -0
- byteplussdkarkruntime/types/responses/mcp_input_item_param.py +109 -0
- byteplussdkarkruntime/types/responses/mcp_tool.py +80 -0
- byteplussdkarkruntime/types/responses/mcp_tool_param.py +78 -0
- byteplussdkarkruntime/types/responses/response.py +152 -0
- byteplussdkarkruntime/types/responses/response_annotation_added_event.py +36 -0
- byteplussdkarkruntime/types/responses/response_caching.py +25 -0
- byteplussdkarkruntime/types/responses/response_caching_param.py +22 -0
- byteplussdkarkruntime/types/responses/response_completed_event.py +26 -0
- byteplussdkarkruntime/types/responses/response_content_part_added_event.py +39 -0
- byteplussdkarkruntime/types/responses/response_content_part_done_event.py +39 -0
- byteplussdkarkruntime/types/responses/response_create_params.py +26 -0
- byteplussdkarkruntime/types/responses/response_created_event.py +26 -0
- byteplussdkarkruntime/types/responses/response_error.py +25 -0
- byteplussdkarkruntime/types/responses/response_error_event.py +32 -0
- byteplussdkarkruntime/types/responses/response_failed_event.py +26 -0
- byteplussdkarkruntime/types/responses/response_format_text_config.py +25 -0
- byteplussdkarkruntime/types/responses/response_format_text_config_param.py +25 -0
- byteplussdkarkruntime/types/responses/response_function_call_arguments_delta_event.py +33 -0
- byteplussdkarkruntime/types/responses/response_function_call_arguments_done_event.py +30 -0
- byteplussdkarkruntime/types/responses/response_function_tool_call.py +42 -0
- byteplussdkarkruntime/types/responses/response_function_tool_call_item.py +20 -0
- byteplussdkarkruntime/types/responses/response_function_tool_call_output_item.py +39 -0
- byteplussdkarkruntime/types/responses/response_function_tool_call_param.py +31 -0
- byteplussdkarkruntime/types/responses/response_in_progress_event.py +26 -0
- byteplussdkarkruntime/types/responses/response_includable.py +19 -0
- byteplussdkarkruntime/types/responses/response_incomplete_details.py +30 -0
- byteplussdkarkruntime/types/responses/response_incomplete_event.py +26 -0
- byteplussdkarkruntime/types/responses/response_input_content.py +24 -0
- byteplussdkarkruntime/types/responses/response_input_content_param.py +23 -0
- byteplussdkarkruntime/types/responses/response_input_image.py +38 -0
- byteplussdkarkruntime/types/responses/response_input_image_param.py +42 -0
- byteplussdkarkruntime/types/responses/response_input_image_pixel_limit_param.py +29 -0
- byteplussdkarkruntime/types/responses/response_input_message_content_list.py +20 -0
- byteplussdkarkruntime/types/responses/response_input_message_content_list_param.py +26 -0
- byteplussdkarkruntime/types/responses/response_input_message_item.py +43 -0
- byteplussdkarkruntime/types/responses/response_input_param.py +51 -0
- byteplussdkarkruntime/types/responses/response_input_text.py +25 -0
- byteplussdkarkruntime/types/responses/response_input_text_param.py +25 -0
- byteplussdkarkruntime/types/responses/response_input_video_param.py +34 -0
- byteplussdkarkruntime/types/responses/response_item.py +40 -0
- byteplussdkarkruntime/types/responses/response_item_list.py +36 -0
- byteplussdkarkruntime/types/responses/response_mcp_call_arguments_delta_event.py +37 -0
- byteplussdkarkruntime/types/responses/response_mcp_call_arguments_done_event.py +34 -0
- byteplussdkarkruntime/types/responses/response_mcp_call_completed_event.py +31 -0
- byteplussdkarkruntime/types/responses/response_mcp_call_failed_event.py +31 -0
- byteplussdkarkruntime/types/responses/response_mcp_call_in_progress_event.py +31 -0
- byteplussdkarkruntime/types/responses/response_mcp_item.py +110 -0
- byteplussdkarkruntime/types/responses/response_mcp_list_tools_completed_event.py +31 -0
- byteplussdkarkruntime/types/responses/response_mcp_list_tools_failed_event.py +31 -0
- byteplussdkarkruntime/types/responses/response_mcp_list_tools_in_progress_event.py +31 -0
- byteplussdkarkruntime/types/responses/response_output_item.py +36 -0
- byteplussdkarkruntime/types/responses/response_output_item_added_event.py +29 -0
- byteplussdkarkruntime/types/responses/response_output_item_done_event.py +29 -0
- byteplussdkarkruntime/types/responses/response_output_message.py +43 -0
- byteplussdkarkruntime/types/responses/response_output_text.py +61 -0
- byteplussdkarkruntime/types/responses/response_output_text_param.py +77 -0
- byteplussdkarkruntime/types/responses/response_reasoning_item.py +46 -0
- byteplussdkarkruntime/types/responses/response_reasoning_item_param.py +37 -0
- byteplussdkarkruntime/types/responses/response_reasoning_summary_part_added_event.py +42 -0
- byteplussdkarkruntime/types/responses/response_reasoning_summary_part_done_event.py +42 -0
- byteplussdkarkruntime/types/responses/response_reasoning_summary_text_delta_event.py +34 -0
- byteplussdkarkruntime/types/responses/response_reasoning_summary_text_done_event.py +34 -0
- byteplussdkarkruntime/types/responses/response_status.py +17 -0
- byteplussdkarkruntime/types/responses/response_stream_event.py +93 -0
- byteplussdkarkruntime/types/responses/response_text_config.py +28 -0
- byteplussdkarkruntime/types/responses/response_text_config_param.py +31 -0
- byteplussdkarkruntime/types/responses/response_text_delta_event.py +34 -0
- byteplussdkarkruntime/types/responses/response_text_done_event.py +34 -0
- byteplussdkarkruntime/types/responses/response_tool_usage.py +32 -0
- byteplussdkarkruntime/types/responses/response_usage.py +54 -0
- byteplussdkarkruntime/types/responses/response_web_search_call_completed_event.py +29 -0
- byteplussdkarkruntime/types/responses/response_web_search_call_in_progress_event.py +29 -0
- byteplussdkarkruntime/types/responses/response_web_search_call_searching_event.py +29 -0
- byteplussdkarkruntime/types/responses/response_web_search_item.py +43 -0
- byteplussdkarkruntime/types/responses/tool.py +25 -0
- byteplussdkarkruntime/types/responses/tool_choice_function.py +25 -0
- byteplussdkarkruntime/types/responses/tool_choice_function_param.py +25 -0
- byteplussdkarkruntime/types/responses/tool_choice_mcp_param.py +29 -0
- byteplussdkarkruntime/types/responses/tool_choice_options.py +17 -0
- byteplussdkarkruntime/types/responses/tool_param.py +24 -0
- byteplussdkarkruntime/types/responses/web_search_tool.py +49 -0
- byteplussdkarkruntime/types/responses/web_search_tool_param.py +46 -0
- byteplussdkarkruntime/types/shared/__init__.py +21 -0
- byteplussdkarkruntime/types/shared/reasoning.py +10 -0
- byteplussdkarkruntime/types/shared/reasoning_effort.py +16 -0
- byteplussdkarkruntime/types/shared/response_format_json_object.py +22 -0
- byteplussdkarkruntime/types/shared/response_format_json_schema.py +56 -0
- byteplussdkarkruntime/types/shared/response_format_text.py +22 -0
- byteplussdkarkruntime/types/shared/thinking.py +25 -0
- byteplussdkarkruntime/types/shared_params/__init__.py +13 -0
- byteplussdkarkruntime/types/shared_params/function_definition.py +34 -0
- byteplussdkarkruntime/types/shared_params/function_parameters.py +9 -0
- byteplussdkarkruntime/types/shared_params/metadata.py +20 -0
- byteplussdkarkruntime/types/shared_params/reasoning.py +12 -0
- byteplussdkarkruntime/types/shared_params/reasoning_effort.py +8 -0
- byteplussdkarkruntime/types/shared_params/response_format_json_object.py +22 -0
- byteplussdkarkruntime/types/shared_params/response_format_json_schema.py +54 -0
- byteplussdkarkruntime/types/shared_params/response_format_text.py +22 -0
- byteplussdkarkruntime/types/shared_params/thinking.py +22 -0
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import inspect
|
|
5
|
+
from types import TracebackType
|
|
6
|
+
from typing import (
|
|
7
|
+
TYPE_CHECKING,
|
|
8
|
+
Any,
|
|
9
|
+
Generic,
|
|
10
|
+
TypeVar,
|
|
11
|
+
Iterator,
|
|
12
|
+
AsyncIterator,
|
|
13
|
+
cast,
|
|
14
|
+
Optional,
|
|
15
|
+
)
|
|
16
|
+
from typing_extensions import (
|
|
17
|
+
Self,
|
|
18
|
+
Protocol,
|
|
19
|
+
TypeGuard,
|
|
20
|
+
override,
|
|
21
|
+
get_origin,
|
|
22
|
+
runtime_checkable,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
import httpx
|
|
26
|
+
from ._constants import CLIENT_REQUEST_HEADER
|
|
27
|
+
from ._utils import extract_type_var_from_base
|
|
28
|
+
from ._exceptions import ArkAPIError
|
|
29
|
+
from ._utils._utils import is_mapping
|
|
30
|
+
|
|
31
|
+
if TYPE_CHECKING:
|
|
32
|
+
from ._client import Ark, AsyncArk
|
|
33
|
+
|
|
34
|
+
_T = TypeVar("_T")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Stream(Generic[_T]):
|
|
38
|
+
"""Provides the core interface to iterate over a synchronous stream response."""
|
|
39
|
+
|
|
40
|
+
response: httpx.Response
|
|
41
|
+
|
|
42
|
+
_decoder: SSEBytesDecoder
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
*,
|
|
47
|
+
cast_to: type[_T],
|
|
48
|
+
response: httpx.Response,
|
|
49
|
+
client: Ark,
|
|
50
|
+
iterator: Optional[Iterator[_T]] | None = None,
|
|
51
|
+
) -> None:
|
|
52
|
+
if iterator is not None:
|
|
53
|
+
self._iterator = iterator
|
|
54
|
+
else:
|
|
55
|
+
self.response = response
|
|
56
|
+
self._cast_to = cast_to
|
|
57
|
+
self._client = client
|
|
58
|
+
self._decoder = client._make_sse_decoder()
|
|
59
|
+
self._iterator = self.__stream__()
|
|
60
|
+
|
|
61
|
+
@classmethod
|
|
62
|
+
def _make_stream_from_iterator(cls, iterator: Iterator[_T]) -> Stream[_T]:
|
|
63
|
+
return Stream(cast_to=None, response=None, client=None, iterator=iterator)
|
|
64
|
+
|
|
65
|
+
def __next__(self) -> _T:
|
|
66
|
+
return self._iterator.__next__()
|
|
67
|
+
|
|
68
|
+
def __iter__(self) -> Iterator[_T]:
|
|
69
|
+
for item in self._iterator:
|
|
70
|
+
yield item
|
|
71
|
+
|
|
72
|
+
def _iter_events(self) -> Iterator[ServerSentEvent]:
|
|
73
|
+
yield from self._decoder.iter_bytes(self.response.iter_bytes())
|
|
74
|
+
|
|
75
|
+
def __stream__(self) -> Iterator[_T]:
|
|
76
|
+
cast_to = cast(Any, self._cast_to)
|
|
77
|
+
response = self.response
|
|
78
|
+
process_data = self._client._process_response_data
|
|
79
|
+
iterator = self._iter_events()
|
|
80
|
+
request_id = (
|
|
81
|
+
self.response.headers.get(CLIENT_REQUEST_HEADER, "") if response else None
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
for sse in iterator:
|
|
85
|
+
if sse.data.startswith("[DONE]"):
|
|
86
|
+
break
|
|
87
|
+
|
|
88
|
+
if sse.event is None or (isinstance(sse.event, str) and len(sse.event) > 0):
|
|
89
|
+
data = sse.json()
|
|
90
|
+
if is_mapping(data) and data.get("error"):
|
|
91
|
+
message = None
|
|
92
|
+
error = data.get("error")
|
|
93
|
+
if is_mapping(error):
|
|
94
|
+
message = error.get("message")
|
|
95
|
+
if not message or not isinstance(message, str):
|
|
96
|
+
message = "An error occurred during streaming"
|
|
97
|
+
|
|
98
|
+
raise ArkAPIError(
|
|
99
|
+
message=message,
|
|
100
|
+
request=self.response.request,
|
|
101
|
+
body=data["error"],
|
|
102
|
+
request_id=request_id,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
yield process_data(data=data, cast_to=cast_to, response=response)
|
|
106
|
+
|
|
107
|
+
else:
|
|
108
|
+
data = sse.json()
|
|
109
|
+
|
|
110
|
+
if sse.event == "error" and is_mapping(data) and data.get("error"):
|
|
111
|
+
message = None
|
|
112
|
+
error = data.get("error")
|
|
113
|
+
if is_mapping(error):
|
|
114
|
+
message = error.get("message")
|
|
115
|
+
if not message or not isinstance(message, str):
|
|
116
|
+
message = "An error occurred during streaming"
|
|
117
|
+
|
|
118
|
+
raise ArkAPIError(
|
|
119
|
+
message=message,
|
|
120
|
+
request=self.response.request,
|
|
121
|
+
body=data["error"],
|
|
122
|
+
request_id=request_id,
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
yield process_data(
|
|
126
|
+
data={"data": data, "event": sse.event},
|
|
127
|
+
cast_to=cast_to,
|
|
128
|
+
response=response,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
# Ensure the entire stream is consumed
|
|
132
|
+
for _sse in iterator:
|
|
133
|
+
...
|
|
134
|
+
|
|
135
|
+
def __enter__(self) -> Self:
|
|
136
|
+
return self
|
|
137
|
+
|
|
138
|
+
def __exit__(
|
|
139
|
+
self,
|
|
140
|
+
exc_type: type[BaseException] | None,
|
|
141
|
+
exc: BaseException | None,
|
|
142
|
+
exc_tb: TracebackType | None,
|
|
143
|
+
) -> None:
|
|
144
|
+
self.close()
|
|
145
|
+
|
|
146
|
+
def close(self) -> None:
|
|
147
|
+
"""
|
|
148
|
+
Close the response and release the connection.
|
|
149
|
+
|
|
150
|
+
Automatically called if the response body is read to completion.
|
|
151
|
+
"""
|
|
152
|
+
self.response.close()
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class AsyncStream(Generic[_T]):
|
|
156
|
+
"""Provides the core interface to iterate over an asynchronous stream response."""
|
|
157
|
+
|
|
158
|
+
response: httpx.Response
|
|
159
|
+
|
|
160
|
+
_decoder: SSEDecoder | SSEBytesDecoder
|
|
161
|
+
|
|
162
|
+
def __init__(
|
|
163
|
+
self,
|
|
164
|
+
*,
|
|
165
|
+
cast_to: type[_T],
|
|
166
|
+
response: httpx.Response,
|
|
167
|
+
client: AsyncArk,
|
|
168
|
+
iterator: Optional[AsyncIterator[_T]] | None = None,
|
|
169
|
+
) -> None:
|
|
170
|
+
if iterator is not None:
|
|
171
|
+
self._iterator = iterator
|
|
172
|
+
else:
|
|
173
|
+
self.response = response
|
|
174
|
+
self._cast_to = cast_to
|
|
175
|
+
self._client = client
|
|
176
|
+
self._decoder = client._make_sse_decoder()
|
|
177
|
+
self._iterator = self.__stream__()
|
|
178
|
+
|
|
179
|
+
@classmethod
|
|
180
|
+
def _make_stream_from_iterator(cls, iterator: AsyncIterator[_T]) -> AsyncStream[_T]:
|
|
181
|
+
return AsyncStream(cast_to=None, response=None, client=None, iterator=iterator)
|
|
182
|
+
|
|
183
|
+
async def __anext__(self) -> _T:
|
|
184
|
+
return await self._iterator.__anext__()
|
|
185
|
+
|
|
186
|
+
async def __aiter__(self) -> AsyncIterator[_T]:
|
|
187
|
+
async for item in self._iterator:
|
|
188
|
+
yield item
|
|
189
|
+
|
|
190
|
+
async def _iter_events(self) -> AsyncIterator[ServerSentEvent]:
|
|
191
|
+
async for sse in self._decoder.aiter_bytes(self.response.aiter_bytes()):
|
|
192
|
+
yield sse
|
|
193
|
+
|
|
194
|
+
async def __stream__(self) -> AsyncIterator[_T]:
|
|
195
|
+
cast_to = cast(Any, self._cast_to)
|
|
196
|
+
response = self.response
|
|
197
|
+
process_data = self._client._process_response_data
|
|
198
|
+
iterator = self._iter_events()
|
|
199
|
+
request_id = (
|
|
200
|
+
response.headers.get(CLIENT_REQUEST_HEADER, "") if response else None
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
async for sse in iterator:
|
|
204
|
+
if sse.data.startswith("[DONE]"):
|
|
205
|
+
break
|
|
206
|
+
|
|
207
|
+
if sse.event is None or (isinstance(sse.event, str) and len(sse.event) > 0):
|
|
208
|
+
data = sse.json()
|
|
209
|
+
if is_mapping(data) and data.get("error"):
|
|
210
|
+
message = None
|
|
211
|
+
error = data.get("error")
|
|
212
|
+
if is_mapping(error):
|
|
213
|
+
message = error.get("message")
|
|
214
|
+
if not message or not isinstance(message, str):
|
|
215
|
+
message = "An error occurred during streaming"
|
|
216
|
+
|
|
217
|
+
raise ArkAPIError(
|
|
218
|
+
message=message,
|
|
219
|
+
request=self.response.request,
|
|
220
|
+
body=data["error"],
|
|
221
|
+
request_id=request_id,
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
yield process_data(data=data, cast_to=cast_to, response=response)
|
|
225
|
+
|
|
226
|
+
else:
|
|
227
|
+
data = sse.json()
|
|
228
|
+
|
|
229
|
+
if sse.event == "error" and is_mapping(data) and data.get("error"):
|
|
230
|
+
message = None
|
|
231
|
+
error = data.get("error")
|
|
232
|
+
if is_mapping(error):
|
|
233
|
+
message = error.get("message")
|
|
234
|
+
if not message or not isinstance(message, str):
|
|
235
|
+
message = "An error occurred during streaming"
|
|
236
|
+
|
|
237
|
+
raise ArkAPIError(
|
|
238
|
+
message=message,
|
|
239
|
+
request=self.response.request,
|
|
240
|
+
body=data["error"],
|
|
241
|
+
request_id=request_id,
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
yield process_data(
|
|
245
|
+
data={"data": data, "event": sse.event},
|
|
246
|
+
cast_to=cast_to,
|
|
247
|
+
response=response,
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
# Ensure the entire stream is consumed
|
|
251
|
+
async for _sse in iterator:
|
|
252
|
+
...
|
|
253
|
+
|
|
254
|
+
async def __aenter__(self) -> Self:
|
|
255
|
+
return self
|
|
256
|
+
|
|
257
|
+
async def __aexit__(
|
|
258
|
+
self,
|
|
259
|
+
exc_type: type[BaseException] | None,
|
|
260
|
+
exc: BaseException | None,
|
|
261
|
+
exc_tb: TracebackType | None,
|
|
262
|
+
) -> None:
|
|
263
|
+
await self.close()
|
|
264
|
+
|
|
265
|
+
async def close(self) -> None:
|
|
266
|
+
"""
|
|
267
|
+
Close the response and release the connection.
|
|
268
|
+
|
|
269
|
+
Automatically called if the response body is read to completion.
|
|
270
|
+
"""
|
|
271
|
+
await self.response.aclose()
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
class ServerSentEvent:
|
|
275
|
+
def __init__(
|
|
276
|
+
self,
|
|
277
|
+
*,
|
|
278
|
+
event: str | None = None,
|
|
279
|
+
data: str | None = None,
|
|
280
|
+
id: str | None = None,
|
|
281
|
+
retry: int | None = None,
|
|
282
|
+
) -> None:
|
|
283
|
+
if data is None:
|
|
284
|
+
data = ""
|
|
285
|
+
|
|
286
|
+
self._id = id
|
|
287
|
+
self._data = data
|
|
288
|
+
self._event = event or None
|
|
289
|
+
self._retry = retry
|
|
290
|
+
|
|
291
|
+
@property
|
|
292
|
+
def event(self) -> str | None:
|
|
293
|
+
return self._event
|
|
294
|
+
|
|
295
|
+
@property
|
|
296
|
+
def id(self) -> str | None:
|
|
297
|
+
return self._id
|
|
298
|
+
|
|
299
|
+
@property
|
|
300
|
+
def retry(self) -> int | None:
|
|
301
|
+
return self._retry
|
|
302
|
+
|
|
303
|
+
@property
|
|
304
|
+
def data(self) -> str:
|
|
305
|
+
return self._data
|
|
306
|
+
|
|
307
|
+
def json(self) -> Any:
|
|
308
|
+
return json.loads(self.data)
|
|
309
|
+
|
|
310
|
+
@override
|
|
311
|
+
def __repr__(self) -> str:
|
|
312
|
+
return f"ServerSentEvent(event={self.event}, data={self.data}, id={self.id}, retry={self.retry})"
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
class SSEDecoder:
|
|
316
|
+
_data: list[str]
|
|
317
|
+
_event: str | None
|
|
318
|
+
_retry: int | None
|
|
319
|
+
_last_event_id: str | None
|
|
320
|
+
|
|
321
|
+
def __init__(self) -> None:
|
|
322
|
+
self._event = None
|
|
323
|
+
self._data = []
|
|
324
|
+
self._last_event_id = None
|
|
325
|
+
self._retry = None
|
|
326
|
+
|
|
327
|
+
def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]:
|
|
328
|
+
"""Given an iterator that yields raw binary data, iterate over it & yield every event encountered"""
|
|
329
|
+
for chunk in self._iter_chunks(iterator):
|
|
330
|
+
# Split before decoding so splitlines() only uses \r and \n
|
|
331
|
+
for raw_line in chunk.splitlines():
|
|
332
|
+
line = raw_line.decode("utf-8")
|
|
333
|
+
sse = self.decode(line)
|
|
334
|
+
if sse:
|
|
335
|
+
yield sse
|
|
336
|
+
|
|
337
|
+
def _iter_chunks(self, iterator: Iterator[bytes]) -> Iterator[bytes]:
|
|
338
|
+
"""Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks"""
|
|
339
|
+
data = b""
|
|
340
|
+
for chunk in iterator:
|
|
341
|
+
for line in chunk.splitlines(keepends=True):
|
|
342
|
+
data += line
|
|
343
|
+
if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")):
|
|
344
|
+
yield data
|
|
345
|
+
data = b""
|
|
346
|
+
if data:
|
|
347
|
+
yield data
|
|
348
|
+
|
|
349
|
+
async def aiter_bytes(
|
|
350
|
+
self, iterator: AsyncIterator[bytes]
|
|
351
|
+
) -> AsyncIterator[ServerSentEvent]:
|
|
352
|
+
"""Given an iterator that yields raw binary data, iterate over it & yield every event encountered"""
|
|
353
|
+
async for chunk in self._aiter_chunks(iterator):
|
|
354
|
+
# Split before decoding so splitlines() only uses \r and \n
|
|
355
|
+
for raw_line in chunk.splitlines():
|
|
356
|
+
line = raw_line.decode("utf-8")
|
|
357
|
+
sse = self.decode(line)
|
|
358
|
+
if sse:
|
|
359
|
+
yield sse
|
|
360
|
+
|
|
361
|
+
async def _aiter_chunks(
|
|
362
|
+
self, iterator: AsyncIterator[bytes]
|
|
363
|
+
) -> AsyncIterator[bytes]:
|
|
364
|
+
"""Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks"""
|
|
365
|
+
data = b""
|
|
366
|
+
async for chunk in iterator:
|
|
367
|
+
for line in chunk.splitlines(keepends=True):
|
|
368
|
+
data += line
|
|
369
|
+
if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")):
|
|
370
|
+
yield data
|
|
371
|
+
data = b""
|
|
372
|
+
if data:
|
|
373
|
+
yield data
|
|
374
|
+
|
|
375
|
+
def decode(self, line: str) -> ServerSentEvent | None:
|
|
376
|
+
if not line:
|
|
377
|
+
if (
|
|
378
|
+
not self._event
|
|
379
|
+
and not self._data
|
|
380
|
+
and not self._last_event_id
|
|
381
|
+
and self._retry is None
|
|
382
|
+
):
|
|
383
|
+
return None
|
|
384
|
+
|
|
385
|
+
sse = ServerSentEvent(
|
|
386
|
+
event=self._event,
|
|
387
|
+
data="\n".join(self._data),
|
|
388
|
+
id=self._last_event_id,
|
|
389
|
+
retry=self._retry,
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
# NOTE: as per the SSE spec, do not reset last_event_id.
|
|
393
|
+
self._event = None
|
|
394
|
+
self._data = []
|
|
395
|
+
self._retry = None
|
|
396
|
+
|
|
397
|
+
return sse
|
|
398
|
+
|
|
399
|
+
if line.startswith(":"):
|
|
400
|
+
return None
|
|
401
|
+
|
|
402
|
+
fieldname, _, value = line.partition(":")
|
|
403
|
+
|
|
404
|
+
if value.startswith(" "):
|
|
405
|
+
value = value[1:]
|
|
406
|
+
|
|
407
|
+
if fieldname == "event":
|
|
408
|
+
self._event = value
|
|
409
|
+
elif fieldname == "data":
|
|
410
|
+
self._data.append(value)
|
|
411
|
+
elif fieldname == "id":
|
|
412
|
+
if "\0" in value:
|
|
413
|
+
pass
|
|
414
|
+
else:
|
|
415
|
+
self._last_event_id = value
|
|
416
|
+
elif fieldname == "retry":
|
|
417
|
+
try:
|
|
418
|
+
self._retry = int(value)
|
|
419
|
+
except (TypeError, ValueError):
|
|
420
|
+
pass
|
|
421
|
+
else:
|
|
422
|
+
pass # Field is ignored.
|
|
423
|
+
|
|
424
|
+
return None
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
@runtime_checkable
|
|
428
|
+
class SSEBytesDecoder(Protocol):
|
|
429
|
+
def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]:
|
|
430
|
+
"""Given an iterator that yields raw binary data, iterate over it & yield every event encountered"""
|
|
431
|
+
...
|
|
432
|
+
|
|
433
|
+
def aiter_bytes(
|
|
434
|
+
self, iterator: AsyncIterator[bytes]
|
|
435
|
+
) -> AsyncIterator[ServerSentEvent]:
|
|
436
|
+
"""Given an async iterator that yields raw binary data, iterate over it & yield every event encountered"""
|
|
437
|
+
...
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def is_stream_class_type(
|
|
441
|
+
typ: type,
|
|
442
|
+
) -> TypeGuard[type[Stream[object]] | type[AsyncStream[object]]]:
|
|
443
|
+
"""TypeGuard for determining whether or not the given type is a subclass of `Stream` / `AsyncStream`"""
|
|
444
|
+
origin = get_origin(typ) or typ
|
|
445
|
+
return inspect.isclass(origin) and issubclass(origin, (Stream, AsyncStream))
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def extract_stream_chunk_type(
|
|
449
|
+
stream_cls: type,
|
|
450
|
+
*,
|
|
451
|
+
failure_message: str | None = None,
|
|
452
|
+
) -> type:
|
|
453
|
+
"""Given a type like `Stream[T]`, returns the generic type variable `T`.
|
|
454
|
+
|
|
455
|
+
This also handles the case where a concrete subclass is given, e.g.
|
|
456
|
+
```py
|
|
457
|
+
class MyStream(Stream[bytes]):
|
|
458
|
+
...
|
|
459
|
+
|
|
460
|
+
extract_stream_chunk_type(MyStream) -> bytes
|
|
461
|
+
```
|
|
462
|
+
"""
|
|
463
|
+
from ._base_client import Stream, AsyncStream
|
|
464
|
+
|
|
465
|
+
return extract_type_var_from_base(
|
|
466
|
+
stream_cls,
|
|
467
|
+
index=0,
|
|
468
|
+
generic_bases=cast("tuple[type, ...]", (Stream, AsyncStream)),
|
|
469
|
+
failure_message=failure_message,
|
|
470
|
+
)
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from os import PathLike
|
|
4
|
+
from typing import (
|
|
5
|
+
IO,
|
|
6
|
+
TYPE_CHECKING,
|
|
7
|
+
Any,
|
|
8
|
+
Dict,
|
|
9
|
+
List,
|
|
10
|
+
Type,
|
|
11
|
+
Tuple,
|
|
12
|
+
Union,
|
|
13
|
+
Mapping,
|
|
14
|
+
TypeVar,
|
|
15
|
+
Callable,
|
|
16
|
+
Optional,
|
|
17
|
+
Sequence,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
import pydantic
|
|
21
|
+
import functools
|
|
22
|
+
from httpx import Response
|
|
23
|
+
from typing_extensions import (
|
|
24
|
+
Set,
|
|
25
|
+
Literal,
|
|
26
|
+
Protocol,
|
|
27
|
+
TypeAlias,
|
|
28
|
+
override,
|
|
29
|
+
runtime_checkable,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
from collections import defaultdict
|
|
33
|
+
|
|
34
|
+
if TYPE_CHECKING:
|
|
35
|
+
from ._models import BaseModel
|
|
36
|
+
from ._response import ArkAPIResponse, ArkAsyncAPIResponse
|
|
37
|
+
|
|
38
|
+
ModelT = TypeVar("ModelT", bound=pydantic.BaseModel)
|
|
39
|
+
_T = TypeVar("_T")
|
|
40
|
+
ResponseT = TypeVar(
|
|
41
|
+
"ResponseT",
|
|
42
|
+
bound=Union[
|
|
43
|
+
object,
|
|
44
|
+
str,
|
|
45
|
+
None,
|
|
46
|
+
"BaseModel",
|
|
47
|
+
List[Any],
|
|
48
|
+
Dict[str, Any],
|
|
49
|
+
Response,
|
|
50
|
+
"ArkAPIResponse[Any]",
|
|
51
|
+
"ArkAsyncAPIResponse[Any]",
|
|
52
|
+
],
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
if TYPE_CHECKING:
|
|
56
|
+
Base64FileInput = Union[IO[bytes], PathLike[str]]
|
|
57
|
+
FileContent = Union[IO[bytes], bytes, PathLike[str]]
|
|
58
|
+
else:
|
|
59
|
+
Base64FileInput = Union[IO[bytes], PathLike]
|
|
60
|
+
FileContent = Union[
|
|
61
|
+
IO[bytes], bytes, PathLike
|
|
62
|
+
] # PathLike is not subscriptable in Python 3.8.
|
|
63
|
+
|
|
64
|
+
FileTypes = Union[
|
|
65
|
+
# file (or bytes)
|
|
66
|
+
FileContent,
|
|
67
|
+
# (filename, file (or bytes))
|
|
68
|
+
Tuple[Optional[str], FileContent],
|
|
69
|
+
# (filename, file (or bytes), content_type)
|
|
70
|
+
Tuple[Optional[str], FileContent, Optional[str]],
|
|
71
|
+
# (filename, file (or bytes), content_type, headers)
|
|
72
|
+
Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]],
|
|
73
|
+
]
|
|
74
|
+
RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]]
|
|
75
|
+
|
|
76
|
+
# duplicate of the above but without our custom file support
|
|
77
|
+
HttpxFileContent = Union[IO[bytes], bytes]
|
|
78
|
+
HttpxFileTypes = Union[
|
|
79
|
+
# file (or bytes)
|
|
80
|
+
HttpxFileContent,
|
|
81
|
+
# (filename, file (or bytes))
|
|
82
|
+
Tuple[Optional[str], HttpxFileContent],
|
|
83
|
+
# (filename, file (or bytes), content_type)
|
|
84
|
+
Tuple[Optional[str], HttpxFileContent, Optional[str]],
|
|
85
|
+
# (filename, file (or bytes), content_type, headers)
|
|
86
|
+
Tuple[Optional[str], HttpxFileContent, Optional[str], Mapping[str, str]],
|
|
87
|
+
]
|
|
88
|
+
HttpxRequestFiles = Union[
|
|
89
|
+
Mapping[str, HttpxFileTypes], Sequence[Tuple[str, HttpxFileTypes]]
|
|
90
|
+
]
|
|
91
|
+
|
|
92
|
+
if TYPE_CHECKING:
|
|
93
|
+
NoneType: Type[None]
|
|
94
|
+
else:
|
|
95
|
+
NoneType = type(None)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class NotGiven:
|
|
99
|
+
"""
|
|
100
|
+
A sentinel singleton class used to distinguish omitted keyword arguments
|
|
101
|
+
from those passed in with the value None (which may have different behavior).
|
|
102
|
+
|
|
103
|
+
For example:
|
|
104
|
+
|
|
105
|
+
```py
|
|
106
|
+
def get(timeout: Union[int, NotGiven, None] = NotGiven()) -> Response:
|
|
107
|
+
...
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
get(timeout=1) # 1s timeout
|
|
111
|
+
get(timeout=None) # No timeout
|
|
112
|
+
get() # Default timeout behavior, which may not be statically known at the method definition.
|
|
113
|
+
```
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
def __bool__(self) -> Literal[False]:
|
|
117
|
+
return False
|
|
118
|
+
|
|
119
|
+
@override
|
|
120
|
+
def __repr__(self) -> str:
|
|
121
|
+
return "NOT_GIVEN"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
NotGivenOr = Union[_T, NotGiven]
|
|
125
|
+
NOT_GIVEN = NotGiven()
|
|
126
|
+
|
|
127
|
+
Headers = Dict[str, str]
|
|
128
|
+
Query = Dict[str, object]
|
|
129
|
+
Body = Dict[str, object]
|
|
130
|
+
AnyMapping = Mapping[str, object]
|
|
131
|
+
|
|
132
|
+
IncEx: TypeAlias = Union[
|
|
133
|
+
Set[int],
|
|
134
|
+
Set[str],
|
|
135
|
+
Mapping[int, Union["IncEx", bool]],
|
|
136
|
+
Mapping[str, Union["IncEx", bool]],
|
|
137
|
+
]
|
|
138
|
+
|
|
139
|
+
PostParser = Callable[[Any], Any]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@runtime_checkable
|
|
143
|
+
class InheritsGeneric(Protocol):
|
|
144
|
+
"""Represents a type that has inherited from `Generic`
|
|
145
|
+
|
|
146
|
+
The `__orig_bases__` property can be used to determine the resolved
|
|
147
|
+
type variable for a given base class.
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
__orig_bases__: tuple[_GenericAlias]
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class _GenericAlias(Protocol):
|
|
154
|
+
__origin__: type[object]
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
_overload_registry = defaultdict(functools.partial(defaultdict, dict))
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _overload_dummy(*args, **kwds):
|
|
161
|
+
"""Helper for @overload to raise when called."""
|
|
162
|
+
raise NotImplementedError(
|
|
163
|
+
"You should not call an overloaded function. "
|
|
164
|
+
"A series of @overload-decorated functions "
|
|
165
|
+
"outside a stub module should always be followed "
|
|
166
|
+
"by an implementation that is not @overload-ed."
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def overload(func):
|
|
171
|
+
"""Decorator for overloaded functions/methods.
|
|
172
|
+
|
|
173
|
+
In a stub file, place two or more stub definitions for the same
|
|
174
|
+
function in a row, each decorated with @overload.
|
|
175
|
+
|
|
176
|
+
For example::
|
|
177
|
+
|
|
178
|
+
@overload
|
|
179
|
+
def utf8(value: None) -> None: ...
|
|
180
|
+
@overload
|
|
181
|
+
def utf8(value: bytes) -> bytes: ...
|
|
182
|
+
@overload
|
|
183
|
+
def utf8(value: str) -> bytes: ...
|
|
184
|
+
|
|
185
|
+
In a non-stub file (i.e. a regular .py file), do the same but
|
|
186
|
+
follow it with an implementation. The implementation should *not*
|
|
187
|
+
be decorated with @overload::
|
|
188
|
+
|
|
189
|
+
@overload
|
|
190
|
+
def utf8(value: None) -> None: ...
|
|
191
|
+
@overload
|
|
192
|
+
def utf8(value: bytes) -> bytes: ...
|
|
193
|
+
@overload
|
|
194
|
+
def utf8(value: str) -> bytes: ...
|
|
195
|
+
def utf8(value):
|
|
196
|
+
... # implementation goes here
|
|
197
|
+
|
|
198
|
+
The overloads for a function can be retrieved at runtime using the
|
|
199
|
+
get_overloads() function.
|
|
200
|
+
"""
|
|
201
|
+
# classmethod and staticmethod
|
|
202
|
+
f = getattr(func, "__func__", func)
|
|
203
|
+
try:
|
|
204
|
+
_overload_registry[f.__module__][f.__qualname__][
|
|
205
|
+
f.__code__.co_firstlineno
|
|
206
|
+
] = func
|
|
207
|
+
except AttributeError:
|
|
208
|
+
# Not a normal function; ignore.
|
|
209
|
+
pass
|
|
210
|
+
return _overload_dummy
|