camel-ai 0.1.5.6__py3-none-any.whl → 0.1.5.9__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.
Potentially problematic release.
This version of camel-ai might be problematic. Click here for more details.
- camel/__init__.py +1 -1
- camel/agents/chat_agent.py +3 -3
- camel/agents/critic_agent.py +1 -1
- camel/agents/deductive_reasoner_agent.py +4 -4
- camel/agents/embodied_agent.py +1 -1
- camel/agents/knowledge_graph_agent.py +2 -2
- camel/agents/role_assignment_agent.py +1 -1
- camel/agents/search_agent.py +4 -5
- camel/agents/task_agent.py +5 -5
- camel/configs/__init__.py +9 -0
- camel/configs/gemini_config.py +15 -14
- camel/configs/groq_config.py +119 -0
- camel/configs/litellm_config.py +1 -1
- camel/configs/mistral_config.py +81 -0
- camel/configs/ollama_config.py +1 -1
- camel/configs/openai_config.py +1 -1
- camel/configs/vllm_config.py +103 -0
- camel/configs/zhipuai_config.py +1 -1
- camel/embeddings/__init__.py +2 -0
- camel/embeddings/mistral_embedding.py +89 -0
- camel/interpreters/__init__.py +2 -0
- camel/interpreters/ipython_interpreter.py +167 -0
- camel/models/__init__.py +8 -0
- camel/models/anthropic_model.py +7 -2
- camel/models/azure_openai_model.py +152 -0
- camel/models/base_model.py +9 -2
- camel/models/gemini_model.py +14 -2
- camel/models/groq_model.py +131 -0
- camel/models/litellm_model.py +26 -4
- camel/models/mistral_model.py +169 -0
- camel/models/model_factory.py +30 -3
- camel/models/ollama_model.py +21 -2
- camel/models/open_source_model.py +11 -3
- camel/models/openai_model.py +7 -2
- camel/models/stub_model.py +4 -4
- camel/models/vllm_model.py +138 -0
- camel/models/zhipuai_model.py +7 -4
- camel/prompts/__init__.py +2 -2
- camel/prompts/task_prompt_template.py +4 -4
- camel/prompts/{descripte_video_prompt.py → video_description_prompt.py} +1 -1
- camel/retrievers/auto_retriever.py +2 -0
- camel/storages/graph_storages/neo4j_graph.py +5 -0
- camel/toolkits/__init__.py +36 -0
- camel/toolkits/base.py +1 -1
- camel/toolkits/code_execution.py +1 -1
- camel/toolkits/github_toolkit.py +3 -2
- camel/toolkits/google_maps_toolkit.py +367 -0
- camel/toolkits/math_toolkit.py +79 -0
- camel/toolkits/open_api_toolkit.py +548 -0
- camel/toolkits/retrieval_toolkit.py +76 -0
- camel/toolkits/search_toolkit.py +326 -0
- camel/toolkits/slack_toolkit.py +308 -0
- camel/toolkits/twitter_toolkit.py +522 -0
- camel/toolkits/weather_toolkit.py +173 -0
- camel/types/enums.py +149 -34
- camel/utils/__init__.py +2 -0
- camel/utils/async_func.py +1 -1
- camel/utils/token_counting.py +148 -40
- {camel_ai-0.1.5.6.dist-info → camel_ai-0.1.5.9.dist-info}/METADATA +42 -3
- camel_ai-0.1.5.9.dist-info/RECORD +165 -0
- camel/functions/__init__.py +0 -51
- camel/functions/google_maps_function.py +0 -335
- camel/functions/math_functions.py +0 -61
- camel/functions/open_api_function.py +0 -508
- camel/functions/retrieval_functions.py +0 -61
- camel/functions/search_functions.py +0 -298
- camel/functions/slack_functions.py +0 -286
- camel/functions/twitter_function.py +0 -479
- camel/functions/weather_functions.py +0 -144
- camel_ai-0.1.5.6.dist-info/RECORD +0 -157
- /camel/{functions → toolkits}/open_api_specs/biztoc/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/biztoc/ai-plugin.json +0 -0
- /camel/{functions → toolkits}/open_api_specs/biztoc/openapi.yaml +0 -0
- /camel/{functions → toolkits}/open_api_specs/coursera/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/coursera/openapi.yaml +0 -0
- /camel/{functions → toolkits}/open_api_specs/create_qr_code/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/create_qr_code/openapi.yaml +0 -0
- /camel/{functions → toolkits}/open_api_specs/klarna/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/klarna/openapi.yaml +0 -0
- /camel/{functions → toolkits}/open_api_specs/nasa_apod/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/nasa_apod/openapi.yaml +0 -0
- /camel/{functions → toolkits}/open_api_specs/outschool/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/outschool/ai-plugin.json +0 -0
- /camel/{functions → toolkits}/open_api_specs/outschool/openapi.yaml +0 -0
- /camel/{functions → toolkits}/open_api_specs/outschool/paths/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/outschool/paths/get_classes.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/outschool/paths/search_teachers.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/security_config.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/speak/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/speak/openapi.yaml +0 -0
- /camel/{functions → toolkits}/open_api_specs/web_scraper/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/web_scraper/ai-plugin.json +0 -0
- /camel/{functions → toolkits}/open_api_specs/web_scraper/openapi.yaml +0 -0
- /camel/{functions → toolkits}/open_api_specs/web_scraper/paths/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/web_scraper/paths/scraper.py +0 -0
- /camel/{functions → toolkits}/openai_function.py +0 -0
- {camel_ai-0.1.5.6.dist-info → camel_ai-0.1.5.9.dist-info}/WHEEL +0 -0
|
@@ -0,0 +1,548 @@
|
|
|
1
|
+
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
|
|
2
|
+
# Licensed under the Apache License, Version 2.0 (the “License”);
|
|
3
|
+
# you may not use this file except in compliance with the License.
|
|
4
|
+
# You may obtain a copy of the License at
|
|
5
|
+
#
|
|
6
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
7
|
+
#
|
|
8
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
9
|
+
# distributed under the License is distributed on an “AS IS” BASIS,
|
|
10
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
|
+
# See the License for the specific language governing permissions and
|
|
12
|
+
# limitations under the License.
|
|
13
|
+
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple
|
|
17
|
+
|
|
18
|
+
import requests
|
|
19
|
+
|
|
20
|
+
from camel.toolkits import OpenAIFunction, openapi_security_config
|
|
21
|
+
from camel.toolkits.base import BaseToolkit
|
|
22
|
+
from camel.types import OpenAPIName
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class OpenAPIToolkit(BaseToolkit):
|
|
26
|
+
r"""A class representing a toolkit for interacting with OpenAPI APIs.
|
|
27
|
+
|
|
28
|
+
This class provides methods for interacting with APIs based on OpenAPI
|
|
29
|
+
specifications. It dynamically generates functions for each API operation
|
|
30
|
+
defined in the OpenAPI specification, allowing users to make HTTP requests
|
|
31
|
+
to the API endpoints.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def parse_openapi_file(
|
|
35
|
+
self, openapi_spec_path: str
|
|
36
|
+
) -> Optional[Dict[str, Any]]:
|
|
37
|
+
r"""Load and parse an OpenAPI specification file.
|
|
38
|
+
|
|
39
|
+
This function utilizes the `prance.ResolvingParser` to parse and
|
|
40
|
+
resolve the given OpenAPI specification file, returning the parsed
|
|
41
|
+
OpenAPI specification as a dictionary.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
openapi_spec_path (str): The file path or URL to the OpenAPI
|
|
45
|
+
specification.
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
Optional[Dict[str, Any]]: The parsed OpenAPI specification
|
|
49
|
+
as a dictionary. :obj:`None` if the package is not installed.
|
|
50
|
+
"""
|
|
51
|
+
try:
|
|
52
|
+
import prance
|
|
53
|
+
except Exception:
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
# Load the OpenAPI spec
|
|
57
|
+
parser = prance.ResolvingParser(
|
|
58
|
+
openapi_spec_path, backend="openapi-spec-validator", strict=False
|
|
59
|
+
)
|
|
60
|
+
openapi_spec = parser.specification
|
|
61
|
+
version = openapi_spec.get('openapi', {})
|
|
62
|
+
if not version:
|
|
63
|
+
raise ValueError(
|
|
64
|
+
"OpenAPI version not specified in the spec. "
|
|
65
|
+
"Only OPENAPI 3.0.x and 3.1.x are supported."
|
|
66
|
+
)
|
|
67
|
+
if not (version.startswith('3.0') or version.startswith('3.1')):
|
|
68
|
+
raise ValueError(
|
|
69
|
+
f"Unsupported OpenAPI version: {version}. "
|
|
70
|
+
f"Only OPENAPI 3.0.x and 3.1.x are supported."
|
|
71
|
+
)
|
|
72
|
+
return openapi_spec
|
|
73
|
+
|
|
74
|
+
def openapi_spec_to_openai_schemas(
|
|
75
|
+
self, api_name: str, openapi_spec: Dict[str, Any]
|
|
76
|
+
) -> List[Dict[str, Any]]:
|
|
77
|
+
r"""Convert OpenAPI specification to OpenAI schema format.
|
|
78
|
+
|
|
79
|
+
This function iterates over the paths and operations defined in an
|
|
80
|
+
OpenAPI specification, filtering out deprecated operations. For each
|
|
81
|
+
operation, it constructs a schema in a format suitable for OpenAI,
|
|
82
|
+
including operation metadata such as function name, description,
|
|
83
|
+
parameters, and request bodies. It raises a ValueError if an operation
|
|
84
|
+
lacks a description or summary.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
api_name (str): The name of the API, used to prefix generated
|
|
88
|
+
function names.
|
|
89
|
+
openapi_spec (Dict[str, Any]): The OpenAPI specification as a
|
|
90
|
+
dictionary.
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
List[Dict[str, Any]]: A list of dictionaries, each representing a
|
|
94
|
+
function in the OpenAI schema format, including details about
|
|
95
|
+
the function's name, description, and parameters.
|
|
96
|
+
|
|
97
|
+
Raises:
|
|
98
|
+
ValueError: If an operation in the OpenAPI specification
|
|
99
|
+
does not have a description or summary.
|
|
100
|
+
|
|
101
|
+
Note:
|
|
102
|
+
This function assumes that the OpenAPI specification
|
|
103
|
+
follows the 3.0+ format.
|
|
104
|
+
|
|
105
|
+
Reference:
|
|
106
|
+
https://swagger.io/specification/
|
|
107
|
+
"""
|
|
108
|
+
result = []
|
|
109
|
+
|
|
110
|
+
for path, path_item in openapi_spec.get('paths', {}).items():
|
|
111
|
+
for method, op in path_item.items():
|
|
112
|
+
if op.get('deprecated') is True:
|
|
113
|
+
continue
|
|
114
|
+
|
|
115
|
+
# Get the function name from the operationId
|
|
116
|
+
# or construct it from the API method, and path
|
|
117
|
+
function_name = f"{api_name}"
|
|
118
|
+
operation_id = op.get('operationId')
|
|
119
|
+
if operation_id:
|
|
120
|
+
function_name += f"_{operation_id}"
|
|
121
|
+
else:
|
|
122
|
+
function_name += f"{method}{path.replace('/', '_')}"
|
|
123
|
+
|
|
124
|
+
description = op.get('description') or op.get('summary')
|
|
125
|
+
if not description:
|
|
126
|
+
raise ValueError(
|
|
127
|
+
f"{method} {path} Operation from {api_name} "
|
|
128
|
+
f"does not have a description or summary."
|
|
129
|
+
)
|
|
130
|
+
description += " " if description[-1] != " " else ""
|
|
131
|
+
description += f"This function is from {api_name} API. "
|
|
132
|
+
|
|
133
|
+
# If the OpenAPI spec has a description,
|
|
134
|
+
# add it to the operation description
|
|
135
|
+
if 'description' in openapi_spec.get('info', {}):
|
|
136
|
+
description += f"{openapi_spec['info']['description']}"
|
|
137
|
+
|
|
138
|
+
# Get the parameters for the operation, if any
|
|
139
|
+
params = op.get('parameters', [])
|
|
140
|
+
properties: Dict[str, Any] = {}
|
|
141
|
+
required = []
|
|
142
|
+
|
|
143
|
+
for param in params:
|
|
144
|
+
if not param.get('deprecated', False):
|
|
145
|
+
param_name = param['name'] + '_in_' + param['in']
|
|
146
|
+
properties[param_name] = {}
|
|
147
|
+
|
|
148
|
+
if 'description' in param:
|
|
149
|
+
properties[param_name]['description'] = param[
|
|
150
|
+
'description'
|
|
151
|
+
]
|
|
152
|
+
|
|
153
|
+
if 'schema' in param:
|
|
154
|
+
if (
|
|
155
|
+
properties[param_name].get('description')
|
|
156
|
+
and 'description' in param['schema']
|
|
157
|
+
):
|
|
158
|
+
param['schema'].pop('description')
|
|
159
|
+
properties[param_name].update(param['schema'])
|
|
160
|
+
|
|
161
|
+
if param.get('required'):
|
|
162
|
+
required.append(param_name)
|
|
163
|
+
|
|
164
|
+
# If the property dictionary does not have a
|
|
165
|
+
# description, use the parameter name as
|
|
166
|
+
# the description
|
|
167
|
+
if 'description' not in properties[param_name]:
|
|
168
|
+
properties[param_name]['description'] = param[
|
|
169
|
+
'name'
|
|
170
|
+
]
|
|
171
|
+
|
|
172
|
+
if 'type' not in properties[param_name]:
|
|
173
|
+
properties[param_name]['type'] = 'Any'
|
|
174
|
+
|
|
175
|
+
# Process requestBody if present
|
|
176
|
+
if 'requestBody' in op:
|
|
177
|
+
properties['requestBody'] = {}
|
|
178
|
+
requestBody = op['requestBody']
|
|
179
|
+
if requestBody.get('required') is True:
|
|
180
|
+
required.append('requestBody')
|
|
181
|
+
|
|
182
|
+
content = requestBody.get('content', {})
|
|
183
|
+
json_content = content.get('application/json', {})
|
|
184
|
+
json_schema = json_content.get('schema', {})
|
|
185
|
+
if json_schema:
|
|
186
|
+
properties['requestBody'] = json_schema
|
|
187
|
+
if 'description' not in properties['requestBody']:
|
|
188
|
+
properties['requestBody']['description'] = (
|
|
189
|
+
"The request body, with parameters specifically "
|
|
190
|
+
"described under the `properties` key"
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
function = {
|
|
194
|
+
"type": "function",
|
|
195
|
+
"function": {
|
|
196
|
+
"name": function_name,
|
|
197
|
+
"description": description,
|
|
198
|
+
"parameters": {
|
|
199
|
+
"type": "object",
|
|
200
|
+
"properties": properties,
|
|
201
|
+
"required": required,
|
|
202
|
+
},
|
|
203
|
+
},
|
|
204
|
+
}
|
|
205
|
+
result.append(function)
|
|
206
|
+
|
|
207
|
+
return result # Return the result list
|
|
208
|
+
|
|
209
|
+
def openapi_function_decorator(
|
|
210
|
+
self,
|
|
211
|
+
api_name: str,
|
|
212
|
+
base_url: str,
|
|
213
|
+
path: str,
|
|
214
|
+
method: str,
|
|
215
|
+
openapi_security: List[Dict[str, Any]],
|
|
216
|
+
sec_schemas: Dict[str, Dict[str, Any]],
|
|
217
|
+
operation: Dict[str, Any],
|
|
218
|
+
) -> Callable:
|
|
219
|
+
r"""Decorate a function to make HTTP requests based on OpenAPI
|
|
220
|
+
specification details.
|
|
221
|
+
|
|
222
|
+
This decorator dynamically constructs and executes an API request based
|
|
223
|
+
on the provided OpenAPI operation specifications, security
|
|
224
|
+
requirements, and parameters. It supports operations secured with
|
|
225
|
+
`apiKey` type security schemes and automatically injects the necessary
|
|
226
|
+
API keys from environment variables. Parameters in `path`, `query`,
|
|
227
|
+
`header`, and `cookie` are also supported.
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
api_name (str): The name of the API, used to retrieve API key names
|
|
231
|
+
and URLs from the configuration.
|
|
232
|
+
base_url (str): The base URL for the API.
|
|
233
|
+
path (str): The path for the API endpoint,
|
|
234
|
+
relative to the base URL.
|
|
235
|
+
method (str): The HTTP method (e.g., 'get', 'post')
|
|
236
|
+
for the request.
|
|
237
|
+
openapi_security (List[Dict[str, Any]]): The global security
|
|
238
|
+
definitions as specified in the OpenAPI specs.
|
|
239
|
+
sec_schemas (Dict[str, Dict[str, Any]]): Detailed security schemes.
|
|
240
|
+
operation (Dict[str, Any]): A dictionary containing the OpenAPI
|
|
241
|
+
operation details, including parameters and request body
|
|
242
|
+
definitions.
|
|
243
|
+
|
|
244
|
+
Returns:
|
|
245
|
+
Callable: A decorator that, when applied to a function, enables the
|
|
246
|
+
function to make HTTP requests based on the provided OpenAPI
|
|
247
|
+
operation details.
|
|
248
|
+
|
|
249
|
+
Raises:
|
|
250
|
+
TypeError: If the security requirements include unsupported types.
|
|
251
|
+
ValueError: If required API keys are missing from environment
|
|
252
|
+
variables or if the content type of the request body is
|
|
253
|
+
unsupported.
|
|
254
|
+
"""
|
|
255
|
+
|
|
256
|
+
def inner_decorator(openapi_function: Callable) -> Callable:
|
|
257
|
+
def wrapper(**kwargs):
|
|
258
|
+
request_url = f"{base_url.rstrip('/')}/{path.lstrip('/')}"
|
|
259
|
+
headers = {}
|
|
260
|
+
params = {}
|
|
261
|
+
cookies = {}
|
|
262
|
+
|
|
263
|
+
# Security definition of operation overrides any declared
|
|
264
|
+
# top-level security.
|
|
265
|
+
sec_requirements = operation.get('security', openapi_security)
|
|
266
|
+
avail_sec_requirement = {}
|
|
267
|
+
# Write to avaliable_security_requirement only if all the
|
|
268
|
+
# security_type are "apiKey"
|
|
269
|
+
for security_requirement in sec_requirements:
|
|
270
|
+
have_unsupported_type = False
|
|
271
|
+
for sec_scheme_name, _ in security_requirement.items():
|
|
272
|
+
sec_type = sec_schemas.get(sec_scheme_name).get('type')
|
|
273
|
+
if sec_type != "apiKey":
|
|
274
|
+
have_unsupported_type = True
|
|
275
|
+
break
|
|
276
|
+
if have_unsupported_type is False:
|
|
277
|
+
avail_sec_requirement = security_requirement
|
|
278
|
+
break
|
|
279
|
+
|
|
280
|
+
if sec_requirements and not avail_sec_requirement:
|
|
281
|
+
raise TypeError(
|
|
282
|
+
"Only security schemas of type `apiKey` are supported."
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
for sec_scheme_name, _ in avail_sec_requirement.items():
|
|
286
|
+
try:
|
|
287
|
+
API_KEY_NAME = openapi_security_config.get(
|
|
288
|
+
api_name
|
|
289
|
+
).get(sec_scheme_name)
|
|
290
|
+
api_key_value = os.environ[API_KEY_NAME]
|
|
291
|
+
except Exception:
|
|
292
|
+
api_key_url = openapi_security_config.get(
|
|
293
|
+
api_name
|
|
294
|
+
).get('get_api_key_url')
|
|
295
|
+
raise ValueError(
|
|
296
|
+
f"`{API_KEY_NAME}` not found in environment "
|
|
297
|
+
f"variables. "
|
|
298
|
+
f"Get `{API_KEY_NAME}` here: {api_key_url}"
|
|
299
|
+
)
|
|
300
|
+
request_key_name = sec_schemas.get(sec_scheme_name).get(
|
|
301
|
+
'name'
|
|
302
|
+
)
|
|
303
|
+
request_key_in = sec_schemas.get(sec_scheme_name).get('in')
|
|
304
|
+
if request_key_in == 'query':
|
|
305
|
+
params[request_key_name] = api_key_value
|
|
306
|
+
elif request_key_in == 'header':
|
|
307
|
+
headers[request_key_name] = api_key_value
|
|
308
|
+
elif request_key_in == 'coolie':
|
|
309
|
+
cookies[request_key_name] = api_key_value
|
|
310
|
+
|
|
311
|
+
# Assign parameters to the correct position
|
|
312
|
+
for param in operation.get('parameters', []):
|
|
313
|
+
input_param_name = param['name'] + '_in_' + param['in']
|
|
314
|
+
# Irrelevant arguments does not affect function operation
|
|
315
|
+
if input_param_name in kwargs:
|
|
316
|
+
if param['in'] == 'path':
|
|
317
|
+
request_url = request_url.replace(
|
|
318
|
+
f"{{{param['name']}}}",
|
|
319
|
+
str(kwargs[input_param_name]),
|
|
320
|
+
)
|
|
321
|
+
elif param['in'] == 'query':
|
|
322
|
+
params[param['name']] = kwargs[input_param_name]
|
|
323
|
+
elif param['in'] == 'header':
|
|
324
|
+
headers[param['name']] = kwargs[input_param_name]
|
|
325
|
+
elif param['in'] == 'cookie':
|
|
326
|
+
cookies[param['name']] = kwargs[input_param_name]
|
|
327
|
+
|
|
328
|
+
if 'requestBody' in operation:
|
|
329
|
+
request_body = kwargs.get('requestBody', {})
|
|
330
|
+
content_type_list = list(
|
|
331
|
+
operation.get('requestBody', {})
|
|
332
|
+
.get('content', {})
|
|
333
|
+
.keys()
|
|
334
|
+
)
|
|
335
|
+
if content_type_list:
|
|
336
|
+
content_type = content_type_list[0]
|
|
337
|
+
headers.update({"Content-Type": content_type})
|
|
338
|
+
|
|
339
|
+
# send the request body based on the Content-Type
|
|
340
|
+
if content_type == "application/json":
|
|
341
|
+
response = requests.request(
|
|
342
|
+
method.upper(),
|
|
343
|
+
request_url,
|
|
344
|
+
params=params,
|
|
345
|
+
headers=headers,
|
|
346
|
+
cookies=cookies,
|
|
347
|
+
json=request_body,
|
|
348
|
+
)
|
|
349
|
+
else:
|
|
350
|
+
raise ValueError(
|
|
351
|
+
f"Unsupported content type: {content_type}"
|
|
352
|
+
)
|
|
353
|
+
else:
|
|
354
|
+
# If there is no requestBody, no request body is sent
|
|
355
|
+
response = requests.request(
|
|
356
|
+
method.upper(),
|
|
357
|
+
request_url,
|
|
358
|
+
params=params,
|
|
359
|
+
headers=headers,
|
|
360
|
+
cookies=cookies,
|
|
361
|
+
)
|
|
362
|
+
|
|
363
|
+
try:
|
|
364
|
+
return response.json()
|
|
365
|
+
except json.JSONDecodeError:
|
|
366
|
+
raise ValueError(
|
|
367
|
+
"Response could not be decoded as JSON. "
|
|
368
|
+
"Please check the input parameters."
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
return wrapper
|
|
372
|
+
|
|
373
|
+
return inner_decorator
|
|
374
|
+
|
|
375
|
+
def generate_openapi_funcs(
|
|
376
|
+
self, api_name: str, openapi_spec: Dict[str, Any]
|
|
377
|
+
) -> List[Callable]:
|
|
378
|
+
r"""Generates a list of Python functions based on
|
|
379
|
+
OpenAPI specification.
|
|
380
|
+
|
|
381
|
+
This function dynamically creates a list of callable functions that
|
|
382
|
+
represent the API operations defined in an OpenAPI specification
|
|
383
|
+
document. Each function is designed to perform an HTTP request
|
|
384
|
+
corresponding to an API operation (e.g., GET, POST) as defined in
|
|
385
|
+
the specification. The functions are decorated with
|
|
386
|
+
`openapi_function_decorator`, which configures them to construct and
|
|
387
|
+
send the HTTP requests with appropriate parameters, headers, and body
|
|
388
|
+
content.
|
|
389
|
+
|
|
390
|
+
Args:
|
|
391
|
+
api_name (str): The name of the API, used to prefix generated
|
|
392
|
+
function names.
|
|
393
|
+
openapi_spec (Dict[str, Any]): The OpenAPI specification as a
|
|
394
|
+
dictionary.
|
|
395
|
+
|
|
396
|
+
Returns:
|
|
397
|
+
List[Callable]: A list containing the generated functions. Each
|
|
398
|
+
function, when called, will make an HTTP request according to
|
|
399
|
+
its corresponding API operation defined in the OpenAPI
|
|
400
|
+
specification.
|
|
401
|
+
|
|
402
|
+
Raises:
|
|
403
|
+
ValueError: If the OpenAPI specification does not contain server
|
|
404
|
+
information, which is necessary for determining the base URL
|
|
405
|
+
for the API requests.
|
|
406
|
+
"""
|
|
407
|
+
# Check server information
|
|
408
|
+
servers = openapi_spec.get('servers', [])
|
|
409
|
+
if not servers:
|
|
410
|
+
raise ValueError("No server information found in OpenAPI spec.")
|
|
411
|
+
base_url = servers[0].get('url') # Use the first server URL
|
|
412
|
+
|
|
413
|
+
# Security requirement objects for all methods
|
|
414
|
+
openapi_security = openapi_spec.get('security', {})
|
|
415
|
+
# Security schemas which can be reused by different methods
|
|
416
|
+
sec_schemas = openapi_spec.get('components', {}).get(
|
|
417
|
+
'securitySchemes', {}
|
|
418
|
+
)
|
|
419
|
+
functions = []
|
|
420
|
+
|
|
421
|
+
# Traverse paths and methods
|
|
422
|
+
for path, methods in openapi_spec.get('paths', {}).items():
|
|
423
|
+
for method, operation in methods.items():
|
|
424
|
+
# Get the function name from the operationId
|
|
425
|
+
# or construct it from the API method, and path
|
|
426
|
+
operation_id = operation.get('operationId')
|
|
427
|
+
if operation_id:
|
|
428
|
+
function_name = f"{api_name}_{operation_id}"
|
|
429
|
+
else:
|
|
430
|
+
sanitized_path = path.replace('/', '_').strip('_')
|
|
431
|
+
function_name = f"{api_name}_{method}_{sanitized_path}"
|
|
432
|
+
|
|
433
|
+
@self.openapi_function_decorator(
|
|
434
|
+
api_name,
|
|
435
|
+
base_url,
|
|
436
|
+
path,
|
|
437
|
+
method,
|
|
438
|
+
openapi_security,
|
|
439
|
+
sec_schemas,
|
|
440
|
+
operation,
|
|
441
|
+
)
|
|
442
|
+
def openapi_function(**kwargs):
|
|
443
|
+
pass
|
|
444
|
+
|
|
445
|
+
openapi_function.__name__ = function_name
|
|
446
|
+
|
|
447
|
+
functions.append(openapi_function)
|
|
448
|
+
|
|
449
|
+
return functions
|
|
450
|
+
|
|
451
|
+
def apinames_filepaths_to_funs_schemas(
|
|
452
|
+
self,
|
|
453
|
+
apinames_filepaths: List[Tuple[str, str]],
|
|
454
|
+
) -> Tuple[List[Callable], List[Dict[str, Any]]]:
|
|
455
|
+
r"""Combines functions and schemas from multiple OpenAPI
|
|
456
|
+
specifications, using API names as keys.
|
|
457
|
+
|
|
458
|
+
This function iterates over tuples of API names and OpenAPI spec file
|
|
459
|
+
paths, parsing each spec to generate callable functions and schema
|
|
460
|
+
dictionaries, all organized by API name.
|
|
461
|
+
|
|
462
|
+
Args:
|
|
463
|
+
apinames_filepaths (List[Tuple[str, str]]): A list of tuples, where
|
|
464
|
+
each tuple consists of:
|
|
465
|
+
- The API name (str) as the first element.
|
|
466
|
+
- The file path (str) to the API's OpenAPI specification file as
|
|
467
|
+
the second element.
|
|
468
|
+
|
|
469
|
+
Returns:
|
|
470
|
+
Tuple[List[Callable], List[Dict[str, Any]]]:: one of callable
|
|
471
|
+
functions for API operations, and another of dictionaries
|
|
472
|
+
representing the schemas from the specifications.
|
|
473
|
+
"""
|
|
474
|
+
combined_func_lst = []
|
|
475
|
+
combined_schemas_list = []
|
|
476
|
+
for api_name, file_path in apinames_filepaths:
|
|
477
|
+
# Parse the OpenAPI specification for each API
|
|
478
|
+
current_dir = os.path.dirname(__file__)
|
|
479
|
+
file_path = os.path.join(
|
|
480
|
+
current_dir, 'open_api_specs', f'{api_name}', 'openapi.yaml'
|
|
481
|
+
)
|
|
482
|
+
|
|
483
|
+
openapi_spec = self.parse_openapi_file(file_path)
|
|
484
|
+
if openapi_spec is None:
|
|
485
|
+
return [], []
|
|
486
|
+
|
|
487
|
+
# Generate and merge function schemas
|
|
488
|
+
openapi_functions_schemas = self.openapi_spec_to_openai_schemas(
|
|
489
|
+
api_name, openapi_spec
|
|
490
|
+
)
|
|
491
|
+
combined_schemas_list.extend(openapi_functions_schemas)
|
|
492
|
+
|
|
493
|
+
# Generate and merge function lists
|
|
494
|
+
openapi_functions_list = self.generate_openapi_funcs(
|
|
495
|
+
api_name, openapi_spec
|
|
496
|
+
)
|
|
497
|
+
combined_func_lst.extend(openapi_functions_list)
|
|
498
|
+
|
|
499
|
+
return combined_func_lst, combined_schemas_list
|
|
500
|
+
|
|
501
|
+
def generate_apinames_filepaths(self) -> List[Tuple[str, str]]:
|
|
502
|
+
"""Generates a list of tuples containing API names and their
|
|
503
|
+
corresponding file paths.
|
|
504
|
+
|
|
505
|
+
This function iterates over the OpenAPIName enum, constructs the file
|
|
506
|
+
path for each API's OpenAPI specification file, and appends a tuple of
|
|
507
|
+
the API name and its file path to the list. The file paths are relative
|
|
508
|
+
to the 'open_api_specs' directory located in the same directory as this
|
|
509
|
+
script.
|
|
510
|
+
|
|
511
|
+
Returns:
|
|
512
|
+
List[Tuple[str, str]]: A list of tuples where each tuple contains
|
|
513
|
+
two elements. The first element of each tuple is a string
|
|
514
|
+
representing the name of an API, and the second element is a
|
|
515
|
+
string that specifies the file path to that API's OpenAPI
|
|
516
|
+
specification file.
|
|
517
|
+
"""
|
|
518
|
+
apinames_filepaths = []
|
|
519
|
+
current_dir = os.path.dirname(__file__)
|
|
520
|
+
for api_name in OpenAPIName:
|
|
521
|
+
file_path = os.path.join(
|
|
522
|
+
current_dir,
|
|
523
|
+
'open_api_specs',
|
|
524
|
+
f'{api_name.value}',
|
|
525
|
+
'openapi.yaml',
|
|
526
|
+
)
|
|
527
|
+
apinames_filepaths.append((api_name.value, file_path))
|
|
528
|
+
return apinames_filepaths
|
|
529
|
+
|
|
530
|
+
def get_tools(self) -> List[OpenAIFunction]:
|
|
531
|
+
r"""Returns a list of OpenAIFunction objects representing the
|
|
532
|
+
functions in the toolkit.
|
|
533
|
+
|
|
534
|
+
Returns:
|
|
535
|
+
List[OpenAIFunction]: A list of OpenAIFunction objects
|
|
536
|
+
representing the functions in the toolkit.
|
|
537
|
+
"""
|
|
538
|
+
apinames_filepaths = self.generate_apinames_filepaths()
|
|
539
|
+
all_funcs_lst, all_schemas_lst = (
|
|
540
|
+
self.apinames_filepaths_to_funs_schemas(apinames_filepaths)
|
|
541
|
+
)
|
|
542
|
+
return [
|
|
543
|
+
OpenAIFunction(a_func, a_schema)
|
|
544
|
+
for a_func, a_schema in zip(all_funcs_lst, all_schemas_lst)
|
|
545
|
+
]
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
OPENAPI_FUNCS: List[OpenAIFunction] = OpenAPIToolkit().get_tools()
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
|
|
2
|
+
# Licensed under the Apache License, Version 2.0 (the “License”);
|
|
3
|
+
# you may not use this file except in compliance with the License.
|
|
4
|
+
# You may obtain a copy of the License at
|
|
5
|
+
#
|
|
6
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
7
|
+
#
|
|
8
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
9
|
+
# distributed under the License is distributed on an “AS IS” BASIS,
|
|
10
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
|
+
# See the License for the specific language governing permissions and
|
|
12
|
+
# limitations under the License.
|
|
13
|
+
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
|
|
14
|
+
from typing import List, Union
|
|
15
|
+
|
|
16
|
+
from camel.retrievers import AutoRetriever
|
|
17
|
+
from camel.toolkits import OpenAIFunction
|
|
18
|
+
from camel.toolkits.base import BaseToolkit
|
|
19
|
+
from camel.types import StorageType
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class RetrievalToolkit(BaseToolkit):
|
|
23
|
+
r"""A class representing a toolkit for information retrieval.
|
|
24
|
+
|
|
25
|
+
This class provides methods for retrieving information from a local vector
|
|
26
|
+
storage system based on a specified query.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def information_retrieval(
|
|
30
|
+
self, query: str, content_input_paths: Union[str, List[str]]
|
|
31
|
+
) -> str:
|
|
32
|
+
r"""Retrieves information from a local vector storage based on the
|
|
33
|
+
specified query. This function connects to a local vector storage
|
|
34
|
+
system and retrieves relevant information by processing the input
|
|
35
|
+
query. It is essential to use this function when the answer to a
|
|
36
|
+
question requires external knowledge sources.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
query (str): The question or query for which an answer is required.
|
|
40
|
+
content_input_paths (Union[str, List[str]]): Paths to local
|
|
41
|
+
files or remote URLs.
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
str: The information retrieved in response to the query, aggregated
|
|
45
|
+
and formatted as a string.
|
|
46
|
+
|
|
47
|
+
Example:
|
|
48
|
+
# Retrieve information about CAMEL AI.
|
|
49
|
+
information_retrieval(query = "what is CAMEL AI?",
|
|
50
|
+
content_input_paths="https://www.camel-ai.org/")
|
|
51
|
+
"""
|
|
52
|
+
auto_retriever = AutoRetriever(
|
|
53
|
+
vector_storage_local_path="camel/temp_storage",
|
|
54
|
+
storage_type=StorageType.QDRANT,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
retrieved_info = auto_retriever.run_vector_retriever(
|
|
58
|
+
query=query, content_input_paths=content_input_paths, top_k=3
|
|
59
|
+
)
|
|
60
|
+
return retrieved_info
|
|
61
|
+
|
|
62
|
+
def get_tools(self) -> List[OpenAIFunction]:
|
|
63
|
+
r"""Returns a list of OpenAIFunction objects representing the
|
|
64
|
+
functions in the toolkit.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
List[OpenAIFunction]: A list of OpenAIFunction objects
|
|
68
|
+
representing the functions in the toolkit.
|
|
69
|
+
"""
|
|
70
|
+
return [
|
|
71
|
+
OpenAIFunction(self.information_retrieval),
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# add the function to OpenAIFunction list
|
|
76
|
+
RETRIEVAL_FUNCS: List[OpenAIFunction] = RetrievalToolkit().get_tools()
|