connectors_api.md
  1  ---
  2  title: Connectors
  3  id: connectors-api
  4  description: Various connectors to integrate with external services.
  5  slug: "/connectors-api"
  6  ---
  7  
  8  <a id="openapi_service"></a>
  9  
 10  # Module openapi\_service
 11  
 12  <a id="openapi_service.OpenAPIServiceConnector"></a>
 13  
 14  ## OpenAPIServiceConnector
 15  
 16  A component which connects the Haystack framework to OpenAPI services.
 17  
 18  The `OpenAPIServiceConnector` component connects the Haystack framework to OpenAPI services, enabling it to call
 19  operations as defined in the OpenAPI specification of the service.
 20  
 21  It integrates with `ChatMessage` dataclass, where the payload in messages is used to determine the method to be
 22  called and the parameters to be passed. The message payload should be an OpenAI JSON formatted function calling
 23  string consisting of the method name and the parameters to be passed to the method. The method name and parameters
 24  are then used to invoke the method on the OpenAPI service. The response from the service is returned as a
 25  `ChatMessage`.
 26  
 27  Before using this component, users usually resolve service endpoint parameters with a help of
 28  `OpenAPIServiceToFunctions` component.
 29  
 30  The example below demonstrates how to use the `OpenAPIServiceConnector` to invoke a method on a https://serper.dev/
 31  service specified via OpenAPI specification.
 32  
 33  Note, however, that `OpenAPIServiceConnector` is usually not meant to be used directly, but rather as part of a
 34  pipeline that includes the `OpenAPIServiceToFunctions` component and an `OpenAIChatGenerator` component using LLM
 35  with the function calling capabilities. In the example below we use the function calling payload directly, but in a
 36  real-world scenario, the function calling payload would usually be generated by the `OpenAIChatGenerator` component.
 37  
 38  Usage example:
 39  
 40  ```python
 41  import json
 42  import requests
 43  
 44  from haystack.components.connectors import OpenAPIServiceConnector
 45  from haystack.dataclasses import ChatMessage
 46  
 47  
 48  fc_payload = [{'function': {'arguments': '{"q": "Why was Sam Altman ousted from OpenAI?"}', 'name': 'search'},
 49                 'id': 'call_PmEBYvZ7mGrQP5PUASA5m9wO', 'type': 'function'}]
 50  
 51  serper_token = <your_serper_dev_token>
 52  serperdev_openapi_spec = json.loads(requests.get("https://bit.ly/serper_dev_spec").text)
 53  service_connector = OpenAPIServiceConnector()
 54  result = service_connector.run(messages=[ChatMessage.from_assistant(json.dumps(fc_payload))],
 55                                 service_openapi_spec=serperdev_openapi_spec, service_credentials=serper_token)
 56  print(result)
 57  
 58  >> {'service_response': [ChatMessage(_role=<ChatRole.ASSISTANT: 'assistant'>, _content=[TextContent(text=
 59  >> '{"searchParameters": {"q": "Why was Sam Altman ousted from OpenAI?",
 60  >> "type": "search", "engine": "google"}, "answerBox": {"snippet": "Concerns over AI safety and OpenAI's role
 61  >> in protecting were at the center of Altman's brief ouster from the company."...
 62  ```
 63  
 64  <a id="openapi_service.OpenAPIServiceConnector.__init__"></a>
 65  
 66  #### OpenAPIServiceConnector.\_\_init\_\_
 67  
 68  ```python
 69  def __init__(ssl_verify: Optional[Union[bool, str]] = None)
 70  ```
 71  
 72  Initializes the OpenAPIServiceConnector instance
 73  
 74  **Arguments**:
 75  
 76  - `ssl_verify`: Decide if to use SSL verification to the requests or not,
 77  in case a string is passed, will be used as the CA.
 78  
 79  <a id="openapi_service.OpenAPIServiceConnector.run"></a>
 80  
 81  #### OpenAPIServiceConnector.run
 82  
 83  ```python
 84  @component.output_types(service_response=dict[str, Any])
 85  def run(
 86      messages: list[ChatMessage],
 87      service_openapi_spec: dict[str, Any],
 88      service_credentials: Optional[Union[dict, str]] = None
 89  ) -> dict[str, list[ChatMessage]]
 90  ```
 91  
 92  Processes a list of chat messages to invoke a method on an OpenAPI service.
 93  
 94  It parses the last message in the list, expecting it to contain tool calls.
 95  
 96  **Arguments**:
 97  
 98  - `messages`: A list of `ChatMessage` objects containing the messages to be processed. The last message
 99  should contain the tool calls.
