mixpeek 0.2__py3-none-any.whl → 0.6.1__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.
Files changed (74) hide show
  1. mixpeek/__init__.py +95 -71
  2. mixpeek/base_client.py +128 -0
  3. mixpeek/client.py +65 -0
  4. mixpeek/core/__init__.py +25 -0
  5. mixpeek/core/api_error.py +15 -0
  6. mixpeek/core/client_wrapper.py +83 -0
  7. mixpeek/core/datetime_utils.py +28 -0
  8. mixpeek/core/file.py +38 -0
  9. mixpeek/core/http_client.py +130 -0
  10. mixpeek/core/jsonable_encoder.py +103 -0
  11. mixpeek/core/remove_none_from_dict.py +11 -0
  12. mixpeek/core/request_options.py +32 -0
  13. mixpeek/errors/__init__.py +17 -0
  14. mixpeek/errors/bad_request_error.py +9 -0
  15. mixpeek/errors/forbidden_error.py +9 -0
  16. mixpeek/errors/internal_server_error.py +9 -0
  17. mixpeek/errors/not_found_error.py +9 -0
  18. mixpeek/errors/unauthorized_error.py +9 -0
  19. mixpeek/errors/unprocessable_entity_error.py +9 -0
  20. mixpeek/generators/__init__.py +2 -0
  21. mixpeek/generators/client.py +239 -0
  22. mixpeek/parse/__init__.py +2 -0
  23. mixpeek/parse/client.py +349 -0
  24. mixpeek/parse_client.py +14 -0
  25. mixpeek/pipelines/__init__.py +2 -0
  26. mixpeek/pipelines/client.py +546 -0
  27. mixpeek/py.typed +0 -0
  28. mixpeek/storage/__init__.py +2 -0
  29. mixpeek/storage/client.py +254 -0
  30. mixpeek/types/__init__.py +73 -0
  31. mixpeek/types/audio_params.py +29 -0
  32. mixpeek/types/configs_request.py +31 -0
  33. mixpeek/types/configs_response.py +31 -0
  34. mixpeek/types/connection.py +36 -0
  35. mixpeek/types/connection_engine.py +5 -0
  36. mixpeek/types/csv_params.py +29 -0
  37. mixpeek/types/destination_schema.py +31 -0
  38. mixpeek/types/embedding_request.py +32 -0
  39. mixpeek/types/embedding_response.py +30 -0
  40. mixpeek/types/error_message.py +29 -0
  41. mixpeek/types/error_response.py +30 -0
  42. mixpeek/types/field_schema.py +33 -0
  43. mixpeek/types/field_type.py +5 -0
  44. mixpeek/types/generation_response.py +34 -0
  45. mixpeek/types/html_params.py +29 -0
  46. mixpeek/types/http_validation_error.py +30 -0
  47. mixpeek/types/image_params.py +32 -0
  48. mixpeek/types/message.py +30 -0
  49. mixpeek/types/metadata.py +34 -0
  50. mixpeek/types/modality.py +5 -0
  51. mixpeek/types/model.py +30 -0
  52. mixpeek/types/pdf_params.py +41 -0
  53. mixpeek/types/pipeline_response.py +39 -0
  54. mixpeek/types/ppt_params.py +27 -0
  55. mixpeek/types/pptx_params.py +27 -0
  56. mixpeek/types/settings.py +35 -0
  57. mixpeek/types/source_schema.py +32 -0
  58. mixpeek/types/txt_params.py +27 -0
  59. mixpeek/types/validation_error.py +32 -0
  60. mixpeek/types/validation_error_loc_item.py +5 -0
  61. mixpeek/types/video_params.py +27 -0
  62. mixpeek/types/workflow_response.py +32 -0
  63. mixpeek/types/workflow_settings.py +30 -0
  64. mixpeek/types/xlsx_params.py +29 -0
  65. mixpeek/version.py +4 -0
  66. mixpeek/workflows/__init__.py +2 -0
  67. mixpeek/workflows/client.py +418 -0
  68. mixpeek-0.2.dist-info/LICENSE.rst → mixpeek-0.6.1.dist-info/LICENSE +10 -9
  69. mixpeek-0.6.1.dist-info/METADATA +145 -0
  70. mixpeek-0.6.1.dist-info/RECORD +71 -0
  71. {mixpeek-0.2.dist-info → mixpeek-0.6.1.dist-info}/WHEEL +1 -2
  72. mixpeek-0.2.dist-info/METADATA +0 -12
  73. mixpeek-0.2.dist-info/RECORD +0 -6
  74. mixpeek-0.2.dist-info/top_level.txt +0 -1
