camel-ai 0.1.1__py3-none-any.whl → 0.1.4__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 (117) hide show
  1. camel/__init__.py +1 -11
  2. camel/agents/__init__.py +7 -5
  3. camel/agents/chat_agent.py +134 -86
  4. camel/agents/critic_agent.py +28 -17
  5. camel/agents/deductive_reasoner_agent.py +235 -0
  6. camel/agents/embodied_agent.py +92 -40
  7. camel/agents/knowledge_graph_agent.py +221 -0
  8. camel/agents/role_assignment_agent.py +27 -17
  9. camel/agents/task_agent.py +60 -34
  10. camel/agents/tool_agents/base.py +0 -1
  11. camel/agents/tool_agents/hugging_face_tool_agent.py +7 -4
  12. camel/configs/__init__.py +29 -0
  13. camel/configs/anthropic_config.py +73 -0
  14. camel/configs/base_config.py +22 -0
  15. camel/{configs.py → configs/openai_config.py} +37 -64
  16. camel/embeddings/__init__.py +2 -0
  17. camel/embeddings/base.py +3 -2
  18. camel/embeddings/openai_embedding.py +10 -5
  19. camel/embeddings/sentence_transformers_embeddings.py +65 -0
  20. camel/functions/__init__.py +18 -3
  21. camel/functions/google_maps_function.py +335 -0
  22. camel/functions/math_functions.py +7 -7
  23. camel/functions/open_api_function.py +380 -0
  24. camel/functions/open_api_specs/coursera/__init__.py +13 -0
  25. camel/functions/open_api_specs/coursera/openapi.yaml +82 -0
  26. camel/functions/open_api_specs/klarna/__init__.py +13 -0
  27. camel/functions/open_api_specs/klarna/openapi.yaml +87 -0
  28. camel/functions/open_api_specs/speak/__init__.py +13 -0
  29. camel/functions/open_api_specs/speak/openapi.yaml +151 -0
  30. camel/functions/openai_function.py +346 -42
  31. camel/functions/retrieval_functions.py +61 -0
  32. camel/functions/search_functions.py +100 -35
  33. camel/functions/slack_functions.py +275 -0
  34. camel/functions/twitter_function.py +484 -0
  35. camel/functions/weather_functions.py +36 -23
  36. camel/generators.py +65 -46
  37. camel/human.py +17 -11
  38. camel/interpreters/__init__.py +25 -0
  39. camel/interpreters/base.py +49 -0
  40. camel/{utils/python_interpreter.py → interpreters/internal_python_interpreter.py} +129 -48
  41. camel/interpreters/interpreter_error.py +19 -0
  42. camel/interpreters/subprocess_interpreter.py +190 -0
  43. camel/loaders/__init__.py +22 -0
  44. camel/{functions/base_io_functions.py → loaders/base_io.py} +38 -35
  45. camel/{functions/unstructured_io_fuctions.py → loaders/unstructured_io.py} +199 -110
  46. camel/memories/__init__.py +17 -7
  47. camel/memories/agent_memories.py +156 -0
  48. camel/memories/base.py +97 -32
  49. camel/memories/blocks/__init__.py +21 -0
  50. camel/memories/{chat_history_memory.py → blocks/chat_history_block.py} +34 -34
  51. camel/memories/blocks/vectordb_block.py +101 -0
  52. camel/memories/context_creators/__init__.py +3 -2
  53. camel/memories/context_creators/score_based.py +32 -20
  54. camel/memories/records.py +6 -5
  55. camel/messages/__init__.py +2 -2
  56. camel/messages/base.py +99 -16
  57. camel/messages/func_message.py +7 -4
  58. camel/models/__init__.py +6 -2
  59. camel/models/anthropic_model.py +146 -0
  60. camel/models/base_model.py +10 -3
  61. camel/models/model_factory.py +17 -11
  62. camel/models/open_source_model.py +25 -13
  63. camel/models/openai_audio_models.py +251 -0
  64. camel/models/openai_model.py +20 -13
  65. camel/models/stub_model.py +10 -5
  66. camel/prompts/__init__.py +7 -5
  67. camel/prompts/ai_society.py +21 -14
  68. camel/prompts/base.py +54 -47
  69. camel/prompts/code.py +22 -14
  70. camel/prompts/evaluation.py +8 -5
  71. camel/prompts/misalignment.py +26 -19
  72. camel/prompts/object_recognition.py +35 -0
  73. camel/prompts/prompt_templates.py +14 -8
  74. camel/prompts/role_description_prompt_template.py +16 -10
  75. camel/prompts/solution_extraction.py +9 -5
  76. camel/prompts/task_prompt_template.py +24 -21
  77. camel/prompts/translation.py +9 -5
  78. camel/responses/agent_responses.py +5 -2
  79. camel/retrievers/__init__.py +26 -0
  80. camel/retrievers/auto_retriever.py +330 -0
  81. camel/retrievers/base.py +69 -0
  82. camel/retrievers/bm25_retriever.py +140 -0
  83. camel/retrievers/cohere_rerank_retriever.py +108 -0
  84. camel/retrievers/vector_retriever.py +183 -0
  85. camel/societies/__init__.py +1 -1
  86. camel/societies/babyagi_playing.py +56 -32
  87. camel/societies/role_playing.py +188 -133
  88. camel/storages/__init__.py +18 -0
  89. camel/storages/graph_storages/__init__.py +23 -0
  90. camel/storages/graph_storages/base.py +82 -0
  91. camel/storages/graph_storages/graph_element.py +74 -0
  92. camel/storages/graph_storages/neo4j_graph.py +582 -0
  93. camel/storages/key_value_storages/base.py +1 -2
  94. camel/storages/key_value_storages/in_memory.py +1 -2
  95. camel/storages/key_value_storages/json.py +8 -13
  96. camel/storages/vectordb_storages/__init__.py +33 -0
  97. camel/storages/vectordb_storages/base.py +202 -0
  98. camel/storages/vectordb_storages/milvus.py +396 -0
  99. camel/storages/vectordb_storages/qdrant.py +373 -0
  100. camel/terminators/__init__.py +1 -1
  101. camel/terminators/base.py +2 -3
  102. camel/terminators/response_terminator.py +21 -12
  103. camel/terminators/token_limit_terminator.py +5 -3
  104. camel/toolkits/__init__.py +21 -0
  105. camel/toolkits/base.py +22 -0
  106. camel/toolkits/github_toolkit.py +245 -0
  107. camel/types/__init__.py +18 -6
  108. camel/types/enums.py +129 -15
  109. camel/types/openai_types.py +10 -5
  110. camel/utils/__init__.py +20 -13
  111. camel/utils/commons.py +170 -85
  112. camel/utils/token_counting.py +135 -15
  113. {camel_ai-0.1.1.dist-info → camel_ai-0.1.4.dist-info}/METADATA +123 -75
  114. camel_ai-0.1.4.dist-info/RECORD +119 -0
  115. {camel_ai-0.1.1.dist-info → camel_ai-0.1.4.dist-info}/WHEEL +1 -1
  116. camel/memories/context_creators/base.py +0 -72
  117. camel_ai-0.1.1.dist-info/RECORD +0 -75
