phenoml 0.0.6__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 (244) hide show
  1. phenoml/__init__.py +30 -0
  2. phenoml/agent/__init__.py +56 -0
  3. phenoml/agent/client.py +939 -0
  4. phenoml/agent/errors/__init__.py +11 -0
  5. phenoml/agent/errors/bad_request_error.py +10 -0
  6. phenoml/agent/errors/forbidden_error.py +10 -0
  7. phenoml/agent/errors/internal_server_error.py +10 -0
  8. phenoml/agent/errors/not_found_error.py +10 -0
  9. phenoml/agent/errors/unauthorized_error.py +10 -0
  10. phenoml/agent/prompts/__init__.py +7 -0
  11. phenoml/agent/prompts/client.py +707 -0
  12. phenoml/agent/prompts/raw_client.py +1345 -0
  13. phenoml/agent/prompts/types/__init__.py +8 -0
  14. phenoml/agent/prompts/types/prompts_delete_response.py +20 -0
  15. phenoml/agent/prompts/types/prompts_list_response.py +22 -0
  16. phenoml/agent/raw_client.py +1668 -0
  17. phenoml/agent/types/__init__.py +43 -0
  18. phenoml/agent/types/agent_chat_response.py +33 -0
  19. phenoml/agent/types/agent_create_request.py +53 -0
  20. phenoml/agent/types/agent_create_request_provider.py +5 -0
  21. phenoml/agent/types/agent_delete_response.py +20 -0
  22. phenoml/agent/types/agent_get_chat_messages_request_order.py +5 -0
  23. phenoml/agent/types/agent_get_chat_messages_response.py +22 -0
  24. phenoml/agent/types/agent_list_response.py +22 -0
  25. phenoml/agent/types/agent_prompts_response.py +22 -0
  26. phenoml/agent/types/agent_response.py +22 -0
  27. phenoml/agent/types/agent_template.py +58 -0
  28. phenoml/agent/types/agent_template_provider.py +5 -0
  29. phenoml/agent/types/chat_message_template.py +72 -0
  30. phenoml/agent/types/chat_session_template.py +67 -0
  31. phenoml/agent/types/json_patch.py +7 -0
  32. phenoml/agent/types/json_patch_operation.py +40 -0
  33. phenoml/agent/types/json_patch_operation_op.py +5 -0
  34. phenoml/agent/types/prompt_template.py +52 -0
  35. phenoml/agent/types/success_response.py +20 -0
  36. phenoml/authtoken/__init__.py +17 -0
  37. phenoml/authtoken/auth/__init__.py +7 -0
  38. phenoml/authtoken/auth/client.py +129 -0
  39. phenoml/authtoken/auth/raw_client.py +173 -0
  40. phenoml/authtoken/auth/types/__init__.py +7 -0
  41. phenoml/authtoken/auth/types/auth_generate_token_response.py +22 -0
  42. phenoml/authtoken/client.py +39 -0
  43. phenoml/authtoken/errors/__init__.py +8 -0
  44. phenoml/authtoken/errors/bad_request_error.py +10 -0
  45. phenoml/authtoken/errors/unauthorized_error.py +10 -0
  46. phenoml/authtoken/raw_client.py +13 -0
  47. phenoml/authtoken/types/__init__.py +8 -0
  48. phenoml/authtoken/types/bad_request_error_body.py +21 -0
  49. phenoml/authtoken/types/unauthorized_error_body.py +21 -0
  50. phenoml/client.py +177 -0
  51. phenoml/cohort/__init__.py +8 -0
  52. phenoml/cohort/client.py +113 -0
  53. phenoml/cohort/errors/__init__.py +9 -0
  54. phenoml/cohort/errors/bad_request_error.py +10 -0
  55. phenoml/cohort/errors/internal_server_error.py +10 -0
  56. phenoml/cohort/errors/unauthorized_error.py +10 -0
  57. phenoml/cohort/raw_client.py +185 -0
  58. phenoml/cohort/types/__init__.py +8 -0
  59. phenoml/cohort/types/cohort_response.py +33 -0
  60. phenoml/cohort/types/search_concept.py +37 -0
  61. phenoml/construe/__init__.py +45 -0
  62. phenoml/construe/client.py +399 -0
  63. phenoml/construe/errors/__init__.py +11 -0
  64. phenoml/construe/errors/bad_request_error.py +10 -0
  65. phenoml/construe/errors/conflict_error.py +10 -0
  66. phenoml/construe/errors/failed_dependency_error.py +10 -0
  67. phenoml/construe/errors/internal_server_error.py +10 -0
  68. phenoml/construe/errors/unauthorized_error.py +10 -0
  69. phenoml/construe/raw_client.py +706 -0
  70. phenoml/construe/types/__init__.py +41 -0
  71. phenoml/construe/types/bad_request_error_body.py +27 -0
  72. phenoml/construe/types/construe_cohort_request_config.py +37 -0
  73. phenoml/construe/types/construe_cohort_response.py +33 -0
  74. phenoml/construe/types/construe_cohort_response_queries_item.py +49 -0
  75. phenoml/construe/types/construe_cohort_response_queries_item_code_extract_results_item.py +31 -0
  76. phenoml/construe/types/construe_cohort_response_queries_item_code_extract_results_item_codes_item.py +32 -0
  77. phenoml/construe/types/construe_upload_code_system_response.py +19 -0
  78. phenoml/construe/types/extract_codes_result.py +22 -0
  79. phenoml/construe/types/extract_request_config.py +23 -0
  80. phenoml/construe/types/extract_request_config_chunking_method.py +5 -0
  81. phenoml/construe/types/extract_request_system.py +37 -0
  82. phenoml/construe/types/extracted_code_result.py +41 -0
  83. phenoml/construe/types/internal_server_error_body.py +27 -0
  84. phenoml/construe/types/unauthorized_error_body.py +27 -0
  85. phenoml/construe/types/upload_request_format.py +5 -0
  86. phenoml/core/__init__.py +52 -0
  87. phenoml/core/api_error.py +23 -0
  88. phenoml/core/client_wrapper.py +87 -0
  89. phenoml/core/datetime_utils.py +28 -0
  90. phenoml/core/file.py +67 -0
  91. phenoml/core/force_multipart.py +16 -0
  92. phenoml/core/http_client.py +543 -0
  93. phenoml/core/http_response.py +55 -0
  94. phenoml/core/jsonable_encoder.py +100 -0
  95. phenoml/core/pydantic_utilities.py +255 -0
  96. phenoml/core/query_encoder.py +58 -0
  97. phenoml/core/remove_none_from_dict.py +11 -0
  98. phenoml/core/request_options.py +35 -0
  99. phenoml/core/serialization.py +276 -0
  100. phenoml/environment.py +7 -0
  101. phenoml/fhir/__init__.py +36 -0
  102. phenoml/fhir/client.py +970 -0
  103. phenoml/fhir/errors/__init__.py +10 -0
  104. phenoml/fhir/errors/bad_request_error.py +10 -0
  105. phenoml/fhir/errors/internal_server_error.py +10 -0
  106. phenoml/fhir/errors/not_found_error.py +10 -0
  107. phenoml/fhir/errors/unauthorized_error.py +10 -0
  108. phenoml/fhir/raw_client.py +1385 -0
  109. phenoml/fhir/types/__init__.py +29 -0
  110. phenoml/fhir/types/error_response.py +36 -0
  111. phenoml/fhir/types/fhir_bundle.py +43 -0
  112. phenoml/fhir/types/fhir_bundle_entry_item.py +34 -0
  113. phenoml/fhir/types/fhir_bundle_entry_item_request.py +25 -0
  114. phenoml/fhir/types/fhir_bundle_entry_item_request_method.py +5 -0
  115. phenoml/fhir/types/fhir_bundle_entry_item_response.py +24 -0
  116. phenoml/fhir/types/fhir_patch_request_body_item.py +40 -0
  117. phenoml/fhir/types/fhir_patch_request_body_item_op.py +7 -0
  118. phenoml/fhir/types/fhir_resource.py +40 -0
  119. phenoml/fhir/types/fhir_resource_meta.py +28 -0
  120. phenoml/fhir/types/fhir_search_response.py +8 -0
  121. phenoml/fhir_provider/__init__.py +43 -0
  122. phenoml/fhir_provider/client.py +731 -0
  123. phenoml/fhir_provider/errors/__init__.py +11 -0
  124. phenoml/fhir_provider/errors/bad_request_error.py +10 -0
  125. phenoml/fhir_provider/errors/forbidden_error.py +10 -0
  126. phenoml/fhir_provider/errors/internal_server_error.py +10 -0
  127. phenoml/fhir_provider/errors/not_found_error.py +10 -0
  128. phenoml/fhir_provider/errors/unauthorized_error.py +10 -0
  129. phenoml/fhir_provider/raw_client.py +1445 -0
  130. phenoml/fhir_provider/types/__init__.py +35 -0
  131. phenoml/fhir_provider/types/auth_method.py +7 -0
  132. phenoml/fhir_provider/types/fhir_provider_auth_config.py +53 -0
  133. phenoml/fhir_provider/types/fhir_provider_delete_response.py +20 -0
  134. phenoml/fhir_provider/types/fhir_provider_list_response.py +22 -0
  135. phenoml/fhir_provider/types/fhir_provider_remove_auth_config_response.py +22 -0
  136. phenoml/fhir_provider/types/fhir_provider_response.py +22 -0
  137. phenoml/fhir_provider/types/fhir_provider_set_active_auth_config_response.py +22 -0
  138. phenoml/fhir_provider/types/fhir_provider_template.py +66 -0
  139. phenoml/fhir_provider/types/fhir_query_response.py +27 -0
  140. phenoml/fhir_provider/types/fhir_query_response_data.py +5 -0
  141. phenoml/fhir_provider/types/json_web_key.py +51 -0
  142. phenoml/fhir_provider/types/provider.py +8 -0
  143. phenoml/fhir_provider/types/service_account_key.py +35 -0
  144. phenoml/fhir_provider/types/smart_configuration.py +46 -0
  145. phenoml/lang2fhir/__init__.py +27 -0
  146. phenoml/lang2fhir/client.py +430 -0
  147. phenoml/lang2fhir/errors/__init__.py +11 -0
  148. phenoml/lang2fhir/errors/bad_request_error.py +10 -0
  149. phenoml/lang2fhir/errors/failed_dependency_error.py +10 -0
  150. phenoml/lang2fhir/errors/forbidden_error.py +10 -0
  151. phenoml/lang2fhir/errors/internal_server_error.py +10 -0
  152. phenoml/lang2fhir/errors/unauthorized_error.py +10 -0
  153. phenoml/lang2fhir/raw_client.py +788 -0
  154. phenoml/lang2fhir/types/__init__.py +19 -0
  155. phenoml/lang2fhir/types/create_request_resource.py +25 -0
  156. phenoml/lang2fhir/types/document_request_file_type.py +7 -0
  157. phenoml/lang2fhir/types/document_request_resource.py +5 -0
  158. phenoml/lang2fhir/types/fhir_resource.py +5 -0
  159. phenoml/lang2fhir/types/lang2fhir_upload_profile_response.py +23 -0
  160. phenoml/lang2fhir/types/search_response.py +33 -0
  161. phenoml/py.typed +0 -0
  162. phenoml/tools/__init__.py +37 -0
  163. phenoml/tools/client.py +359 -0
  164. phenoml/tools/errors/__init__.py +11 -0
  165. phenoml/tools/errors/bad_request_error.py +10 -0
  166. phenoml/tools/errors/failed_dependency_error.py +10 -0
  167. phenoml/tools/errors/forbidden_error.py +10 -0
  168. phenoml/tools/errors/internal_server_error.py +10 -0
  169. phenoml/tools/errors/unauthorized_error.py +10 -0
  170. phenoml/tools/mcp_server/__init__.py +7 -0
  171. phenoml/tools/mcp_server/client.py +336 -0
  172. phenoml/tools/mcp_server/raw_client.py +641 -0
  173. phenoml/tools/mcp_server/tools/__init__.py +4 -0
  174. phenoml/tools/mcp_server/tools/client.py +358 -0
  175. phenoml/tools/mcp_server/tools/raw_client.py +656 -0
  176. phenoml/tools/raw_client.py +696 -0
  177. phenoml/tools/types/__init__.py +27 -0
  178. phenoml/tools/types/cohort_response.py +49 -0
  179. phenoml/tools/types/lang2fhir_and_create_request_resource.py +25 -0
  180. phenoml/tools/types/lang2fhir_and_create_response.py +33 -0
  181. phenoml/tools/types/lang2fhir_and_search_response.py +40 -0
  182. phenoml/tools/types/mcp_server_response.py +33 -0
  183. phenoml/tools/types/mcp_server_response_data.py +51 -0
  184. phenoml/tools/types/mcp_server_tool_call_response.py +37 -0
  185. phenoml/tools/types/mcp_server_tool_response.py +33 -0
  186. phenoml/tools/types/mcp_server_tool_response_data.py +61 -0
  187. phenoml/tools/types/search_concept.py +41 -0
  188. phenoml/types/__init__.py +21 -0
  189. phenoml/types/cohort_response.py +5 -0
  190. phenoml/types/lang2fhir_and_create_response.py +5 -0
  191. phenoml/types/lang2fhir_and_search_response.py +5 -0
  192. phenoml/types/mcp_server_response.py +5 -0
  193. phenoml/types/mcp_server_tool_call_response.py +5 -0
  194. phenoml/types/mcp_server_tool_response.py +5 -0
  195. phenoml/types/search_concept.py +5 -0
  196. phenoml/version.py +3 -0
  197. phenoml/workflows/__init__.py +66 -0
  198. phenoml/workflows/client.py +210 -0
  199. phenoml/workflows/errors/__init__.py +11 -0
  200. phenoml/workflows/errors/bad_request_error.py +10 -0
  201. phenoml/workflows/errors/forbidden_error.py +10 -0
  202. phenoml/workflows/errors/internal_server_error.py +10 -0
  203. phenoml/workflows/errors/not_found_error.py +10 -0
  204. phenoml/workflows/errors/unauthorized_error.py +10 -0
  205. phenoml/workflows/mcp_server/__init__.py +7 -0
  206. phenoml/workflows/mcp_server/client.py +274 -0
  207. phenoml/workflows/mcp_server/raw_client.py +226 -0
  208. phenoml/workflows/mcp_server/tools/__init__.py +4 -0
  209. phenoml/workflows/mcp_server/tools/client.py +287 -0
  210. phenoml/workflows/mcp_server/tools/raw_client.py +244 -0
  211. phenoml/workflows/raw_client.py +169 -0
  212. phenoml/workflows/types/__init__.py +43 -0
  213. phenoml/workflows/types/create_workflow_response.py +44 -0
  214. phenoml/workflows/types/decision_node_definition.py +32 -0
  215. phenoml/workflows/types/execute_workflow_response.py +30 -0
  216. phenoml/workflows/types/execute_workflow_response_results.py +22 -0
  217. phenoml/workflows/types/lang2fhir_create_definition.py +37 -0
  218. phenoml/workflows/types/lang2fhir_search_definition.py +42 -0
  219. phenoml/workflows/types/list_workflows_response.py +39 -0
  220. phenoml/workflows/types/step_operation.py +26 -0
  221. phenoml/workflows/types/sub_workflow_definition.py +32 -0
  222. phenoml/workflows/types/workflow_config.py +27 -0
  223. phenoml/workflows/types/workflow_definition.py +57 -0
  224. phenoml/workflows/types/workflow_graph.py +23 -0
  225. phenoml/workflows/types/workflow_response.py +61 -0
  226. phenoml/workflows/types/workflow_response_graph.py +23 -0
  227. phenoml/workflows/types/workflow_step.py +55 -0
  228. phenoml/workflows/types/workflow_step_summary.py +47 -0
  229. phenoml/workflows/types/workflow_step_summary_type.py +5 -0
  230. phenoml/workflows/types/workflow_step_type.py +5 -0
  231. phenoml/workflows/workflows/__init__.py +19 -0
  232. phenoml/workflows/workflows/client.py +694 -0
  233. phenoml/workflows/workflows/raw_client.py +1266 -0
  234. phenoml/workflows/workflows/types/__init__.py +17 -0
  235. phenoml/workflows/workflows/types/create_workflow_request_fhir_provider_id.py +5 -0
  236. phenoml/workflows/workflows/types/update_workflow_request_fhir_provider_id.py +5 -0
  237. phenoml/workflows/workflows/types/workflows_delete_response.py +20 -0
  238. phenoml/workflows/workflows/types/workflows_get_response.py +26 -0
  239. phenoml/workflows/workflows/types/workflows_update_response.py +31 -0
  240. phenoml/wrapper_client.py +123 -0
  241. phenoml-0.0.6.dist-info/LICENSE +21 -0
  242. phenoml-0.0.6.dist-info/METADATA +192 -0
  243. phenoml-0.0.6.dist-info/RECORD +244 -0
  244. phenoml-0.0.6.dist-info/WHEEL +4 -0
