zep-cloud 0.0.1rc1__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 (63) hide show
  1. zep/__init__.py +68 -0
  2. zep/base_client.py +152 -0
  3. zep/client.py +57 -0
  4. zep/core/__init__.py +27 -0
  5. zep/core/api_error.py +15 -0
  6. zep/core/client_wrapper.py +45 -0
  7. zep/core/datetime_utils.py +28 -0
  8. zep/core/file.py +38 -0
  9. zep/core/http_client.py +130 -0
  10. zep/core/jsonable_encoder.py +99 -0
  11. zep/core/pydantic_utilities.py +12 -0
  12. zep/core/remove_none_from_dict.py +11 -0
  13. zep/core/request_options.py +32 -0
  14. zep/document/__init__.py +2 -0
  15. zep/document/client.py +2255 -0
  16. zep/environment.py +7 -0
  17. zep/errors/__init__.py +8 -0
  18. zep/errors/bad_request_error.py +9 -0
  19. zep/errors/internal_server_error.py +9 -0
  20. zep/errors/not_found_error.py +9 -0
  21. zep/errors/unauthorized_error.py +9 -0
  22. zep/external_clients/document.py +16 -0
  23. zep/external_clients/memory.py +16 -0
  24. zep/external_clients/user.py +16 -0
  25. zep/langchain/__init__.py +7 -0
  26. zep/langchain/helpers.py +16 -0
  27. zep/langchain/history.py +196 -0
  28. zep/langchain/vectorstore.py +554 -0
  29. zep/memory/__init__.py +5 -0
  30. zep/memory/client.py +2566 -0
  31. zep/memory/types/__init__.py +5 -0
  32. zep/memory/types/memory_get_request_memory_type.py +7 -0
  33. zep/py.typed +0 -0
  34. zep/types/__init__.py +51 -0
  35. zep/types/api_error.py +25 -0
  36. zep/types/classify_session_response.py +28 -0
  37. zep/types/create_document_request.py +28 -0
  38. zep/types/document_collection_response.py +47 -0
  39. zep/types/document_response.py +34 -0
  40. zep/types/document_search_result.py +35 -0
  41. zep/types/document_search_result_page.py +30 -0
  42. zep/types/memory.py +45 -0
  43. zep/types/memory_search_result.py +31 -0
  44. zep/types/message.py +66 -0
  45. zep/types/message_list_response.py +39 -0
  46. zep/types/models_zep_data_class.py +27 -0
  47. zep/types/question.py +25 -0
  48. zep/types/role_type.py +5 -0
  49. zep/types/search_scope.py +5 -0
  50. zep/types/search_type.py +5 -0
  51. zep/types/session.py +41 -0
  52. zep/types/success_response.py +25 -0
  53. zep/types/summary.py +47 -0
  54. zep/types/summary_list_response.py +28 -0
  55. zep/types/update_document_list_request.py +29 -0
  56. zep/types/user.py +38 -0
  57. zep/types/user_list_response.py +28 -0
  58. zep/user/__init__.py +2 -0
  59. zep/user/client.py +963 -0
  60. zep/version.py +4 -0
  61. zep_cloud-0.0.1rc1.dist-info/METADATA +123 -0
  62. zep_cloud-0.0.1rc1.dist-info/RECORD +63 -0
  63. zep_cloud-0.0.1rc1.dist-info/WHEEL +4 -0
