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