dhisana 0.0.1.dev243__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.
- dhisana/__init__.py +1 -0
- dhisana/cli/__init__.py +1 -0
- dhisana/cli/cli.py +20 -0
- dhisana/cli/datasets.py +27 -0
- dhisana/cli/models.py +26 -0
- dhisana/cli/predictions.py +20 -0
- dhisana/schemas/__init__.py +1 -0
- dhisana/schemas/common.py +399 -0
- dhisana/schemas/sales.py +965 -0
- dhisana/ui/__init__.py +1 -0
- dhisana/ui/components.py +472 -0
- dhisana/utils/__init__.py +1 -0
- dhisana/utils/add_mapping.py +352 -0
- dhisana/utils/agent_tools.py +51 -0
- dhisana/utils/apollo_tools.py +1597 -0
- dhisana/utils/assistant_tool_tag.py +4 -0
- dhisana/utils/built_with_api_tools.py +282 -0
- dhisana/utils/cache_output_tools.py +98 -0
- dhisana/utils/cache_output_tools_local.py +78 -0
- dhisana/utils/check_email_validity_tools.py +717 -0
- dhisana/utils/check_for_intent_signal.py +107 -0
- dhisana/utils/check_linkedin_url_validity.py +209 -0
- dhisana/utils/clay_tools.py +43 -0
- dhisana/utils/clean_properties.py +135 -0
- dhisana/utils/company_utils.py +60 -0
- dhisana/utils/compose_salesnav_query.py +259 -0
- dhisana/utils/compose_search_query.py +759 -0
- dhisana/utils/compose_three_step_workflow.py +234 -0
- dhisana/utils/composite_tools.py +137 -0
- dhisana/utils/dataframe_tools.py +237 -0
- dhisana/utils/domain_parser.py +45 -0
- dhisana/utils/email_body_utils.py +72 -0
- dhisana/utils/email_parse_helpers.py +132 -0
- dhisana/utils/email_provider.py +375 -0
- dhisana/utils/enrich_lead_information.py +933 -0
- dhisana/utils/extract_email_content_for_llm.py +101 -0
- dhisana/utils/fetch_openai_config.py +129 -0
- dhisana/utils/field_validators.py +426 -0
- dhisana/utils/g2_tools.py +104 -0
- dhisana/utils/generate_content.py +41 -0
- dhisana/utils/generate_custom_message.py +271 -0
- dhisana/utils/generate_email.py +278 -0
- dhisana/utils/generate_email_response.py +465 -0
- dhisana/utils/generate_flow.py +102 -0
- dhisana/utils/generate_leads_salesnav.py +303 -0
- dhisana/utils/generate_linkedin_connect_message.py +224 -0
- dhisana/utils/generate_linkedin_response_message.py +317 -0
- dhisana/utils/generate_structured_output_internal.py +462 -0
- dhisana/utils/google_custom_search.py +267 -0
- dhisana/utils/google_oauth_tools.py +727 -0
- dhisana/utils/google_workspace_tools.py +1294 -0
- dhisana/utils/hubspot_clearbit.py +96 -0
- dhisana/utils/hubspot_crm_tools.py +2440 -0
- dhisana/utils/instantly_tools.py +149 -0
- dhisana/utils/linkedin_crawler.py +168 -0
- dhisana/utils/lusha_tools.py +333 -0
- dhisana/utils/mailgun_tools.py +156 -0
- dhisana/utils/mailreach_tools.py +123 -0
- dhisana/utils/microsoft365_tools.py +455 -0
- dhisana/utils/openai_assistant_and_file_utils.py +267 -0
- dhisana/utils/openai_helpers.py +977 -0
- dhisana/utils/openapi_spec_to_tools.py +45 -0
- dhisana/utils/openapi_tool/__init__.py +1 -0
- dhisana/utils/openapi_tool/api_models.py +633 -0
- dhisana/utils/openapi_tool/convert_openai_spec_to_tool.py +271 -0
- dhisana/utils/openapi_tool/openapi_tool.py +319 -0
- dhisana/utils/parse_linkedin_messages_txt.py +100 -0
- dhisana/utils/profile.py +37 -0
- dhisana/utils/proxy_curl_tools.py +1226 -0
- dhisana/utils/proxycurl_search_leads.py +426 -0
- dhisana/utils/python_function_to_tools.py +83 -0
- dhisana/utils/research_lead.py +176 -0
- dhisana/utils/sales_navigator_crawler.py +1103 -0
- dhisana/utils/salesforce_crm_tools.py +477 -0
- dhisana/utils/search_router.py +131 -0
- dhisana/utils/search_router_jobs.py +51 -0
- dhisana/utils/sendgrid_tools.py +162 -0
- dhisana/utils/serarch_router_local_business.py +75 -0
- dhisana/utils/serpapi_additional_tools.py +290 -0
- dhisana/utils/serpapi_google_jobs.py +117 -0
- dhisana/utils/serpapi_google_search.py +188 -0
- dhisana/utils/serpapi_local_business_search.py +129 -0
- dhisana/utils/serpapi_search_tools.py +852 -0
- dhisana/utils/serperdev_google_jobs.py +125 -0
- dhisana/utils/serperdev_local_business.py +154 -0
- dhisana/utils/serperdev_search.py +233 -0
- dhisana/utils/smtp_email_tools.py +582 -0
- dhisana/utils/test_connect.py +2087 -0
- dhisana/utils/trasform_json.py +173 -0
- dhisana/utils/web_download_parse_tools.py +189 -0
- dhisana/utils/workflow_code_model.py +5 -0
- dhisana/utils/zoominfo_tools.py +357 -0
- dhisana/workflow/__init__.py +1 -0
- dhisana/workflow/agent.py +18 -0
- dhisana/workflow/flow.py +44 -0
- dhisana/workflow/task.py +43 -0
- dhisana/workflow/test.py +90 -0
- dhisana-0.0.1.dev243.dist-info/METADATA +43 -0
- dhisana-0.0.1.dev243.dist-info/RECORD +102 -0
- dhisana-0.0.1.dev243.dist-info/WHEEL +5 -0
- dhisana-0.0.1.dev243.dist-info/entry_points.txt +2 -0
- dhisana-0.0.1.dev243.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# Given Any OpenAPI Spec convert it to a list of tools.
|
|
2
|
+
# These tools can be used in the assistant API for orchestration.
|
|
3
|
+
# The spec can be custom and have natural language descriptions that will help the Agent.
|
|
4
|
+
|
|
5
|
+
from .openapi_tool.convert_openai_spec_to_tool import openapi_spec_to_openai_fn
|
|
6
|
+
from .openapi_tool.openapi_tool import OpenAPISpec
|
|
7
|
+
|
|
8
|
+
# Parse the OpenAPI spec and convert it to a list of tools
|
|
9
|
+
# OpenAI tools input Tools will be in openapi_GLOBAL_OPENAI_ASSISTANT_TOOLS
|
|
10
|
+
# Callable functions will be in openapi_callable_functions. This is invoked with assistant tool callback API
|
|
11
|
+
# src/dhisana/utils/openapi_spec_to_tools.py
|
|
12
|
+
|
|
13
|
+
# Ensure OPENAPI_GLOBAL_OPENAI_ASSISTANT_TOOLS is only initialized once
|
|
14
|
+
if 'OPENAPI_GLOBAL_OPENAI_ASSISTANT_TOOLS' not in globals():
|
|
15
|
+
OPENAPI_GLOBAL_OPENAI_ASSISTANT_TOOLS = []
|
|
16
|
+
|
|
17
|
+
# Ensure OPENAPI_CALLABALE_FUNCTIONS is only initialized once
|
|
18
|
+
if 'OPENAPI_CALLABALE_FUNCTIONS' not in globals():
|
|
19
|
+
OPENAPI_CALLABALE_FUNCTIONS = {}
|
|
20
|
+
|
|
21
|
+
# Ensure OPENAPI_TOOL_CONFIGURATIONS is only initialized once
|
|
22
|
+
if 'OPENAPI_TOOL_CONFIGURATIONS' not in globals():
|
|
23
|
+
OPENAPI_TOOL_CONFIGURATIONS = {}
|
|
24
|
+
|
|
25
|
+
def convert_spec_to_tools(file_path: str):
|
|
26
|
+
# Open the file and load spec from there
|
|
27
|
+
with open(file_path, 'r') as file:
|
|
28
|
+
openapi_spec = file.read()
|
|
29
|
+
spec = OpenAPISpec.from_text(openapi_spec)
|
|
30
|
+
openai_fns, call_api_fn = openapi_spec_to_openai_fn(spec)
|
|
31
|
+
return openai_fns, call_api_fn
|
|
32
|
+
|
|
33
|
+
# Parse and save the OpenAI Tools parsed and the corresponding callable functions
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def add_openapi_spec_to_tools_list(file_path: str):
|
|
37
|
+
openai_fns, call_api_fn = convert_spec_to_tools(file_path)
|
|
38
|
+
if (len(openai_fns) > 0):
|
|
39
|
+
OPENAPI_GLOBAL_OPENAI_ASSISTANT_TOOLS.extend(openai_fns)
|
|
40
|
+
for fn in openai_fns:
|
|
41
|
+
name = fn["function"]["name"]
|
|
42
|
+
if name:
|
|
43
|
+
OPENAPI_CALLABALE_FUNCTIONS[name] = call_api_fn
|
|
44
|
+
return OPENAPI_GLOBAL_OPENAI_ASSISTANT_TOOLS
|
|
45
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
|
|
@@ -0,0 +1,633 @@
|
|
|
1
|
+
"""Pydantic models for parsing an OpenAPI spec."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from enum import Enum
|
|
7
|
+
from typing import (
|
|
8
|
+
TYPE_CHECKING,
|
|
9
|
+
Any,
|
|
10
|
+
Dict,
|
|
11
|
+
List,
|
|
12
|
+
Optional,
|
|
13
|
+
Sequence,
|
|
14
|
+
Tuple,
|
|
15
|
+
Type,
|
|
16
|
+
Union,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from pydantic import BaseModel, Field
|
|
20
|
+
|
|
21
|
+
from .openapi_tool import HTTPVerb, OpenAPISpec
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
PRIMITIVE_TYPES = {
|
|
25
|
+
"integer": int,
|
|
26
|
+
"number": float,
|
|
27
|
+
"string": str,
|
|
28
|
+
"boolean": bool,
|
|
29
|
+
"array": List,
|
|
30
|
+
"object": Dict,
|
|
31
|
+
"null": None,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterIn
|
|
36
|
+
# for more info.
|
|
37
|
+
class APIPropertyLocation(Enum):
|
|
38
|
+
"""The location of the property."""
|
|
39
|
+
|
|
40
|
+
QUERY = "query"
|
|
41
|
+
PATH = "path"
|
|
42
|
+
HEADER = "header"
|
|
43
|
+
COOKIE = "cookie" # Not yet supported
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def from_str(cls, location: str) -> "APIPropertyLocation":
|
|
47
|
+
"""Parse an APIPropertyLocation."""
|
|
48
|
+
try:
|
|
49
|
+
return cls(location)
|
|
50
|
+
except ValueError:
|
|
51
|
+
raise ValueError(
|
|
52
|
+
f"Invalid APIPropertyLocation. Valid values are {cls.__members__}"
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
_SUPPORTED_MEDIA_TYPES = ("application/json",)
|
|
57
|
+
|
|
58
|
+
SUPPORTED_LOCATIONS = {
|
|
59
|
+
APIPropertyLocation.HEADER,
|
|
60
|
+
APIPropertyLocation.QUERY,
|
|
61
|
+
APIPropertyLocation.PATH,
|
|
62
|
+
}
|
|
63
|
+
INVALID_LOCATION_TEMPL = (
|
|
64
|
+
'Unsupported APIPropertyLocation "{location}"'
|
|
65
|
+
" for parameter {name}. "
|
|
66
|
+
+ f"Valid values are {[loc.value for loc in SUPPORTED_LOCATIONS]}"
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
SCHEMA_TYPE = Union[str, Type, tuple, None, Enum]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class APIPropertyBase(BaseModel):
|
|
73
|
+
"""Base model for an API property."""
|
|
74
|
+
|
|
75
|
+
# The name of the parameter is required and is case-sensitive.
|
|
76
|
+
# If "in" is "path", the "name" field must correspond to a template expression
|
|
77
|
+
# within the path field in the Paths Object.
|
|
78
|
+
# If "in" is "header" and the "name" field is "Accept", "Content-Type",
|
|
79
|
+
# or "Authorization", the parameter definition is ignored.
|
|
80
|
+
# For all other cases, the "name" corresponds to the parameter
|
|
81
|
+
# name used by the "in" property.
|
|
82
|
+
name: str = Field(alias="name")
|
|
83
|
+
"""The name of the property."""
|
|
84
|
+
|
|
85
|
+
required: bool = Field(alias="required")
|
|
86
|
+
"""Whether the property is required."""
|
|
87
|
+
|
|
88
|
+
type: SCHEMA_TYPE = Field(alias="type")
|
|
89
|
+
"""The type of the property.
|
|
90
|
+
|
|
91
|
+
Either a primitive type, a component/parameter type,
|
|
92
|
+
or an array or 'object' (dict) of the above."""
|
|
93
|
+
|
|
94
|
+
default: Optional[Any] = Field(alias="default", default=None)
|
|
95
|
+
"""The default value of the property."""
|
|
96
|
+
|
|
97
|
+
description: Optional[str] = Field(alias="description", default=None)
|
|
98
|
+
"""The description of the property."""
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
if TYPE_CHECKING:
|
|
102
|
+
from openapi_pydantic import (
|
|
103
|
+
MediaType,
|
|
104
|
+
Parameter,
|
|
105
|
+
RequestBody,
|
|
106
|
+
Schema,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class APIProperty(APIPropertyBase):
|
|
111
|
+
"""A model for a property in the query, path, header, or cookie params."""
|
|
112
|
+
|
|
113
|
+
location: APIPropertyLocation = Field(alias="location")
|
|
114
|
+
"""The path/how it's being passed to the endpoint."""
|
|
115
|
+
|
|
116
|
+
@staticmethod
|
|
117
|
+
def _cast_schema_list_type(
|
|
118
|
+
schema: Schema,
|
|
119
|
+
) -> Optional[Union[str, Tuple[str, ...]]]:
|
|
120
|
+
type_ = schema.type
|
|
121
|
+
if not isinstance(type_, list):
|
|
122
|
+
return type_
|
|
123
|
+
else:
|
|
124
|
+
return tuple(type_)
|
|
125
|
+
|
|
126
|
+
@staticmethod
|
|
127
|
+
def _get_schema_type_for_enum(parameter: Parameter, schema: Schema) -> Enum:
|
|
128
|
+
"""Get the schema type when the parameter is an enum."""
|
|
129
|
+
param_name = f"{parameter.name}Enum"
|
|
130
|
+
return Enum(param_name, {str(v): v for v in schema.enum})
|
|
131
|
+
|
|
132
|
+
@staticmethod
|
|
133
|
+
def _get_schema_type_for_array(
|
|
134
|
+
schema: Schema,
|
|
135
|
+
) -> Optional[Union[str, Tuple[str, ...]]]:
|
|
136
|
+
from openapi_pydantic import (
|
|
137
|
+
Reference,
|
|
138
|
+
Schema,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
items = schema.items
|
|
142
|
+
if isinstance(items, Schema):
|
|
143
|
+
schema_type = APIProperty._cast_schema_list_type(items)
|
|
144
|
+
elif isinstance(items, Reference):
|
|
145
|
+
ref_name = items.ref.split("/")[-1]
|
|
146
|
+
schema_type = ref_name # TODO: Add ref definitions to make his valid
|
|
147
|
+
else:
|
|
148
|
+
raise ValueError(f"Unsupported array items: {items}")
|
|
149
|
+
|
|
150
|
+
if isinstance(schema_type, str):
|
|
151
|
+
# TODO: recurse
|
|
152
|
+
schema_type = (schema_type,)
|
|
153
|
+
|
|
154
|
+
return schema_type
|
|
155
|
+
|
|
156
|
+
@staticmethod
|
|
157
|
+
def _get_schema_type(parameter: Parameter, schema: Optional[Schema]) -> SCHEMA_TYPE:
|
|
158
|
+
if schema is None:
|
|
159
|
+
return None
|
|
160
|
+
schema_type: SCHEMA_TYPE = APIProperty._cast_schema_list_type(schema)
|
|
161
|
+
if schema_type == "array":
|
|
162
|
+
schema_type = APIProperty._get_schema_type_for_array(schema)
|
|
163
|
+
elif schema_type == "object":
|
|
164
|
+
# TODO: Resolve array and object types to components.
|
|
165
|
+
raise NotImplementedError("Objects not yet supported")
|
|
166
|
+
elif schema_type in PRIMITIVE_TYPES:
|
|
167
|
+
if schema.enum:
|
|
168
|
+
schema_type = APIProperty._get_schema_type_for_enum(parameter, schema)
|
|
169
|
+
else:
|
|
170
|
+
# Directly use the primitive type
|
|
171
|
+
pass
|
|
172
|
+
else:
|
|
173
|
+
raise NotImplementedError(f"Unsupported type: {schema_type}")
|
|
174
|
+
|
|
175
|
+
return schema_type
|
|
176
|
+
|
|
177
|
+
@staticmethod
|
|
178
|
+
def _validate_location(location: APIPropertyLocation, name: str) -> None:
|
|
179
|
+
if location not in SUPPORTED_LOCATIONS:
|
|
180
|
+
raise NotImplementedError(
|
|
181
|
+
INVALID_LOCATION_TEMPL.format(location=location, name=name)
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
@staticmethod
|
|
185
|
+
def _validate_content(content: Optional[Dict[str, MediaType]]) -> None:
|
|
186
|
+
if content:
|
|
187
|
+
raise ValueError(
|
|
188
|
+
"API Properties with media content not supported. "
|
|
189
|
+
"Media content only supported within APIRequestBodyProperty's"
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
@staticmethod
|
|
193
|
+
def _get_schema(parameter: Parameter, spec: OpenAPISpec) -> Optional[Schema]:
|
|
194
|
+
from openapi_pydantic import (
|
|
195
|
+
Reference,
|
|
196
|
+
Schema,
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
schema = parameter.param_schema
|
|
200
|
+
if isinstance(schema, Reference):
|
|
201
|
+
schema = spec.get_referenced_schema(schema)
|
|
202
|
+
elif schema is None:
|
|
203
|
+
return None
|
|
204
|
+
elif not isinstance(schema, Schema):
|
|
205
|
+
raise ValueError(f"Error dereferencing schema: {schema}")
|
|
206
|
+
|
|
207
|
+
return schema
|
|
208
|
+
|
|
209
|
+
@staticmethod
|
|
210
|
+
def is_supported_location(location: str) -> bool:
|
|
211
|
+
"""Return whether the provided location is supported."""
|
|
212
|
+
try:
|
|
213
|
+
return APIPropertyLocation.from_str(location) in SUPPORTED_LOCATIONS
|
|
214
|
+
except ValueError:
|
|
215
|
+
return False
|
|
216
|
+
|
|
217
|
+
@classmethod
|
|
218
|
+
def from_parameter(cls, parameter: Parameter, spec: OpenAPISpec) -> "APIProperty":
|
|
219
|
+
"""Instantiate from an OpenAPI Parameter."""
|
|
220
|
+
location = APIPropertyLocation.from_str(parameter.param_in)
|
|
221
|
+
cls._validate_location(
|
|
222
|
+
location,
|
|
223
|
+
parameter.name,
|
|
224
|
+
)
|
|
225
|
+
cls._validate_content(parameter.content)
|
|
226
|
+
schema = cls._get_schema(parameter, spec)
|
|
227
|
+
schema_type = cls._get_schema_type(parameter, schema)
|
|
228
|
+
default_val = schema.default if schema is not None else None
|
|
229
|
+
return cls(
|
|
230
|
+
name=parameter.name,
|
|
231
|
+
location=location,
|
|
232
|
+
default=default_val,
|
|
233
|
+
description=parameter.description,
|
|
234
|
+
required=parameter.required,
|
|
235
|
+
type=schema_type,
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
class APIRequestBodyProperty(APIPropertyBase):
|
|
240
|
+
"""A model for a request body property."""
|
|
241
|
+
|
|
242
|
+
properties: List["APIRequestBodyProperty"] = Field(alias="properties")
|
|
243
|
+
"""The sub-properties of the property."""
|
|
244
|
+
|
|
245
|
+
# This is useful for handling nested property cycles.
|
|
246
|
+
# We can define separate types in that case.
|
|
247
|
+
references_used: List[str] = Field(alias="references_used")
|
|
248
|
+
"""The references used by the property."""
|
|
249
|
+
|
|
250
|
+
@classmethod
|
|
251
|
+
def _process_object_schema(
|
|
252
|
+
cls, schema: Schema, spec: OpenAPISpec, references_used: List[str]
|
|
253
|
+
) -> Tuple[Union[str, List[str], None], List["APIRequestBodyProperty"]]:
|
|
254
|
+
from openapi_pydantic import (
|
|
255
|
+
Reference,
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
properties = []
|
|
259
|
+
required_props = schema.required or []
|
|
260
|
+
if schema.properties is None:
|
|
261
|
+
raise ValueError(
|
|
262
|
+
f"No properties found when processing object schema: {schema}"
|
|
263
|
+
)
|
|
264
|
+
for prop_name, prop_schema in schema.properties.items():
|
|
265
|
+
if isinstance(prop_schema, Reference):
|
|
266
|
+
ref_name = prop_schema.ref.split("/")[-1]
|
|
267
|
+
if ref_name not in references_used:
|
|
268
|
+
references_used.append(ref_name)
|
|
269
|
+
prop_schema = spec.get_referenced_schema(prop_schema)
|
|
270
|
+
else:
|
|
271
|
+
continue
|
|
272
|
+
|
|
273
|
+
properties.append(
|
|
274
|
+
cls.from_schema(
|
|
275
|
+
schema=prop_schema,
|
|
276
|
+
name=prop_name,
|
|
277
|
+
required=prop_name in required_props,
|
|
278
|
+
spec=spec,
|
|
279
|
+
references_used=references_used,
|
|
280
|
+
)
|
|
281
|
+
)
|
|
282
|
+
return schema.type, properties
|
|
283
|
+
|
|
284
|
+
@classmethod
|
|
285
|
+
def _process_array_schema(
|
|
286
|
+
cls,
|
|
287
|
+
schema: Schema,
|
|
288
|
+
name: str,
|
|
289
|
+
spec: OpenAPISpec,
|
|
290
|
+
references_used: List[str],
|
|
291
|
+
) -> str:
|
|
292
|
+
from openapi_pydantic import Reference, Schema
|
|
293
|
+
|
|
294
|
+
items = schema.items
|
|
295
|
+
if items is not None:
|
|
296
|
+
if isinstance(items, Reference):
|
|
297
|
+
ref_name = items.ref.split("/")[-1]
|
|
298
|
+
if ref_name not in references_used:
|
|
299
|
+
references_used.append(ref_name)
|
|
300
|
+
items = spec.get_referenced_schema(items)
|
|
301
|
+
else:
|
|
302
|
+
pass
|
|
303
|
+
return f"Array<{ref_name}>"
|
|
304
|
+
else:
|
|
305
|
+
pass
|
|
306
|
+
|
|
307
|
+
if isinstance(items, Schema):
|
|
308
|
+
array_type = cls.from_schema(
|
|
309
|
+
schema=items,
|
|
310
|
+
name=f"{name}Item",
|
|
311
|
+
required=True, # TODO: Add required
|
|
312
|
+
spec=spec,
|
|
313
|
+
references_used=references_used,
|
|
314
|
+
)
|
|
315
|
+
return f"Array<{array_type.type}>"
|
|
316
|
+
|
|
317
|
+
return "array"
|
|
318
|
+
|
|
319
|
+
@classmethod
|
|
320
|
+
def from_schema(
|
|
321
|
+
cls,
|
|
322
|
+
schema: Schema,
|
|
323
|
+
name: str,
|
|
324
|
+
required: bool,
|
|
325
|
+
spec: OpenAPISpec,
|
|
326
|
+
references_used: Optional[List[str]] = None,
|
|
327
|
+
) -> "APIRequestBodyProperty":
|
|
328
|
+
"""Recursively populate from an OpenAPI Schema."""
|
|
329
|
+
if references_used is None:
|
|
330
|
+
references_used = []
|
|
331
|
+
|
|
332
|
+
schema_type = schema.type
|
|
333
|
+
properties: List[APIRequestBodyProperty] = []
|
|
334
|
+
if schema_type == "object" and schema.properties:
|
|
335
|
+
schema_type, properties = cls._process_object_schema(
|
|
336
|
+
schema, spec, references_used
|
|
337
|
+
)
|
|
338
|
+
elif schema_type == "array":
|
|
339
|
+
schema_type = cls._process_array_schema(schema, name, spec, references_used)
|
|
340
|
+
elif schema_type in PRIMITIVE_TYPES:
|
|
341
|
+
# Use the primitive type directly
|
|
342
|
+
pass
|
|
343
|
+
elif schema_type is None:
|
|
344
|
+
# No typing specified/parsed. WIll map to 'any'
|
|
345
|
+
pass
|
|
346
|
+
else:
|
|
347
|
+
raise ValueError(f"Unsupported type: {schema_type}")
|
|
348
|
+
|
|
349
|
+
return cls(
|
|
350
|
+
name=name,
|
|
351
|
+
required=required,
|
|
352
|
+
type=schema_type,
|
|
353
|
+
default=schema.default,
|
|
354
|
+
description=schema.description,
|
|
355
|
+
properties=properties,
|
|
356
|
+
references_used=references_used,
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
# class APIRequestBodyProperty(APIPropertyBase):
|
|
361
|
+
class APIRequestBody(BaseModel):
|
|
362
|
+
"""A model for a request body."""
|
|
363
|
+
|
|
364
|
+
description: Optional[str] = Field(alias="description")
|
|
365
|
+
"""The description of the request body."""
|
|
366
|
+
|
|
367
|
+
properties: List[APIRequestBodyProperty] = Field(alias="properties")
|
|
368
|
+
|
|
369
|
+
# E.g., application/json - we only support JSON at the moment.
|
|
370
|
+
media_type: str = Field(alias="media_type")
|
|
371
|
+
"""The media type of the request body."""
|
|
372
|
+
|
|
373
|
+
@classmethod
|
|
374
|
+
def _process_supported_media_type(
|
|
375
|
+
cls,
|
|
376
|
+
media_type_obj: MediaType,
|
|
377
|
+
spec: OpenAPISpec,
|
|
378
|
+
) -> List[APIRequestBodyProperty]:
|
|
379
|
+
"""Process the media type of the request body."""
|
|
380
|
+
from openapi_pydantic import Reference
|
|
381
|
+
|
|
382
|
+
references_used = []
|
|
383
|
+
schema = media_type_obj.media_type_schema
|
|
384
|
+
if isinstance(schema, Reference):
|
|
385
|
+
references_used.append(schema.ref.split("/")[-1])
|
|
386
|
+
schema = spec.get_referenced_schema(schema)
|
|
387
|
+
if schema is None:
|
|
388
|
+
raise ValueError(
|
|
389
|
+
f"Could not resolve schema for media type: {media_type_obj}"
|
|
390
|
+
)
|
|
391
|
+
api_request_body_properties = []
|
|
392
|
+
required_properties = schema.required or []
|
|
393
|
+
if schema.type == "object" and schema.properties:
|
|
394
|
+
for prop_name, prop_schema in schema.properties.items():
|
|
395
|
+
if isinstance(prop_schema, Reference):
|
|
396
|
+
prop_schema = spec.get_referenced_schema(prop_schema)
|
|
397
|
+
|
|
398
|
+
api_request_body_properties.append(
|
|
399
|
+
APIRequestBodyProperty.from_schema(
|
|
400
|
+
schema=prop_schema,
|
|
401
|
+
name=prop_name,
|
|
402
|
+
required=prop_name in required_properties,
|
|
403
|
+
spec=spec,
|
|
404
|
+
)
|
|
405
|
+
)
|
|
406
|
+
else:
|
|
407
|
+
api_request_body_properties.append(
|
|
408
|
+
APIRequestBodyProperty(
|
|
409
|
+
name="body",
|
|
410
|
+
required=True,
|
|
411
|
+
type=schema.type,
|
|
412
|
+
default=schema.default,
|
|
413
|
+
description=schema.description,
|
|
414
|
+
properties=[],
|
|
415
|
+
references_used=references_used,
|
|
416
|
+
)
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
return api_request_body_properties
|
|
420
|
+
|
|
421
|
+
@classmethod
|
|
422
|
+
def from_request_body(
|
|
423
|
+
cls, request_body: RequestBody, spec: OpenAPISpec
|
|
424
|
+
) -> "APIRequestBody":
|
|
425
|
+
"""Instantiate from an OpenAPI RequestBody."""
|
|
426
|
+
properties = []
|
|
427
|
+
for media_type, media_type_obj in request_body.content.items():
|
|
428
|
+
if media_type not in _SUPPORTED_MEDIA_TYPES:
|
|
429
|
+
continue
|
|
430
|
+
api_request_body_properties = cls._process_supported_media_type(
|
|
431
|
+
media_type_obj,
|
|
432
|
+
spec,
|
|
433
|
+
)
|
|
434
|
+
properties.extend(api_request_body_properties)
|
|
435
|
+
|
|
436
|
+
return cls(
|
|
437
|
+
description=request_body.description,
|
|
438
|
+
properties=properties,
|
|
439
|
+
media_type=media_type,
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
# class APIRequestBodyProperty(APIPropertyBase):
|
|
444
|
+
# class APIRequestBody(BaseModel):
|
|
445
|
+
class APIOperation(BaseModel):
|
|
446
|
+
"""A model for a single API operation."""
|
|
447
|
+
|
|
448
|
+
operation_id: str = Field(alias="operation_id")
|
|
449
|
+
"""The unique identifier of the operation."""
|
|
450
|
+
|
|
451
|
+
description: Optional[str] = Field(alias="description")
|
|
452
|
+
"""The description of the operation."""
|
|
453
|
+
|
|
454
|
+
base_url: str = Field(alias="base_url")
|
|
455
|
+
"""The base URL of the operation."""
|
|
456
|
+
|
|
457
|
+
path: str = Field(alias="path")
|
|
458
|
+
"""The path of the operation."""
|
|
459
|
+
|
|
460
|
+
method: HTTPVerb = Field(alias="method")
|
|
461
|
+
"""The HTTP method of the operation."""
|
|
462
|
+
|
|
463
|
+
properties: Sequence[APIProperty] = Field(alias="properties")
|
|
464
|
+
|
|
465
|
+
# TODO: Add parse in used components to be able to specify what type of
|
|
466
|
+
# referenced object it is.
|
|
467
|
+
# """The properties of the operation."""
|
|
468
|
+
# components: Dict[str, BaseModel] = Field(alias="components")
|
|
469
|
+
|
|
470
|
+
request_body: Optional[APIRequestBody] = Field(alias="request_body")
|
|
471
|
+
"""The request body of the operation."""
|
|
472
|
+
|
|
473
|
+
@staticmethod
|
|
474
|
+
def _get_properties_from_parameters(
|
|
475
|
+
parameters: List[Parameter], spec: OpenAPISpec
|
|
476
|
+
) -> List[APIProperty]:
|
|
477
|
+
"""Get the properties of the operation."""
|
|
478
|
+
properties = []
|
|
479
|
+
for param in parameters:
|
|
480
|
+
if APIProperty.is_supported_location(param.param_in):
|
|
481
|
+
properties.append(APIProperty.from_parameter(param, spec))
|
|
482
|
+
elif param.required:
|
|
483
|
+
raise ValueError(
|
|
484
|
+
INVALID_LOCATION_TEMPL.format(
|
|
485
|
+
location=param.param_in, name=param.name
|
|
486
|
+
)
|
|
487
|
+
)
|
|
488
|
+
else:
|
|
489
|
+
logger.warning(
|
|
490
|
+
INVALID_LOCATION_TEMPL.format(
|
|
491
|
+
location=param.param_in, name=param.name
|
|
492
|
+
)
|
|
493
|
+
+ " Ignoring optional parameter"
|
|
494
|
+
)
|
|
495
|
+
pass
|
|
496
|
+
return properties
|
|
497
|
+
|
|
498
|
+
@classmethod
|
|
499
|
+
def from_openapi_url(
|
|
500
|
+
cls,
|
|
501
|
+
spec_url: str,
|
|
502
|
+
path: str,
|
|
503
|
+
method: str,
|
|
504
|
+
) -> "APIOperation":
|
|
505
|
+
"""Create an APIOperation from an OpenAPI URL."""
|
|
506
|
+
spec = OpenAPISpec.from_url(spec_url)
|
|
507
|
+
return cls.from_openapi_spec(spec, path, method)
|
|
508
|
+
|
|
509
|
+
@classmethod
|
|
510
|
+
def from_openapi_spec(
|
|
511
|
+
cls,
|
|
512
|
+
spec: OpenAPISpec,
|
|
513
|
+
path: str,
|
|
514
|
+
method: str,
|
|
515
|
+
) -> "APIOperation":
|
|
516
|
+
"""Create an APIOperation from an OpenAPI spec."""
|
|
517
|
+
operation = spec.get_operation(path, method)
|
|
518
|
+
parameters = spec.get_parameters_for_operation(operation)
|
|
519
|
+
properties = cls._get_properties_from_parameters(parameters, spec)
|
|
520
|
+
operation_id = OpenAPISpec.get_cleaned_operation_id(spec, operation, path, method)
|
|
521
|
+
request_body = spec.get_request_body_for_operation(operation)
|
|
522
|
+
api_request_body = (
|
|
523
|
+
APIRequestBody.from_request_body(request_body, spec)
|
|
524
|
+
if request_body is not None
|
|
525
|
+
else None
|
|
526
|
+
)
|
|
527
|
+
description = operation.description or operation.summary
|
|
528
|
+
if not description and spec.paths is not None:
|
|
529
|
+
description = spec.paths[path].description or spec.paths[path].summary
|
|
530
|
+
return cls(
|
|
531
|
+
operation_id=operation_id,
|
|
532
|
+
description=description or "",
|
|
533
|
+
base_url=spec.base_url,
|
|
534
|
+
path=path,
|
|
535
|
+
method=method, # type: ignore[arg-type]
|
|
536
|
+
properties=properties,
|
|
537
|
+
request_body=api_request_body,
|
|
538
|
+
)
|
|
539
|
+
|
|
540
|
+
@staticmethod
|
|
541
|
+
def ts_type_from_python(type_: SCHEMA_TYPE) -> str:
|
|
542
|
+
if type_ is None:
|
|
543
|
+
# TODO: Handle Nones better. These often result when
|
|
544
|
+
# parsing specs that are < v3
|
|
545
|
+
return "any"
|
|
546
|
+
elif isinstance(type_, str):
|
|
547
|
+
return {
|
|
548
|
+
"str": "string",
|
|
549
|
+
"integer": "number",
|
|
550
|
+
"float": "number",
|
|
551
|
+
"date-time": "string",
|
|
552
|
+
}.get(type_, type_)
|
|
553
|
+
elif isinstance(type_, tuple):
|
|
554
|
+
return f"Array<{APIOperation.ts_type_from_python(type_[0])}>"
|
|
555
|
+
elif isinstance(type_, type) and issubclass(type_, Enum):
|
|
556
|
+
return " | ".join([f"'{e.value}'" for e in type_])
|
|
557
|
+
else:
|
|
558
|
+
return str(type_)
|
|
559
|
+
|
|
560
|
+
def _format_nested_properties(
|
|
561
|
+
self, properties: List[APIRequestBodyProperty], indent: int = 2
|
|
562
|
+
) -> str:
|
|
563
|
+
"""Format nested properties."""
|
|
564
|
+
formatted_props = []
|
|
565
|
+
|
|
566
|
+
for prop in properties:
|
|
567
|
+
prop_name = prop.name
|
|
568
|
+
prop_type = self.ts_type_from_python(prop.type)
|
|
569
|
+
prop_required = "" if prop.required else "?"
|
|
570
|
+
prop_desc = f"/* {prop.description} */" if prop.description else ""
|
|
571
|
+
|
|
572
|
+
if prop.properties:
|
|
573
|
+
nested_props = self._format_nested_properties(
|
|
574
|
+
prop.properties, indent + 2
|
|
575
|
+
)
|
|
576
|
+
prop_type = f"{{\n{nested_props}\n{' ' * indent}}}"
|
|
577
|
+
|
|
578
|
+
formatted_props.append(
|
|
579
|
+
f"{prop_desc}\n{' ' * indent}{prop_name}"
|
|
580
|
+
f"{prop_required}: {prop_type},"
|
|
581
|
+
)
|
|
582
|
+
|
|
583
|
+
return "\n".join(formatted_props)
|
|
584
|
+
|
|
585
|
+
def to_typescript(self) -> str:
|
|
586
|
+
"""Get typescript string representation of the operation."""
|
|
587
|
+
operation_name = self.operation_id
|
|
588
|
+
params = []
|
|
589
|
+
|
|
590
|
+
if self.request_body:
|
|
591
|
+
formatted_request_body_props = self._format_nested_properties(
|
|
592
|
+
self.request_body.properties
|
|
593
|
+
)
|
|
594
|
+
params.append(formatted_request_body_props)
|
|
595
|
+
|
|
596
|
+
for prop in self.properties:
|
|
597
|
+
prop_name = prop.name
|
|
598
|
+
prop_type = self.ts_type_from_python(prop.type)
|
|
599
|
+
prop_required = "" if prop.required else "?"
|
|
600
|
+
prop_desc = f"/* {prop.description} */" if prop.description else ""
|
|
601
|
+
params.append(f"{prop_desc}\n\t\t{prop_name}{prop_required}: {prop_type},")
|
|
602
|
+
|
|
603
|
+
formatted_params = "\n".join(params).strip()
|
|
604
|
+
description_str = f"/* {self.description} */" if self.description else ""
|
|
605
|
+
typescript_definition = f"""
|
|
606
|
+
{description_str}
|
|
607
|
+
type {operation_name} = (_: {{
|
|
608
|
+
{formatted_params}
|
|
609
|
+
}}) => any;
|
|
610
|
+
"""
|
|
611
|
+
return typescript_definition.strip()
|
|
612
|
+
|
|
613
|
+
@property
|
|
614
|
+
def query_params(self) -> List[str]:
|
|
615
|
+
return [
|
|
616
|
+
property.name
|
|
617
|
+
for property in self.properties
|
|
618
|
+
if property.location == APIPropertyLocation.QUERY
|
|
619
|
+
]
|
|
620
|
+
|
|
621
|
+
@property
|
|
622
|
+
def path_params(self) -> List[str]:
|
|
623
|
+
return [
|
|
624
|
+
property.name
|
|
625
|
+
for property in self.properties
|
|
626
|
+
if property.location == APIPropertyLocation.PATH
|
|
627
|
+
]
|
|
628
|
+
|
|
629
|
+
@property
|
|
630
|
+
def body_params(self) -> List[str]:
|
|
631
|
+
if self.request_body is None:
|
|
632
|
+
return []
|
|
633
|
+
return [prop.name for prop in self.request_body.properties]
|