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  
  9  ## openapi
 10  
 11  ### OpenAPIConnector
 12  
 13  OpenAPIConnector enables direct invocation of REST endpoints defined in an OpenAPI specification.
 14  
 15  The OpenAPIConnector serves as a bridge between Haystack pipelines and any REST API that follows
 16  the OpenAPI(formerly Swagger) specification. It dynamically interprets the API specification and
 17  provides an interface for executing API operations. It is usually invoked by passing input
 18  arguments to it from a Haystack pipeline run method or by other components in a pipeline that
 19  pass input arguments to this component.
 20  
 21  Example:
 22  
 23  <!-- test-ignore -->
 24  
 25  ```python
 26  from haystack.utils import Secret
 27  from haystack.components.connectors.openapi import OpenAPIConnector
 28  
 29  serper_dev_token = Secret.from_env_var("SERPERDEV_API_KEY")
 30  
 31  def my_custom_config_factory():
 32      # Create and return a custom configuration for the OpenAPIClient
 33      pass
 34  
 35  connector = OpenAPIConnector(
 36      openapi_spec="https://bit.ly/serperdev_openapi",
 37      credentials=serper_dev_token,
 38      service_kwargs={"config_factory": my_custom_config_factory()}
 39  )
 40  response = connector.run(
 41      operation_id="search",
 42      arguments={"q": "Who was Nikola Tesla?"}
 43  )
 44  ```
 45  
 46  Note:
 47  
 48  - The `service_kwargs` argument is optional, it can be used to pass additional options to the OpenAPIClient.
 49  
 50  #### __init__
 51  
 52  ```python
 53  __init__(
 54      openapi_spec: str,
 55      credentials: Secret | None = None,
 56      service_kwargs: dict[str, Any] | None = None,
 57  ) -> None
 58  ```
 59  
 60  Initialize the OpenAPIConnector with a specification and optional credentials.
 61  
 62  **Parameters:**
 63  
 64  - **openapi_spec** (<code>str</code>) – URL, file path, or raw string of the OpenAPI specification
 65  - **credentials** (<code>Secret | None</code>) – Optional API key or credentials for the service wrapped in a Secret
 66  - **service_kwargs** (<code>dict\[str, Any\] | None</code>) – Additional keyword arguments passed to OpenAPIClient.from_spec()
 67    For example, you can pass a custom config_factory or other configuration options.
 68  
 69  #### to_dict
 70  
 71  ```python
 72  to_dict() -> dict[str, Any]
 73  ```
 74  
 75  Serialize this component to a dictionary.
 76  
 77  #### from_dict
 78  
 79  ```python
 80  from_dict(data: dict[str, Any]) -> OpenAPIConnector
 81  ```
 82  
 83  Deserialize this component from a dictionary.
 84  
 85  #### run
 86  
 87  ```python
 88  run(
 89      operation_id: str, arguments: dict[str, Any] | None = None
 90  ) -> dict[str, Any]
 91  ```
 92  
 93  Invokes a REST endpoint specified in the OpenAPI specification.
 94  
 95  **Parameters:**
 96  
 97  - **operation_id** (<code>str</code>) – The operationId from the OpenAPI spec to invoke
 98  - **arguments** (<code>dict\[str, Any\] | None</code>) – Optional parameters for the endpoint (query, path, or body parameters)
 99  