@@ -0,0 +1,151 @@
1
+ openapi: 3.0.1
2
+ info:
3
+ title: Speak
4
+ description: Learn how to say anything in another language with Speak, your AI-powered language tutor.
5
+ version: 'v1'
6
+ servers:
7
+ - url: https://api.speak.com
8
+ paths:
9
+ /v1/public/openai/translate:
10
+ post:
11
+ operationId: translate
12
+ summary: Translate and explain how to say a specific phrase or word in another language.
13
+ requestBody:
14
+ required: true
15
+ content:
16
+ application/json:
17
+ schema:
18
+ $ref: '#/components/schemas/translateRequest'
19
+ responses:
20
+ "200":
21
+ description: OK
22
+ content:
23
+ application/json:
24
+ schema:
25
+ $ref: '#/components/schemas/translateResponse'
26
+ /v1/public/openai/explain-phrase:
27
+ post:
28
+ operationId: explainPhrase
29
+ summary: Explain the meaning and usage of a specific foreign language phrase that the user is asking about.
30
+ requestBody:
31
+ required: true
32
+ content:
33
+ application/json:
34
+ schema:
35
+ $ref: '#/components/schemas/explainPhraseRequest'
36
+ responses:
37
+ "200":
38
+ description: OK
39
+ content:
40
+ application/json:
41
+ schema:
42
+ $ref: '#/components/schemas/explainPhraseResponse'
43
+ /v1/public/openai/explain-task:
44
+ post:
45
+ operationId: explainTask
46
+ summary: Explain the best way to say or do something in a specific situation or context with a foreign language. Use this endpoint when the user asks more general or high-level questions.
47
+ requestBody:
48
+ required: true
49
+ content:
50
+ application/json:
51
+ schema:
52
+ $ref: '#/components/schemas/explainTaskRequest'
53
+ responses:
54
+ "200":
55
+ description: OK
56
+ content:
57
+ application/json:
58
+ schema:
59
+ $ref: '#/components/schemas/explainTaskResponse'
60
+ components:
61
+ schemas:
62
+ translateRequest:
63
+ type: object
64
+ required:
65
+ - phrase_to_translate
66
+ - learning_language
67
+ - native_language
68
+ - additional_context
69
+ - full_query
70
+ properties:
71
+ phrase_to_translate:
72
+ type: string
73
+ description: Phrase or concept to translate into the foreign language and explain further.
74
+ learning_language:
75
+ type: string
76
+ description: The foreign language that the user is learning and asking about. Always use the full name of the language (e.g. Spanish, French).
77
+ native_language:
78
+ type: string
79
+ description: The user's native language. Infer this value from the language the user asked their question in. Always use the full name of the language (e.g. Spanish, French).
80
+ additional_context:
81
+ type: string
82
+ description: A description of any additional context in the user's question that could affect the explanation - e.g. setting, scenario, situation, tone, speaking style and formality, usage notes, or any other qualifiers.
83
+ full_query:
84
+ type: string
85
+ description: Full text of the user's question.
86
+ translateResponse:
87
+ type: object
88
+ properties:
89
+ explanation:
90
+ type: string
91
+ description: An explanation of how to say the input phrase in the foreign language.
92
+ explainPhraseRequest:
93
+ type: object
94
+ required:
95
+ - foreign_phrase
96
+ - learning_language
97
+ - native_language
98
+ - additional_context
99
+ - full_query
100
+ properties:
101
+ foreign_phrase:
102
+ type: string
103
+ description: Foreign language phrase or word that the user wants an explanation for.
104
+ learning_language:
105
+ type: string
106
+ description: The language that the user is asking their language question about. The value can be inferred from question - e.g. for "Somebody said no mames to me, what does that mean", the value should be "Spanish" because "no mames" is a Spanish phrase. Always use the full name of the language (e.g. Spanish, French).
107
+ native_language:
108
+ type: string
109
+ description: The user's native language. Infer this value from the language the user asked their question in. Always use the full name of the language (e.g. Spanish, French).
110
+ additional_context:
111
+ type: string
112
+ description: A description of any additional context in the user's question that could affect the explanation - e.g. setting, scenario, situation, tone, speaking style and formality, usage notes, or any other qualifiers.
113
+ full_query:
114
+ type: string
115
+ description: Full text of the user's question.
116
+ explainPhraseResponse:
117
+ type: object
118
+ properties:
119
+ explanation:
120
+ type: string
121
+ description: An explanation of what the foreign language phrase means, and when you might use it.
122
+ explainTaskRequest:
123
+ type: object
124
+ required:
125
+ - task_description
126
+ - learning_language
127
+ - native_language
128
+ - additional_context
129
+ - full_query
130
+ properties:
131
+ task_description:
132
+ type: string
133
+ description: Description of the task that the user wants to accomplish or do. For example, "tell the waiter they messed up my order" or "compliment someone on their shirt"
134
+ learning_language:
135
+ type: string
136
+ description: The foreign language that the user is learning and asking about. The value can be inferred from question - for example, if the user asks "how do i ask a girl out in mexico city", the value should be "Spanish" because of Mexico City. Always use the full name of the language (e.g. Spanish, French).
137
+ native_language:
138
+ type: string
139
+ description: The user's native language. Infer this value from the language the user asked their question in. Always use the full name of the language (e.g. Spanish, French).
140
+ additional_context:
141
+ type: string
142
+ description: A description of any additional context in the user's question that could affect the explanation - e.g. setting, scenario, situation, tone, speaking style and formality, usage notes, or any other qualifiers.
143
+ full_query:
144
+ type: string
145
+ description: Full text of the user's question.
146
+ explainTaskResponse:
147
+ type: object
148
+ properties:
149
+ explanation:
150
+ type: string
151
+ description: An explanation of the best thing to say in the foreign language to accomplish the task described in the user's question.
@@ -11,44 +11,358 @@
11
11
  # See the License for the specific language governing permissions and