@@ -0,0 +1,100 @@
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 base64
12
+ import dataclasses
13
+ import datetime as dt
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, Union
18
+
19
+ import pydantic
20
+ from .datetime_utils import serialize_datetime
21
+ from .pydantic_utilities import (
22
+ IS_PYDANTIC_V2,
23
+ encode_by_type,
24
+ to_jsonable_with_fallback,
25
+ )
26
+
27
+ SetIntStr = Set[Union[int, str]]
28
+ DictIntStrAny = Dict[Union[int, str], Any]
29
+
30
+
31
+ def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any:
32
+ custom_encoder = custom_encoder or {}
33
+ if custom_encoder:
34
+ if type(obj) in custom_encoder:
35
+ return custom_encoder[type(obj)](obj)
36
+ else:
37
+ for encoder_type, encoder_instance in custom_encoder.items():
38
+ if isinstance(obj, encoder_type):
39
+ return encoder_instance(obj)
40
+ if isinstance(obj, pydantic.BaseModel):
41
+ if IS_PYDANTIC_V2:
42
+ encoder = getattr(obj.model_config, "json_encoders", {}) # type: ignore # Pydantic v2
43
+ else:
44
+ encoder = getattr(obj.__config__, "json_encoders", {}) # type: ignore # Pydantic v1
45
+ if custom_encoder:
46
+ encoder.update(custom_encoder)
47
+ obj_dict = obj.dict(by_alias=True)
48
+ if "__root__" in obj_dict:
49
+ obj_dict = obj_dict["__root__"]
50
+ if "root" in obj_dict:
51
+ obj_dict = obj_dict["root"]
52
+ return jsonable_encoder(obj_dict, custom_encoder=encoder)
53
+ if dataclasses.is_dataclass(obj):
54
+ obj_dict = dataclasses.asdict(obj) # type: ignore
55
+ return jsonable_encoder(obj_dict, custom_encoder=custom_encoder)
56
+ if isinstance(obj, bytes):
57
+ return base64.b64encode(obj).decode("utf-8")
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
+ def fallback_serializer(o: Any) -> Any:
84
+ attempt_encode = encode_by_type(o)
85
+ if attempt_encode is not None:
86
+ return attempt_encode
87
+
88
+ try:
89
+ data = dict(o)
90
+ except Exception as e:
91
+ errors: List[Exception] = []
92
+ errors.append(e)
93
+ try:
94
+ data = vars(o)
95
+ except Exception as e:
96
+ errors.append(e)
97
+ raise ValueError(errors) from e
98
+ return jsonable_encoder(data, custom_encoder=custom_encoder)
99
+
100
+ return to_jsonable_with_fallback(obj, fallback_serializer)
@@ -0,0 +1,255 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ # nopycln: file
4
+ import datetime as dt
5
+ from collections import defaultdict
6
+ from typing import Any, Callable, ClassVar, Dict, List, Mapping, Optional, Set, Tuple, Type, TypeVar, Union, cast
7
+
8
+ import pydantic
9
+
10
+ IS_PYDANTIC_V2 = pydantic.VERSION.startswith("2.")
11
+
12
+ if IS_PYDANTIC_V2:
13
+ from pydantic.v1.datetime_parse import parse_date as parse_date
14
+ from pydantic.v1.datetime_parse import parse_datetime as parse_datetime
15
+ from pydantic.v1.fields import ModelField as ModelField
16
+ from pydantic.v1.json import ENCODERS_BY_TYPE as encoders_by_type # type: ignore[attr-defined]
17
+ from pydantic.v1.typing import get_args as get_args
18
+ from pydantic.v1.typing import get_origin as get_origin
19
+ from pydantic.v1.typing import is_literal_type as is_literal_type
20
+ from pydantic.v1.typing import is_union as is_union
21
+ else:
22
+ from pydantic.datetime_parse import parse_date as parse_date # type: ignore[no-redef]
23
+ from pydantic.datetime_parse import parse_datetime as parse_datetime # type: ignore[no-redef]
24
+ from pydantic.fields import ModelField as ModelField # type: ignore[attr-defined, no-redef]
25
+ from pydantic.json import ENCODERS_BY_TYPE as encoders_by_type # type: ignore[no-redef]
26
+ from pydantic.typing import get_args as get_args # type: ignore[no-redef]
27
+ from pydantic.typing import get_origin as get_origin # type: ignore[no-redef]
28
+ from pydantic.typing import is_literal_type as is_literal_type # type: ignore[no-redef]
29
+ from pydantic.typing import is_union as is_union # type: ignore[no-redef]
30
+
31
+ from .datetime_utils import serialize_datetime
32
+ from .serialization import convert_and_respect_annotation_metadata
33
+ from typing_extensions import TypeAlias
34
+
35
+ T = TypeVar("T")
36
+ Model = TypeVar("Model", bound=pydantic.BaseModel)
37
+
38
+
39
+ def parse_obj_as(type_: Type[T], object_: Any) -> T:
40
+ dealiased_object = convert_and_respect_annotation_metadata(object_=object_, annotation=type_, direction="read")
41
+ if IS_PYDANTIC_V2:
42
+ adapter = pydantic.TypeAdapter(type_) # type: ignore[attr-defined]
43
+ return adapter.validate_python(dealiased_object)
44
+ return pydantic.parse_obj_as(type_, dealiased_object)
45
+
46
+
47
+ def to_jsonable_with_fallback(obj: Any, fallback_serializer: Callable[[Any], Any]) -> Any:
48
+ if IS_PYDANTIC_V2:
49
+ from pydantic_core import to_jsonable_python
50
+
51
+ return to_jsonable_python(obj, fallback=fallback_serializer)
52
+ return fallback_serializer(obj)
53
+
54
+
55
+ class UniversalBaseModel(pydantic.BaseModel):
56
+ if IS_PYDANTIC_V2:
57
+ model_config: ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( # type: ignore[typeddict-unknown-key]
58
+ # Allow fields beginning with `model_` to be used in the model
59
+ protected_namespaces=(),
60
+ )
61
+
62
+ @pydantic.model_serializer(mode="plain", when_used="json") # type: ignore[attr-defined]
63
+ def serialize_model(self) -> Any: # type: ignore[name-defined]
64
+ serialized = self.model_dump()
65
+ data = {k: serialize_datetime(v) if isinstance(v, dt.datetime) else v for k, v in serialized.items()}
66
+ return data
67
+
68
+ else:
69
+
70
+ class Config:
71
+ smart_union = True
72
+ json_encoders = {dt.datetime: serialize_datetime}
73
+
74
+ @classmethod
75
+ def model_construct(cls: Type["Model"], _fields_set: Optional[Set[str]] = None, **values: Any) -> "Model":
76
+ dealiased_object = convert_and_respect_annotation_metadata(object_=values, annotation=cls, direction="read")
77
+ return cls.construct(_fields_set, **dealiased_object)
78
+
79
+ @classmethod
80
+ def construct(cls: Type["Model"], _fields_set: Optional[Set[str]] = None, **values: Any) -> "Model":
81
+ dealiased_object = convert_and_respect_annotation_metadata(object_=values, annotation=cls, direction="read")
82
+ if IS_PYDANTIC_V2:
83
+ return super().model_construct(_fields_set, **dealiased_object) # type: ignore[misc]
84
+ return super().construct(_fields_set, **dealiased_object)
85
+
86
+ def json(self, **kwargs: Any) -> str:
87
+ kwargs_with_defaults = {
88
+ "by_alias": True,
89
+ "exclude_unset": True,
90
+ **kwargs,
91
+ }
92
+ if IS_PYDANTIC_V2:
93
+ return super().model_dump_json(**kwargs_with_defaults) # type: ignore[misc]
94
+ return super().json(**kwargs_with_defaults)
95
+
96
+ def dict(self, **kwargs: Any) -> Dict[str, Any]:
97
+ """
98
+ Override the default dict method to `exclude_unset` by default. This function patches
99
+ `exclude_unset` to work include fields within non-None default values.
100
+ """
101
+ # Note: the logic here is multiplexed given the levers exposed in Pydantic V1 vs V2
102
+ # Pydantic V1's .dict can be extremely slow, so we do not want to call it twice.
103
+ #
104
+ # We'd ideally do the same for Pydantic V2, but it shells out to a library to serialize models
105
+ # that we have less control over, and this is less intrusive than custom serializers for now.
106
+ if IS_PYDANTIC_V2:
107
+ kwargs_with_defaults_exclude_unset = {
108
+ **kwargs,
109
+ "by_alias": True,
110
+ "exclude_unset": True,
111
+ "exclude_none": False,
112
+ }
113
+ kwargs_with_defaults_exclude_none = {
114
+ **kwargs,
115
+ "by_alias": True,
116
+ "exclude_none": True,
117
+ "exclude_unset": False,
118
+ }
119
+ dict_dump = deep_union_pydantic_dicts(
120
+ super().model_dump(**kwargs_with_defaults_exclude_unset), # type: ignore[misc]
121
+ super().model_dump(**kwargs_with_defaults_exclude_none), # type: ignore[misc]
122
+ )
123
+
124
+ else:
125
+ _fields_set = self.__fields_set__.copy()
126
+
127
+ fields = _get_model_fields(self.__class__)
128
+ for name, field in fields.items():
129
+ if name not in _fields_set:
130
+ default = _get_field_default(field)
131
+
132
+ # If the default values are non-null act like they've been set
133
+ # This effectively allows exclude_unset to work like exclude_none where
134
+ # the latter passes through intentionally set none values.
135
+ if default is not None or ("exclude_unset" in kwargs and not kwargs["exclude_unset"]):
136
+ _fields_set.add(name)
137
+
138
+ if default is not None:
139
+ self.__fields_set__.add(name)
140
+
141
+ kwargs_with_defaults_exclude_unset_include_fields = {
142
+ "by_alias": True,
143
+ "exclude_unset": True,
144
+ "include": _fields_set,
145
+ **kwargs,
146
+ }
147
+
148
+ dict_dump = super().dict(**kwargs_with_defaults_exclude_unset_include_fields)
149
+
150
+ return convert_and_respect_annotation_metadata(object_=dict_dump, annotation=self.__class__, direction="write")
151
+
152
+
153
+ def _union_list_of_pydantic_dicts(source: List[Any], destination: List[Any]) -> List[Any]:
154
+ converted_list: List[Any] = []
155
+ for i, item in enumerate(source):
156
+ destination_value = destination[i]
157
+ if isinstance(item, dict):
158
+ converted_list.append(deep_union_pydantic_dicts(item, destination_value))
159
+ elif isinstance(item, list):
160
+ converted_list.append(_union_list_of_pydantic_dicts(item, destination_value))
161
+ else:
162
+ converted_list.append(item)
163
+ return converted_list
164
+
165
+
166
+ def deep_union_pydantic_dicts(source: Dict[str, Any], destination: Dict[str, Any]) -> Dict[str, Any]:
167
+ for key, value in source.items():
168
+ node = destination.setdefault(key, {})
169
+ if isinstance(value, dict):
170
+ deep_union_pydantic_dicts(value, node)
171
+ # Note: we do not do this same processing for sets given we do not have sets of models
172
+ # and given the sets are unordered, the processing of the set and matching objects would
173
+ # be non-trivial.
174
+ elif isinstance(value, list):
175
+ destination[key] = _union_list_of_pydantic_dicts(value, node)
176
+ else:
177
+ destination[key] = value
178
+
179
+ return destination
180
+
181
+
182
+ if IS_PYDANTIC_V2:
183
+
184
+ class V2RootModel(UniversalBaseModel, pydantic.RootModel): # type: ignore[misc, name-defined, type-arg]
185
+ pass
186
+
187
+ UniversalRootModel: TypeAlias = V2RootModel # type: ignore[misc]
188
+ else:
189
+ UniversalRootModel: TypeAlias = UniversalBaseModel # type: ignore[misc, no-redef]
190
+
191
+
192
+ def encode_by_type(o: Any) -> Any:
193
+ encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(tuple)
194
+ for type_, encoder in encoders_by_type.items():
195
+ encoders_by_class_tuples[encoder] += (type_,)
196
+
197
+ if type(o) in encoders_by_type:
198
+ return encoders_by_type[type(o)](o)
199
+ for encoder, classes_tuple in encoders_by_class_tuples.items():
200
+ if isinstance(o, classes_tuple):
201
+ return encoder(o)
202
+
203
+
204
+ def update_forward_refs(model: Type["Model"], **localns: Any) -> None:
205
+ if IS_PYDANTIC_V2:
206
+ model.model_rebuild(raise_errors=False) # type: ignore[attr-defined]
207
+ else:
208
+ model.update_forward_refs(**localns)
209
+
210
+
211
+ # Mirrors Pydantic's internal typing
212
+ AnyCallable = Callable[..., Any]
213
+
214
+
215
+ def universal_root_validator(
216
+ pre: bool = False,
217
+ ) -> Callable[[AnyCallable], AnyCallable]:
218
+ def decorator(func: AnyCallable) -> AnyCallable:
219
+ if IS_PYDANTIC_V2:
220
+ return cast(AnyCallable, pydantic.model_validator(mode="before" if pre else "after")(func)) # type: ignore[attr-defined]
221
+ return cast(AnyCallable, pydantic.root_validator(pre=pre)(func)) # type: ignore[call-overload]
222
+
223
+ return decorator
224
+
225
+
226
+ def universal_field_validator(field_name: str, pre: bool = False) -> Callable[[AnyCallable], AnyCallable]:
227
+ def decorator(func: AnyCallable) -> AnyCallable:
228
+ if IS_PYDANTIC_V2:
229
+ return cast(AnyCallable, pydantic.field_validator(field_name, mode="before" if pre else "after")(func)) # type: ignore[attr-defined]
230
+ return cast(AnyCallable, pydantic.validator(field_name, pre=pre)(func))
231
+
232
+ return decorator
233
+
234
+
235
+ PydanticField = Union[ModelField, pydantic.fields.FieldInfo]
236
+
237
+
238
+ def _get_model_fields(model: Type["Model"]) -> Mapping[str, PydanticField]:
239
+ if IS_PYDANTIC_V2:
240
+ return cast(Mapping[str, PydanticField], model.model_fields) # type: ignore[attr-defined]
241
+ return cast(Mapping[str, PydanticField], model.__fields__)
242
+
243
+
244
+ def _get_field_default(field: PydanticField) -> Any:
245
+ try:
246
+ value = field.get_default() # type: ignore[union-attr]
247
+ except:
248
+ value = field.default
249
+ if IS_PYDANTIC_V2:
250
+ from pydantic_core import PydanticUndefined
251
+
252
+ if value == PydanticUndefined:
253
+ return None
254
+ return value
255
+ return value
@@ -0,0 +1,58 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ from typing import Any, Dict, List, Optional, Tuple
4
+
5
+ import pydantic
6
+
7
+
8
+ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict
9
+ def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> List[Tuple[str, Any]]:
10
+ result = []
11
+ for k, v in dict_flat.items():
12
+ key = f"{key_prefix}[{k}]" if key_prefix is not None else k
13
+ if isinstance(v, dict):
14
+ result.extend(traverse_query_dict(v, key))
15
+ elif isinstance(v, list):
16
+ for arr_v in v:
17
+ if isinstance(arr_v, dict):
18
+ result.extend(traverse_query_dict(arr_v, key))
19
+ else:
20
+ result.append((key, arr_v))
21
+ else:
22
+ result.append((key, v))
23
+ return result
24
+
25
+
26
+ def single_query_encoder(query_key: str, query_value: Any) -> List[Tuple[str, Any]]:
27
+ if isinstance(query_value, pydantic.BaseModel) or isinstance(query_value, dict):
28
+ if isinstance(query_value, pydantic.BaseModel):
29
+ obj_dict = query_value.dict(by_alias=True)
30
+ else:
31
+ obj_dict = query_value
32
+ return traverse_query_dict(obj_dict, query_key)
33
+ elif isinstance(query_value, list):
34
+ encoded_values: List[Tuple[str, Any]] = []
35
+ for value in query_value:
36
+ if isinstance(value, pydantic.BaseModel) or isinstance(value, dict):
37
+ if isinstance(value, pydantic.BaseModel):
38
+ obj_dict = value.dict(by_alias=True)
39
+ elif isinstance(value, dict):
40
+ obj_dict = value
41
+
42
+ encoded_values.extend(single_query_encoder(query_key, obj_dict))
43
+ else:
44
+ encoded_values.append((query_key, value))
45
+
46
+ return encoded_values
47
+
48
+ return [(query_key, query_value)]
49
+
50
+
51
+ def encode_query(query: Optional[Dict[str, Any]]) -> Optional[List[Tuple[str, Any]]]:
52
+ if query is None:
53
+ return None
54
+
55
+ encoded_query = []
56
+ for k, v in query.items():
57
+ encoded_query.extend(single_query_encoder(k, v))
58
+ return encoded_query
@@ -0,0 +1,11 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ from typing import Any, Dict, Mapping, Optional
4
+
5
+
6
+ def remove_none_from_dict(original: Mapping[str, Optional[Any]]) -> Dict[str, Any]:
7
+ new: Dict[str, Any] = {}
8
+ for key, value in original.items():
9
+ if value is not None:
10
+ new[key] = value
11
+ return new
@@ -0,0 +1,35 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import typing
4
+
5
+ try:
6
+ from typing import NotRequired # type: ignore
7
+ except ImportError:
8
+ from typing_extensions import NotRequired
9
+
10
+
11
+ class RequestOptions(typing.TypedDict, total=False):
12
+ """
13
+ Additional options for request-specific configuration when calling APIs via the SDK.
14
+ This is used primarily as an optional final parameter for service functions.
15
+
16
+ Attributes:
17
+ - timeout_in_seconds: int. The number of seconds to await an API call before timing out.
18
+
19
+ - max_retries: int. The max number of retries to attempt if the API call fails.
20
+
21
+ - additional_headers: typing.Dict[str, typing.Any]. A dictionary containing additional parameters to spread into the request's header dict
22
+
23
+ - additional_query_parameters: typing.Dict[str, typing.Any]. A dictionary containing additional parameters to spread into the request's query parameters dict
24
+
25
+ - additional_body_parameters: typing.Dict[str, typing.Any]. A dictionary containing additional parameters to spread into the request's body parameters dict
26
+
27
+ - chunk_size: int. The size, in bytes, to process each chunk of data being streamed back within the response. This equates to leveraging `chunk_size` within `requests` or `httpx`, and is only leveraged for file downloads.
28
+ """
29
+
30
+ timeout_in_seconds: NotRequired[int]
31
+ max_retries: NotRequired[int]
32
+ additional_headers: NotRequired[typing.Dict[str, typing.Any]]
33
+ additional_query_parameters: NotRequired[typing.Dict[str, typing.Any]]
34
+ additional_body_parameters: NotRequired[typing.Dict[str, typing.Any]]
35
+ chunk_size: NotRequired[int]