100  - `service_openapi_spec`: The OpenAPI JSON specification object of the service to be invoked. All the refs
101  should already be resolved.
102  - `service_credentials`: The credentials to be used for authentication with the service.
103  Currently, only the http and apiKey OpenAPI security schemes are supported.
104  
105  **Raises**:
106  
107  - `ValueError`: If the last message is not from the assistant or if it does not contain tool calls.
108  
109  **Returns**:
110  
111  A dictionary with the following keys:
112  - `service_response`:  a list of `ChatMessage` objects, each containing the response from the service. The
113  response is in JSON format, and the `content` attribute of the `ChatMessage` contains
114  the JSON string.
115  
116  <a id="openapi_service.OpenAPIServiceConnector.to_dict"></a>
117  
118  #### OpenAPIServiceConnector.to\_dict
119  
120  ```python
121  def to_dict() -> dict[str, Any]
122  ```
123  
124  Serializes the component to a dictionary.
125  
126  **Returns**:
127  
128  Dictionary with serialized data.
129  
130  <a id="openapi_service.OpenAPIServiceConnector.from_dict"></a>
131  
132  #### OpenAPIServiceConnector.from\_dict
133  
134  ```python
135  @classmethod
136  def from_dict(cls, data: dict[str, Any]) -> "OpenAPIServiceConnector"
137  ```
138  
139  Deserializes the component from a dictionary.
140  
141  **Arguments**:
142  
143  - `data`: The dictionary to deserialize from.
144  
145  **Returns**:
146  
147  The deserialized component.
148  
149  <a id="openapi"></a>
150  
151  # Module openapi
152  
153  <a id="openapi.OpenAPIConnector"></a>
154  
155  ## OpenAPIConnector
156  
157  OpenAPIConnector enables direct invocation of REST endpoints defined in an OpenAPI specification.
158  
159  The OpenAPIConnector serves as a bridge between Haystack pipelines and any REST API that follows
160  the OpenAPI(formerly Swagger) specification. It dynamically interprets the API specification and
161  provides an interface for executing API operations. It is usually invoked by passing input
162  arguments to it from a Haystack pipeline run method or by other components in a pipeline that
163  pass input arguments to this component.
164  
165  **Example**:
166  
167  ```python
168  from haystack.utils import Secret
169  from haystack.components.connectors.openapi import OpenAPIConnector
170  
171  connector = OpenAPIConnector(
172      openapi_spec="https://bit.ly/serperdev_openapi",
173      credentials=Secret.from_env_var("SERPERDEV_API_KEY"),
174      service_kwargs={"config_factory": my_custom_config_factory}
175  )
176  response = connector.run(
177      operation_id="search",
178      arguments={"q": "Who was Nikola Tesla?"}
179  )
180  ```
181  
182  **Notes**:
183  
184    - The `parameters` argument is required for this component.
185    - The `service_kwargs` argument is optional, it can be used to pass additional options to the OpenAPIClient.
186  
187  <a id="openapi.OpenAPIConnector.__init__"></a>
188  
189  #### OpenAPIConnector.\_\_init\_\_
190  
191  ```python
192  def __init__(openapi_spec: str,
193               credentials: Optional[Secret] = None,
194               service_kwargs: Optional[dict[str, Any]] = None)
195  ```
196  
197  Initialize the OpenAPIConnector with a specification and optional credentials.
198  
199  **Arguments**:
200  
201  - `openapi_spec`: URL, file path, or raw string of the OpenAPI specification
202  - `credentials`: Optional API key or credentials for the service wrapped in a Secret
203  - `service_kwargs`: Additional keyword arguments passed to OpenAPIClient.from_spec()
204  For example, you can pass a custom config_factory or other configuration options.
205  
206  <a id="openapi.OpenAPIConnector.to_dict"></a>
207  
208  #### OpenAPIConnector.to\_dict
209  
210  ```python
211  def to_dict() -> dict[str, Any]
212  ```
213  
214  Serialize this component to a dictionary.
215  
216  <a id="openapi.OpenAPIConnector.from_dict"></a>
217  
218  #### OpenAPIConnector.from\_dict
219  
220  ```python
221  @classmethod
222  def from_dict(cls, data: dict[str, Any]) -> "OpenAPIConnector"
223  ```
224  
225  Deserialize this component from a dictionary.
226  
227  <a id="openapi.OpenAPIConnector.run"></a>
228  
229  #### OpenAPIConnector.run
230  
231  ```python
232  @component.output_types(response=dict[str, Any])
233  def run(operation_id: str,
234          arguments: Optional[dict[str, Any]] = None) -> dict[str, Any]
235  ```
236  
237  Invokes a REST endpoint specified in the OpenAPI specification.
238  
239  **Arguments**:
240  
241  - `operation_id`: The operationId from the OpenAPI spec to invoke
242  - `arguments`: Optional parameters for the endpoint (query, path, or body parameters)
243  
244  **Returns**:
245  
246  Dictionary containing the service response