12
12
  # limitations under the License.
13
13
  # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
14
- from typing import Any, Callable, Dict, Optional
14
+ from inspect import Parameter, signature
15
+ from typing import Any, Callable, Dict, Mapping, Optional, Tuple
15
16
 
17
+ from docstring_parser import parse
18
+ from jsonschema.exceptions import SchemaError
16
19
  from jsonschema.validators import Draft202012Validator as JSONValidator
20
+ from pydantic import create_model
21
+ from pydantic.fields import FieldInfo
17
22
 
18
- from camel.utils import parse_doc
23
+ from camel.utils import PYDANTIC_V2, to_pascal
24
+
25
+
26
+ def _remove_a_key(d: Dict, remove_key: Any) -> None:
27
+ r"""Remove a key from a dictionary recursively."""
28
+ if isinstance(d, dict):
29
+ for key in list(d.keys()):
30
+ if key == remove_key:
31
+ del d[key]
32
+ else:
33
+ _remove_a_key(d[key], remove_key)
34
+
35
+
36
+ def get_openai_function_schema(func: Callable) -> Dict[str, Any]:
37
+ r"""Generates a schema dict for an OpenAI function based on its signature.
38
+
39
+ This function is deprecated and will be replaced by
40
+ :obj:`get_openai_tool_schema()` in future versions. It parses the
41
+ function's parameters and docstring to construct a JSON schema-like
42
+ dictionary.
43
+
44
+ Args:
45
+ func (Callable): The OpenAI function to generate the schema for.
46
+
47
+ Returns:
48
+ Dict[str, Any]: A dictionary representing the JSON schema of the
49
+ function, including its name, description, and parameter
50
+ specifications.
51
+ """
52
+ openai_function_schema = get_openai_tool_schema(func)["function"]
53
+ return openai_function_schema
54
+
55
+
56
+ def get_openai_tool_schema(func: Callable) -> Dict[str, Any]:
57
+ r"""Generates an OpenAI JSON schema from a given Python function.
58
+
59
+ This function creates a schema compatible with OpenAI's API specifications,
60
+ based on the provided Python function. It processes the function's
61
+ parameters, types, and docstrings, and constructs a schema accordingly.
62
+
63
+ Note:
64
+ - Each parameter in `func` must have a type annotation; otherwise, it's
65
+ treated as 'Any'.
66
+ - Variable arguments (*args) and keyword arguments (**kwargs) are not
67
+ supported and will be ignored.
68
+ - A functional description including a brief and detailed explanation
69
+ should be provided in the docstring of `func`.
70
+ - All parameters of `func` must be described in its docstring.
71
+ - Supported docstring styles: ReST, Google, Numpydoc, and Epydoc.
72
+
73
+ Args:
74
+ func (Callable): The Python function to be converted into an OpenAI
75
+ JSON schema.
76
+
77
+ Returns:
78
+ Dict[str, Any]: A dictionary representing the OpenAI JSON schema of
79
+ the provided function.
80
+
81
+ See Also:
82
+ `OpenAI API Reference
83
+ <https://platform.openai.com/docs/api-reference/assistants/object>`_
84
+ """
85
+ params: Mapping[str, Parameter] = signature(func).parameters
86
+ fields: Dict[str, Tuple[type, FieldInfo]] = {}
87
+ for param_name, p in params.items():
88
+ param_type = p.annotation
89
+ param_default = p.default
90
+ param_kind = p.kind
91
+ param_annotation = p.annotation
92
+ # Variable parameters are not supported
93
+ if (
94
+ param_kind == Parameter.VAR_POSITIONAL
95
+ or param_kind == Parameter.VAR_KEYWORD
96
+ ):
97
+ continue
98
+ # If the parameter type is not specified, it defaults to typing.Any
99
+ if param_annotation is Parameter.empty:
100
+ param_type = Any
101
+ # Check if the parameter has a default value
102
+ if param_default is Parameter.empty:
103
+ fields[param_name] = (param_type, FieldInfo())
104
+ else:
105
+ fields[param_name] = (param_type, FieldInfo(default=param_default))
106
+
107
+ # Applying `create_model()` directly will result in a mypy error,
108
+ # create an alias to avoid this.
109
+ def _create_mol(name, field):
110
+ return create_model(name, **field)
111
+
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()
119
+ # The `"title"` is generated by `model.model_json_schema()`
120
+ # but is useless for openai json schema
121
+ _remove_a_key(parameters_dict, "title")
122
+
123
+ docstring = parse(func.__doc__ or "")
124
+ for param in docstring.params:
125
+ if (name := param.arg_name) in parameters_dict["properties"] and (
126
+ description := param.description
127
+ ):
128
+ parameters_dict["properties"][name]["description"] = description
129
+
130
+ short_description = docstring.short_description or ""
131
+ long_description = docstring.long_description or ""
132
+ if long_description:
133
+ func_description = f"{short_description}\n{long_description}"
134
+ else:
135
+ func_description = short_description
136
+
137
+ openai_function_schema = {
138
+ "name": func.__name__,
139
+ "description": func_description,
140
+ "parameters": parameters_dict,
141
+ }
142
+
143
+ openai_tool_schema = {
144
+ "type": "function",
145
+ "function": openai_function_schema,
146
+ }
147
+ return openai_tool_schema
19
148
 
