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