100  **Returns:**
101  
102  - <code>dict\[str, Any\]</code> – Dictionary containing the service response
103  
104  ## openapi_service
105  
106  ### patch_request
107  
108  ```python
109  patch_request(
110      self: Operation,
111      base_url: str,
112      *,
113      data: Any | None = None,
114      parameters: dict[str, Any] | None = None,
115      raw_response: bool = False,
116      security: dict[str, str] | None = None,
117      session: Any | None = None,
118      verify: bool | str = True
119  ) -> Any | None
120  ```
121  
122  Sends an HTTP request as described by this path.
123  
124  **Parameters:**
125  
126  - **base_url** (<code>str</code>) – The URL to append this operation's path to when making
127    the call.
128  - **data** (<code>Any | None</code>) – The request body to send.
129  - **parameters** (<code>dict\[str, Any\] | None</code>) – The parameters used to create the path.
130  - **raw_response** (<code>bool</code>) – If true, return the raw response instead of validating
131    and extrapolating it.
132  - **security** (<code>dict\[str, str\] | None</code>) – The security scheme to use, and the values it needs to
133    process successfully.
134  - **session** (<code>Any | None</code>) – A persistent request session.
135  - **verify** (<code>bool | str</code>) – If we should do an SSL verification on the request or not.
136    In case str was provided, will use that as the CA.
137  
138  **Returns:**
139  
140  - <code>Any | None</code> – The response data, either raw or processed depending on raw_response flag.
141  
142  ### OpenAPIServiceConnector
143  
144  A component which connects the Haystack framework to OpenAPI services.
145  
146  The `OpenAPIServiceConnector` component connects the Haystack framework to OpenAPI services, enabling it to call
147  operations as defined in the OpenAPI specification of the service.
148  
149  It integrates with `ChatMessage` dataclass, where the `ToolCall` entries in messages are used to determine the
150  method to be called and the parameters to be passed. The method name and parameters are then used to invoke the
151  method on the OpenAPI service. The response from the service is returned as a `ChatMessage`.
152  
153  Before using this component, users usually resolve service endpoint parameters with a help of
154  `OpenAPIServiceToFunctions` component.
155  
156  The example below demonstrates how to use the `OpenAPIServiceConnector` to invoke a method on a https://serper.dev/
157  service specified via OpenAPI specification.
158  
159  Note, however, that `OpenAPIServiceConnector` is usually not meant to be used directly, but rather as part of a
160  pipeline that includes the `OpenAPIServiceToFunctions` component and a Chat Generator component using an LLM
161  with tool calling capabilities. In the example below we use the tool call payload directly, but in a
162  real-world scenario, the tool calls would usually be generated by the Chat Generator component.
163  
164  You need to define the `serper_token` variable with your Serper.dev API token for the example to work.
165  Can be through the `SERPERDEV_API_KEY` environment variable or by directly assigning the token string to the
166  variable in the code.
167  
168  Usage example:
169  
170  <!-- test-ignore -->
171  
172  ```python
173  import json
174  import httpx
175  
176  from haystack.components.connectors import OpenAPIServiceConnector
177  from haystack.dataclasses import ChatMessage, ToolCall
178  from haystack.utils import Secret
179  
180  tool_call = ToolCall(
181      tool_name="search",
182      arguments={"q": "Why was Sam Altman ousted from OpenAI?"},
183  )
184  message = ChatMessage.from_assistant(tool_calls=[tool_call])
185  
186  serper_token = Secret.from_env_var("SERPERDEV_API_KEY").resolve_value()
187  serperdev_openapi_spec = json.loads(httpx.get("https://bit.ly/serper_dev_spec", follow_redirects=True).text)
188  service_connector = OpenAPIServiceConnector()
189  result = service_connector.run(
190      messages=[message],
191      service_openapi_spec=serperdev_openapi_spec,
192      service_credentials=serper_token,
193  )
194  print(result)
195  
196  # {'service_response': ChatMessage(_role=<ChatRole.USER: 'user'>, _content=[TextContent(text=
197  # '{"searchParameters": {"q": "Why was Sam Altman ousted from OpenAI?",
198  # "type": "search", "engine": "google"}, "answerBox": {"snippet": "Concerns over AI safety and OpenAI's role
199  # in protecting were at the center of Altman's brief ouster from the company."...
200  ```
201  
202  #### __init__
203  
204  ```python
205  __init__(ssl_verify: bool | str | None = None) -> None
206  ```
207  
208  Initializes the OpenAPIServiceConnector instance
209  
210  **Parameters:**
211  
212  - **ssl_verify** (<code>[bool | str | None</code>) – Decide if to use SSL verification to the requests or not,
213    in case a string is passed, will be used as the CA.
214  
215  #### run
216  
217  ```python
218  run(
219      messages: list[ChatMessage],
220      service_openapi_spec: dict[str, Any],
221      service_credentials: dict | str | None = None,
222  ) -> dict[str, list[ChatMessage]]
223  ```
224  
225  Processes a list of chat messages to invoke a method on an OpenAPI service.
226  
227  It parses the last message in the list, expecting it to contain tool calls.
228  
229  **Parameters:**
230  
231  - **messages** (<code>list\[ChatMessage\]</code>) – A list of `ChatMessage` objects containing the messages to be processed. The last message
232    should contain the tool calls.
233  - **service_openapi_spec** (<code>dict\[str, Any\]</code>) – The OpenAPI JSON specification object of the service to be invoked. All the refs
234    should already be resolved.
235  - **service_credentials** (<code>dict | str | None</code>) – The credentials to be used for authentication with the service.
236    Currently, only the http and apiKey OpenAPI security schemes are supported.
237  
238  **Returns:**
239  
240  - <code>dict\[str, list\[ChatMessage\]\]</code> – A dictionary with the following keys:
241  - `service_response`: a list of `ChatMessage` objects, each containing the response from the service. The
242    response is in JSON format, and the `content` attribute of the `ChatMessage` contains
243    the JSON string.
244  
245  **Raises:**
246  
247  - <code>ValueError</code> – If the last message is not from the assistant or if it does not contain tool calls.
248  
249  #### to_dict
250  
251  ```python
252  to_dict() -> dict[str, Any]
253  ```
254  
255  Serializes the component to a dictionary.
256  
257  **Returns:**
258  
259  - <code>dict\[str, Any\]</code> – Dictionary with serialized data.
260  
261  #### from_dict
262  
263  ```python
264  from_dict(data: dict[str, Any]) -> OpenAPIServiceConnector
265  ```
266  
267  Deserializes the component from a dictionary.
268  
269  **Parameters:**
270  
271  - **data** (<code>dict\[str, Any\]</code>) – The dictionary to deserialize from.
272  
273  **Returns:**
274  
275  - <code>OpenAPIServiceConnector</code> – The deserialized component.