20
149
 
21
150
  class OpenAIFunction:
22
151
  r"""An abstraction of a function that OpenAI chat models can call. See
23
- https://platform.openai.com/docs/guides/gpt/function-calling. If
24
- :obj:`description` and :obj:`parameters` are both :obj:`None`, try to use
25
- document parser to generate them.
152
+ https://platform.openai.com/docs/api-reference/chat/create.
153
+
154
+ By default, the tool schema will be parsed from the func, or you can
155
+ provide a user-defined tool schema to override.
26
156
 
27
- # flake8: noqa :E501
28
157
  Args:
29
- func (Callable): The function to call.
30
- name (str, optional): The name of the function to be called. Must be
31
- a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum
32
- length of 64. If :obj:`None`, use the name of :obj:`func`.
158
+ func (Callable): The function to call.The tool schema is parsed from
159
+ the signature and docstring by default.
160
+ openai_tool_schema (Optional[Dict[str, Any]], optional): A user-defined
161
+ openai tool schema to override the default result.
33
162
  (default: :obj:`None`)
34
- description (str, optional): The description of what the
35
- function does. (default: :obj:`None`)
36
- parameters (dict, optional): The parameters the
37
- functions accepts, described as a JSON Schema object. See the
38
- `Function calling guide <https://platform.openai.com/docs/guides/gpt/function-calling>`_
39
- for examples, and the `JSON Schema reference <https://json-schema.org/understanding-json-schema/>`_
40
- for documentation about the format.
41
163
  """
