camel-ai 0.1.5.6__py3-none-any.whl → 0.1.6.1__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.

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