zep/__init__.py ADDED
@@ -0,0 +1,68 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ from .types import (
4
+ ApiError,
5
+ ClassifySessionResponse,
6
+ CreateDocumentRequest,
7
+ DocumentCollectionResponse,
8
+ DocumentResponse,
9
+ DocumentSearchResult,
10
+ DocumentSearchResultPage,
11
+ Memory,
12
+ MemorySearchResult,
13
+ Message,
14
+ MessageListResponse,
15
+ ModelsZepDataClass,
16
+ Question,
17
+ RoleType,
18
+ SearchScope,
19
+ SearchType,
20
+ Session,
21
+ SuccessResponse,
22
+ Summary,
23
+ SummaryListResponse,
24
+ UpdateDocumentListRequest,
25
+ User,
26
+ UserListResponse,
27
+ )
28
+ from .errors import BadRequestError, InternalServerError, NotFoundError, UnauthorizedError
29
+ from . import document, memory, user
30
+ from .environment import ZepEnvironment
31
+ from .memory import MemoryGetRequestMemoryType
32
+ from .version import __version__
33
+
34
+ __all__ = [
35
+ "ApiError",
36
+ "BadRequestError",
37
+ "ClassifySessionResponse",
38
+ "CreateDocumentRequest",
39
+ "DocumentCollectionResponse",
40
+ "DocumentResponse",
41
+ "DocumentSearchResult",
42
+ "DocumentSearchResultPage",
43
+ "InternalServerError",
44
+ "Memory",
45
+ "MemoryGetRequestMemoryType",
46
+ "MemorySearchResult",
47
+ "Message",
48
+ "MessageListResponse",
49
+ "ModelsZepDataClass",
50
+ "NotFoundError",
51
+ "Question",
52
+ "RoleType",
53
+ "SearchScope",
54
+ "SearchType",
55
+ "Session",
56
+ "SuccessResponse",
57
+ "Summary",
58
+ "SummaryListResponse",
59
+ "UnauthorizedError",
60
+ "UpdateDocumentListRequest",
61
+ "User",
62
+ "UserListResponse",
63
+ "ZepEnvironment",
64
+ "__version__",
65
+ "document",
66
+ "memory",
67
+ "user",
68
+ ]
zep/base_client.py ADDED
@@ -0,0 +1,152 @@
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 .document.client import AsyncDocumentClient, DocumentClient
11
+ from .environment import ZepEnvironment
12
+ from .memory.client import AsyncMemoryClient, MemoryClient
13
+ from .user.client import AsyncUserClient, UserClient
14
+
15
+
16
+ class BaseClient:
17
+ """
18
+ 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.
19
+
20
+ Parameters
21
+ ----------
22
+ base_url : typing.Optional[str]
23
+ The base url to use for requests from the client.
24
+
25
+ environment : ZepEnvironment
26
+ The environment to use for requests from the client. from .environment import ZepEnvironment
27
+
28
+
29
+
30
+ Defaults to ZepEnvironment.DEFAULT
31
+
32
+
33
+
34
+ api_key : typing.Optional[str]
35
+ timeout : typing.Optional[float]
36
+ 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.
37
+
38
+ follow_redirects : typing.Optional[bool]
39
+ Whether the default httpx client follows redirects or not, this is irrelevant if a custom httpx client is passed in.
40
+
41
+ httpx_client : typing.Optional[httpx.Client]
42
+ 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.
43
+
44
+ Examples
45
+ --------
46
+ from zep.client import Zep
47
+
48
+ client = Zep(
49
+ api_key="YOUR_API_KEY",
50
+ )
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ *,
56
+ base_url: typing.Optional[str] = None,
57
+ environment: ZepEnvironment = ZepEnvironment.DEFAULT,
58
+ api_key: typing.Optional[str] = os.getenv("ZEP_API_KEY"),
59
+ timeout: typing.Optional[float] = None,
60
+ follow_redirects: typing.Optional[bool] = True,
61
+ httpx_client: typing.Optional[httpx.Client] = None
62
+ ):
63
+ _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None
64
+ if api_key is None:
65
+ raise ApiError(body="The client must be instantiated be either passing in api_key or setting ZEP_API_KEY")
66
+ self._client_wrapper = SyncClientWrapper(
67
+ base_url=_get_base_url(base_url=base_url, environment=environment),
68
+ api_key=api_key,
69
+ httpx_client=httpx_client
70
+ if httpx_client is not None
71
+ else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects)
72
+ if follow_redirects is not None
73
+ else httpx.Client(timeout=_defaulted_timeout),
74
+ timeout=_defaulted_timeout,
75
+ )
76
+ self.document = DocumentClient(client_wrapper=self._client_wrapper)
77
+ self.memory = MemoryClient(client_wrapper=self._client_wrapper)
78
+ self.user = UserClient(client_wrapper=self._client_wrapper)
79
+
80
+
81
+ class AsyncBaseClient:
82
+ """
83
+ 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.
84
+
85
+ Parameters
86
+ ----------
87
+ base_url : typing.Optional[str]
88
+ The base url to use for requests from the client.
89
+
90
+ environment : ZepEnvironment
91
+ The environment to use for requests from the client. from .environment import ZepEnvironment
92
+
93
+
94
+
95
+ Defaults to ZepEnvironment.DEFAULT
96
+
97
+
98
+
99
+ api_key : typing.Optional[str]
100
+ timeout : typing.Optional[float]
101
+ 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.
102
+
103
+ follow_redirects : typing.Optional[bool]
104
+ Whether the default httpx client follows redirects or not, this is irrelevant if a custom httpx client is passed in.
105
+
106
+ httpx_client : typing.Optional[httpx.AsyncClient]
107
+ 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.
108
+
109
+ Examples
110
+ --------
111
+ from zep.client import AsyncZep
112
+
113
+ client = AsyncZep(
114
+ api_key="YOUR_API_KEY",
115
+ )
116
+ """
117
+
118
+ def __init__(
119
+ self,
120
+ *,
121
+ base_url: typing.Optional[str] = None,
122
+ environment: ZepEnvironment = ZepEnvironment.DEFAULT,
123
+ api_key: typing.Optional[str] = os.getenv("ZEP_API_KEY"),
124
+ timeout: typing.Optional[float] = None,
125
+ follow_redirects: typing.Optional[bool] = True,
126
+ httpx_client: typing.Optional[httpx.AsyncClient] = None
127
+ ):
128
+ _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None
129
+ if api_key is None:
130
+ raise ApiError(body="The client must be instantiated be either passing in api_key or setting ZEP_API_KEY")
131
+ self._client_wrapper = AsyncClientWrapper(
132
+ base_url=_get_base_url(base_url=base_url, environment=environment),
133
+ api_key=api_key,
134
+ httpx_client=httpx_client
135
+ if httpx_client is not None
136
+ else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects)
137
+ if follow_redirects is not None
138
+ else httpx.AsyncClient(timeout=_defaulted_timeout),
139
+ timeout=_defaulted_timeout,
140
+ )
141
+ self.document = AsyncDocumentClient(client_wrapper=self._client_wrapper)
142
+ self.memory = AsyncMemoryClient(client_wrapper=self._client_wrapper)
143
+ self.user = AsyncUserClient(client_wrapper=self._client_wrapper)
144
+
145
+
146
+ def _get_base_url(*, base_url: typing.Optional[str] = None, environment: ZepEnvironment) -> str:
147
+ if base_url is not None:
148
+ return base_url
149
+ elif environment is not None:
150
+ return environment.value
151
+ else:
152
+ raise Exception("Please pass in either base_url or environment to construct the client")
zep/client.py ADDED
@@ -0,0 +1,57 @@
1
+ from .base_client import \
2
+ BaseClient, AsyncBaseClient
3
+ import typing
4
+ import os
5
+ import httpx
6
+ from .environment import ZepEnvironment
7
+ from .external_clients.memory import MemoryClient, AsyncMemoryClient
8
+ from .external_clients.document import DocumentClient, AsyncDocumentClient
9
+ from .external_clients.user import UserClient, AsyncUserClient
10
+
11
+
12
+ class Zep(BaseClient):
13
+ def __init__(
14
+ self,
15
+ *,
16
+ base_url: typing.Optional[str] = None,
17
+ environment: ZepEnvironment = ZepEnvironment.DEFAULT,
18
+ api_key: typing.Optional[str] = os.getenv("ZEP_API_KEY"),
19
+ timeout: typing.Optional[float] = None,
20
+ follow_redirects: typing.Optional[bool] = None,
21
+ httpx_client: typing.Optional[httpx.Client] = None
22
+ ):
23
+ super().__init__(
24
+ base_url=base_url,
25
+ environment=environment,
26
+ api_key=api_key,
27
+ timeout=timeout,
28
+ follow_redirects=follow_redirects,
29
+ httpx_client=httpx_client
30
+ )
31
+ self.memory = MemoryClient(client_wrapper=self._client_wrapper)
32
+ self.document = DocumentClient(client_wrapper=self._client_wrapper)
33
+ self.user = UserClient(client_wrapper=self._client_wrapper)
34
+
35
+
36
+ class AsyncZep(AsyncBaseClient):
37
+ def __init__(
38
+ self,
39
+ *,
40
+ base_url: typing.Optional[str] = None,
41
+ environment: ZepEnvironment = ZepEnvironment.DEFAULT,
42
+ api_key: typing.Optional[str] = os.getenv("ZEP_API_KEY"),
43
+ timeout: typing.Optional[float] = None,
44
+ follow_redirects: typing.Optional[bool] = None,
45
+ httpx_client: typing.Optional[httpx.AsyncClient] = None
46
+ ):
47
+ super().__init__(
48
+ base_url=base_url,
49
+ environment=environment,
50
+ api_key=api_key,
51
+ timeout=timeout,
52
+ follow_redirects=follow_redirects,
53
+ httpx_client=httpx_client
54
+ )
55
+ self.memory = AsyncMemoryClient(client_wrapper=self._client_wrapper)
56
+ self.document = AsyncDocumentClient(client_wrapper=self._client_wrapper)
57
+ self.user = AsyncUserClient(client_wrapper=self._client_wrapper)
zep/core/__init__.py ADDED
@@ -0,0 +1,27 @@
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 .pydantic_utilities import pydantic_v1
10
+ from .remove_none_from_dict import remove_none_from_dict
11
+ from .request_options import RequestOptions
12
+
13
+ __all__ = [
14
+ "ApiError",
15
+ "AsyncClientWrapper",
16
+ "AsyncHttpClient",
17
+ "BaseClientWrapper",
18
+ "File",
19
+ "HttpClient",
20
+ "RequestOptions",
21
+ "SyncClientWrapper",
22
+ "convert_file_dict_to_httpx_tuples",
23
+ "jsonable_encoder",
24
+ "pydantic_v1",
25
+ "remove_none_from_dict",
26
+ "serialize_datetime",
27
+ ]
zep/core/api_error.py ADDED
@@ -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,45 @@
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__(self, *, api_key: str, base_url: str, timeout: typing.Optional[float] = None):
12
+ self.api_key = api_key
13
+ self._base_url = base_url
14
+ self._timeout = timeout
15
+
16
+ def get_headers(self) -> typing.Dict[str, str]:
17
+ headers: typing.Dict[str, str] = {
18
+ "X-Fern-Language": "Python",
19
+ "X-Fern-SDK-Name": "zep",
20
+ "X-Fern-SDK-Version": "1.0.0",
21
+ }
22
+ headers["Authorization"] = f"Api-Key {self.api_key}"
23
+ return headers
24
+
25
+ def get_base_url(self) -> str:
26
+ return self._base_url
27
+
28
+ def get_timeout(self) -> typing.Optional[float]:
29
+ return self._timeout
30
+
31
+
32
+ class SyncClientWrapper(BaseClientWrapper):
33
+ def __init__(
34
+ self, *, api_key: str, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client
35
+ ):
36
+ super().__init__(api_key=api_key, base_url=base_url, timeout=timeout)
37
+ self.httpx_client = HttpClient(httpx_client=httpx_client)
38
+
39
+
40
+ class AsyncClientWrapper(BaseClientWrapper):
41
+ def __init__(
42
+ self, *, api_key: str, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient
43
+ ):
44
+ super().__init__(api_key=api_key, base_url=base_url, timeout=timeout)
45
+ 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)
zep/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
@@ -0,0 +1,99 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ """
4
+ jsonable_encoder converts a Python object to a JSON-friendly dict
5
+ (e.g. datetimes to strings, Pydantic models to dicts).
6
+
7
+ Taken from FastAPI, and made a bit simpler
8
+ https://github.com/tiangolo/fastapi/blob/master/fastapi/encoders.py
9
+ """
10
+
11
+ import dataclasses
12
+ import datetime as dt
13
+ from collections import defaultdict
14
+ from enum import Enum
15
+ from pathlib import PurePath
16
+ from types import GeneratorType
17
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
18
+
19
+ from .datetime_utils import serialize_datetime
20
+ from .pydantic_utilities import pydantic_v1
21
+
22
+ SetIntStr = Set[Union[int, str]]
23
+ DictIntStrAny = Dict[Union[int, str], Any]
24
+
25
+
26
+ def generate_encoders_by_class_tuples(
27
+ type_encoder_map: Dict[Any, Callable[[Any], Any]]
28
+ ) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]:
29
+ encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(tuple)
30
+ for type_, encoder in type_encoder_map.items():
31
+ encoders_by_class_tuples[encoder] += (type_,)
32
+ return encoders_by_class_tuples
33
+
34
+
35
+ encoders_by_class_tuples = generate_encoders_by_class_tuples(pydantic_v1.json.ENCODERS_BY_TYPE)
36
+
37
+
38
+ def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any:
39
+ custom_encoder = custom_encoder or {}
40
+ if custom_encoder:
41
+ if type(obj) in custom_encoder:
42
+ return custom_encoder[type(obj)](obj)
43
+ else:
44
+ for encoder_type, encoder_instance in custom_encoder.items():
45
+ if isinstance(obj, encoder_type):
46
+ return encoder_instance(obj)
47
+ if isinstance(obj, pydantic_v1.BaseModel):
48
+ encoder = getattr(obj.__config__, "json_encoders", {})
49
+ if custom_encoder:
50
+ encoder.update(custom_encoder)
51
+ obj_dict = obj.dict(by_alias=True)
52
+ if "__root__" in obj_dict:
53
+ obj_dict = obj_dict["__root__"]
54
+ return jsonable_encoder(obj_dict, custom_encoder=encoder)
55
+ if dataclasses.is_dataclass(obj):
56
+ obj_dict = dataclasses.asdict(obj)
57
+ return jsonable_encoder(obj_dict, custom_encoder=custom_encoder)
58
+ if isinstance(obj, Enum):
59
+ return obj.value
60
+ if isinstance(obj, PurePath):
61
+ return str(obj)
62
+ if isinstance(obj, (str, int, float, type(None))):
63
+ return obj
64
+ if isinstance(obj, dt.datetime):
65
+ return serialize_datetime(obj)
66
+ if isinstance(obj, dt.date):
67
+ return str(obj)
68
+ if isinstance(obj, dict):
69
+ encoded_dict = {}
70
+ allowed_keys = set(obj.keys())
71
+ for key, value in obj.items():
72
+ if key in allowed_keys:
73
+ encoded_key = jsonable_encoder(key, custom_encoder=custom_encoder)
74
+ encoded_value = jsonable_encoder(value, custom_encoder=custom_encoder)
75
+ encoded_dict[encoded_key] = encoded_value
76
+ return encoded_dict
77
+ if isinstance(obj, (list, set, frozenset, GeneratorType, tuple)):
78
+ encoded_list = []
79
+ for item in obj:
80
+ encoded_list.append(jsonable_encoder(item, custom_encoder=custom_encoder))
81
+ return encoded_list
82
+
83
+ if type(obj) in pydantic_v1.json.ENCODERS_BY_TYPE:
84
+ return pydantic_v1.json.ENCODERS_BY_TYPE[type(obj)](obj)
85
+ for encoder, classes_tuple in encoders_by_class_tuples.items():
86
+ if isinstance(obj, classes_tuple):
87
+ return encoder(obj)
88
+
89
+ try:
90
+ data = dict(obj)
91
+ except Exception as e:
92
+ errors: List[Exception] = []
93
+ errors.append(e)
94
+ try:
95
+ data = vars(obj)
96
+ except Exception as e:
97
+ errors.append(e)
98
+ raise ValueError(errors) from e
99
+ return jsonable_encoder(data, custom_encoder=custom_encoder)
@@ -0,0 +1,12 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import pydantic
4
+
5
+ IS_PYDANTIC_V2 = pydantic.VERSION.startswith("2.")
6
+
7
+ if IS_PYDANTIC_V2:
8
+ import pydantic.v1 as pydantic_v1 # type: ignore # nopycln: import
9
+ else:
10
+ import pydantic as pydantic_v1 # type: ignore # nopycln: import
11
+
12
+ __all__ = ["pydantic_v1"]