42
164
 
43
- def __init__(self, func: Callable, name: Optional[str] = None,
44
- description: Optional[str] = None,
45
- parameters: Optional[Dict[str, Any]] = None):
165
+ def __init__(
166
+ self,
167
+ func: Callable,
168
+ openai_tool_schema: Optional[Dict[str, Any]] = None,
169
+ ) -> None:
46
170
  self.func = func
47
- self.name = name or func.__name__
171
+ self.openai_tool_schema = openai_tool_schema or get_openai_tool_schema(
172
+ func
173
+ )
174
+
175
+ @staticmethod
176
+ def validate_openai_tool_schema(openai_tool_schema: Dict[str, Any]) -> None:
177
+ r"""Validates the OpenAI tool schema against
178
+ :obj:`ToolAssistantToolsFunction`.
179
+ This function checks if the provided :obj:`openai_tool_schema` adheres
180
+ to the specifications required by OpenAI's
181
+ :obj:`ToolAssistantToolsFunction`. It ensures that the function
182
+ description and parameters are correctly formatted according to JSON
183
+ Schema specifications.
184
+ Args:
185
+ openai_tool_schema (Dict[str, Any]): The OpenAI tool schema to
186
+ validate.
187
+ Raises:
188
+ ValidationError: If the schema does not comply with the
189
+ specifications.
190
+ ValueError: If the function description or parameter descriptions
191
+ are missing in the schema.
192
+ SchemaError: If the parameters do not meet JSON Schema reference
193
+ specifications.
194
+ """
195
+ # Check the type
196
+ if not openai_tool_schema["type"]:
197
+ raise ValueError("miss type")
198
+ # Check the function description
199
+ if not openai_tool_schema["function"]["description"]:
200
+ raise ValueError("miss function description")
201
+
202
+ # Validate whether parameters
203
+ # meet the JSON Schema reference specifications.
204
+ # See https://platform.openai.com/docs/guides/gpt/function-calling
205
+ # for examples, and the
206
+ # https://json-schema.org/understanding-json-schema/ for
207
+ # documentation about the format.
208
+ parameters = openai_tool_schema["function"]["parameters"]
209
+ try:
210
+ JSONValidator.check_schema(parameters)
211
+ except SchemaError as e:
212
+ raise e
213
+ # Check the parameter description
214
+ properties: Dict[str, Any] = parameters["properties"]
215
+ for param_name in properties.keys():
216
+ param_dict = properties[param_name]
217
+ if "description" not in param_dict:
218
+ raise ValueError(
219
+ f'miss description of parameter "{param_name}"'
220
+ )
221
+
222
+ def get_openai_tool_schema(self) -> Dict[str, Any]:
223
+ r"""Gets the OpenAI tool schema for this function.
224
+
225
+ This method returns the OpenAI tool schema associated with this
226
+ function, after validating it to ensure it meets OpenAI's
227
+ specifications.
228
+
229
+ Returns:
230
+ Dict[str, Any]: The OpenAI tool schema for this function.
231
+ """
232
+ self.validate_openai_tool_schema(self.openai_tool_schema)
233
+ return self.openai_tool_schema
234
+
235
+ def set_openai_tool_schema(self, schema: Dict[str, Any]) -> None:
236
+ r"""Sets the OpenAI tool schema for this function.
237
+
238
+ Allows setting a custom OpenAI tool schema for this function.
239
+
240
+ Args:
241
+ schema (Dict[str, Any]): The OpenAI tool schema to set.
242
+ """
243
+ self.openai_tool_schema = schema
244
+
245
+ def get_openai_function_schema(self) -> Dict[str, Any]:
246
+ r"""Gets the schema of the function from the OpenAI tool schema.
247
+
248
+ This method extracts and returns the function-specific part of the
249
+ OpenAI tool schema associated with this function.
250
+
251
+ Returns:
252
+ Dict[str, Any]: The schema of the function within the OpenAI tool
253
+ schema.
254
+ """
255
+ self.validate_openai_tool_schema(self.openai_tool_schema)
256
+ return self.openai_tool_schema["function"]
48
257
 