mixpeek/__init__.py CHANGED
@@ -1,73 +1,97 @@
1
- # mixpeek.py
2
- import requests
3
- import json
1
+ # This file was auto-generated by Fern from our API Definition.
4
2
 
3
+ from .types import (
4
+ AudioParams,
5
+ ConfigsRequest,
6
+ ConfigsResponse,
7
+ Connection,
8
+ ConnectionEngine,
9
+ CsvParams,
10
+ DestinationSchema,
11
+ EmbeddingRequest,
12
+ EmbeddingResponse,
13
+ ErrorMessage,
14
+ ErrorResponse,
15
+ FieldSchema,
16
+ FieldType,
17
+ GenerationResponse,
18
+ HtmlParams,
19
+ HttpValidationError,
20
+ ImageParams,
21
+ Message,
22
+ Metadata,
23
+ Modality,
24
+ Model,
25
+ PdfParams,
26
+ PipelineResponse,
27
+ PptParams,
28
+ PptxParams,
29
+ Settings,
30
+ SourceSchema,
31
+ TxtParams,
32
+ ValidationError,
33
+ ValidationErrorLocItem,
34
+ VideoParams,
35
+ WorkflowResponse,
36
+ WorkflowSettings,
37
+ XlsxParams,
38
+ )
39
+ from .errors import (
40
+ BadRequestError,
41
+ ForbiddenError,
42
+ InternalServerError,
43
+ NotFoundError,
44
+ UnauthorizedError,
45
+ UnprocessableEntityError,
46
+ )
47
+ from . import generators, parse, pipelines, storage, workflows
48
+ from .version import __version__
5
49
 
