camel-ai 0.1.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.
- camel/__init__.py +30 -0
- camel/agents/__init__.py +40 -0
- camel/agents/base.py +29 -0
- camel/agents/chat_agent.py +539 -0
- camel/agents/critic_agent.py +179 -0
- camel/agents/embodied_agent.py +138 -0
- camel/agents/role_assignment_agent.py +117 -0
- camel/agents/task_agent.py +382 -0
- camel/agents/tool_agents/__init__.py +20 -0
- camel/agents/tool_agents/base.py +40 -0
- camel/agents/tool_agents/hugging_face_tool_agent.py +203 -0
- camel/configs.py +159 -0
- camel/embeddings/__init__.py +20 -0
- camel/embeddings/base.py +65 -0
- camel/embeddings/openai_embedding.py +74 -0
- camel/functions/__init__.py +27 -0
- camel/functions/base_io_functions.py +261 -0
- camel/functions/math_functions.py +61 -0
- camel/functions/openai_function.py +88 -0
- camel/functions/search_functions.py +309 -0
- camel/functions/unstructured_io_fuctions.py +616 -0
- camel/functions/weather_functions.py +136 -0
- camel/generators.py +263 -0
- camel/human.py +130 -0
- camel/memories/__init__.py +28 -0
- camel/memories/base.py +75 -0
- camel/memories/chat_history_memory.py +111 -0
- camel/memories/context_creators/__init__.py +18 -0
- camel/memories/context_creators/base.py +72 -0
- camel/memories/context_creators/score_based.py +130 -0
- camel/memories/records.py +92 -0
- camel/messages/__init__.py +38 -0
- camel/messages/base.py +223 -0
- camel/messages/func_message.py +106 -0
- camel/models/__init__.py +26 -0
- camel/models/base_model.py +110 -0
- camel/models/model_factory.py +59 -0
- camel/models/open_source_model.py +144 -0
- camel/models/openai_model.py +103 -0
- camel/models/stub_model.py +106 -0
- camel/prompts/__init__.py +38 -0
- camel/prompts/ai_society.py +121 -0
- camel/prompts/base.py +227 -0
- camel/prompts/code.py +111 -0
- camel/prompts/evaluation.py +40 -0
- camel/prompts/misalignment.py +84 -0
- camel/prompts/prompt_templates.py +117 -0
- camel/prompts/role_description_prompt_template.py +53 -0
- camel/prompts/solution_extraction.py +44 -0
- camel/prompts/task_prompt_template.py +56 -0
- camel/prompts/translation.py +42 -0
- camel/responses/__init__.py +18 -0
- camel/responses/agent_responses.py +42 -0
- camel/societies/__init__.py +20 -0
- camel/societies/babyagi_playing.py +254 -0
- camel/societies/role_playing.py +456 -0
- camel/storages/__init__.py +23 -0
- camel/storages/key_value_storages/__init__.py +23 -0
- camel/storages/key_value_storages/base.py +57 -0
- camel/storages/key_value_storages/in_memory.py +51 -0
- camel/storages/key_value_storages/json.py +97 -0
- camel/terminators/__init__.py +23 -0
- camel/terminators/base.py +44 -0
- camel/terminators/response_terminator.py +118 -0
- camel/terminators/token_limit_terminator.py +55 -0
- camel/types/__init__.py +54 -0
- camel/types/enums.py +176 -0
- camel/types/openai_types.py +39 -0
- camel/utils/__init__.py +47 -0
- camel/utils/commons.py +243 -0
- camel/utils/python_interpreter.py +435 -0
- camel/utils/token_counting.py +220 -0
- camel_ai-0.1.1.dist-info/METADATA +311 -0
- camel_ai-0.1.1.dist-info/RECORD +75 -0
- camel_ai-0.1.1.dist-info/WHEEL +4 -0
camel/utils/commons.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
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 inspect
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import socket
|
|
18
|
+
import time
|
|
19
|
+
import zipfile
|
|
20
|
+
from functools import wraps
|
|
21
|
+
from typing import (
|
|
22
|
+
Any,
|
|
23
|
+
Callable,
|
|
24
|
+
Dict,
|
|
25
|
+
List,
|
|
26
|
+
Optional,
|
|
27
|
+
Set,
|
|
28
|
+
Tuple,
|
|
29
|
+
TypeVar,
|
|
30
|
+
cast,
|
|
31
|
+
)
|
|
32
|
+
from urllib.parse import urlparse
|
|
33
|
+
|
|
34
|
+
import requests
|
|
35
|
+
|
|
36
|
+
from camel.types import TaskType
|
|
37
|
+
|
|
38
|
+
F = TypeVar('F', bound=Callable[..., Any])
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def openai_api_key_required(func: F) -> F:
|
|
42
|
+
r"""Decorator that checks if the OpenAI API key is available in the
|
|
43
|
+
environment variables.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
func (callable): The function to be wrapped.
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
callable: The decorated function.
|
|
50
|
+
|
|
51
|
+
Raises:
|
|
52
|
+
ValueError: If the OpenAI API key is not found in the environment
|
|
53
|
+
variables.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
@wraps(func)
|
|
57
|
+
def wrapper(self, *args, **kwargs):
|
|
58
|
+
if 'OPENAI_API_KEY' in os.environ:
|
|
59
|
+
return func(self, *args, **kwargs)
|
|
60
|
+
else:
|
|
61
|
+
raise ValueError('OpenAI API key not found.')
|
|
62
|
+
|
|
63
|
+
return cast(F, wrapper)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def print_text_animated(text, delay: float = 0.02, end: str = ""):
|
|
67
|
+
r"""Prints the given text with an animated effect.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
text (str): The text to print.
|
|
71
|
+
delay (float, optional): The delay between each character printed.
|
|
72
|
+
(default: :obj:`0.02`)
|
|
73
|
+
end (str, optional): The end character to print after each
|
|
74
|
+
character of text. (default: :obj:`""`)
|
|
75
|
+
"""
|
|
76
|
+
for char in text:
|
|
77
|
+
print(char, end=end, flush=True)
|
|
78
|
+
time.sleep(delay)
|
|
79
|
+
print('\n')
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def get_prompt_template_key_words(template: str) -> Set[str]:
|
|
83
|
+
r"""Given a string template containing curly braces {}, return a set of
|
|
84
|
+
the words inside the braces.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
template (str): A string containing curly braces.
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
List[str]: A list of the words inside the curly braces.
|
|
91
|
+
|
|
92
|
+
Example:
|
|
93
|
+
>>> get_prompt_template_key_words('Hi, {name}! How are you {status}?')
|
|
94
|
+
{'name', 'status'}
|
|
95
|
+
"""
|
|
96
|
+
return set(re.findall(r'{([^}]*)}', template))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def get_first_int(string: str) -> Optional[int]:
|
|
100
|
+
r"""Returns the first integer number found in the given string.
|
|
101
|
+
|
|
102
|
+
If no integer number is found, returns None.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
string (str): The input string.
|
|
106
|
+
|
|
107
|
+
Returns:
|
|
108
|
+
int or None: The first integer number found in the string, or None if
|
|
109
|
+
no integer number is found.
|
|
110
|
+
"""
|
|
111
|
+
match = re.search(r'\d+', string)
|
|
112
|
+
if match:
|
|
113
|
+
return int(match.group())
|
|
114
|
+
else:
|
|
115
|
+
return None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def download_tasks(task: TaskType, folder_path: str) -> None:
|
|
119
|
+
# Define the path to save the zip file
|
|
120
|
+
zip_file_path = os.path.join(folder_path, "tasks.zip")
|
|
121
|
+
|
|
122
|
+
# Download the zip file from the Google Drive link
|
|
123
|
+
response = requests.get("https://huggingface.co/datasets/camel-ai/"
|
|
124
|
+
f"metadata/resolve/main/{task.value}_tasks.zip")
|
|
125
|
+
|
|
126
|
+
# Save the zip file
|
|
127
|
+
with open(zip_file_path, "wb") as f:
|
|
128
|
+
f.write(response.content)
|
|
129
|
+
|
|
130
|
+
with zipfile.ZipFile(zip_file_path, "r") as zip_ref:
|
|
131
|
+
zip_ref.extractall(folder_path)
|
|
132
|
+
|
|
133
|
+
# Delete the zip file
|
|
134
|
+
os.remove(zip_file_path)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def parse_doc(func: Callable) -> Dict[str, Any]:
|
|
138
|
+
r"""Parse the docstrings of a function to extract the function name,
|
|
139
|
+
description and parameters.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
func (Callable): The function to be parsed.
|
|
143
|
+
Returns:
|
|
144
|
+
Dict[str, Any]: A dictionary with the function's name,
|
|
145
|
+
description, and parameters.
|
|
146
|
+
"""
|
|
147
|
+
|
|
148
|
+
doc = inspect.getdoc(func)
|
|
149
|
+
if not doc:
|
|
150
|
+
raise ValueError(
|
|
151
|
+
f"Invalid function {func.__name__}: no docstring provided.")
|
|
152
|
+
|
|
153
|
+
properties = {}
|
|
154
|
+
required = []
|
|
155
|
+
|
|
156
|
+
parts = re.split(r'\n\s*\n', doc)
|
|
157
|
+
func_desc = parts[0].strip()
|
|
158
|
+
|
|
159
|
+
args_section = next((p for p in parts if 'Args:' in p), None)
|
|
160
|
+
if args_section:
|
|
161
|
+
args_descs: List[Tuple[str, str, str, ]] = re.findall(
|
|
162
|
+
r'(\w+)\s*\((\w+)\):\s*(.*)', args_section)
|
|
163
|
+
properties = {
|
|
164
|
+
name.strip(): {
|
|
165
|
+
'type': type,
|
|
166
|
+
'description': desc
|
|
167
|
+
}
|
|
168
|
+
for name, type, desc in args_descs
|
|
169
|
+
}
|
|
170
|
+
for name in properties:
|
|
171
|
+
required.append(name)
|
|
172
|
+
|
|
173
|
+
# Parameters from the function signature
|
|
174
|
+
sign_params = list(inspect.signature(func).parameters.keys())
|
|
175
|
+
if len(sign_params) != len(required):
|
|
176
|
+
raise ValueError(
|
|
177
|
+
f"Number of parameters in function signature ({len(sign_params)})"
|
|
178
|
+
f" does not match that in docstring ({len(required)}).")
|
|
179
|
+
|
|
180
|
+
for param in sign_params:
|
|
181
|
+
if param not in required:
|
|
182
|
+
raise ValueError(f"Parameter '{param}' in function signature"
|
|
183
|
+
" is missing in the docstring.")
|
|
184
|
+
|
|
185
|
+
parameters = {
|
|
186
|
+
"type": "object",
|
|
187
|
+
"properties": properties,
|
|
188
|
+
"required": required,
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
# Construct the function dictionary
|
|
192
|
+
function_dict = {
|
|
193
|
+
"name": func.__name__,
|
|
194
|
+
"description": func_desc,
|
|
195
|
+
"parameters": parameters,
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
return function_dict
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def get_task_list(task_response: str) -> List[str]:
|
|
202
|
+
r"""Parse the response of the Agent and return task list.
|
|
203
|
+
|
|
204
|
+
Args:
|
|
205
|
+
task_response (str): The string response of the Agent.
|
|
206
|
+
|
|
207
|
+
Returns:
|
|
208
|
+
List[str]: A list of the string tasks.
|
|
209
|
+
"""
|
|
210
|
+
|
|
211
|
+
new_tasks_list = []
|
|
212
|
+
task_string_list = task_response.strip().split('\n')
|
|
213
|
+
# each task starts with #.
|
|
214
|
+
for task_string in task_string_list:
|
|
215
|
+
task_parts = task_string.strip().split(".", 1)
|
|
216
|
+
if len(task_parts) == 2:
|
|
217
|
+
task_id = ''.join(s for s in task_parts[0] if s.isnumeric())
|
|
218
|
+
task_name = re.sub(r'[^\w\s_]+', '', task_parts[1]).strip()
|
|
219
|
+
if task_name.strip() and task_id.isnumeric():
|
|
220
|
+
new_tasks_list.append(task_name)
|
|
221
|
+
return new_tasks_list
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def check_server_running(server_url: str) -> bool:
|
|
225
|
+
r"""Check whether the port refered by the URL to the server
|
|
226
|
+
is open.
|
|
227
|
+
|
|
228
|
+
Args:
|
|
229
|
+
server_url (str): The URL to the server running LLM inference
|
|
230
|
+
service.
|
|
231
|
+
|
|
232
|
+
Returns:
|
|
233
|
+
bool: Whether the port is open for packets (server is running).
|
|
234
|
+
"""
|
|
235
|
+
parsed_url = urlparse(server_url)
|
|
236
|
+
url_tuple = (parsed_url.hostname, parsed_url.port)
|
|
237
|
+
|
|
238
|
+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
239
|
+
result = sock.connect_ex(url_tuple)
|
|
240
|
+
sock.close()
|
|
241
|
+
|
|
242
|
+
# if the port is open, the result should be 0.
|
|
243
|
+
return result == 0
|
|
@@ -0,0 +1,435 @@
|
|
|
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 ast
|
|
15
|
+
import difflib
|
|
16
|
+
import importlib
|
|
17
|
+
import typing
|
|
18
|
+
from typing import Any, Dict, List, Optional
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class InterpreterError(ValueError):
|
|
22
|
+
r"""An error raised when the interpreter cannot evaluate a Python
|
|
23
|
+
expression, due to syntax error or unsupported operations.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class PythonInterpreter():
|
|
30
|
+
r"""A customized python interpreter to control the execution of
|
|
31
|
+
LLM-generated codes. The interpreter makes sure the code can only execute
|
|
32
|
+
functions given in action space and import white list. It also supports
|
|
33
|
+
fuzzy variable matching to reveive uncertain input variable name.
|
|
34
|
+
|
|
35
|
+
.. highlight:: none
|
|
36
|
+
|
|
37
|
+
This class is adapted from the hugging face implementation
|
|
38
|
+
`python_interpreter.py <https://github.com/huggingface/transformers/blob/8f
|
|
39
|
+
093fb799246f7dd9104ff44728da0c53a9f67a/src/transformers/tools/python_interp
|
|
40
|
+
reter.py>`_. The original license applies::
|
|
41
|
+
|
|
42
|
+
Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
|
43
|
+
|
|
44
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
45
|
+
you may not use this file except in compliance with the License.
|
|
46
|
+
You may obtain a copy of the License at
|
|
47
|
+
|
|
48
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
49
|
+
|
|
50
|
+
Unless required by applicable law or agreed to in writing, software
|
|
51
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
52
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
53
|
+
implied. See the License for the specific language governing
|
|
54
|
+
permissions and limitations under the License.
|
|
55
|
+
|
|
56
|
+
We have modified the original code to suit our requirements. We have
|
|
57
|
+
encapsulated the original functions within a class and saved the
|
|
58
|
+
interpreter state after execution. We have added support for "import"
|
|
59
|
+
statements, "for" statements, and several binary and unary operators. We
|
|
60
|
+
have added import white list to keep `import` statement safe. Additionally,
|
|
61
|
+
we have modified the variable matching logic and introduced the
|
|
62
|
+
:obj:`fuzz_state` for fuzzy matching.
|
|
63
|
+
|
|
64
|
+
Modifications copyright (C) 2023 CAMEL-AI.org
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
action_space (Dict[str, Any]): A dictionary that maps action names to
|
|
68
|
+
their corresponding functions or objects. The interpreter can only
|
|
69
|
+
execute functions that are either directly listed in this
|
|
70
|
+
dictionary or are member functions of objects listed in this
|
|
71
|
+
dictionary. The concept of :obj:`action_space` is derived from
|
|
72
|
+
EmbodiedAgent, representing the actions that an agent is capable of
|
|
73
|
+
performing.
|
|
74
|
+
import_white_list (Optional[List[str]], optional): A list that stores
|
|
75
|
+
the Python modules or functions that can be imported in the code.
|
|
76
|
+
All submodules and functions of the modules listed in this list are
|
|
77
|
+
importable. Any other import statements will be rejected. The
|
|
78
|
+
module and its submodule or function name are separated by a period
|
|
79
|
+
(:obj:`.`). (default: :obj:`None`)
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def __init__(self, action_space: Dict[str, Any],
|
|
83
|
+
import_white_list: Optional[List[str]] = None) -> None:
|
|
84
|
+
self.action_space = action_space
|
|
85
|
+
self.state = self.action_space.copy()
|
|
86
|
+
self.fuzz_state: Dict[str, Any] = {}
|
|
87
|
+
self.import_white_list = import_white_list or []
|
|
88
|
+
|
|
89
|
+
def execute(self, code: str, state: Optional[Dict[str, Any]] = None,
|
|
90
|
+
fuzz_state: Optional[Dict[str, Any]] = None,
|
|
91
|
+
keep_state: bool = True) -> Any:
|
|
92
|
+
r""" Execute the input python codes in a security environment.
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
code (str): Generated python code to be executed.
|
|
96
|
+
state (Optional[Dict[str, Any]], optional): External variables that
|
|
97
|
+
may be used in the generated code. (default: :obj:`None`)
|
|
98
|
+
fuzz_state (Optional[Dict[str, Any]], optional): External varibles
|
|
99
|
+
that do not have certain varible names. The interpreter will
|
|
100
|
+
use fuzzy matching to access these varibales. For example, if
|
|
101
|
+
:obj:`fuzz_state` has a variable :obj:`image`, the generated
|
|
102
|
+
code can use :obj:`input_image` to access it. (default:
|
|
103
|
+
:obj:`None`)
|
|
104
|
+
keep_state (bool, optional): If :obj:`True`, :obj:`state` and
|
|
105
|
+
:obj:`fuzz_state` will be kept for later execution. Otherwise,
|
|
106
|
+
they will be cleared. (default: :obj:`True`)
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
Any: The value of the last statement (excluding "import") in the
|
|
110
|
+
code. For this interpreter, the value of an expression is its
|
|
111
|
+
value, the value of an "assign" statement is the assigned
|
|
112
|
+
value, and the value of an "if" and "for" block statement is
|
|
113
|
+
the value of the last statement in the block.
|
|
114
|
+
"""
|
|
115
|
+
if state is not None:
|
|
116
|
+
self.state.update(state)
|
|
117
|
+
if fuzz_state is not None:
|
|
118
|
+
self.fuzz_state.update(fuzz_state)
|
|
119
|
+
|
|
120
|
+
try:
|
|
121
|
+
expression = ast.parse(code)
|
|
122
|
+
except SyntaxError as e:
|
|
123
|
+
raise InterpreterError(f"Syntax error in code: {e}")
|
|
124
|
+
|
|
125
|
+
result = None
|
|
126
|
+
for idx, node in enumerate(expression.body):
|
|
127
|
+
try:
|
|
128
|
+
line_result = self._execute_ast(node)
|
|
129
|
+
except InterpreterError as e:
|
|
130
|
+
if not keep_state:
|
|
131
|
+
self.clear_state()
|
|
132
|
+
msg = (f"Evaluation of the code stopped at node {idx}. "
|
|
133
|
+
f"See:\n{e}")
|
|
134
|
+
# More information can be provided by `ast.unparse()`,
|
|
135
|
+
# which is new in python 3.9.
|
|
136
|
+
raise InterpreterError(msg)
|
|
137
|
+
if line_result is not None:
|
|
138
|
+
result = line_result
|
|
139
|
+
|
|
140
|
+
if not keep_state:
|
|
141
|
+
self.clear_state()
|
|
142
|
+
|
|
143
|
+
return result
|
|
144
|
+
|
|
145
|
+
def clear_state(self) -> None:
|
|
146
|
+
r"""Initialize :obj:`state` and :obj:`fuzz_state`"""
|
|
147
|
+
self.state = self.action_space.copy()
|
|
148
|
+
self.fuzz_state = {}
|
|
149
|
+
|
|
150
|
+
# ast.Index is deprecated after python 3.9, which cannot pass type check,
|
|
151
|
+
# but is still necessary for older versions.
|
|
152
|
+
@typing.no_type_check
|
|
153
|
+
def _execute_ast(self, expression: ast.AST) -> Any:
|
|
154
|
+
if isinstance(expression, ast.Assign):
|
|
155
|
+
# Assignment -> evaluate the assignment which should
|
|
156
|
+
# update the state. We return the variable assigned as it may
|
|
157
|
+
# be used to determine the final result.
|
|
158
|
+
return self._execute_assign(expression)
|
|
159
|
+
elif isinstance(expression, ast.Attribute):
|
|
160
|
+
value = self._execute_ast(expression.value)
|
|
161
|
+
return getattr(value, expression.attr)
|
|
162
|
+
elif isinstance(expression, ast.BinOp):
|
|
163
|
+
# Binary Operator -> return the result value
|
|
164
|
+
return self._execute_binop(expression)
|
|
165
|
+
elif isinstance(expression, ast.Call):
|
|
166
|
+
# Function call -> return the value of the function call
|
|
167
|
+
return self._execute_call(expression)
|
|
168
|
+
elif isinstance(expression, ast.Compare):
|
|
169
|
+
# Compare -> return True or False
|
|
170
|
+
return self._execute_condition(expression)
|
|
171
|
+
elif isinstance(expression, ast.Constant):
|
|
172
|
+
# Constant -> just return the value
|
|
173
|
+
return expression.value
|
|
174
|
+
elif isinstance(expression, ast.Dict):
|
|
175
|
+
# Dict -> evaluate all keys and values
|
|
176
|
+
result: Dict = {}
|
|
177
|
+
for k, v in zip(expression.keys, expression.values):
|
|
178
|
+
if k is not None:
|
|
179
|
+
result[self._execute_ast(k)] = self._execute_ast(v)
|
|
180
|
+
else:
|
|
181
|
+
result.update(self._execute_ast(v))
|
|
182
|
+
return result
|
|
183
|
+
elif isinstance(expression, ast.Expr):
|
|
184
|
+
# Expression -> evaluate the content
|
|
185
|
+
return self._execute_ast(expression.value)
|
|
186
|
+
elif isinstance(expression, ast.For):
|
|
187
|
+
return self._execute_for(expression)
|
|
188
|
+
elif isinstance(expression, ast.FormattedValue):
|
|
189
|
+
# Formatted value (part of f-string) -> evaluate the content
|
|
190
|
+
# and return
|
|
191
|
+
return self._execute_ast(expression.value)
|
|
192
|
+
elif isinstance(expression, ast.If):
|
|
193
|
+
# If -> execute the right branch
|
|
194
|
+
return self._execute_if(expression)
|
|
195
|
+
elif isinstance(expression, ast.Import):
|
|
196
|
+
# Import -> add imported names in self.state and return None.
|
|
197
|
+
self._execute_import(expression)
|
|
198
|
+
return None
|
|
199
|
+
elif isinstance(expression, ast.ImportFrom):
|
|
200
|
+
self._execute_import_from(expression)
|
|
201
|
+
return None
|
|
202
|
+
elif hasattr(ast, "Index") and isinstance(expression, ast.Index):
|
|
203
|
+
# cannot pass type check
|
|
204
|
+
return self._execute_ast(expression.value)
|
|
205
|
+
elif isinstance(expression, ast.JoinedStr):
|
|
206
|
+
return "".join(
|
|
207
|
+
[str(self._execute_ast(v)) for v in expression.values])
|
|
208
|
+
elif isinstance(expression, ast.List):
|
|
209
|
+
# List -> evaluate all elements
|
|
210
|
+
return [self._execute_ast(elt) for elt in expression.elts]
|
|
211
|
+
elif isinstance(expression, ast.Name):
|
|
212
|
+
# Name -> pick up the value in the state
|
|
213
|
+
return self._execute_name(expression)
|
|
214
|
+
elif isinstance(expression, ast.Subscript):
|
|
215
|
+
# Subscript -> return the value of the indexing
|
|
216
|
+
return self._execute_subscript(expression)
|
|
217
|
+
elif isinstance(expression, ast.Tuple):
|
|
218
|
+
return tuple([self._execute_ast(elt) for elt in expression.elts])
|
|
219
|
+
elif isinstance(expression, ast.UnaryOp):
|
|
220
|
+
# Binary Operator -> return the result value
|
|
221
|
+
return self._execute_unaryop(expression)
|
|
222
|
+
else:
|
|
223
|
+
# For now we refuse anything else. Let's add things as we need
|
|
224
|
+
# them.
|
|
225
|
+
raise InterpreterError(
|
|
226
|
+
f"{expression.__class__.__name__} is not supported.")
|
|
227
|
+
|
|
228
|
+
def _execute_assign(self, assign: ast.Assign) -> Any:
|
|
229
|
+
targets = assign.targets
|
|
230
|
+
result = self._execute_ast(assign.value)
|
|
231
|
+
|
|
232
|
+
for target in targets:
|
|
233
|
+
self._assign(target, result)
|
|
234
|
+
return result
|
|
235
|
+
|
|
236
|
+
def _assign(self, target: ast.expr, value: Any):
|
|
237
|
+
if isinstance(target, ast.Name):
|
|
238
|
+
self.state[target.id] = value
|
|
239
|
+
elif isinstance(target, ast.Tuple):
|
|
240
|
+
if not isinstance(value, tuple):
|
|
241
|
+
raise InterpreterError(f"Expected type tuple, but got"
|
|
242
|
+
f"{value.__class__.__name__} instead.")
|
|
243
|
+
if len(target.elts) != len(value):
|
|
244
|
+
raise InterpreterError(
|
|
245
|
+
f"Expected {len(target.elts)} values but got"
|
|
246
|
+
f" {len(value)}.")
|
|
247
|
+
for t, v in zip(target.elts, value):
|
|
248
|
+
self.state[self._execute_ast(t)] = v
|
|
249
|
+
else:
|
|
250
|
+
raise InterpreterError(f"Unsupported variable type. Expected "
|
|
251
|
+
f"ast.Name or ast.Tuple, got "
|
|
252
|
+
f"{target.__class__.__name__} instead.")
|
|
253
|
+
|
|
254
|
+
def _execute_call(self, call: ast.Call) -> Any:
|
|
255
|
+
callable_func = self._execute_ast(call.func)
|
|
256
|
+
|
|
257
|
+
# Todo deal with args
|
|
258
|
+
args = [self._execute_ast(arg) for arg in call.args]
|
|
259
|
+
kwargs = {
|
|
260
|
+
keyword.arg: self._execute_ast(keyword.value)
|
|
261
|
+
for keyword in call.keywords
|
|
262
|
+
}
|
|
263
|
+
return callable_func(*args, **kwargs)
|
|
264
|
+
|
|
265
|
+
def _execute_subscript(self, subscript: ast.Subscript):
|
|
266
|
+
index = self._execute_ast(subscript.slice)
|
|
267
|
+
value = self._execute_ast(subscript.value)
|
|
268
|
+
if not isinstance(subscript.ctx, ast.Load):
|
|
269
|
+
raise InterpreterError(
|
|
270
|
+
f"{subscript.ctx.__class__.__name__} is not supported for "
|
|
271
|
+
"subscript.")
|
|
272
|
+
if isinstance(value, (list, tuple)):
|
|
273
|
+
return value[int(index)]
|
|
274
|
+
if index in value:
|
|
275
|
+
return value[index]
|
|
276
|
+
if isinstance(index, str) and isinstance(value, dict):
|
|
277
|
+
close_matches = difflib.get_close_matches(
|
|
278
|
+
index,
|
|
279
|
+
[key for key in list(value.keys()) if isinstance(key, str)],
|
|
280
|
+
)
|
|
281
|
+
if len(close_matches) > 0:
|
|
282
|
+
return value[close_matches[0]]
|
|
283
|
+
|
|
284
|
+
raise InterpreterError(f"Could not index {value} with '{index}'.")
|
|
285
|
+
|
|
286
|
+
def _execute_name(self, name: ast.Name):
|
|
287
|
+
if isinstance(name.ctx, ast.Store):
|
|
288
|
+
return name.id
|
|
289
|
+
elif isinstance(name.ctx, ast.Load):
|
|
290
|
+
return self._get_value_from_state(name.id)
|
|
291
|
+
else:
|
|
292
|
+
raise InterpreterError(f"{name.ctx} is not supported.")
|
|
293
|
+
|
|
294
|
+
def _execute_condition(self, condition: ast.Compare):
|
|
295
|
+
if len(condition.ops) > 1:
|
|
296
|
+
raise InterpreterError(
|
|
297
|
+
"Cannot evaluate conditions with multiple operators")
|
|
298
|
+
|
|
299
|
+
left = self._execute_ast(condition.left)
|
|
300
|
+
comparator = condition.ops[0]
|
|
301
|
+
right = self._execute_ast(condition.comparators[0])
|
|
302
|
+
|
|
303
|
+
if isinstance(comparator, ast.Eq):
|
|
304
|
+
return left == right
|
|
305
|
+
elif isinstance(comparator, ast.NotEq):
|
|
306
|
+
return left != right
|
|
307
|
+
elif isinstance(comparator, ast.Lt):
|
|
308
|
+
return left < right
|
|
309
|
+
elif isinstance(comparator, ast.LtE):
|
|
310
|
+
return left <= right
|
|
311
|
+
elif isinstance(comparator, ast.Gt):
|
|
312
|
+
return left > right
|
|
313
|
+
elif isinstance(comparator, ast.GtE):
|
|
314
|
+
return left >= right
|
|
315
|
+
elif isinstance(comparator, ast.Is):
|
|
316
|
+
return left is right
|
|
317
|
+
elif isinstance(comparator, ast.IsNot):
|
|
318
|
+
return left is not right
|
|
319
|
+
elif isinstance(comparator, ast.In):
|
|
320
|
+
return left in right
|
|
321
|
+
elif isinstance(comparator, ast.NotIn):
|
|
322
|
+
return left not in right
|
|
323
|
+
else:
|
|
324
|
+
raise InterpreterError(f"Unsupported operator: {comparator}")
|
|
325
|
+
|
|
326
|
+
def _execute_if(self, if_statement: ast.If):
|
|
327
|
+
result = None
|
|
328
|
+
if not isinstance(if_statement.test, ast.Compare):
|
|
329
|
+
raise InterpreterError(
|
|
330
|
+
"Only Campare expr supported in if statement, get"
|
|
331
|
+
f" {if_statement.test.__class__.__name__}")
|
|
332
|
+
if self._execute_condition(if_statement.test):
|
|
333
|
+
for line in if_statement.body:
|
|
334
|
+
line_result = self._execute_ast(line)
|
|
335
|
+
if line_result is not None:
|
|
336
|
+
result = line_result
|
|
337
|
+
else:
|
|
338
|
+
for line in if_statement.orelse:
|
|
339
|
+
line_result = self._execute_ast(line)
|
|
340
|
+
if line_result is not None:
|
|
341
|
+
result = line_result
|
|
342
|
+
return result
|
|
343
|
+
|
|
344
|
+
def _execute_for(self, for_statement: ast.For):
|
|
345
|
+
result = None
|
|
346
|
+
for value in self._execute_ast(for_statement.iter):
|
|
347
|
+
self._assign(for_statement.target, value)
|
|
348
|
+
for line in for_statement.body:
|
|
349
|
+
line_result = self._execute_ast(line)
|
|
350
|
+
if line_result is not None:
|
|
351
|
+
result = line_result
|
|
352
|
+
|
|
353
|
+
return result
|
|
354
|
+
|
|
355
|
+
def _execute_import(self, import_module: ast.Import) -> None:
|
|
356
|
+
for module in import_module.names:
|
|
357
|
+
self._validate_import(module.name)
|
|
358
|
+
alias = module.asname or module.name
|
|
359
|
+
self.state[alias] = importlib.import_module(module.name)
|
|
360
|
+
|
|
361
|
+
def _execute_import_from(self, import_from: ast.ImportFrom):
|
|
362
|
+
if import_from.module is None:
|
|
363
|
+
raise InterpreterError("\"from . import\" is not supported.")
|
|
364
|
+
for import_name in import_from.names:
|
|
365
|
+
full_name = import_from.module + f".{import_name.name}"
|
|
366
|
+
self._validate_import(full_name)
|
|
367
|
+
imported_module = importlib.import_module(import_from.module)
|
|
368
|
+
alias = import_name.asname or import_name.name
|
|
369
|
+
self.state[alias] = getattr(imported_module, import_name.name)
|
|
370
|
+
|
|
371
|
+
def _validate_import(self, full_name: str):
|
|
372
|
+
tmp_name = ""
|
|
373
|
+
found_name = False
|
|
374
|
+
for name in full_name.split("."):
|
|
375
|
+
tmp_name += name if tmp_name == "" else f".{name}"
|
|
376
|
+
if tmp_name in self.import_white_list:
|
|
377
|
+
found_name = True
|
|
378
|
+
return
|
|
379
|
+
|
|
380
|
+
if not found_name:
|
|
381
|
+
raise InterpreterError(f"It is not permitted to import modules "
|
|
382
|
+
f"than module white list (try to import "
|
|
383
|
+
f"{full_name}).")
|
|
384
|
+
|
|
385
|
+
def _execute_binop(self, binop: ast.BinOp):
|
|
386
|
+
left = self._execute_ast(binop.left)
|
|
387
|
+
operator = binop.op
|
|
388
|
+
right = self._execute_ast(binop.right)
|
|
389
|
+
|
|
390
|
+
if isinstance(operator, ast.Add):
|
|
391
|
+
return left + right
|
|
392
|
+
elif isinstance(operator, ast.Sub):
|
|
393
|
+
return left - right
|
|
394
|
+
elif isinstance(operator, ast.Mult):
|
|
395
|
+
return left * right
|
|
396
|
+
elif isinstance(operator, ast.Div):
|
|
397
|
+
return left / right
|
|
398
|
+
elif isinstance(operator, ast.FloorDiv):
|
|
399
|
+
return left // right
|
|
400
|
+
elif isinstance(operator, ast.Mod):
|
|
401
|
+
return left % right
|
|
402
|
+
elif isinstance(operator, ast.Pow):
|
|
403
|
+
return left**right
|
|
404
|
+
elif isinstance(operator, ast.LShift):
|
|
405
|
+
return left << right
|
|
406
|
+
elif isinstance(operator, ast.RShift):
|
|
407
|
+
return left >> right
|
|
408
|
+
elif isinstance(operator, ast.MatMult):
|
|
409
|
+
return left @ right
|
|
410
|
+
else:
|
|
411
|
+
raise InterpreterError(f"Operator not supported: {operator}")
|
|
412
|
+
|
|
413
|
+
def _execute_unaryop(self, unaryop: ast.UnaryOp):
|
|
414
|
+
operand = self._execute_ast(unaryop.operand)
|
|
415
|
+
operator = unaryop.op
|
|
416
|
+
|
|
417
|
+
if isinstance(operator, ast.UAdd):
|
|
418
|
+
return +operand
|
|
419
|
+
elif isinstance(operator, ast.USub):
|
|
420
|
+
return -operand
|
|
421
|
+
elif isinstance(operator, ast.Not):
|
|
422
|
+
return not operand
|
|
423
|
+
else:
|
|
424
|
+
raise InterpreterError(f"Operator not supported: {operator}")
|
|
425
|
+
|
|
426
|
+
def _get_value_from_state(self, key: str) -> Any:
|
|
427
|
+
if key in self.state:
|
|
428
|
+
return self.state[key]
|
|
429
|
+
else:
|
|
430
|
+
close_matches = (difflib.get_close_matches(
|
|
431
|
+
key, list(self.fuzz_state.keys()), n=1))
|
|
432
|
+
if close_matches:
|
|
433
|
+
return self.fuzz_state[close_matches[0]]
|
|
434
|
+
else:
|
|
435
|
+
raise InterpreterError(f"The variable `{key}` is not defined.")
|