openapi-haystack 0.1.0__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.
@@ -0,0 +1,7 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ from .openapi import OpenAPIConnector
5
+ from .openapi_service import OpenAPIServiceConnector
6
+
7
+ __all__ = ["OpenAPIConnector", "OpenAPIServiceConnector"]
@@ -0,0 +1,98 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from typing import Any
6
+
7
+ from haystack import component, default_from_dict, default_to_dict
8
+ from haystack.utils import Secret
9
+ from openapi_llm.client.openapi import OpenAPIClient
10
+
11
+
12
+ @component
13
+ class OpenAPIConnector:
14
+ """
15
+ OpenAPIConnector enables direct invocation of REST endpoints defined in an OpenAPI specification.
16
+
17
+ The OpenAPIConnector serves as a bridge between Haystack pipelines and any REST API that follows
18
+ the OpenAPI(formerly Swagger) specification. It dynamically interprets the API specification and
19
+ provides an interface for executing API operations. It is usually invoked by passing input
20
+ arguments to it from a Haystack pipeline run method or by other components in a pipeline that
21
+ pass input arguments to this component.
22
+
23
+ Example:
24
+ ```python
25
+ from haystack.utils import Secret
26
+ from haystack_integrations.components.connectors.openapi import OpenAPIConnector
27
+
28
+ serper_dev_token = Secret.from_env_var("SERPERDEV_API_KEY")
29
+
30
+ def my_custom_config_factory():
31
+ # Create and return a custom configuration for the OpenAPIClient
32
+ pass
33
+
34
+ connector = OpenAPIConnector(
35
+ openapi_spec="https://bit.ly/serperdev_openapi",
36
+ credentials=serper_dev_token,
37
+ service_kwargs={"config_factory": my_custom_config_factory()}
38
+ )
39
+ response = connector.run(
40
+ operation_id="search",
41
+ arguments={"q": "Who was Nikola Tesla?"}
42
+ )
43
+ ```
44
+ Note:
45
+ - The `service_kwargs` argument is optional, it can be used to pass additional options to the OpenAPIClient.
46
+
47
+ """
48
+
49
+ def __init__(
50
+ self, openapi_spec: str, credentials: Secret | None = None, service_kwargs: dict[str, Any] | None = None
51
+ ) -> None:
52
+ """
53
+ Initialize the OpenAPIConnector with a specification and optional credentials.
54
+
55
+ :param openapi_spec: URL, file path, or raw string of the OpenAPI specification
56
+ :param credentials: Optional API key or credentials for the service wrapped in a Secret
57
+ :param service_kwargs: Additional keyword arguments passed to OpenAPIClient.from_spec()
58
+ For example, you can pass a custom config_factory or other configuration options.
59
+ """
60
+ self.openapi_spec = openapi_spec
61
+ self.credentials = credentials
62
+ self.service_kwargs = service_kwargs or {}
63
+
64
+ self.client = OpenAPIClient.from_spec(
65
+ openapi_spec=openapi_spec,
66
+ credentials=credentials.resolve_value() if credentials else None,
67
+ **self.service_kwargs,
68
+ )
69
+
70
+ def to_dict(self) -> dict[str, Any]:
71
+ """
72
+ Serialize this component to a dictionary.
73
+ """
74
+ return default_to_dict(
75
+ self, openapi_spec=self.openapi_spec, credentials=self.credentials, service_kwargs=self.service_kwargs
76
+ )
77
+
78
+ @classmethod
79
+ def from_dict(cls, data: dict[str, Any]) -> "OpenAPIConnector":
80
+ """
81
+ Deserialize this component from a dictionary.
82
+ """
83
+ return default_from_dict(cls, data)
84
+
85
+ @component.output_types(response=dict[str, Any])
86
+ def run(self, operation_id: str, arguments: dict[str, Any] | None = None) -> dict[str, Any]:
87
+ """
88
+ Invokes a REST endpoint specified in the OpenAPI specification.
89
+
90
+ :param operation_id: The operationId from the OpenAPI spec to invoke
91
+ :param arguments: Optional parameters for the endpoint (query, path, or body parameters)
92
+ :return: Dictionary containing the service response
93
+ """
94
+ payload = {"name": operation_id, "arguments": arguments or {}}
95
+
96
+ # Invoke the endpoint using openapi-llm client
97
+ response = self.client.invoke(payload)
98
+ return {"response": response}
@@ -0,0 +1,402 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import json
6
+ from collections import defaultdict
7
+ from copy import copy
8
+ from typing import Any
9
+
10
+ import requests
11
+ from haystack import component, default_from_dict, default_to_dict
12
+ from haystack.dataclasses import ChatMessage, ChatRole
13
+ from openapi3 import OpenAPI
14
+ from openapi3.errors import UnexpectedResponseError
15
+ from openapi3.paths import Operation
16
+
17
+
18
+ # Patch the request method to add support for the proper raw_response handling
19
+ # If you see that https://github.com/Dorthu/openapi3/pull/124/
20
+ # is merged, we can remove this patch - notify authors of this code
21
+ def patch_request(
22
+ self: "Operation",
23
+ base_url: str,
24
+ *,
25
+ data: Any | None = None,
26
+ parameters: dict[str, Any] | None = None,
27
+ raw_response: bool = False,
28
+ security: dict[str, str] | None = None,
29
+ session: Any | None = None,
30
+ verify: bool | str = True,
31
+ ) -> Any | None:
32
+ """
33
+ Sends an HTTP request as described by this path.
34
+
35
+ :param base_url: The URL to append this operation's path to when making
36
+ the call.
37
+ :param data: The request body to send.
38
+ :param parameters: The parameters used to create the path.
39
+ :param raw_response: If true, return the raw response instead of validating
40
+ and extrapolating it.
41
+ :param security: The security scheme to use, and the values it needs to
42
+ process successfully.
43
+ :param session: A persistent request session.
44
+ :param verify: If we should do an SSL verification on the request or not.
45
+ In case str was provided, will use that as the CA.
46
+ :return: The response data, either raw or processed depending on raw_response flag.
47
+ """
48
+ # Set request method (e.g. 'GET')
49
+ self._request = requests.Request(self.path[-1])
50
+
51
+ # Set self._request.url to base_url w/ path
52
+ self._request.url = base_url + self.path[-2]
53
+
54
+ parameters = parameters or {}
55
+ security = security or {}
56
+
57
+ if security and self.security:
58
+ security_requirement = None
59
+ for scheme, value in security.items():
60
+ security_requirement = None
61
+ for r in self.security:
62
+ if r.name == scheme:
63
+ security_requirement = r
64
+ self._request_handle_secschemes(r, value)
65
+
66
+ if security_requirement is None:
67
+ err_msg = """No security requirement satisfied (accepts {}) \
68
+ """.format(", ".join(self.security.keys()))
69
+ raise ValueError(err_msg)
70
+
71
+ if self.requestBody:
72
+ if self.requestBody.required and data is None:
73
+ err_msg = "Request Body is required but none was provided."
74
+ raise ValueError(err_msg)
75
+
76
+ self._request_handle_body(data)
77
+
78
+ self._request_handle_parameters(parameters)
79
+
80
+ if session is None:
81
+ session = self._session
82
+
83
+ # send the prepared request
84
+ result = session.send(self._request.prepare(), verify=verify)
85
+
86
+ # spec enforces these are strings
87
+ status_code = str(result.status_code)
88
+
89
+ # find the response model in spec we received
90
+ expected_response = None
91
+ if status_code in self.responses:
92
+ expected_response = self.responses[status_code]
93
+ elif "default" in self.responses:
94
+ expected_response = self.responses["default"]
95
+
96
+ if expected_response is None:
97
+ raise UnexpectedResponseError(result, self)
98
+
99
+ # if we got back a valid response code (or there was a default) and no
100
+ # response content was expected, return None
101
+ if expected_response.content is None:
102
+ return None
103
+
104
+ content_type = result.headers["Content-Type"]
105
+ if ";" in content_type:
106
+ # if the content type that came in included an encoding, we'll ignore
107
+ # it for now (requests has already parsed it for us) and only look at
108
+ # the MIME type when determining if an expected content type was returned.
109
+ content_type = content_type.split(";")[0].strip()
110
+
111
+ expected_media = expected_response.content.get(content_type, None)
112
+
113
+ # If raw_response is True, return the raw text or json based on content type
114
+ if raw_response:
115
+ if "application/json" in content_type:
116
+ return result.json()
117
+ return result.text
118
+
119
+ if expected_media is None and "/" in content_type:
120
+ # accept media type ranges in the spec. the most specific matching
121
+ # type should always be chosen, but if we do not have a match here
122
+ # a generic range should be accepted if one if provided
123
+ # https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#response-object
124
+
125
+ generic_type = content_type.split("/")[0] + "/*"
126
+ expected_media = expected_response.content.get(generic_type, None)
127
+
128
+ if expected_media is None:
129
+ err_msg = """Unexpected Content-Type {} returned for operation {} \
130
+ (expected one of {})"""
131
+ err_var = result.headers["Content-Type"], self.operationId, ",".join(expected_response.content.keys())
132
+
133
+ raise RuntimeError(err_msg.format(*err_var))
134
+
135
+ if content_type.lower() == "application/json":
136
+ return expected_media.schema.model(result.json())
137
+
138
+ raise NotImplementedError("Only application/json content type is supported")
139
+
140
+
141
+ # Apply the patch
142
+ Operation.request = patch_request
143
+
144
+
145
+ @component
146
+ class OpenAPIServiceConnector:
147
+ """
148
+ A component which connects the Haystack framework to OpenAPI services.
149
+
150
+ The `OpenAPIServiceConnector` component connects the Haystack framework to OpenAPI services, enabling it to call
151
+ operations as defined in the OpenAPI specification of the service.
152
+
153
+ It integrates with `ChatMessage` dataclass, where the `ToolCall` entries in messages are used to determine the
154
+ method to be called and the parameters to be passed. The method name and parameters are then used to invoke the
155
+ method on the OpenAPI service. The response from the service is returned as a `ChatMessage`.
156
+
157
+ Before using this component, users usually resolve service endpoint parameters with a help of
158
+ `OpenAPIServiceToFunctions` component.
159
+
160
+ The example below demonstrates how to use the `OpenAPIServiceConnector` to invoke a method on a https://serper.dev/
161
+ service specified via OpenAPI specification.
162
+
163
+ Note, however, that `OpenAPIServiceConnector` is usually not meant to be used directly, but rather as part of a
164
+ pipeline that includes the `OpenAPIServiceToFunctions` component and a Chat Generator component using an LLM
165
+ with tool calling capabilities. In the example below we use the tool call payload directly, but in a
166
+ real-world scenario, the tool calls would usually be generated by the Chat Generator component.
167
+
168
+ You need to define the `serper_token` variable with your Serper.dev API token for the example to work.
169
+ Can be through the `SERPERDEV_API_KEY` environment variable or by directly assigning the token string to the
170
+ variable in the code.
171
+
172
+ Usage example:
173
+ ```python
174
+ import json
175
+ import httpx
176
+
177
+ from haystack.dataclasses import ChatMessage, ToolCall
178
+ from haystack.utils import Secret
179
+ from haystack_integrations.components.connectors.openapi import OpenAPIServiceConnector
180
+
181
+ tool_call = ToolCall(
182
+ tool_name="search",
183
+ arguments={"q": "Why was Sam Altman ousted from OpenAI?"},
184
+ )
185
+ message = ChatMessage.from_assistant(tool_calls=[tool_call])
186
+
187
+ serper_token = Secret.from_env_var("SERPERDEV_API_KEY").resolve_value()
188
+ serperdev_openapi_spec = json.loads(httpx.get("https://bit.ly/serper_dev_spec", follow_redirects=True).text)
189
+ service_connector = OpenAPIServiceConnector()
190
+ result = service_connector.run(
191
+ messages=[message],
192
+ service_openapi_spec=serperdev_openapi_spec,
193
+ service_credentials=serper_token,
194
+ )
195
+ print(result)
196
+
197
+ # {'service_response': [ChatMessage(_role=<ChatRole.USER: 'user'>, _content=[TextContent(text=
198
+ # '{"searchParameters": {"q": "Why was Sam Altman ousted from OpenAI?",
199
+ # "type": "search", "engine": "google"}, "answerBox": {"snippet": "Concerns over AI safety and OpenAI\'s role
200
+ # in protecting were at the center of Altman\'s brief ouster from the company."...
201
+ ```
202
+
203
+ """
204
+
205
+ def __init__(self, ssl_verify: bool | str | None = None) -> None:
206
+ """
207
+ Initializes the OpenAPIServiceConnector instance
208
+
209
+ :param ssl_verify: Decide if to use SSL verification to the requests or not,
210
+ in case a string is passed, will be used as the CA.
211
+ """
212
+ self.ssl_verify = ssl_verify
213
+
214
+ @component.output_types(service_response=dict[str, Any])
215
+ def run(
216
+ self,
217
+ messages: list[ChatMessage],
218
+ service_openapi_spec: dict[str, Any],
219
+ service_credentials: dict | str | None = None,
220
+ ) -> dict[str, list[ChatMessage]]:
221
+ """
222
+ Processes a list of chat messages to invoke a method on an OpenAPI service.
223
+
224
+ It parses the last message in the list, expecting it to contain tool calls.
225
+
226
+ :param messages: A list of `ChatMessage` objects containing the messages to be processed. The last message
227
+ should contain the tool calls.
228
+ :param service_openapi_spec: The OpenAPI JSON specification object of the service to be invoked. All the refs
229
+ should already be resolved.
230
+ :param service_credentials: The credentials to be used for authentication with the service.
231
+ Currently, only the http and apiKey OpenAPI security schemes are supported.
232
+
233
+ :return: A dictionary with the following keys:
234
+ - `service_response`: a list of `ChatMessage` objects, each containing the response from the service. The
235
+ response is in JSON format, and the `content` attribute of the `ChatMessage` contains
236
+ the JSON string.
237
+
238
+ :raises ValueError: If the last message is not from the assistant or if it does not contain tool calls.
239
+ """
240
+
241
+ last_message = messages[-1]
242
+ if not last_message.is_from(ChatRole.ASSISTANT):
243
+ raise ValueError(f"{last_message} is not from the assistant.")
244
+
245
+ tool_calls = last_message.tool_calls
246
+ if not tool_calls:
247
+ raise ValueError(f"The provided ChatMessage has no tool calls.\nChatMessage: {last_message}")
248
+
249
+ function_payloads = []
250
+ for tool_call in tool_calls:
251
+ function_payloads.append({"arguments": tool_call.arguments, "name": tool_call.tool_name})
252
+
253
+ # instantiate the OpenAPI service for the given specification
254
+ openapi_service = OpenAPI(service_openapi_spec, ssl_verify=self.ssl_verify)
255
+ self._authenticate_service(openapi_service, service_credentials)
256
+
257
+ response_messages = []
258
+ for method_invocation_descriptor in function_payloads:
259
+ service_response = self._invoke_method(openapi_service, method_invocation_descriptor)
260
+ # openapi3 parses the JSON service response into a model object, which is not our focus at the moment.
261
+ # Instead, we require direct access to the raw JSON data of the response, rather than the model objects
262
+ # provided by the openapi3 library. This approach helps us avoid issues related to (de)serialization.
263
+ # By accessing the raw JSON response through `service_response._raw_data`, we can serialize this data
264
+ # into a string. Finally, we use this string to create a ChatMessage object.
265
+ response_messages.append(ChatMessage.from_user(json.dumps(service_response)))
266
+
267
+ return {"service_response": response_messages}
268
+
269
+ def to_dict(self) -> dict[str, Any]:
270
+ """
271
+ Serializes the component to a dictionary.
272
+
273
+ :returns:
274
+ Dictionary with serialized data.
275
+ """
276
+ return default_to_dict(self, ssl_verify=self.ssl_verify)
277
+
278
+ @classmethod
279
+ def from_dict(cls, data: dict[str, Any]) -> "OpenAPIServiceConnector":
280
+ """
281
+ Deserializes the component from a dictionary.
282
+
283
+ :param data:
284
+ The dictionary to deserialize from.
285
+ :returns:
286
+ The deserialized component.
287
+ """
288
+ return default_from_dict(cls, data)
289
+
290
+ def _authenticate_service(self, openapi_service: "OpenAPI", credentials: dict | str | None = None) -> None:
291
+ """
292
+ Authentication with an OpenAPI service.
293
+
294
+ Authenticates with the OpenAPI service if required, supporting both single (str) and multiple
295
+ authentication methods (dict).
296
+
297
+ OpenAPI spec v3 supports the following security schemes:
298
+ http - for Basic, Bearer and other HTTP authentications schemes
299
+ apiKey - for API keys and cookie authentication
300
+ oauth2 - for OAuth 2
301
+ openIdConnect - for OpenID Connect Discovery
302
+
303
+ Currently, only the http and apiKey schemes are supported. Multiple security schemes can be defined in the
304
+ OpenAPI spec, and the credentials should be provided as a dictionary with keys matching the security scheme
305
+ names. If only one security scheme is defined, the credentials can be provided as a simple string.
306
+
307
+ :param openapi_service: The OpenAPI service instance.
308
+ :param credentials: Credentials for authentication, which can be either a string (e.g. token) or a dictionary
309
+ with keys matching the authentication method names.
310
+ :raises ValueError: If authentication fails, is not found, or if appropriate credentials are missing.
311
+ """
312
+ if openapi_service.raw_element.get("components", {}).get("securitySchemes"):
313
+ service_name = openapi_service.info.title
314
+ if not credentials:
315
+ raise ValueError(f"Service {service_name} requires authentication but no credentials were provided.")
316
+
317
+ # a dictionary of security schemes defined in the OpenAPI spec
318
+ # each key is the name of the security scheme, and the value is the scheme definition
319
+ security_schemes = openapi_service.components.securitySchemes.raw_element
320
+ supported_schemes = ["http", "apiKey"] # todo: add support for oauth2 and openIdConnect
321
+
322
+ authenticated = False
323
+ for scheme_name, scheme in security_schemes.items():
324
+ if scheme["type"] in supported_schemes:
325
+ auth_credentials = None
326
+ if isinstance(credentials, str):
327
+ auth_credentials = credentials
328
+ elif isinstance(credentials, dict) and scheme_name in credentials:
329
+ auth_credentials = credentials[scheme_name]
330
+ if auth_credentials:
331
+ openapi_service.authenticate(scheme_name, auth_credentials)
332
+ authenticated = True
333
+ break
334
+
335
+ raise ValueError(
336
+ f"Service {service_name} requires {scheme_name} security scheme but no "
337
+ f"credentials were provided for it. Check the service configuration and credentials."
338
+ )
339
+ if not authenticated:
340
+ raise ValueError(
341
+ f"Service {service_name} requires authentication but no credentials were provided "
342
+ f"for it. Check the service configuration and credentials."
343
+ )
344
+
345
+ def _invoke_method(self, openapi_service: "OpenAPI", method_invocation_descriptor: dict[str, Any]) -> Any:
346
+ """
347
+ Invokes the specified method on the OpenAPI service.
348
+
349
+ The method name and arguments are passed in the method_invocation_descriptor.
350
+
351
+ :param openapi_service: The OpenAPI service instance.
352
+ :param method_invocation_descriptor: The method name and arguments to be passed to the method. The payload
353
+ should contain the method name (key: "name") and the arguments (key: "arguments"). The name is a string, and
354
+ the arguments are a dictionary of key-value pairs.
355
+ :return: A service JSON response.
356
+ :raises ValueError: If the descriptor is malformed or a required parameter is missing.
357
+ :raises TypeError: If the operation is not found in the OpenAPI specification.
358
+ """
359
+ name = method_invocation_descriptor.get("name")
360
+ invocation_arguments = copy(method_invocation_descriptor.get("arguments", {}))
361
+ if not name or not invocation_arguments:
362
+ raise ValueError(
363
+ f"Invalid function calling descriptor: {method_invocation_descriptor} . It should contain "
364
+ f"a method name and arguments."
365
+ )
366
+
367
+ # openapi3 specific method to call the operation, do we have it?
368
+ method_to_call = getattr(openapi_service, f"call_{name}", None)
369
+ if not callable(method_to_call):
370
+ raise TypeError(f"Operation {name} not found in OpenAPI specification {openapi_service.info.title}")
371
+
372
+ # get the operation reference from the method_to_call
373
+ operation = method_to_call.operation.__self__
374
+ operation_dict = operation.raw_element
375
+
376
+ # Pack URL/query parameters under "parameters" key
377
+ method_call_params: dict[str, dict[str, Any]] = defaultdict(dict)
378
+ parameters = operation_dict.get("parameters", [])
379
+ request_body = operation_dict.get("requestBody", {})
380
+
381
+ for param in parameters:
382
+ param_name = param["name"]
383
+ param_value = invocation_arguments.get(param_name)
384
+ if param_value:
385
+ method_call_params["parameters"][param_name] = param_value
386
+ elif param.get("required", False):
387
+ raise ValueError(f"Missing parameter: '{param_name}' required for the '{name}' operation.")
388
+
389
+ # Pack request body parameters under "data" key
390
+ if request_body:
391
+ schema = request_body.get("content", {}).get("application/json", {}).get("schema", {})
392
+ required_params = schema.get("required", [])
393
+ for param_name in schema.get("properties", {}):
394
+ param_value = invocation_arguments.get(param_name)
395
+ if param_value:
396
+ method_call_params["data"][param_name] = param_value
397
+ elif param_name in required_params:
398
+ raise ValueError(
399
+ f"Missing requestBody parameter: '{param_name}' required for the '{name}' operation."
400
+ )
401
+ # call the underlying service REST API with the parameters
402
+ return method_to_call(**method_call_params, raw_response=True)
File without changes
@@ -0,0 +1,6 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ from .openapi_functions import OpenAPIServiceToFunctions
5
+
6
+ __all__ = ["OpenAPIServiceToFunctions"]
@@ -0,0 +1,256 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import jsonref
11
+ import yaml
12
+ from haystack import component, logging
13
+ from haystack.dataclasses.byte_stream import ByteStream
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ @component
19
+ class OpenAPIServiceToFunctions:
20
+ """
21
+ Converts OpenAPI service definitions to a format suitable for OpenAI function calling.
22
+
23
+ The definition must respect OpenAPI specification 3.0.0 or higher.
24
+ It can be specified in JSON or YAML format.
25
+ Each function must have:
26
+ - unique operationId
27
+ - description
28
+ - requestBody and/or parameters
29
+ - schema for the requestBody and/or parameters
30
+ For more details on OpenAPI specification see the [official documentation](https://github.com/OAI/OpenAPI-Specification).
31
+ For more details on OpenAI function calling see the [official documentation](https://platform.openai.com/docs/guides/function-calling).
32
+
33
+ Usage example:
34
+ ```python
35
+ from haystack.dataclasses.byte_stream import ByteStream
36
+ from haystack_integrations.components.converters.openapi import OpenAPIServiceToFunctions
37
+
38
+ converter = OpenAPIServiceToFunctions()
39
+ spec = ByteStream.from_string(
40
+ '{"openapi":"3.0.0","info":{"title":"API","version":"1.0.0"},"paths":{"/search":{"get":{"operationId":"search","summary":"Search","parameters":[{"name":"q","in":"query","required":true,"schema":{"type":"string"}}]}}}}'
41
+ )
42
+ result = converter.run(sources=[spec])
43
+ assert result["functions"]
44
+ ```
45
+ """
46
+
47
+ MIN_REQUIRED_OPENAPI_SPEC_VERSION = 3
48
+
49
+ def __init__(self) -> None:
50
+ """
51
+ Create an OpenAPIServiceToFunctions component.
52
+ """
53
+
54
+ @component.output_types(functions=list[dict[str, Any]], openapi_specs=list[dict[str, Any]])
55
+ def run(self, sources: list[str | Path | ByteStream]) -> dict[str, Any]:
56
+ """
57
+ Converts OpenAPI definitions in OpenAI function calling format.
58
+
59
+ :param sources:
60
+ File paths or ByteStream objects of OpenAPI definitions (in JSON or YAML format).
61
+
62
+ :returns:
63
+ A dictionary with the following keys:
64
+ - functions: Function definitions in JSON object format
65
+ - openapi_specs: OpenAPI specs in JSON/YAML object format with resolved references
66
+
67
+ :raises RuntimeError:
68
+ If the OpenAPI definitions cannot be downloaded or processed.
69
+ :raises ValueError:
70
+ If the source type is not recognized or no functions are found in the OpenAPI definitions.
71
+ """
72
+ all_extracted_fc_definitions: list[dict[str, Any]] = []
73
+ all_openapi_specs = []
74
+ for source in sources:
75
+ openapi_spec_content = None
76
+ if isinstance(source, (str, Path)):
77
+ if os.path.exists(source):
78
+ try:
79
+ with open(source) as f:
80
+ openapi_spec_content = f.read()
81
+ except OSError as e:
82
+ logger.warning(
83
+ "IO error reading OpenAPI specification file: {source}. Error: {e}", source=source, e=e
84
+ )
85
+ else:
86
+ logger.warning("OpenAPI specification file not found: {source}", source=source)
87
+ elif isinstance(source, ByteStream):
88
+ openapi_spec_content = source.data.decode("utf-8")
89
+ if not openapi_spec_content:
90
+ logger.warning(
91
+ "Invalid OpenAPI specification content provided: {openapi_spec_content}",
92
+ openapi_spec_content=openapi_spec_content,
93
+ )
94
+ else:
95
+ logger.warning(
96
+ "Invalid source type {source}. Only str, Path, and ByteStream are supported.", source=type(source)
97
+ )
98
+ continue
99
+
100
+ if openapi_spec_content:
101
+ try:
102
+ service_openapi_spec = self._parse_openapi_spec(openapi_spec_content)
103
+ functions: list[dict[str, Any]] = self._openapi_to_functions(service_openapi_spec)
104
+ all_extracted_fc_definitions.extend(functions)
105
+ all_openapi_specs.append(service_openapi_spec)
106
+ except Exception as e:
107
+ logger.exception(
108
+ "Error processing OpenAPI specification from source {source}: {error}", source=source, error=e
109
+ )
110
+
111
+ if not all_extracted_fc_definitions:
112
+ logger.warning("No OpenAI function definitions extracted from the provided OpenAPI specification sources.")
113
+
114
+ return {"functions": all_extracted_fc_definitions, "openapi_specs": all_openapi_specs}
115
+
116
+ def _openapi_to_functions(self, service_openapi_spec: dict[str, Any]) -> list[dict[str, Any]]:
117
+ """
118
+ OpenAPI to OpenAI function conversion.
119
+
120
+ Extracts functions from the OpenAPI specification of the service and converts them into a format
121
+ suitable for OpenAI function calling.
122
+
123
+ :param service_openapi_spec: The OpenAPI specification from which functions are to be extracted.
124
+ :type service_openapi_spec: dict[str, Any]
125
+ :return: A list of dictionaries, each representing a function. Each dictionary includes the function's
126
+ name, description, and a schema of its parameters.
127
+ :rtype: list[dict[str, Any]]
128
+ """
129
+
130
+ # Doesn't enforce rigid spec validation because that would require a lot of dependencies
131
+ # We check the version and require minimal fields to be present, so we can extract functions
132
+ spec_version = service_openapi_spec.get("openapi")
133
+ if not spec_version:
134
+ raise ValueError(f"Invalid OpenAPI spec provided. Could not extract version from {service_openapi_spec}")
135
+ service_openapi_spec_version = int(spec_version.split(".")[0])
136
+
137
+ # Compare the versions
138
+ if service_openapi_spec_version < OpenAPIServiceToFunctions.MIN_REQUIRED_OPENAPI_SPEC_VERSION:
139
+ raise ValueError(
140
+ f"Invalid OpenAPI spec version {service_openapi_spec_version}. Must be "
141
+ f"at least {OpenAPIServiceToFunctions.MIN_REQUIRED_OPENAPI_SPEC_VERSION}."
142
+ )
143
+
144
+ functions: list[dict[str, Any]] = []
145
+ for paths in service_openapi_spec["paths"].values():
146
+ for path_spec in paths.values():
147
+ function_dict = self._parse_endpoint_spec(path_spec)
148
+ if function_dict:
149
+ functions.append(function_dict)
150
+ return functions
151
+
152
+ def _parse_endpoint_spec(self, resolved_spec: dict[str, Any]) -> dict[str, Any] | None:
153
+ if not isinstance(resolved_spec, dict):
154
+ logger.warning("Invalid OpenAPI spec format provided. Could not extract function.")
155
+ return {}
156
+
157
+ function_name = resolved_spec.get("operationId")
158
+ description = resolved_spec.get("description") or resolved_spec.get("summary", "")
159
+
160
+ schema: dict[str, Any] = {"type": "object", "properties": {}}
161
+
162
+ # requestBody section
163
+ req_body_schema = (
164
+ resolved_spec.get("requestBody", {}).get("content", {}).get("application/json", {}).get("schema", {})
165
+ )
166
+ if "properties" in req_body_schema:
167
+ for prop_name, prop_schema in req_body_schema["properties"].items():
168
+ schema["properties"][prop_name] = self._parse_property_attributes(prop_schema)
169
+
170
+ if "required" in req_body_schema:
171
+ schema.setdefault("required", []).extend(req_body_schema["required"])
172
+
173
+ # parameters section
174
+ for param in resolved_spec.get("parameters", []):
175
+ if "schema" in param:
176
+ schema_dict = self._parse_property_attributes(param["schema"])
177
+ # these attributes are not in param[schema] level but on param level
178
+ useful_attributes = ["description", "pattern", "enum"]
179
+ schema_dict.update({key: param[key] for key in useful_attributes if param.get(key)})
180
+ schema["properties"][param["name"]] = schema_dict
181
+ if param.get("required", False):
182
+ schema.setdefault("required", []).append(param["name"])
183
+
184
+ if function_name and description and schema["properties"]:
185
+ return {"name": function_name, "description": description, "parameters": schema}
186
+
187
+ logger.warning(
188
+ "Invalid OpenAPI spec format provided. Could not extract function from {spec}", spec=resolved_spec
189
+ )
190
+ return {}
191
+
192
+ def _parse_property_attributes(
193
+ self, property_schema: dict[str, Any], include_attributes: list[str] | None = None
194
+ ) -> dict[str, Any]:
195
+ """
196
+ Parses the attributes of a property schema.
197
+
198
+ Recursively parses the attributes of a property schema, including nested objects and arrays,
199
+ and includes specified attributes like description, pattern, etc.
200
+
201
+ :param property_schema: The schema of the property to parse.
202
+ :param include_attributes: The list of attributes to include in the parsed schema.
203
+ :return: The parsed schema of the property including the specified attributes.
204
+ """
205
+ include_attributes = include_attributes or ["description", "pattern", "enum"]
206
+
207
+ schema_type = property_schema.get("type")
208
+
209
+ parsed_schema = {"type": schema_type} if schema_type else {}
210
+ for attr in include_attributes:
211
+ if attr in property_schema:
212
+ parsed_schema[attr] = property_schema[attr]
213
+
214
+ if schema_type == "object":
215
+ properties = property_schema.get("properties", {})
216
+ parsed_properties = {
217
+ prop_name: self._parse_property_attributes(prop, include_attributes)
218
+ for prop_name, prop in properties.items()
219
+ }
220
+ parsed_schema["properties"] = parsed_properties
221
+
222
+ if "required" in property_schema:
223
+ parsed_schema["required"] = property_schema["required"]
224
+
225
+ elif schema_type == "array":
226
+ items = property_schema.get("items", {})
227
+ parsed_schema["items"] = self._parse_property_attributes(items, include_attributes)
228
+
229
+ return parsed_schema
230
+
231
+ def _parse_openapi_spec(self, content: str) -> dict[str, Any]:
232
+ """
233
+ Parses OpenAPI specification content, supporting both JSON and YAML formats.
234
+
235
+ :param content: The content of the OpenAPI specification.
236
+ :return: The parsed OpenAPI specification.
237
+ """
238
+ open_api_spec_content = None
239
+ try:
240
+ open_api_spec_content = json.loads(content)
241
+ return jsonref.replace_refs(open_api_spec_content)
242
+ except json.JSONDecodeError as json_error:
243
+ # heuristic to confirm that the content is likely malformed JSON
244
+ if content.strip().startswith(("{", "[")):
245
+ raise json_error
246
+
247
+ try:
248
+ open_api_spec_content = yaml.safe_load(content)
249
+ except yaml.YAMLError as e:
250
+ error_message = (
251
+ "Failed to parse the OpenAPI specification. The content does not appear to be valid JSON or YAML.\n\n"
252
+ )
253
+ raise RuntimeError(error_message, content) from e
254
+
255
+ # Replace references in the object with their resolved values, if any
256
+ return jsonref.replace_refs(open_api_spec_content)
File without changes
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: openapi-haystack
3
+ Version: 0.1.0
4
+ Summary: Haystack integration for openapi
5
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/openapi#readme
6
+ Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
7
+ Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/openapi
8
+ Author-email: deepset GmbH <info@deepset.ai>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
11
+ Keywords: api,connector,function-calling,haystack,openapi,rest
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: Implementation :: CPython
21
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: haystack-ai>=2.23.0
24
+ Requires-Dist: openapi-llm>=0.4.1
25
+ Requires-Dist: openapi3>=1.8.2
26
+ Description-Content-Type: text/markdown
27
+
28
+ # openapi-haystack
29
+
30
+ [![PyPI - Version](https://img.shields.io/pypi/v/openapi-haystack.svg)](https://pypi.org/project/openapi-haystack)
31
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/openapi-haystack.svg)](https://pypi.org/project/openapi-haystack)
32
+
33
+ - [Integration page](https://haystack.deepset.ai/integrations/openapi)
34
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/openapi/CHANGELOG.md)
35
+
36
+ ---
37
+
38
+ ## Contributing
39
+
40
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
@@ -0,0 +1,11 @@
1
+ haystack_integrations/components/connectors/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ haystack_integrations/components/connectors/openapi/__init__.py,sha256=n2wOErOeajviZ404v1SjBSSD6hsUW0chCLLYjuVwTKA,260
3
+ haystack_integrations/components/connectors/openapi/openapi.py,sha256=pvokis7cYm4QNkwmE7jhG89nZzZg4eC1sKIjoC4CP8Q,3826
4
+ haystack_integrations/components/connectors/openapi/openapi_service.py,sha256=_QChS7DmOy2ErVyM4Ln7MfuCpu8TAMJhY1ti2x5dKhY,18598
5
+ haystack_integrations/components/converters/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ haystack_integrations/components/converters/openapi/__init__.py,sha256=S90Ozy9211q-WBermg31Qd33o6_VF7CQawbZO-iL7bE,208
7
+ haystack_integrations/components/converters/openapi/openapi_functions.py,sha256=B-qT6BHDmbQ5UC8Kzhnehm4yLQnLp9u3mkag77WE8Co,11541
8
+ openapi_haystack-0.1.0.dist-info/METADATA,sha256=7xbX56KA5Mum-0CGOPOT_2xBPzMtxvOuipeMnC-bLik,1903
9
+ openapi_haystack-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
10
+ openapi_haystack-0.1.0.dist-info/licenses/LICENSE.txt,sha256=OrAtTu4aPmrTjKDSTzkSPgo_ji6NOMWO2N9JOTFyAzM,11350
11
+ openapi_haystack-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023-present deepset GmbH
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.