6
- class Mixpeek:
7
- def __init__(self, api_key):
8
- self.base_url = "http://localhost:8000"
9
- self.headers = {
10
- "Authorization": f"Bearer {api_key}",
11
- "Content-Type": "application/json",
12
- }
13
- self.generate = self.Generate(self)
14
- self.parse = self.Parse(self)
15
-
16
- def _send_post(self, url, payload):
17
- return requests.post(url, headers=self.headers, data=json.dumps(payload)).json()
18
-
19
- def _send_get(self, url):
20
- return requests.get(url, headers=self.headers).json()
21
-
22
- class Generate:
23
- def __init__(self, mixpeek):
24
- self.mixpeek = mixpeek
25
- self.openai = self.OpenAI(self.mixpeek)
26
-
27
- class OpenAI:
28
- def __init__(self, mixpeek):
29
- self.mixpeek = mixpeek
30
- self.generate_openai_url = f"{self.mixpeek.base_url}/generate"
31
-
32
- def _construct_request_format(
33
- self, model, context, response_format, settings=None
34
- ):
35
- payload = {
36
- "model": {"provider": "gpt", "model": model},
37
- "context": context,
38
- "messages": [{"role": "user", "content": ""}],
39
- **settings,
40
- }
41
-
42
- if response_format is not None:
43
- json_schema = response_format.model_json_schema()
44
- payload["response_format"] = json_schema
45
-
46
- return payload
47
-
48
- def chat(self, model, response_format, context, settings=None):
49
- payload = self._construct_request_format(
50
- model, context, response_format, settings
51
- )
52
- return self.mixpeek._send_post(self.generate_openai_url, payload)
53
-
54
- class Parse:
55
- def __init__(self, mixpeek):
56
- self.mixpeek = mixpeek
57
- self.text = self.Text(self.mixpeek)
58
-
59
- class Text:
60
- def __init__(self, mixpeek):
61
- self.mixpeek = mixpeek
62
- self.parse_url = f"{self.mixpeek.base_url}/parsers"
63
-
64
- def extract(self, file_url, should_chunk=True):
65
- url = self.parse_url + "?should_chunk=" + str(should_chunk)
66
- return self.mixpeek._send_post(url, {"file_url": file_url})
67
-
68
- def chunk(self, corpus):
69
- pass
70
-
71
- class Index:
72
- def __init__(self):
73
- pass
50
+ __all__ = [
51
+ "AudioParams",
52
+ "BadRequestError",
53
+ "ConfigsRequest",
54
+ "ConfigsResponse",
55
+ "Connection",
56
+ "ConnectionEngine",
57
+ "CsvParams",
58
+ "DestinationSchema",
59
+ "EmbeddingRequest",
60
+ "EmbeddingResponse",
61
+ "ErrorMessage",
62
+ "ErrorResponse",
63
+ "FieldSchema",
64
+ "FieldType",
65
+ "ForbiddenError",
66
+ "GenerationResponse",
67
+ "HtmlParams",
68
+ "HttpValidationError",
69
+ "ImageParams",
70
+ "InternalServerError",
71
+ "Message",
72
+ "Metadata",
73
+ "Modality",
74
+ "Model",
75
+ "NotFoundError",
76
+ "PdfParams",
77
+ "PipelineResponse",
78
+ "PptParams",
79
+ "PptxParams",
80
+ "Settings",
81
+ "SourceSchema",
82
+ "TxtParams",
83
+ "UnauthorizedError",
84
+ "UnprocessableEntityError",
85
+ "ValidationError",
86
+ "ValidationErrorLocItem",
87
+ "VideoParams",
88
+ "WorkflowResponse",
89
+ "WorkflowSettings",
90
+ "XlsxParams",
91
+ "__version__",
92
+ "generators",
93
+ "parse",
94
+ "pipelines",
95
+ "storage",
96
+ "workflows",
97
+ ]
mixpeek/base_client.py ADDED
@@ -0,0 +1,128 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import os
4
+ import typing
5
+
6
+ import httpx
7
+
8
+ from .core.api_error import ApiError
9
+ from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
10
+ from .generators.client import AsyncGeneratorsClient, GeneratorsClient
11
+ from .parse.client import AsyncParseClient, ParseClient
12
+ from .pipelines.client import AsyncPipelinesClient, PipelinesClient
13
+ from .storage.client import AsyncStorageClient, StorageClient
14
+ from .workflows.client import AsyncWorkflowsClient, WorkflowsClient
15
+
16
+
17
+ class BaseMixpeek:
18
+ """
19
+ Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propogate to these functions.
20
+
21
+ Parameters:
22
+ - base_url: str. The base url to use for requests from the client.
23
+
24
+ - authorization: typing.Optional[str].
25
+
26
+ - index_id: typing.Optional[str].
27
+
28
+ - api_key: typing.Optional[typing.Union[str, typing.Callable[[], str]]].
29
+
30
+ - timeout: typing.Optional[float]. The timeout to be used, in seconds, for requests by default the timeout is 60 seconds, unless a custom httpx client is used, in which case a default is not set.
31
+
32
+ - httpx_client: typing.Optional[httpx.Client]. The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration.
33
+ ---
34
+ from mixpeek.client import Mixpeek
35
+
36
+ client = Mixpeek(
37
+ authorization="YOUR_AUTHORIZATION",
38
+ index_id="YOUR_INDEX_ID",
39
+ api_key="YOUR_API_KEY",
40
+ base_url="https://yourhost.com/path/to/api",
41
+ )
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ *,
47
+ base_url: str,
48
+ authorization: typing.Optional[str] = None,
49
+ index_id: typing.Optional[str] = None,
50
+ api_key: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = os.getenv("MIXPEEK_API_KEY"),
51
+ timeout: typing.Optional[float] = None,
52
+ httpx_client: typing.Optional[httpx.Client] = None
53
+ ):
54
+ _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None
55
+ if api_key is None:
56
+ raise ApiError(
57
+ body="The client must be instantiated be either passing in api_key or setting MIXPEEK_API_KEY"
58
+ )
59
+ self._client_wrapper = SyncClientWrapper(
60
+ base_url=base_url,
61
+ authorization=authorization,
62
+ index_id=index_id,
63
+ api_key=api_key,
64
+ httpx_client=httpx.Client(timeout=_defaulted_timeout) if httpx_client is None else httpx_client,
65
+ timeout=_defaulted_timeout,
66
+ )
67
+ self.pipelines = PipelinesClient(client_wrapper=self._client_wrapper)
68
+ self.parse = ParseClient(client_wrapper=self._client_wrapper)
69
+ self.workflows = WorkflowsClient(client_wrapper=self._client_wrapper)
70
+ self.generators = GeneratorsClient(client_wrapper=self._client_wrapper)
71
+ self.storage = StorageClient(client_wrapper=self._client_wrapper)
72
+
73
+
74
+ class AsyncBaseMixpeek:
75
+ """
76
+ Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propogate to these functions.
77
+
78
+ Parameters:
79
+ - base_url: str. The base url to use for requests from the client.
80
+
81
+ - authorization: typing.Optional[str].
82
+
83
+ - index_id: typing.Optional[str].
84
+
85
+ - api_key: typing.Optional[typing.Union[str, typing.Callable[[], str]]].
86
+
87
+ - timeout: typing.Optional[float]. The timeout to be used, in seconds, for requests by default the timeout is 60 seconds, unless a custom httpx client is used, in which case a default is not set.
88
+
89
+ - httpx_client: typing.Optional[httpx.AsyncClient]. The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration.
90
+ ---
91
+ from mixpeek.client import AsyncMixpeek
92
+
93
+ client = AsyncMixpeek(
94
+ authorization="YOUR_AUTHORIZATION",
95
+ index_id="YOUR_INDEX_ID",
96
+ api_key="YOUR_API_KEY",
97
+ base_url="https://yourhost.com/path/to/api",
98
+ )
99
+ """
100
+
101
+ def __init__(
102
+ self,
103
+ *,
104
+ base_url: str,
105
+ authorization: typing.Optional[str] = None,
106
+ index_id: typing.Optional[str] = None,
107
+ api_key: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = os.getenv("MIXPEEK_API_KEY"),
108
+ timeout: typing.Optional[float] = None,
109
+ httpx_client: typing.Optional[httpx.AsyncClient] = None
110
+ ):
111
+ _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None
112
+ if api_key is None:
113
+ raise ApiError(
114
+ body="The client must be instantiated be either passing in api_key or setting MIXPEEK_API_KEY"
115
+ )
116
+ self._client_wrapper = AsyncClientWrapper(
117
+ base_url=base_url,
118
+ authorization=authorization,
119
+ index_id=index_id,
120
+ api_key=api_key,
121
+ httpx_client=httpx.AsyncClient(timeout=_defaulted_timeout) if httpx_client is None else httpx_client,
122
+ timeout=_defaulted_timeout,
123
+ )
124
+ self.pipelines = AsyncPipelinesClient(client_wrapper=self._client_wrapper)
125
+ self.parse = AsyncParseClient(client_wrapper=self._client_wrapper)
126
+ self.workflows = AsyncWorkflowsClient(client_wrapper=self._client_wrapper)
127
+ self.generators = AsyncGeneratorsClient(client_wrapper=self._client_wrapper)
128
+ self.storage = AsyncStorageClient(client_wrapper=self._client_wrapper)
mixpeek/client.py ADDED
@@ -0,0 +1,65 @@
1
+
2
+ import typing
3
+ import httpx
4
+
5
+ from .base_client import BaseMixpeek, \
6
+ AsyncBaseMixpeek
7
+ from .types.message import Message
8
+ from .types.model import Model
9
+ from .types.settings import Settings
10
+ from .types.generation_response import GenerationResponse
11
+ from .core.request_options import RequestOptions
12
+
13
+
14
+ # this is used as the default value for optional parameters
15
+ OMIT = typing.cast(typing.Any, ...)
16
+
17
+
18
+ class Mixpeek(BaseMixpeek):
19
+
20
+ def generate(
21
+ self,
22
+ *,
23
+ model: Model,
24
+ # Pydantic model that represents the JSON schema of the response
25
+ response_format: typing.Optional[typing.Any],
26
+ context: typing.Optional[str] = OMIT,
27
+ messages: typing.Sequence[Message],
28
+ settings: typing.Optional[Settings] = OMIT,
29
+ request_options: typing.Optional[RequestOptions] = None,
30
+ ) -> GenerationResponse:
31
+ if response_format is not None:
32
+ response_format = response_format.model_json_schema()
33
+ return self.generators.generate(
34
+ model=model,
35
+ response_format=response_format,
36
+ context=context,
37
+ messages=messages,
38
+ settings=settings,
39
+ request_options=request_options,
40
+ )
41
+
42
+
43
+ class AsyncMixpeek(AsyncBaseMixpeek):
44
+
45
+ async def generate(
46
+ self,
47
+ *,
48
+ model: Model,
49
+ # Pydantic model that represents the JSON schema of the response
50
+ response_format: typing.Optional[typing.Any],
51
+ context: typing.Optional[str] = OMIT,
52
+ messages: typing.Sequence[Message],
53
+ settings: typing.Optional[Settings] = OMIT,
54
+ request_options: typing.Optional[RequestOptions] = None,
55
+ ) -> GenerationResponse:
56
+ if response_format is not None:
57
+ response_format = response_format.model_json_schema()
58
+ return await self.generators.generate(
59
+ model=model,
60
+ response_format=response_format,
61
+ context=context,
62
+ messages=messages,
63
+ settings=settings,
64
+ request_options=request_options,
65
+ )
@@ -0,0 +1,25 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ from .api_error import ApiError
4
+ from .client_wrapper import AsyncClientWrapper, BaseClientWrapper, SyncClientWrapper
5
+ from .datetime_utils import serialize_datetime
6
+ from .file import File, convert_file_dict_to_httpx_tuples
7
+ from .http_client import AsyncHttpClient, HttpClient
8
+ from .jsonable_encoder import jsonable_encoder
9
+ from .remove_none_from_dict import remove_none_from_dict
10
+ from .request_options import RequestOptions
11
+
12
+ __all__ = [
13
+ "ApiError",
14
+ "AsyncClientWrapper",
15
+ "AsyncHttpClient",
16
+ "BaseClientWrapper",
17
+ "File",
18
+ "HttpClient",
19
+ "RequestOptions",
20
+ "SyncClientWrapper",
21
+ "convert_file_dict_to_httpx_tuples",
22
+ "jsonable_encoder",
23
+ "remove_none_from_dict",
24
+ "serialize_datetime",
25
+ ]
@@ -0,0 +1,15 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import typing
4
+
5
+
6
+ class ApiError(Exception):
7
+ status_code: typing.Optional[int]
8
+ body: typing.Any
9
+
10
+ def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None):
11
+ self.status_code = status_code
12
+ self.body = body
13
+
14
+ def __str__(self) -> str:
15
+ return f"status_code: {self.status_code}, body: {self.body}"
@@ -0,0 +1,83 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import typing
4
+
5
+ import httpx
6
+
7
+ from .http_client import AsyncHttpClient, HttpClient
8
+
9
+
10
+ class BaseClientWrapper:
11
+ def __init__(
12
+ self,
13
+ *,
14
+ authorization: typing.Optional[str] = None,
15
+ index_id: typing.Optional[str] = None,
16
+ api_key: typing.Union[str, typing.Callable[[], str]],
17
+ base_url: str,
18
+ timeout: typing.Optional[float] = None,
19
+ ):
20
+ self._authorization = authorization
21
+ self._index_id = index_id
22
+ self._api_key = api_key
23
+ self._base_url = base_url
24
+ self._timeout = timeout
25
+
26
+ def get_headers(self) -> typing.Dict[str, str]:
27
+ headers: typing.Dict[str, str] = {
28
+ "X-Fern-Language": "Python",
29
+ "X-Fern-SDK-Name": "mixpeek",
30
+ "X-Fern-SDK-Version": "0.6.1",
31
+ }
32
+ if self._authorization is not None:
33
+ headers["Authorization"] = self._authorization
34
+ if self._index_id is not None:
35
+ headers["index-id"] = self._index_id
36
+ headers["Authorization"] = f"Bearer {self._get_api_key()}"
37
+ return headers
38
+
39
+ def _get_api_key(self) -> str:
40
+ if isinstance(self._api_key, str):
41
+ return self._api_key
42
+ else:
43
+ return self._api_key()
44
+
45
+ def get_base_url(self) -> str:
46
+ return self._base_url
47
+
48
+ def get_timeout(self) -> typing.Optional[float]:
49
+ return self._timeout
50
+
51
+
52
+ class SyncClientWrapper(BaseClientWrapper):
53
+ def __init__(
54
+ self,
55
+ *,
56
+ authorization: typing.Optional[str] = None,
57
+ index_id: typing.Optional[str] = None,
58
+ api_key: typing.Union[str, typing.Callable[[], str]],
59
+ base_url: str,
60
+ timeout: typing.Optional[float] = None,
61
+ httpx_client: httpx.Client,
62
+ ):
63
+ super().__init__(
64
+ authorization=authorization, index_id=index_id, api_key=api_key, base_url=base_url, timeout=timeout
65
+ )
66
+ self.httpx_client = HttpClient(httpx_client=httpx_client)
67
+
68
+
69
+ class AsyncClientWrapper(BaseClientWrapper):
70
+ def __init__(
71
+ self,
72
+ *,
73
+ authorization: typing.Optional[str] = None,
74
+ index_id: typing.Optional[str] = None,
75
+ api_key: typing.Union[str, typing.Callable[[], str]],
76
+ base_url: str,
77
+ timeout: typing.Optional[float] = None,
78
+ httpx_client: httpx.AsyncClient,
79
+ ):
80
+ super().__init__(
81
+ authorization=authorization, index_id=index_id, api_key=api_key, base_url=base_url, timeout=timeout
82
+ )
83
+ self.httpx_client = AsyncHttpClient(httpx_client=httpx_client)
@@ -0,0 +1,28 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import datetime as dt
4
+
5
+
6
+ def serialize_datetime(v: dt.datetime) -> str:
7
+ """
8
+ Serialize a datetime including timezone info.
9
+
10
+ Uses the timezone info provided if present, otherwise uses the current runtime's timezone info.
11
+
12
+ UTC datetimes end in "Z" while all other timezones are represented as offset from UTC, e.g. +05:00.
13
+ """
14
+
15
+ def _serialize_zoned_datetime(v: dt.datetime) -> str:
16
+ if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None):
17
+ # UTC is a special case where we use "Z" at the end instead of "+00:00"
18
+ return v.isoformat().replace("+00:00", "Z")
19
+ else:
20
+ # Delegate to the typical +/- offset format
21
+ return v.isoformat()
22
+
23
+ if v.tzinfo is not None:
24
+ return _serialize_zoned_datetime(v)
25
+ else:
26
+ local_tz = dt.datetime.now().astimezone().tzinfo
27
+ localized_dt = v.replace(tzinfo=local_tz)
28
+ return _serialize_zoned_datetime(localized_dt)
mixpeek/core/file.py ADDED
@@ -0,0 +1,38 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import typing
4
+
5
+ # File typing inspired by the flexibility of types within the httpx library
6
+ # https://github.com/encode/httpx/blob/master/httpx/_types.py
7
+ FileContent = typing.Union[typing.IO[bytes], bytes, str]
8
+ File = typing.Union[
9
+ # file (or bytes)
10
+ FileContent,
11
+ # (filename, file (or bytes))
12
+ typing.Tuple[typing.Optional[str], FileContent],
13
+ # (filename, file (or bytes), content_type)
14
+ typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]],
15
+ # (filename, file (or bytes), content_type, headers)
16
+ typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]],
17
+ ]
18
+
19
+
20
+ def convert_file_dict_to_httpx_tuples(
21
+ d: typing.Dict[str, typing.Union[File, typing.List[File]]]
22
+ ) -> typing.List[typing.Tuple[str, File]]:
23
+ """
24
+ The format we use is a list of tuples, where the first element is the
25
+ name of the file and the second is the file object. Typically HTTPX wants
26
+ a dict, but to be able to send lists of files, you have to use the list
27
+ approach (which also works for non-lists)
28
+ https://github.com/encode/httpx/pull/1032
29
+ """
30
+
31
+ httpx_tuples = []
32
+ for key, file_like in d.items():
33
+ if isinstance(file_like, list):
34
+ for file_like_item in file_like:
35
+ httpx_tuples.append((key, file_like_item))
36
+ else:
37
+ httpx_tuples.append((key, file_like))
38
+ return httpx_tuples
@@ -0,0 +1,130 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import asyncio
4
+ import email.utils
5
+ import re
6
+ import time
7
+ import typing
8
+ from contextlib import asynccontextmanager, contextmanager
9
+ from functools import wraps
10
+ from random import random
11
+
12
+ import httpx
13
+
14
+ INITIAL_RETRY_DELAY_SECONDS = 0.5
15
+ MAX_RETRY_DELAY_SECONDS = 10
16
+ MAX_RETRY_DELAY_SECONDS_FROM_HEADER = 30
17
+
18
+
19
+ def _parse_retry_after(response_headers: httpx.Headers) -> typing.Optional[float]:
20
+ """
21
+ This function parses the `Retry-After` header in a HTTP response and returns the number of seconds to wait.
22
+
23
+ Inspired by the urllib3 retry implementation.
24
+ """
25
+ retry_after_ms = response_headers.get("retry-after-ms")
26
+ if retry_after_ms is not None:
27
+ try:
28
+ return int(retry_after_ms) / 1000 if retry_after_ms > 0 else 0
29
+ except Exception:
30
+ pass
31
+
32
+ retry_after = response_headers.get("retry-after")
33
+ if retry_after is None:
34
+ return None
35
+
36
+ # Attempt to parse the header as an int.
37
+ if re.match(r"^\s*[0-9]+\s*$", retry_after):
38
+ seconds = float(retry_after)
39
+ # Fallback to parsing it as a date.
40
+ else:
41
+ retry_date_tuple = email.utils.parsedate_tz(retry_after)
42
+ if retry_date_tuple is None:
43
+ return None
44
+ if retry_date_tuple[9] is None: # Python 2
45
+ # Assume UTC if no timezone was specified
46
+ # On Python2.7, parsedate_tz returns None for a timezone offset
47
+ # instead of 0 if no timezone is given, where mktime_tz treats
48
+ # a None timezone offset as local time.
49
+ retry_date_tuple = retry_date_tuple[:9] + (0,) + retry_date_tuple[10:]
50
+
51
+ retry_date = email.utils.mktime_tz(retry_date_tuple)
52
+ seconds = retry_date - time.time()
53
+
54
+ if seconds < 0:
55
+ seconds = 0
56
+
57
+ return seconds
58
+
59
+
60
+ def _retry_timeout(response: httpx.Response, retries: int) -> float:
61
+ """
62
+ Determine the amount of time to wait before retrying a request.
63
+ This function begins by trying to parse a retry-after header from the response, and then proceeds to use exponential backoff
64
+ with a jitter to determine the number of seconds to wait.
65
+ """
66
+
67
+ # If the API asks us to wait a certain amount of time (and it's a reasonable amount), just do what it says.
68
+ retry_after = _parse_retry_after(response.headers)
69
+ if retry_after is not None and retry_after <= MAX_RETRY_DELAY_SECONDS_FROM_HEADER:
70
+ return retry_after
71
+
72
+ # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS.
73
+ retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS)
74
+
75
+ # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries.
76
+ timeout = retry_delay * (1 - 0.25 * random())
77
+ return timeout if timeout >= 0 else 0
78
+
79
+
80
+ def _should_retry(response: httpx.Response) -> bool:
81
+ retriable_400s = [429, 408, 409]
82
+ return response.status_code >= 500 or response.status_code in retriable_400s
83
+
84
+
85
+ class HttpClient:
86
+ def __init__(self, *, httpx_client: httpx.Client):
87
+ self.httpx_client = httpx_client
88
+
89
+ # Ensure that the signature of the `request` method is the same as the `httpx.Client.request` method
90
+ @wraps(httpx.Client.request)
91
+ def request(
92
+ self, *args: typing.Any, max_retries: int = 0, retries: int = 0, **kwargs: typing.Any
93
+ ) -> httpx.Response:
94
+ response = self.httpx_client.request(*args, **kwargs)
95
+ if _should_retry(response=response):
96
+ if max_retries > retries:
97
+ time.sleep(_retry_timeout(response=response, retries=retries))
98
+ return self.request(max_retries=max_retries, retries=retries + 1, *args, **kwargs)
99
+ return response
100
+
101
+ @wraps(httpx.Client.stream)
102
+ @contextmanager
103
+ def stream(self, *args: typing.Any, max_retries: int = 0, retries: int = 0, **kwargs: typing.Any) -> typing.Any:
104
+ with self.httpx_client.stream(*args, **kwargs) as stream:
105
+ yield stream
106
+
107
+
108
+ class AsyncHttpClient:
109
+ def __init__(self, *, httpx_client: httpx.AsyncClient):
110
+ self.httpx_client = httpx_client
111
+
112
+ # Ensure that the signature of the `request` method is the same as the `httpx.Client.request` method
113
+ @wraps(httpx.AsyncClient.request)
114
+ async def request(
115
+ self, *args: typing.Any, max_retries: int = 0, retries: int = 0, **kwargs: typing.Any
116
+ ) -> httpx.Response:
117
+ response = await self.httpx_client.request(*args, **kwargs)
118
+ if _should_retry(response=response):
119
+ if max_retries > retries:
120
+ await asyncio.sleep(_retry_timeout(response=response, retries=retries))
121
+ return await self.request(max_retries=max_retries, retries=retries + 1, *args, **kwargs)
122
+ return response
123
+
124
+ @wraps(httpx.AsyncClient.stream)
125
+ @asynccontextmanager
126
+ async def stream(
127
+ self, *args: typing.Any, max_retries: int = 0, retries: int = 0, **kwargs: typing.Any
128
+ ) -> typing.Any:
129
+ async with self.httpx_client.stream(*args, **kwargs) as stream:
130
+ yield stream