49
- info = parse_doc(self.func)
50
- self.description = description or info["description"]
51
- self.parameters = parameters or info["parameters"]
258
+ def set_openai_function_schema(
259
+ self,
260
+ openai_function_schema: Dict[str, Any],
261
+ ) -> None:
262
+ r"""Sets the schema of the function within the OpenAI tool schema.
263
+
264
+ Args:
265
+ openai_function_schema (Dict[str, Any]): The function schema to set
266
+ within the OpenAI tool schema.
267
+ """
268
+ self.openai_tool_schema["function"] = openai_function_schema
269
+
270
+ def get_function_name(self) -> str:
271
+ r"""Gets the name of the function from the OpenAI tool schema.
272
+
273
+ Returns:
274
+ str: The name of the function.
275
+ """
276
+ self.validate_openai_tool_schema(self.openai_tool_schema)
277
+ return self.openai_tool_schema["function"]["name"]
278
+
279
+ def set_function_name(self, name: str) -> None:
280
+ r"""Sets the name of the function in the OpenAI tool schema.
281
+
282
+ Args:
283
+ name (str): The name of the function to set.
284
+ """
285
+ self.openai_tool_schema["function"]["name"] = name
286
+
287
+ def get_function_description(self) -> str:
288
+ r"""Gets the description of the function from the OpenAI tool
289
+ schema.
290
+
291
+ Returns:
292
+ str: The description of the function.
293
+ """
294
+ self.validate_openai_tool_schema(self.openai_tool_schema)
295
+ return self.openai_tool_schema["function"]["description"]
296
+
297
+ def set_function_description(self, description: str) -> None:
298
+ r"""Sets the description of the function in the OpenAI tool schema.
299
+
300
+ Args:
301
+ description (str): The description for the function.
302
+ """
303
+ self.openai_tool_schema["function"]["description"] = description
304
+
305
+ def get_paramter_description(self, param_name: str) -> str:
306
+ r"""Gets the description of a specific parameter from the function
307
+ schema.
308
+
309
+ Args:
310
+ param_name (str): The name of the parameter to get the
311
+ description.
312
+
313
+ Returns:
314
+ str: The description of the specified parameter.
315
+ """
316
+ self.validate_openai_tool_schema(self.openai_tool_schema)
317
+ return self.openai_tool_schema["function"]["parameters"]["properties"][
318
+ param_name
319
+ ]["description"]
320
+
321
+ def set_paramter_description(
322
+ self,
323
+ param_name: str,
324
+ description: str,
325
+ ) -> None:
326
+ r"""Sets the description for a specific parameter in the function
327
+ schema.
328
+
329
+ Args:
330
+ param_name (str): The name of the parameter to set the description
331
+ for.
332
+ description (str): The description for the parameter.
333
+ """
334
+ self.openai_tool_schema["function"]["parameters"]["properties"][
335
+ param_name
336
+ ]["description"] = description
337
+
338
+ def get_parameter(self, param_name: str) -> Dict[str, Any]:
339
+ r"""Gets the schema for a specific parameter from the function schema.
340
+
341
+ Args:
342
+ param_name (str): The name of the parameter to get the schema.
343
+
344
+ Returns:
345
+ Dict[str, Any]: The schema of the specified parameter.
346
+ """
347
+ self.validate_openai_tool_schema(self.openai_tool_schema)
348
+ return self.openai_tool_schema["function"]["parameters"]["properties"][
349
+ param_name
350
+ ]
351
+
352
+ def set_parameter(self, param_name: str, value: Dict[str, Any]):
353
+ r"""Sets the schema for a specific parameter in the function schema.
354
+
355
+ Args:
356
+ param_name (str): The name of the parameter to set the schema for.
357
+ value (Dict[str, Any]): The schema to set for the parameter.
358
+ """
359
+ try:
360
+ JSONValidator.check_schema(value)
361
+ except SchemaError as e:
362
+ raise e
363
+ self.openai_tool_schema["function"]["parameters"]["properties"][
364
+ param_name
365
+ ] = value
52
366
 
53
367
  @property
54
368
  def parameters(self) -> Dict[str, Any]:
@@ -58,10 +372,11 @@ class OpenAIFunction:
58
372
  Dict[str, Any]: the dictionary containing information of
59
373
  parameters of this function.
60
374
  """
61
- return self._parameters
375
+ self.validate_openai_tool_schema(self.openai_tool_schema)
376
+ return self.openai_tool_schema["function"]["parameters"]["properties"]
62
377
 
63
378
  @parameters.setter
64
- def parameters(self, value: Dict[str, Any]):
379
+ def parameters(self, value: Dict[str, Any]) -> None:
65
380
  r"""Setter method for the property :obj:`parameters`. It will
66
381
  firstly check if the input parameters schema is valid. If invalid,
67
382
  the method will raise :obj:`jsonschema.exceptions.SchemaError`.
@@ -70,19 +385,8 @@ class OpenAIFunction:
70
385
  value (Dict[str, Any]): the new dictionary value for the
71
386
  function's parameters.
72
387
  """
73
- JSONValidator.check_schema(value)
74
- self._parameters = value
75
-
76
- def as_dict(self) -> Dict[str, Any]:
77
- r"""Method to represent the information of this function into
78
- a dictionary object.
79
-
80
- Returns:
81
- Dict[str, Any]: The dictionary object containing information
82
- of this function's name, description and parameters.
83
- """
84
- return {
85
- attr: getattr(self, attr)
86
- for attr in ["name", "description", "parameters"]
87
- if getattr(self, attr) is not None
88
- }
388
+ try:
389
+ JSONValidator.check_schema(value)
390
+ except SchemaError as e:
391
+ raise e
392
+ self.openai_tool_schema["function"]["parameters"]["properties"] = value
@@ -0,0 +1,61 @@
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.functions import OpenAIFunction
17
+ from camel.retrievers import AutoRetriever
18
+ from camel.types import StorageType
19
+
20
+
21
+ def information_retrieval(
22
+ query: str, content_input_paths: Union[str, List[str]]
23
+ ) -> str:
24
+ r"""Retrieves information from a local vector storage based on the
25
+ specified query. This function connects to a local vector storage system
26
+ and retrieves relevant information by processing the input query. It is
27
+ essential to use this function when the answer to a question requires
28
+ external knowledge sources.
29
+
30
+ Args:
31
+ query (str): The question or query for which an answer is required.
32
+ content_input_paths (Union[str, List[str]]): Paths to local
33
+ files or remote URLs.
34
+
35
+ Returns:
36
+ str: The information retrieved in response to the query, aggregated
37
+ and formatted as a string.
38
+
39
+ Example:
40
+ # Retrieve information about CAMEL AI.
41
+ information_retrieval(query = "what is CAMEL AI?",
42
+ content_input_paths="https://www.camel-ai.org/")
43
+ """
44
+ auto_retriever = AutoRetriever(
45
+ vector_storage_local_path="camel/temp_storage",
46
+ storage_type=StorageType.QDRANT,
47
+ )
48
+
49
+ retrieved_info = auto_retriever.run_vector_retriever(
50
+ query=query, content_input_paths=content_input_paths, top_k=3
51
+ )
52
+ return retrieved_info
53
+
54
+
55
+ # add the function to OpenAIFunction list
56
+ RETRIEVAL_FUNCS: List[OpenAIFunction] = [
57
+ OpenAIFunction(func)
58
+ for func in [
59
+ information_retrieval,
60
+ ]
61
+ ]