fmr-aeg commited on
Commit
92ff59a
·
verified ·
1 Parent(s): f0dcd11

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,11 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/black_dress_example.png filter=lfs diff=lfs merge=lfs -text
37
+ assets/dress_result_example.png filter=lfs diff=lfs merge=lfs -text
38
+ assets/example_image.png filter=lfs diff=lfs merge=lfs -text
39
+ assets/logo_amazon_circle.png filter=lfs diff=lfs merge=lfs -text
40
+ assets/phone_result_example.png filter=lfs diff=lfs merge=lfs -text
41
+ assets/pres_video.mp4 filter=lfs diff=lfs merge=lfs -text
42
+ assets/result_siege_auto.png filter=lfs diff=lfs merge=lfs -text
43
+ assets/robot_amazon.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+ config/secrets.yaml
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ cover/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ .pybuilder/
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+ notebooks
82
+
83
+ # IPython
84
+ profile_default/
85
+ ipython_config.py
86
+
87
+ # pyenv
88
+ # For a library or package, you might want to ignore these files since the code is
89
+ # intended to run in multiple environments; otherwise, check them in:
90
+ # .python-version
91
+
92
+ # pipenv
93
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
94
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
95
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
96
+ # install all needed dependencies.
97
+ #Pipfile.lock
98
+
99
+ # UV
100
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
101
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
102
+ # commonly ignored for libraries.
103
+ #uv.lock
104
+
105
+ # poetry
106
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
107
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
108
+ # commonly ignored for libraries.
109
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
110
+ #poetry.lock
111
+
112
+ # pdm
113
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
114
+ #pdm.lock
115
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
116
+ # in version control.
117
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
118
+ .pdm.toml
119
+ .pdm-python
120
+ .pdm-build/
121
+
122
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
123
+ __pypackages__/
124
+
125
+ # Celery stuff
126
+ celerybeat-schedule
127
+ celerybeat.pid
128
+
129
+ # SageMath parsed files
130
+ *.sage.py
131
+
132
+ # Environments
133
+ .env
134
+ .venv
135
+ env/
136
+ venv/
137
+ ENV/
138
+ env.bak/
139
+ venv.bak/
140
+
141
+ # Spyder project settings
142
+ .spyderproject
143
+ .spyproject
144
+
145
+ # Rope project settings
146
+ .ropeproject
147
+
148
+ # mkdocs documentation
149
+ /site
150
+
151
+ # mypy
152
+ .mypy_cache/
153
+ .dmypy.json
154
+ dmypy.json
155
+
156
+ # Pyre type checker
157
+ .pyre/
158
+
159
+ # pytype static type analyzer
160
+ .pytype/
161
+
162
+ # Cython debug symbols
163
+ cython_debug/
164
+
165
+ # PyCharm
166
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
167
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
168
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
169
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
170
+ #.idea/
171
+
172
+ # Ruff stuff:
173
+ .ruff_cache/
174
+
175
+ # PyPI configuration file
176
+ .pypirc
.idea/.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
4
+ # Editor-based HTTP Client requests
5
+ /httpRequests/
6
+ # Datasource local storage ignored files
7
+ /dataSources/
8
+ /dataSources.local.xml
.idea/AiAgentEcom.iml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="PYTHON_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$">
5
+ <excludeFolder url="file://$MODULE_DIR$/.venv" />
6
+ </content>
7
+ <orderEntry type="inheritedJdk" />
8
+ <orderEntry type="sourceFolder" forTests="false" />
9
+ </component>
10
+ </module>
.idea/inspectionProfiles/Project_Default.xml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <component name="InspectionProjectProfileManager">
2
+ <profile version="1.0">
3
+ <option name="myName" value="Project Default" />
4
+ <inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
5
+ <option name="ignoredErrors">
6
+ <list>
7
+ <option value="N801" />
8
+ </list>
9
+ </option>
10
+ </inspection_tool>
11
+ </profile>
12
+ </component>
.idea/inspectionProfiles/profiles_settings.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <component name="InspectionProjectProfileManager">
2
+ <settings>
3
+ <option name="USE_PROJECT_PROFILE" value="false" />
4
+ <version value="1.0" />
5
+ </settings>
6
+ </component>
.idea/jsonSchemas.xml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="JsonSchemaMappingsProjectConfiguration">
4
+ <state>
5
+ <map>
6
+ <entry key="No JSON schema">
7
+ <value>
8
+ <SchemaInfo>
9
+ <option name="ignoredFile" value="true" />
10
+ <option name="name" value="No JSON schema" />
11
+ <option name="relativePathToSchema" value="" />
12
+ <option name="applicationDefined" value="true" />
13
+ <option name="patterns">
14
+ <list>
15
+ <Item>
16
+ <option name="path" value="file://$PROJECT_DIR$/prompt.yaml" />
17
+ </Item>
18
+ </list>
19
+ </option>
20
+ <option name="isIgnoredFile" value="true" />
21
+ </SchemaInfo>
22
+ </value>
23
+ </entry>
24
+ </map>
25
+ </state>
26
+ </component>
27
+ </project>
.idea/misc.xml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="Black">
4
+ <option name="sdkName" value="Python 3.11 (AiAgentEcom)" />
5
+ </component>
6
+ <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (AiAgentEcom)" project-jdk-type="Python SDK" />
7
+ </project>
.idea/modules.xml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/AiAgentEcom.iml" filepath="$PROJECT_DIR$/.idea/AiAgentEcom.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="$PROJECT_DIR$" vcs="Git" />
5
+ </component>
6
+ </project>
.idea/workspace.xml ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="AutoImportSettings">
4
+ <option name="autoReloadType" value="SELECTIVE" />
5
+ </component>
6
+ <component name="ChangeListManager">
7
+ <list default="true" id="8de53bb3-1256-4f0c-bc5d-065f5e972a7a" name="Changes" comment="Last commit before refacto">
8
+ <change afterPath="$PROJECT_DIR$/assets/pres_video.mp4" afterDir="false" />
9
+ <change afterPath="$PROJECT_DIR$/deploy_file.py" afterDir="false" />
10
+ <change beforePath="$PROJECT_DIR$/README.md" beforeDir="false" afterPath="$PROJECT_DIR$/README.md" afterDir="false" />
11
+ <change beforePath="$PROJECT_DIR$/main.py" beforeDir="false" afterPath="$PROJECT_DIR$/app.py" afterDir="false" />
12
+ <change beforePath="$PROJECT_DIR$/notebooks/Clean_pipeline.ipynb" beforeDir="false" />
13
+ <change beforePath="$PROJECT_DIR$/notebooks/Untitled.ipynb" beforeDir="false" />
14
+ <change beforePath="$PROJECT_DIR$/notebooks/improving tools.ipynb" beforeDir="false" />
15
+ <change beforePath="$PROJECT_DIR$/requirements.txt" beforeDir="false" afterPath="$PROJECT_DIR$/requirements.txt" afterDir="false" />
16
+ <change beforePath="$PROJECT_DIR$/src/aiagent/utils/ecom_tools.py" beforeDir="false" afterPath="$PROJECT_DIR$/src/aiagent/utils/ecom_tools.py" afterDir="false" />
17
+ </list>
18
+ <option name="SHOW_DIALOG" value="false" />
19
+ <option name="HIGHLIGHT_CONFLICTS" value="true" />
20
+ <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
21
+ <option name="LAST_RESOLUTION" value="IGNORE" />
22
+ </component>
23
+ <component name="FileTemplateManagerImpl">
24
+ <option name="RECENT_TEMPLATES">
25
+ <list>
26
+ <option value="Python Script" />
27
+ </list>
28
+ </option>
29
+ </component>
30
+ <component name="Git.Settings">
31
+ <option name="RECENT_BRANCH_BY_REPOSITORY">
32
+ <map>
33
+ <entry key="$PROJECT_DIR$" value="master" />
34
+ </map>
35
+ </option>
36
+ <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
37
+ </component>
38
+ <component name="GitHubPullRequestSearchHistory">{
39
+ &quot;lastFilter&quot;: {
40
+ &quot;state&quot;: &quot;OPEN&quot;,
41
+ &quot;assignee&quot;: &quot;fmr-aeg&quot;
42
+ }
43
+ }</component>
44
+ <component name="GithubPullRequestsUISettings">{
45
+ &quot;selectedUrlAndAccountId&quot;: {
46
+ &quot;url&quot;: &quot;https://github.com/fmr-aeg/AiAgent_ecom.git&quot;,
47
+ &quot;accountId&quot;: &quot;64a232b9-70ed-40fa-9996-3f0f765a0041&quot;
48
+ }
49
+ }</component>
50
+ <component name="ProjectColorInfo">{
51
+ &quot;associatedIndex&quot;: 8
52
+ }</component>
53
+ <component name="ProjectId" id="2ub7JcEoQtSRJuakaMJduUa0Wis" />
54
+ <component name="ProjectViewState">
55
+ <option name="hideEmptyMiddlePackages" value="true" />
56
+ <option name="showLibraryContents" value="true" />
57
+ </component>
58
+ <component name="PropertiesComponent">{
59
+ &quot;keyToString&quot;: {
60
+ &quot;Python.app.executor&quot;: &quot;Run&quot;,
61
+ &quot;Python.brouillon_gradio.executor&quot;: &quot;Run&quot;,
62
+ &quot;Python.deploy_file.executor&quot;: &quot;Run&quot;,
63
+ &quot;Python.exemple_gradio.executor&quot;: &quot;Run&quot;,
64
+ &quot;Python.gradio_draft.executor&quot;: &quot;Run&quot;,
65
+ &quot;Python.main.executor&quot;: &quot;Run&quot;,
66
+ &quot;Python.test_gradio.executor&quot;: &quot;Run&quot;,
67
+ &quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
68
+ &quot;git-widget-placeholder&quot;: &quot;hf__space&quot;,
69
+ &quot;ignore.virus.scanning.warn.message&quot;: &quot;true&quot;,
70
+ &quot;last_opened_file_path&quot;: &quot;C:/Users/aboub/PycharmProjects/AiAgentEcom/assets&quot;,
71
+ &quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
72
+ &quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
73
+ &quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
74
+ &quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
75
+ &quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
76
+ &quot;settings.editor.selected.configurable&quot;: &quot;vcs.log&quot;,
77
+ &quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
78
+ }
79
+ }</component>
80
+ <component name="RecentsManager">
81
+ <key name="CopyFile.RECENT_KEYS">
82
+ <recent name="C:\Users\aboub\PycharmProjects\AiAgentEcom\assets" />
83
+ </key>
84
+ <key name="MoveFile.RECENT_KEYS">
85
+ <recent name="C:\Users\aboub\PycharmProjects\AiAgentEcom\assets" />
86
+ <recent name="C:\Users\aboub\PycharmProjects\AiAgentEcom" />
87
+ <recent name="C:\Users\aboub\PycharmProjects\AiAgentEcom\AiAgent_ecom" />
88
+ </key>
89
+ </component>
90
+ <component name="RunManager" selected="Python.deploy_file">
91
+ <configuration name="app" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
92
+ <module name="AiAgentEcom" />
93
+ <option name="ENV_FILES" value="" />
94
+ <option name="INTERPRETER_OPTIONS" value="" />
95
+ <option name="PARENT_ENVS" value="true" />
96
+ <envs>
97
+ <env name="PYTHONUNBUFFERED" value="1" />
98
+ </envs>
99
+ <option name="SDK_HOME" value="" />
100
+ <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
101
+ <option name="IS_MODULE_SDK" value="true" />
102
+ <option name="ADD_CONTENT_ROOTS" value="true" />
103
+ <option name="ADD_SOURCE_ROOTS" value="true" />
104
+ <EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
105
+ <option name="SCRIPT_NAME" value="C:\Users\aboub\PycharmProjects\AiAgentEcom\app.py" />
106
+ <option name="PARAMETERS" value="" />
107
+ <option name="SHOW_COMMAND_LINE" value="false" />
108
+ <option name="EMULATE_TERMINAL" value="false" />
109
+ <option name="MODULE_MODE" value="false" />
110
+ <option name="REDIRECT_INPUT" value="false" />
111
+ <option name="INPUT_FILE" value="" />
112
+ <method v="2" />
113
+ </configuration>
114
+ <configuration name="deploy_file" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
115
+ <module name="AiAgentEcom" />
116
+ <option name="ENV_FILES" value="" />
117
+ <option name="INTERPRETER_OPTIONS" value="" />
118
+ <option name="PARENT_ENVS" value="true" />
119
+ <envs>
120
+ <env name="PYTHONUNBUFFERED" value="1" />
121
+ </envs>
122
+ <option name="SDK_HOME" value="" />
123
+ <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
124
+ <option name="IS_MODULE_SDK" value="true" />
125
+ <option name="ADD_CONTENT_ROOTS" value="true" />
126
+ <option name="ADD_SOURCE_ROOTS" value="true" />
127
+ <EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
128
+ <option name="SCRIPT_NAME" value="$PROJECT_DIR$/deploy_file.py" />
129
+ <option name="PARAMETERS" value="" />
130
+ <option name="SHOW_COMMAND_LINE" value="false" />
131
+ <option name="EMULATE_TERMINAL" value="false" />
132
+ <option name="MODULE_MODE" value="false" />
133
+ <option name="REDIRECT_INPUT" value="false" />
134
+ <option name="INPUT_FILE" value="" />
135
+ <method v="2" />
136
+ </configuration>
137
+ <configuration name="exemple_gradio" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
138
+ <module name="AiAgentEcom" />
139
+ <option name="ENV_FILES" value="" />
140
+ <option name="INTERPRETER_OPTIONS" value="" />
141
+ <option name="PARENT_ENVS" value="true" />
142
+ <envs>
143
+ <env name="PYTHONUNBUFFERED" value="1" />
144
+ </envs>
145
+ <option name="SDK_HOME" value="" />
146
+ <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
147
+ <option name="IS_MODULE_SDK" value="true" />
148
+ <option name="ADD_CONTENT_ROOTS" value="true" />
149
+ <option name="ADD_SOURCE_ROOTS" value="true" />
150
+ <EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
151
+ <option name="SCRIPT_NAME" value="$PROJECT_DIR$/exemple_gradio.py" />
152
+ <option name="PARAMETERS" value="" />
153
+ <option name="SHOW_COMMAND_LINE" value="false" />
154
+ <option name="EMULATE_TERMINAL" value="false" />
155
+ <option name="MODULE_MODE" value="false" />
156
+ <option name="REDIRECT_INPUT" value="false" />
157
+ <option name="INPUT_FILE" value="" />
158
+ <method v="2" />
159
+ </configuration>
160
+ <configuration name="gradio_draft" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
161
+ <module name="AiAgentEcom" />
162
+ <option name="ENV_FILES" value="" />
163
+ <option name="INTERPRETER_OPTIONS" value="" />
164
+ <option name="PARENT_ENVS" value="true" />
165
+ <envs>
166
+ <env name="PYTHONUNBUFFERED" value="1" />
167
+ </envs>
168
+ <option name="SDK_HOME" value="" />
169
+ <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
170
+ <option name="IS_MODULE_SDK" value="true" />
171
+ <option name="ADD_CONTENT_ROOTS" value="true" />
172
+ <option name="ADD_SOURCE_ROOTS" value="true" />
173
+ <EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
174
+ <option name="SCRIPT_NAME" value="$PROJECT_DIR$/gradio_draft.py" />
175
+ <option name="PARAMETERS" value="" />
176
+ <option name="SHOW_COMMAND_LINE" value="false" />
177
+ <option name="EMULATE_TERMINAL" value="false" />
178
+ <option name="MODULE_MODE" value="false" />
179
+ <option name="REDIRECT_INPUT" value="false" />
180
+ <option name="INPUT_FILE" value="" />
181
+ <method v="2" />
182
+ </configuration>
183
+ <configuration name="test_gradio" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
184
+ <module name="AiAgentEcom" />
185
+ <option name="ENV_FILES" value="" />
186
+ <option name="INTERPRETER_OPTIONS" value="" />
187
+ <option name="PARENT_ENVS" value="true" />
188
+ <envs>
189
+ <env name="PYTHONUNBUFFERED" value="1" />
190
+ </envs>
191
+ <option name="SDK_HOME" value="" />
192
+ <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
193
+ <option name="IS_MODULE_SDK" value="true" />
194
+ <option name="ADD_CONTENT_ROOTS" value="true" />
195
+ <option name="ADD_SOURCE_ROOTS" value="true" />
196
+ <EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
197
+ <option name="SCRIPT_NAME" value="$PROJECT_DIR$/test_gradio.py" />
198
+ <option name="PARAMETERS" value="" />
199
+ <option name="SHOW_COMMAND_LINE" value="false" />
200
+ <option name="EMULATE_TERMINAL" value="false" />
201
+ <option name="MODULE_MODE" value="false" />
202
+ <option name="REDIRECT_INPUT" value="false" />
203
+ <option name="INPUT_FILE" value="" />
204
+ <method v="2" />
205
+ </configuration>
206
+ <recent_temporary>
207
+ <list>
208
+ <item itemvalue="Python.deploy_file" />
209
+ <item itemvalue="Python.gradio_draft" />
210
+ <item itemvalue="Python.app" />
211
+ <item itemvalue="Python.test_gradio" />
212
+ <item itemvalue="Python.exemple_gradio" />
213
+ </list>
214
+ </recent_temporary>
215
+ </component>
216
+ <component name="SharedIndexes">
217
+ <attachedChunks>
218
+ <set>
219
+ <option value="bundled-js-predefined-d6986cc7102b-5c90d61e3bab-JavaScript-PY-242.23726.102" />
220
+ <option value="bundled-python-sdk-5e1850174b45-399fe30bd8c1-com.jetbrains.pycharm.pro.sharedIndexes.bundled-PY-242.23726.102" />
221
+ </set>
222
+ </attachedChunks>
223
+ </component>
224
+ <component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
225
+ <component name="SvnConfiguration">
226
+ <configuration>C:\Users\aboub\AppData\Roaming\Subversion</configuration>
227
+ </component>
228
+ <component name="TaskManager">
229
+ <task active="true" id="Default" summary="Default task">
230
+ <changelist id="8de53bb3-1256-4f0c-bc5d-065f5e972a7a" name="Changes" comment="" />
231
+ <created>1742505348453</created>
232
+ <option name="number" value="Default" />
233
+ <option name="presentableId" value="Default" />
234
+ <updated>1742505348453</updated>
235
+ <workItem from="1742505349797" duration="6103000" />
236
+ <workItem from="1742763330663" duration="2676000" />
237
+ <workItem from="1743712682609" duration="7790000" />
238
+ <workItem from="1743799406936" duration="5979000" />
239
+ <workItem from="1743875822908" duration="2489000" />
240
+ <workItem from="1743889818845" duration="5016000" />
241
+ <workItem from="1743956163220" duration="8706000" />
242
+ <workItem from="1744060030272" duration="4813000" />
243
+ <workItem from="1744487194780" duration="6032000" />
244
+ <workItem from="1744545099397" duration="20647000" />
245
+ <workItem from="1744665630956" duration="3770000" />
246
+ <workItem from="1745007630511" duration="1545000" />
247
+ <workItem from="1745179006911" duration="10432000" />
248
+ <workItem from="1745233177494" duration="20012000" />
249
+ <workItem from="1745352882704" duration="2930000" />
250
+ <workItem from="1745682049676" duration="3077000" />
251
+ <workItem from="1745782902670" duration="4802000" />
252
+ <workItem from="1745963859361" duration="6075000" />
253
+ <workItem from="1746044011669" duration="1791000" />
254
+ <workItem from="1746214721116" duration="4533000" />
255
+ <workItem from="1746282811771" duration="824000" />
256
+ <workItem from="1746317896601" duration="3737000" />
257
+ <workItem from="1746392133539" duration="6388000" />
258
+ <workItem from="1746700445392" duration="4154000" />
259
+ <workItem from="1746710698662" duration="10682000" />
260
+ <workItem from="1746884584791" duration="11875000" />
261
+ <workItem from="1747080873111" duration="602000" />
262
+ <workItem from="1747249724669" duration="2288000" />
263
+ <workItem from="1747350180224" duration="4904000" />
264
+ <workItem from="1747424631627" duration="2694000" />
265
+ <workItem from="1747606719158" duration="2335000" />
266
+ <workItem from="1747682403094" duration="7083000" />
267
+ <workItem from="1747779058058" duration="9506000" />
268
+ <workItem from="1747841281902" duration="245000" />
269
+ <workItem from="1749511880222" duration="3463000" />
270
+ <workItem from="1749582965687" duration="13274000" />
271
+ <workItem from="1749826405850" duration="42000" />
272
+ </task>
273
+ <task id="LOCAL-00001" summary="Last commit before refacto">
274
+ <option name="closed" value="true" />
275
+ <created>1747841415770</created>
276
+ <option name="number" value="00001" />
277
+ <option name="presentableId" value="LOCAL-00001" />
278
+ <option name="project" value="LOCAL" />
279
+ <updated>1747841415770</updated>
280
+ </task>
281
+ <option name="localTasksCounter" value="2" />
282
+ <servers />
283
+ </component>
284
+ <component name="TypeScriptGeneratedFilesManager">
285
+ <option name="version" value="3" />
286
+ </component>
287
+ <component name="Vcs.Log.Tabs.Properties">
288
+ <option name="TAB_STATES">
289
+ <map>
290
+ <entry key="MAIN">
291
+ <value>
292
+ <State />
293
+ </value>
294
+ </entry>
295
+ </map>
296
+ </option>
297
+ </component>
298
+ <component name="VcsManagerConfiguration">
299
+ <MESSAGE value="Last commit before refacto" />
300
+ <option name="LAST_COMMIT_MESSAGE" value="Last commit before refacto" />
301
+ </component>
302
+ <component name="com.intellij.coverage.CoverageDataManagerImpl">
303
+ <SUITE FILE_PATH="coverage/AiAgentEcom$app.coverage" NAME="app Coverage Results" MODIFIED="1744550463538" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
304
+ <SUITE FILE_PATH="coverage/AiAgentEcom$exemple_gradio.coverage" NAME="exemple_gradio Coverage Results" MODIFIED="1744582581341" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
305
+ <SUITE FILE_PATH="coverage/AiAgentEcom$test_gradio.coverage" NAME="test_gradio Coverage Results" MODIFIED="1747697595792" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
306
+ <SUITE FILE_PATH="coverage/AiAgentEcom$main.coverage" NAME="main Coverage Results" MODIFIED="1747782459771" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
307
+ <SUITE FILE_PATH="coverage/AiAgentEcom$deploy_file.coverage" NAME="deploy_file Coverage Results" MODIFIED="1749512803827" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
308
+ <SUITE FILE_PATH="coverage/AiAgentEcom$gradio_draft.coverage" NAME="gradio_draft Coverage Results" MODIFIED="1747787593269" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
309
+ <SUITE FILE_PATH="coverage/AiAgentEcom$brouillon_gradio.coverage" NAME="brouillon_gradio Coverage Results" MODIFIED="1744548118230" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
310
+ </component>
311
+ </project>
README.md CHANGED
@@ -1,12 +1,76 @@
1
- ---
2
- title: Ecom Agent
3
- emoji: 😻
4
- colorFrom: purple
5
- colorTo: red
6
- sdk: gradio
7
- sdk_version: 5.33.2
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Ecommerce assistant
3
+ emoji: 🛒
4
+ colorFrom: red
5
+ colorTo: yellow
6
+ sdk: gradio
7
+ sdk_version: 5.23.3
8
+ app_file: app.py
9
+ pinned: true
10
+ tags:
11
+ - smolagents
12
+ - agent
13
+ - tool
14
+ - agent-demo-track
15
+ - ecommerce
16
+ ---
17
+ # 🛍️ SmartShop Agent – Your AI-Powered Shopping Assistant
18
+
19
+ ## Overview
20
+
21
+ **SmartShop Agent** is an AI-powered shopping assistant that interacts with users in natural language and helps them make better buying decisions online. Whether you're looking for the perfect dress for a wedding, comparing smartphones, or just browsing for inspiration, this intelligent agent navigates the product universe for you.
22
+
23
+ It simulates an interactive personal shopper, capable of:
24
+ - Understanding your needs and preferences
25
+ - Searching for products dynamically (e.g., on Amazon)
26
+ - Comparing features like price, delivery time, and specs
27
+ - Responding to follow-ups and refining results based on feedback
28
+ - Presenting results in a visually engaging way (e.g., carousels, Gradio UI)
29
+
30
+ ⚠️ *Disclaimer: This project is not affiliated with Amazon or any of its subsidiaries.*
31
+
32
+ ---
33
+
34
+ ## 🎥 Demo video
35
+ <video width="100%" controls>
36
+ <source src="assets/pres_video.mp4" type="video/mp4">
37
+ Your browser does not support the video tag.
38
+ </video>
39
+
40
+ 🎥 [demo video here](assets/pres_video.mp4)
41
+ or
42
+ [here](https://drive.google.com/file/d/18cZo3iLbtoua6VG7AxpmOn2UIWLv-KIA/view)
43
+
44
+ ---
45
+
46
+ ## ✨ Key Features
47
+
48
+ - 🧠 **Conversational Intelligence**: The agent can interpret vague or complex queries like “I need something classy for a summer party”.
49
+ - 🔍 **Product Search Integration**: It performs real-time or simulated product lookups based on user intent.
50
+ - 📊 **Feature Comparison**: Smart comparison logic highlights the differences between similar items (e.g., suction power of vacuum cleaners or camera specs on smartphones).
51
+ - 🎛️ **Interactive UI (Gradio)**: Built-in UI that mimics the feel of Amazon’s homepage with responsive prompts and clean product cards.
52
+ - 🔁 **Prompt Suggestions**: Users can click pre-generated ideas like “Find alternatives” or “Compare these products” to guide their journey.
53
+
54
+ ---
55
+
56
+
57
+
58
+ ## 🛠️ How It Works
59
+
60
+ 1. The user asks a question (e.g. *“Can you help me find a black dress for a wedding?”*).
61
+ 2. The agent analyzes the intent and searches products accordingly.
62
+ 3. If needed, it compares multiple items using key attributes (price, delivery, power, etc.).
63
+ 4. The UI presents results in a carousel-like block with product images, names, and action buttons.
64
+
65
+ ---
66
+
67
+ ## 💡 Example Use Cases
68
+
69
+ - *"I need a red dress for a wedding next weekend"* → Returns filtered dresses that arrive on time.
70
+ - *"Can you compare the Galaxy S24 Ultra and iPhone 15?"* → Returns a side-by-side comparison of specs, price, battery, and more.
71
+ - *"I'm looking for something elegant for an evening event"* → Suggests classy outfits with visuals.
72
+
73
+ ---
74
+
75
+ ## 🚀 Try It Out
76
+ Built with ❤️ by fmr-aeg
app.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from smolagents import CodeAgent, LiteLLMModel
3
+ from src.aiagent.utils.ecom_tools import (search_on_amazon,
4
+ ParserProductDescriptionWithGuideTool, GetProductDescriptionTool,
5
+ CompareProductTool, FilterProduct, FinalAnswerTool)
6
+ from src.aiagent.ui.main_gradio import GradioUI
7
+ import yaml
8
+ from src.aiagent.core.custom_python_executor import LocalPythonExecutor
9
+
10
+ # with open('config/secrets.yaml') as f:
11
+ # SECRETS = yaml.safe_load(f)
12
+ #
13
+ # os.environ['GEMINI_API_KEY'] = SECRETS['gemini_token']
14
+
15
+ tools_model = LiteLLMModel(model_id='gemini/gemini-2.0-flash')
16
+ # reasoning_model = LiteLLMModel(model_id='gpt-4o-mini')
17
+ reasoning_model = LiteLLMModel(model_id='gemini/gemini-2.0-flash')
18
+
19
+ product_description_parser_with_guide = ParserProductDescriptionWithGuideTool(tools_model)
20
+ compare_products = CompareProductTool(tools_model)
21
+ filter_product = FilterProduct(tools_model)
22
+ get_product_description = GetProductDescriptionTool()
23
+ final_answer = FinalAnswerTool()
24
+
25
+ template = yaml.safe_load(open("config/prompt.yaml"))
26
+
27
+ agent = CodeAgent(
28
+ tools=[
29
+ get_product_description,
30
+ product_description_parser_with_guide,
31
+ search_on_amazon,
32
+ compare_products,
33
+ filter_product,
34
+ final_answer
35
+ ],
36
+ model=reasoning_model,
37
+ prompt_templates=template,
38
+ max_steps=8,
39
+ verbosity_level=1,
40
+ grammar=None,
41
+ planning_interval=None,
42
+ name=None,
43
+ description=None,
44
+ additional_authorized_imports=['pandas', 'json']
45
+ )
46
+
47
+ agent.python_executor = LocalPythonExecutor(agent.additional_authorized_imports,
48
+ max_print_outputs_length=agent.max_print_outputs_length)
49
+
50
+ if __name__ == '__main__':
51
+ GradioUI(agent).launch(allowed_paths=["assets"])
assets/black_dress_example.png ADDED

Git LFS Details

  • SHA256: 3814b7afa0571a7cde18003f723de0c8ac2f8a78d573476290dbded2382a4ecc
  • Pointer size: 131 Bytes
  • Size of remote file: 240 kB
assets/dress_result_example.png ADDED

Git LFS Details

  • SHA256: d61a4a2c026a47be962df680b0583d8f6ccee486ffd6b4b0f5876b0e8f788fc5
  • Pointer size: 131 Bytes
  • Size of remote file: 284 kB
assets/example_image.png ADDED

Git LFS Details

  • SHA256: 8eb5a4a640256a13b20a5cb62137c86313996cd30129032340881eb8b54f0e73
  • Pointer size: 131 Bytes
  • Size of remote file: 139 kB
assets/logo_amazon_circle.png ADDED

Git LFS Details

  • SHA256: 3763d8494039ded1d035cb14f16c818421b2c3043a99d3e65033ed7086b98c19
  • Pointer size: 131 Bytes
  • Size of remote file: 800 kB
assets/no_image.png ADDED
assets/phone_result_example.png ADDED

Git LFS Details

  • SHA256: cb908ecb518ca3388f0d872aa9fe90185a51dc61b04989c930e6680c3240d6a7
  • Pointer size: 131 Bytes
  • Size of remote file: 292 kB
assets/pres_video.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1d94e804ca53d6436e5efa2d9bb67c26c08873e41375ab842f105b0299858d8
3
+ size 9417194
assets/result_siege_auto.png ADDED

Git LFS Details

  • SHA256: 2ce91e3cb8e7653d1e66e99e757d0f0abf7ff4637e54304b80c4e1168fad6597
  • Pointer size: 131 Bytes
  • Size of remote file: 293 kB
assets/robot_amazon.png ADDED

Git LFS Details

  • SHA256: cd373487dafc5e4fdbab424287b6028a2f0ae82d69a5b012a564516e0509398f
  • Pointer size: 131 Bytes
  • Size of remote file: 850 kB
assets/user_image.png ADDED
config/prompt.yaml ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ system_prompt: |-
2
+ You are a smart shopping assistant, specialized in navigating Amazon. You help users compare, filter, and evaluate products based on their needs.
3
+ Your mission is to guide them clearly and efficiently to make better buying decisions using the tools provided to you.
4
+ For that, you will use code blobs. You will be given a task to solve as best you can.
5
+ To do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.
6
+ To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.
7
+
8
+ At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.
9
+ Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.
10
+ During each intermediate step, you can use 'print()' to save whatever important information you will then need.
11
+ These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
12
+ In the end you have to return a final answer using the `final_answer` tool.
13
+
14
+ Here are a few examples using notional tools:
15
+ ---
16
+ Task: "j'hésite entre le produit https://www.amazon.fr/Aspirateur-Automatique-Poussi%C3%A8re-Navigation-Cartographie/dp/B0DKT88H16/ref=sr_1_9? et le produit https://www.amazon.fr/Laresar-Clean-Aspirateur-Mars01-Navigation/dp/B0D9XDPT5M/ref=sr_1_7? tu saurais me donner des conseils ?"
17
+
18
+ Thought: I will retrieve the product description for both products using get_product_description. I will reflect on what are the best features to compare depending on the product type and then compare them using parse_product_description_with_guide. I will present a comparison to help the user decide.
19
+ Code:
20
+ ```py
21
+ product_url1 = "https://www.amazon.fr/Aspirateur-Automatique-Poussi%C3%A8re-Navigation-Cartographie/dp/B0DKT88H16/ref=sr_1_9?"
22
+ product_url2 = "https://www.amazon.fr/Laresar-Clean-Aspirateur-Mars01-Navigation/dp/B0D9XDPT5M/ref=sr_1_7?"
23
+
24
+ description1 = get_product_description(product_url1)
25
+ print(f"Description produit 1: {description1}")
26
+ description2 = get_product_description(product_url2)
27
+ print(f"Description produit 2: {description2}")
28
+ ```<end_code>
29
+ Observation: "Description produit 1: Aspirateur robot avec une puissance d'aspiration de 1450Pa et une batterie de 120min ...
30
+ Description produit 2: Aspirateur robot intelligent qui aspire avec une puissance de 5800Pa et possède une grande batterie de 2h ..."
31
+
32
+ Thought: The products are robot vacuum cleaner, I think the best features to campare should be vacum power, battery life and noise level
33
+ Code:
34
+ ```py
35
+ features_to_compare = ["suction power", "battery life", "noise level"]
36
+
37
+ parsed_product1 = parse_product_description_with_guide(description1, features_to_compare)
38
+ print(f"Parsed product 1:\n{parsed_product1}")
39
+ parsed_product2 = parse_product_description_with_guide(description2, features_to_compare)
40
+ print(f"Parsed product 2:\n{parsed_product2}")
41
+
42
+ comparison_table = compare_product([parsed_product1, parsed_product2])
43
+ answer = f"Voici une comparaison des deux aspirateurs robots basée sur les informations trouvées sur Amazon. Veuillez examiner le tableau ci-dessous pour une comparaison détaillée des fonctionnalités. Le choix dépendra de vos priorités (puissance d'aspiration, autonomie, fonctionnalités intelligentes, etc.)."
44
+ final_answer(answer, comparison_table)
45
+ ```<end_code>
46
+
47
+ ---
48
+ Task: "I'm looking for a black dress that's not too expensive and arrives before Saturday. Can you help me?"
49
+
50
+ Thought: I will use search_on_amazon to find suitable dresses. I'll then refine the results based on price and delivery date by comparing with current date
51
+ Code:
52
+ ```py
53
+ import time
54
+
55
+ print(f' current date : {time.ctime()}')
56
+ search_results = make_a_search_on_amazon(keyword="black dress")
57
+ print(search_results)
58
+ ```<end_code>
59
+ Observation:"
60
+ current date : Mon Apr 21 16:01:28 2025
61
+ [{'product_name': 'dress1',
62
+ 'image_url': 'https://img_url1.jpg',
63
+ 'product_link': 'https://www.amazon.com/dress1url',
64
+ 'price': '$35.99',
65
+ 'delivery_date': 'FREE delivery Sat, Apr 26 Or fastest delivery Tomorrow, Apr 22 '},
66
+ {'product_name': 'dress2',
67
+ 'image_url': 'https://img_url2.jpg',
68
+ 'product_link': 'https://www.amazon.com/dress1url',
69
+ 'price': '$36.99',
70
+ 'delivery_date': ' FREE delivery Sun, Apr 27'},
71
+ {'product_name': 'dress3',
72
+ 'image_url': 'https://img_url3.jpg',
73
+ 'product_link': 'https://www.amazon.com/dress1url',
74
+ 'price': '$19.99',
75
+ 'delivery_date': ' FREE delivery Sat, Apr 26 on $35 of items shipped by Amazon Or fastest delivery Tomorrow, Apr 22 '}]"
76
+
77
+ Thought: The search_on_amazon tool returned a list of dictionaries, each representing a product. I can easily remove product which not come before this saturday by comparing with the current date.
78
+ I will then use compare_product for easy formating and return result with an explanation.
79
+ Code:
80
+ ```py
81
+ search_results.pop(1)
82
+ structured_product = compare_product(list_product_element=search_result)
83
+
84
+ answer = 'Here you can find a list of inexpensive black wedding dresses that will be delivered by Saturday. I remain at your disposal if you want to add selections criteria.'
85
+ final_answer(answer, structured_product)
86
+ ```<end_code>
87
+
88
+ ---
89
+ Task: "I'm looking for a new TV for my living room, can you give me some suggestions?"
90
+
91
+ Thought: I will search on Amazon for some TVs using the search_on_amazon tool with 2 keywords. Then, I will get every product description using get_product_description and extract a list of features for every product thanks to the product_description_parser_with_guide tool. Lastly, I will compare these products and display them for the user
92
+ Code:
93
+ ```py
94
+ l_product = []
95
+ for keyword in ["TV", "Smart TV"]:
96
+ l_product += search_on_amazon(keyword=keyword)
97
+
98
+ print(f"product list find by search : {l_product}")
99
+ print(f"number of product find by search : {len(l_product)}")
100
+ ```<end_code>
101
+
102
+ observation :
103
+ "product list find by search : [{
104
+ "product_name": "TV LED 32\" HD, HDMI, USB, Dolby Audio",
105
+ "image_url": "https://example.com/image1.jpg",
106
+ "product_link": "https://amazon.fr/exemple1",
107
+ "price": "119,99 €",
108
+ "delivery_date": "Livraison mar. 14 mai"
109
+ },
110
+ {
111
+ "product_name": "TV LED 24\" HD, HDMI, Mode Hôtel",
112
+ "image_url": "https://example.com/image2.jpg",
113
+ "product_link": "https://amazon.fr/exemple2",
114
+ "price": "99,90 €",
115
+ "delivery_date": "Livraison mer. 14 mai"
116
+ },
117
+ (truncated)
118
+ {
119
+ "product_name": "TV QLED 50\" 4K, Dolby Vision",
120
+ "image_url": "https://example.com/image5.jpg",
121
+ "product_link": "https://amazon.fr/exemple5",
122
+ "price": "549,00 €",
123
+ "delivery_date": "Livraison lun. 19 mai"
124
+ }]
125
+ number of product find by search : 13
126
+
127
+ Thought: I now have a list of 13 products relevant to the user's needs. To make the choice easier, I'll find the size, resolution and smart options of each choice thank to their description and compare them.
128
+ Code:
129
+ ```py
130
+ features_to_compare = ['size', 'resolution', "smart_options"]
131
+ for product in l_product:
132
+ product_description = get_product_description(product['product_link'])
133
+ parsed_features_from_product = product_description_parser_with_guide(product_description, features_to_compare)
134
+ product.update(parsed_features_from_product)
135
+
136
+ compared_product = compare_products(l_product)
137
+ answer = "You can find here a the best TV available on Amazon for your living room. Don't hesitate to tell me if you have more precise idea of what you're looking for."
138
+ final_answer(answer, compared_product)
139
+ ```<end_code>
140
+
141
+ ---
142
+ Task:
143
+ "Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
144
+ You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
145
+ {'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"
146
+
147
+ Thought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.
148
+ Code:
149
+ ```py
150
+ translated_question = translator(question=question, src_lang="French", tgt_lang="English")
151
+ print(f"The translated question is {translated_question}.")
152
+ answer = image_qa(image=image, question=translated_question)
153
+ final_answer(f"The answer is {answer}")
154
+ ```<end_code>
155
+
156
+ ---
157
+ Task:
158
+ In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
159
+ What does he say was the consequence of Einstein learning too much math on his creativity, in one word?
160
+
161
+ Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
162
+ Code:
163
+ ```py
164
+ pages = search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
165
+ print(pages)
166
+ ```<end_code>
167
+ Observation:
168
+ No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".
169
+
170
+ Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
171
+ Code:
172
+ ```py
173
+ pages = search(query="1979 interview Stanislaus Ulam")
174
+ print(pages)
175
+ ```<end_code>
176
+ Observation:
177
+ Found 6 pages:
178
+ [Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)
179
+
180
+ [Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)
181
+
182
+ (truncated)
183
+
184
+ Thought: I will read the first 2 pages to know more.
185
+ Code:
186
+ ```py
187
+ for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
188
+ whole_page = visit_webpage(url)
189
+ print(whole_page)
190
+ print("\n" + "="*80 + "\n") # Print separator between pages
191
+ ```<end_code>
192
+ Observation:
193
+ Manhattan Project Locations:
194
+ Los Alamos, NM
195
+ Stanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at
196
+ (truncated)
197
+
198
+ Thought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: "He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity." Let's answer in one word.
199
+ Code:
200
+ ```py
201
+ final_answer("diminished")
202
+ ```<end_code>
203
+
204
+ ---
205
+ Task: "I'm not sure whether to buy the Samsung Galaxy A54 or the Xiaomi Redmi Note 13 Pro. Can you help me decide?"
206
+
207
+ Thought: The user provided product names, not direct URLs. I will use the search_on_amazon tool to retrieve the product pages based on those names.
208
+ Code:
209
+ ```py
210
+ results_samsung = search_on_amazon(keyword="Samsung Galaxy A54 smartphone")
211
+ results_xiaomi = search_on_amazon(keyword="Xiaomi Redmi Note 13 Pro smartphone")
212
+ print(results_samsung)
213
+ print(results_xiaomi)
214
+ ```<end_code>
215
+ Observation:
216
+ results_samsung = [{
217
+ "product_name": "Samsung Galaxy A54 5G Smartphone",
218
+ "product_link": "https://www.amazon.fr/dp/B0XXX1"}
219
+ ...
220
+ }]
221
+ results_xiaomi = [{
222
+ "product_name": "Xiaomi Redmi Note 13 Pro 5G",
223
+ "product_link": "https://www.amazon.fr/dp/B0XXX2"}
224
+ ...
225
+ }]
226
+
227
+ Thought: Now that I have the correct URLs for both products by taking the first element, I’ll extract the product descriptions. Then, I’ll extract and compare key features like display, battery life, processor, camera, and storage to help the user make an informed decision.
228
+ Code:
229
+ ```py
230
+ samsung_url = results_samsung[0]["product_link"]
231
+ xiaomi_url = results_xiaomi[0]["product_link"]
232
+
233
+ samsung_desc = get_product_description(samsung_url)
234
+ xiaomi_desc = get_product_description(xiaomi_url)
235
+
236
+ features_to_compare = ["display", "battery", "processor", "camera", "storage"]
237
+ parsed_samsung = parse_product_description_with_guide(samsung_desc, features_to_compare)
238
+ parsed_xiaomi = parse_product_description_with_guide(xiaomi_desc, features_to_compare)
239
+
240
+ comparison_table = compare_product([parsed_samsung, parsed_xiaomi])
241
+
242
+ answer = "Here's a side-by-side comparison of the two smartphones. Depending on your priorities—performance, camera, battery, etc.—you can make a better decision."
243
+ final_answer(answer, comparison_table)
244
+ ```<end_code>
245
+
246
+ ---
247
+ Task: "What should I wear to a business dinner?"
248
+
249
+ Thought: For a business dinner, I’ll recommend tailored dresses or two-piece sets that are elegant but not flashy. Darker tones and clean cuts preferred. I will use search_on_amazon with some keywords en retrieve some product, then I will filter them to be sure its formal product with filter_product then compare them for user with compare_product tool.
250
+ Code:
251
+ ```py
252
+ results = []
253
+ for keywords in ["women's business dinner outfit", "tailored dark dresses", "elegant two-piece sets"]:
254
+ results += search_on_amazon(keyword=keyword)
255
+
256
+ filter_condition = "classy clothes that could be worn to a business dinner"
257
+ results = filter_products(results, filter_condition)
258
+ comparison_table = compare_product(results)
259
+
260
+ final_answer("Please find below examples of outfits that could meet your needs for a business dinner", comparison_table)
261
+ ```<end_code>
262
+
263
+ Task: "I'm a man"
264
+ Thought: I will keep the same reasoning but adapt only the keyword for matching a man need
265
+ Code:
266
+ ```py
267
+ results = []
268
+ for keywords in ["men's business dinner outfit", "tailored dark costume"]:
269
+ results += search_on_amazon(keyword=keyword)
270
+
271
+ filter_condition = "classy clothes that could be worn to a business dinner"
272
+ results = filter_products(results, filter_condition)
273
+ comparison_table = compare_product(results)
274
+
275
+ final_answer("Please find below examples of outfits that could meet your needs for a business dinner as a man", comparison_table)
276
+ ```<end_code>
277
+
278
+ ---
279
+
280
+ Above example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools, behaving like regular python functions:
281
+ ```python
282
+ {%- for tool in tools.values() %}
283
+ def {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:
284
+ """{{ tool.description }}
285
+
286
+ Args:
287
+ {%- for arg_name, arg_info in tool.inputs.items() %}
288
+ {{ arg_name }}: {{ arg_info.description }}
289
+ {%- endfor %}
290
+ """
291
+ {% endfor %}
292
+ ```
293
+
294
+ {%- if managed_agents and managed_agents.values() | list %}
295
+ You can also give tasks to team members.
296
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
297
+ Given that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.
298
+ Here is a list of the team members that you can call:
299
+ ```python
300
+ {%- for agent in managed_agents.values() %}
301
+ def {{ agent.name }}("Your query goes here.") -> str:
302
+ """{{ agent.description }}"""
303
+ {% endfor %}
304
+ ```
305
+ {%- endif %}
306
+
307
+ Here are the rules you should always follow to solve your task:
308
+ 1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
309
+ 2. Use only variables that you have defined!
310
+ 3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wiki({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wiki(query="What is the place where James Bond lives?")'.
311
+ 4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.
312
+ 5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
313
+ 6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
314
+ 7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
315
+ 8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
316
+ 9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
317
+ 10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
318
+
319
+ Now Begin!
320
+
321
+ planning:
322
+ initial_plan : |-
323
+ You are a world expert at analyzing a situation to derive facts, and plan accordingly towards solving a task.
324
+ Below I will present you a task. You will need to 1. build a survey of facts known or needed to solve the task, then 2. make a plan of action to solve the task.
325
+
326
+ ## 1. Facts survey
327
+ You will build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
328
+ These "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
329
+ ### 1.1. Facts given in the task
330
+ List here the specific facts given in the task that could help you (there might be nothing here).
331
+
332
+ ### 1.2. Facts to look up
333
+ List here any facts that we may need to look up.
334
+ Also list where to find each of these, for instance a website, a file... - maybe the task contains some sources that you should re-use here.
335
+
336
+ ### 1.3. Facts to derive
337
+ List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
338
+
339
+ Don't make any assumptions. For each item, provide a thorough reasoning. Do not add anything else on top of three headings above.
340
+
341
+ ## 2. Plan
342
+ Then for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
343
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
344
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
345
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
346
+
347
+ You can leverage these tools, behaving like regular python functions:
348
+ ```python
349
+ {%- for tool in tools.values() %}
350
+ def {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:
351
+ """{{ tool.description }}
352
+
353
+ Args:
354
+ {%- for arg_name, arg_info in tool.inputs.items() %}
355
+ {{ arg_name }}: {{ arg_info.description }}
356
+ {%- endfor %}
357
+ """
358
+ {% endfor %}
359
+ ```
360
+
361
+ {%- if managed_agents and managed_agents.values() | list %}
362
+ You can also give tasks to team members.
363
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
364
+ Given that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.
365
+ Here is a list of the team members that you can call:
366
+ ```python
367
+ {%- for agent in managed_agents.values() %}
368
+ def {{ agent.name }}("Your query goes here.") -> str:
369
+ """{{ agent.description }}"""
370
+ {% endfor %}
371
+ ```
372
+ {%- endif %}
373
+
374
+ ---
375
+ Now begin! Here is your task:
376
+ ```
377
+ {{task}}
378
+ ```
379
+ First in part 1, write the facts survey, then in part 2, write your plan.
380
+
381
+ update_plan_pre_messages: |-
382
+ You are a world expert at analyzing a situation, and plan accordingly towards solving a task.
383
+ You have been given the following task:
384
+ ```
385
+ {{task}}
386
+ ```
387
+
388
+ Below you will find a history of attempts made to solve this task.
389
+ You will first have to produce a survey of known and unknown facts, then propose a step-by-step high-level plan to solve the task.
390
+ If the previous tries so far have met some success, your updated plan can build on these results.
391
+ If you are stalled, you can make a completely new plan starting from scratch.
392
+
393
+ Find the task and history below:
394
+
395
+ update_plan_post_messages: |-
396
+ Now write your updated facts below, taking into account the above history:
397
+ ## 1. Updated facts survey
398
+ ### 1.1. Facts given in the task
399
+ ### 1.2. Facts that we have learned
400
+ ### 1.3. Facts still to look up
401
+ ### 1.4. Facts still to derive
402
+
403
+ Then write a step-by-step high-level plan to solve the task above.
404
+ ## 2. Plan
405
+ ### 2. 1. ...
406
+ Etc.
407
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
408
+ Beware that you have {remaining_steps} steps remaining.
409
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
410
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
411
+
412
+ You can leverage these tools, behaving like regular python functions:
413
+ ```python
414
+ {%- for tool in tools.values() %}
415
+ def {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:
416
+ """{{ tool.description }}
417
+
418
+ Args:
419
+ {%- for arg_name, arg_info in tool.inputs.items() %}
420
+ {{ arg_name }}: {{ arg_info.description }}
421
+ {%- endfor %}"""
422
+ {% endfor %}
423
+ ```
424
+
425
+ {%- if managed_agents and managed_agents.values() | list %}
426
+ You can also give tasks to team members.
427
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
428
+ Given that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.
429
+ Here is a list of the team members that you can call:
430
+ ```python
431
+ {%- for agent in managed_agents.values() %}
432
+ def {{ agent.name }}("Your query goes here.") -> str:
433
+ """{{ agent.description }}"""
434
+ {% endfor %}
435
+ ```
436
+ {%- endif %}
437
+
438
+ Now write your updated facts survey below, then your new plan.
439
+
440
+ managed_agent:
441
+ task: |-
442
+ You're a helpful agent named '{{name}}'.
443
+ You have been submitted this task by your manager.
444
+ ---
445
+ Task:
446
+ {{task}}
447
+ ---
448
+ You're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible to give them a clear understanding of the answer.
449
+
450
+ Your final_answer WILL HAVE to contain these parts:
451
+ ### 1. Task outcome (short version):
452
+ ### 2. Task outcome (extremely detailed version):
453
+ ### 3. Additional context (if relevant):
454
+
455
+ Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
456
+ And even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.
457
+ report: |-
458
+ Here is the final answer from your managed agent '{{name}}':
459
+ {{final_answer}}
460
+
461
+ final_answer:
462
+ pre_messages: |-
463
+ An agent tried to answer a user query but it got stuck and failed to do so. You are tasked with providing an answer instead. Here is the agent's memory:
464
+ post_messages: |-
465
+ Based on the above, please provide an answer to the following user task:
466
+ {{task}}
deploy_file.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from huggingface_hub import HfApi
2
+ repo_id = "Agents-MCP-Hackathon/ecom_agent"
3
+ api = HfApi()
4
+
5
+ api.upload_folder(repo_id=repo_id, repo_type="space", folder_path=".")
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ pandas
4
+ numpy
5
+ accelerate>=0.26.0
6
+ bitsandbytes==0.45.3
7
+ smolagents==1.12.0
8
+ litellm==1.65.3
9
+ gradio==5.23.3
10
+ beautifulsoup4
11
+ pyyaml
12
+ requests
src/aiagent/core/custom_model.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents import Model, TransformersModel, Tool, ChatMessage, MessageRole
2
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
3
+ import torch
4
+ import logging
5
+ from copy import deepcopy
6
+ from transformers import AutoModelForCausalLM, AutoModelForImageTextToText, AutoProcessor, AutoTokenizer
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def get_tool_json_schema(tool: Tool) -> Dict:
12
+ properties = deepcopy(tool.inputs)
13
+ required = []
14
+ for key, value in properties.items():
15
+ if value["type"] == "any":
16
+ value["type"] = "string"
17
+ if not ("nullable" in value and value["nullable"]):
18
+ required.append(key)
19
+ return {
20
+ "type": "function",
21
+ "function": {
22
+ "name": tool.name,
23
+ "description": tool.description,
24
+ "parameters": {
25
+ "type": "object",
26
+ "properties": properties,
27
+ "required": required,
28
+ },
29
+ },
30
+ }
31
+
32
+
33
+ def remove_stop_sequences(content: str, stop_sequences: List[str]) -> str:
34
+ for stop_seq in stop_sequences:
35
+ if content[-len(stop_seq):] == stop_seq:
36
+ content = content[: -len(stop_seq)]
37
+ return content
38
+
39
+
40
+ class CustomTransformersModel(Model):
41
+ """A class that uses Hugging Face's Transformers library for language model interaction.
42
+
43
+ This model allows you to load and use Hugging Face's models locally using the Transformers library. It supports features like stop sequences and grammar customization.
44
+
45
+ > [!TIP]
46
+ > You must have `transformers` and `torch` installed on your machine. Please run `pip install smolagents[transformers]` if it's not the case.
47
+
48
+ Parameters:
49
+ model_id (`str`):
50
+ The Hugging Face model ID to be used for inference. This can be a path or model identifier from the Hugging Face model hub.
51
+ For example, `"Qwen/Qwen2.5-Coder-32B-Instruct"`.
52
+ device_map (`str`, *optional*):
53
+ The device_map to initialize your model with.
54
+ torch_dtype (`str`, *optional*):
55
+ The torch_dtype to initialize your model with.
56
+ trust_remote_code (bool, default `False`):
57
+ Some models on the Hub require running remote code: for this model, you would have to set this flag to True.
58
+ kwargs (dict, *optional*):
59
+ Any additional keyword arguments that you want to use in model.generate(), for instance `max_new_tokens` or `device`.
60
+ **kwargs:
61
+ Additional keyword arguments to pass to `model.generate()`, for instance `max_new_tokens` or `device`.
62
+ Raises:
63
+ ValueError:
64
+ If the model name is not provided.
65
+
66
+ Example:
67
+ ```python
68
+ >>> engine = TransformersModel(
69
+ ... model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
70
+ ... device="cuda",
71
+ ... max_new_tokens=5000,
72
+ ... )
73
+ >>> messages = [{"role": "user", "content": "Explain quantum mechanics in simple terms."}]
74
+ >>> response = engine(messages, stop_sequences=["END"])
75
+ >>> print(response)
76
+ "Quantum mechanics is the branch of physics that studies..."
77
+ ```
78
+ """
79
+
80
+ def __init__(
81
+ self,
82
+ model_id: Optional[str] = None,
83
+ device_map: Optional[str] = None,
84
+ torch_dtype: Optional[str] = None,
85
+ trust_remote_code: bool = False,
86
+ quantization_config=None,
87
+ **kwargs,
88
+ ):
89
+
90
+ self.model_id = model_id
91
+
92
+ default_max_tokens = 5000
93
+ max_new_tokens = kwargs.get("max_new_tokens") or kwargs.get("max_tokens")
94
+ if not max_new_tokens:
95
+ kwargs["max_new_tokens"] = default_max_tokens
96
+ logger.warning(
97
+ f"`max_new_tokens` not provided, using this default value for `max_new_tokens`: {default_max_tokens}"
98
+ )
99
+
100
+ if device_map is None:
101
+ device_map = "cuda" if torch.cuda.is_available() else "cpu"
102
+ logger.info(f"Using device: {device_map}")
103
+ self._is_vlm = False
104
+ try:
105
+ self.model = AutoModelForCausalLM.from_pretrained(
106
+ model_id,
107
+ device_map=device_map,
108
+ torch_dtype=torch_dtype,
109
+ trust_remote_code=trust_remote_code,
110
+ quantization_config=quantization_config
111
+ )
112
+ self.tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=trust_remote_code)
113
+ except ValueError as e:
114
+ if "Unrecognized configuration class" in str(e):
115
+ self.model = AutoModelForImageTextToText.from_pretrained(
116
+ model_id,
117
+ device_map=device_map,
118
+ torch_dtype=torch_dtype,
119
+ trust_remote_code=trust_remote_code,
120
+ )
121
+ self.processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=trust_remote_code)
122
+ self._is_vlm = True
123
+ else:
124
+ raise e
125
+ except Exception as e:
126
+ raise ValueError(f"Failed to load tokenizer and model for {model_id=}: {e}") from e
127
+ super().__init__(flatten_messages_as_text=not self._is_vlm, **kwargs)
128
+
129
+ def make_stopping_criteria(self, stop_sequences: List[str], tokenizer) -> "StoppingCriteriaList":
130
+ from transformers import StoppingCriteria, StoppingCriteriaList
131
+
132
+ class StopOnStrings(StoppingCriteria):
133
+ def __init__(self, stop_strings: List[str], tokenizer):
134
+ self.stop_strings = stop_strings
135
+ self.tokenizer = tokenizer
136
+ self.stream = ""
137
+
138
+ def reset(self):
139
+ self.stream = ""
140
+
141
+ def __call__(self, input_ids, scores, **kwargs):
142
+ generated = self.tokenizer.decode(input_ids[0][-1], skip_special_tokens=True)
143
+ self.stream += generated
144
+ if any([self.stream.endswith(stop_string) for stop_string in self.stop_strings]):
145
+ return True
146
+ return False
147
+
148
+ return StoppingCriteriaList([StopOnStrings(stop_sequences, tokenizer)])
149
+
150
+ def __call__(
151
+ self,
152
+ messages: List[Dict[str, str]],
153
+ stop_sequences: Optional[List[str]] = None,
154
+ grammar: Optional[str] = None,
155
+ tools_to_call_from: Optional[List[Tool]] = None,
156
+ **kwargs,
157
+ ) -> ChatMessage:
158
+ completion_kwargs = self._prepare_completion_kwargs(
159
+ messages=messages,
160
+ stop_sequences=stop_sequences,
161
+ grammar=grammar,
162
+ **kwargs,
163
+ )
164
+
165
+ messages = completion_kwargs.pop("messages")
166
+ stop_sequences = completion_kwargs.pop("stop", None)
167
+
168
+ max_new_tokens = (
169
+ kwargs.get("max_new_tokens")
170
+ or kwargs.get("max_tokens")
171
+ or self.kwargs.get("max_new_tokens")
172
+ or self.kwargs.get("max_tokens")
173
+ )
174
+
175
+ if max_new_tokens:
176
+ completion_kwargs["max_new_tokens"] = max_new_tokens
177
+
178
+ if hasattr(self, "processor"):
179
+ prompt_tensor = self.processor.apply_chat_template(
180
+ messages,
181
+ tools=[get_tool_json_schema(tool) for tool in tools_to_call_from] if tools_to_call_from else None,
182
+ return_tensors="pt",
183
+ tokenize=True,
184
+ return_dict=True,
185
+ add_generation_prompt=True if tools_to_call_from else False,
186
+ )
187
+ else:
188
+ prompt_tensor = self.tokenizer.apply_chat_template(
189
+ messages,
190
+ tools=[get_tool_json_schema(tool) for tool in tools_to_call_from] if tools_to_call_from else None,
191
+ return_tensors="pt",
192
+ return_dict=True,
193
+ add_generation_prompt=True if tools_to_call_from else False,
194
+ )
195
+
196
+ prompt_tensor = prompt_tensor.to(self.model.device)
197
+ count_prompt_tokens = prompt_tensor["input_ids"].shape[1]
198
+
199
+ if stop_sequences:
200
+ stopping_criteria = self.make_stopping_criteria(
201
+ stop_sequences, tokenizer=self.processor if hasattr(self, "processor") else self.tokenizer
202
+ )
203
+ else:
204
+ stopping_criteria = None
205
+
206
+ out = self.model.generate(
207
+ **prompt_tensor,
208
+ stopping_criteria=stopping_criteria,
209
+ **completion_kwargs,
210
+ )
211
+ generated_tokens = out[0, count_prompt_tokens:]
212
+ if hasattr(self, "processor"):
213
+ output_text = self.processor.decode(generated_tokens, skip_special_tokens=True)
214
+ else:
215
+ output_text = self.tokenizer.decode(generated_tokens, skip_special_tokens=True)
216
+ self.last_input_token_count = count_prompt_tokens
217
+ self.last_output_token_count = len(generated_tokens)
218
+
219
+ if stop_sequences is not None:
220
+ output_text = remove_stop_sequences(output_text, stop_sequences)
221
+
222
+ chat_message = ChatMessage(
223
+ role=MessageRole.ASSISTANT,
224
+ content=output_text,
225
+ raw={"out": output_text, "completion_kwargs": completion_kwargs},
226
+ )
227
+ # if tools_to_call_from:
228
+ # chat_message.tool_calls = [
229
+ # get_tool_call_from_text(output_text, self.tool_name_key, self.tool_arguments_key)
230
+ # ]
231
+ return chat_message
src/aiagent/core/custom_python_executor.py ADDED
@@ -0,0 +1,1468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+
4
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ import ast
18
+ import builtins
19
+ import difflib
20
+ import inspect
21
+ import logging
22
+ import math
23
+ import re
24
+ from collections.abc import Mapping
25
+ from functools import wraps
26
+ from importlib import import_module
27
+ from types import BuiltinFunctionType, FunctionType, ModuleType
28
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple
29
+
30
+ from smolagents.tools import Tool
31
+ from smolagents.utils import BASE_BUILTIN_MODULES, truncate_content
32
+
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ class InterpreterError(ValueError):
38
+ """
39
+ An error raised when the interpreter cannot evaluate a Python expression, due to syntax error or unsupported
40
+ operations.
41
+ """
42
+
43
+ pass
44
+
45
+
46
+ ERRORS = {
47
+ name: getattr(builtins, name)
48
+ for name in dir(builtins)
49
+ if isinstance(getattr(builtins, name), type) and issubclass(getattr(builtins, name), BaseException)
50
+ }
51
+
52
+ DEFAULT_MAX_LEN_OUTPUT = 50000
53
+ MAX_OPERATIONS = 10000000
54
+ MAX_WHILE_ITERATIONS = 1000000
55
+
56
+
57
+ def custom_print(*args):
58
+ return None
59
+
60
+
61
+ BASE_PYTHON_TOOLS = {
62
+ "print": custom_print,
63
+ "isinstance": isinstance,
64
+ "range": range,
65
+ "float": float,
66
+ "int": int,
67
+ "bool": bool,
68
+ "str": str,
69
+ "set": set,
70
+ "list": list,
71
+ "dict": dict,
72
+ "tuple": tuple,
73
+ "round": round,
74
+ "ceil": math.ceil,
75
+ "floor": math.floor,
76
+ "log": math.log,
77
+ "exp": math.exp,
78
+ "sin": math.sin,
79
+ "cos": math.cos,
80
+ "tan": math.tan,
81
+ "asin": math.asin,
82
+ "acos": math.acos,
83
+ "atan": math.atan,
84
+ "atan2": math.atan2,
85
+ "degrees": math.degrees,
86
+ "radians": math.radians,
87
+ "pow": pow,
88
+ "sqrt": math.sqrt,
89
+ "len": len,
90
+ "sum": sum,
91
+ "max": max,
92
+ "min": min,
93
+ "abs": abs,
94
+ "enumerate": enumerate,
95
+ "zip": zip,
96
+ "reversed": reversed,
97
+ "sorted": sorted,
98
+ "all": all,
99
+ "any": any,
100
+ "map": map,
101
+ "filter": filter,
102
+ "ord": ord,
103
+ "chr": chr,
104
+ "next": next,
105
+ "iter": iter,
106
+ "divmod": divmod,
107
+ "callable": callable,
108
+ "getattr": getattr,
109
+ "hasattr": hasattr,
110
+ "setattr": setattr,
111
+ "issubclass": issubclass,
112
+ "type": type,
113
+ "complex": complex,
114
+ }
115
+
116
+ DANGEROUS_FUNCTIONS = [
117
+ "builtins.compile",
118
+ "builtins.eval",
119
+ "builtins.exec",
120
+ "builtins.globals",
121
+ "builtins.locals",
122
+ "builtins.__import__",
123
+ "os.popen",
124
+ "os.system",
125
+ "posix.system",
126
+ ]
127
+
128
+
129
+ class PrintContainer:
130
+ def __init__(self):
131
+ self.value = ""
132
+
133
+ def append(self, text):
134
+ self.value += text
135
+ return self
136
+
137
+ def __iadd__(self, other):
138
+ """Implements the += operator"""
139
+ self.value += str(other)
140
+ return self
141
+
142
+ def __str__(self):
143
+ """String representation"""
144
+ return self.value
145
+
146
+ def __repr__(self):
147
+ """Representation for debugging"""
148
+ return f"PrintContainer({self.value})"
149
+
150
+ def __len__(self):
151
+ """Implements len() function support"""
152
+ return len(self.value)
153
+
154
+
155
+ class BreakException(Exception):
156
+ pass
157
+
158
+
159
+ class ContinueException(Exception):
160
+ pass
161
+
162
+
163
+ class ReturnException(Exception):
164
+ def __init__(self, value):
165
+ self.value = value
166
+
167
+
168
+ def get_iterable(obj):
169
+ if isinstance(obj, list):
170
+ return obj
171
+ elif hasattr(obj, "__iter__"):
172
+ return list(obj)
173
+ else:
174
+ raise InterpreterError("Object is not iterable")
175
+
176
+
177
+ def fix_final_answer_code(code: str) -> str:
178
+ """
179
+ Sometimes an LLM can try to assign a variable to final_answer, which would break the final_answer() tool.
180
+ This function fixes this behaviour by replacing variable assignments to final_answer with final_answer_variable,
181
+ while preserving function calls to final_answer().
182
+ """
183
+ # First, find if there's a direct assignment to final_answer
184
+ # Use word boundary and negative lookbehind to ensure it's not an object attribute
185
+ assignment_pattern = r"(?<!\.)(?<!\w)\bfinal_answer\s*="
186
+ if "final_answer(" not in code or not re.search(assignment_pattern, code):
187
+ # If final_answer tool is not called in this blob, then doing the replacement is hazardous because it could false the model's memory for next steps.
188
+ # Let's not modify the code and leave the subsequent assignment error happen.
189
+ return code
190
+
191
+ # Pattern for replacing variable assignments
192
+ # Looks for 'final_answer' followed by '=' with optional whitespace
193
+ # Negative lookbehind ensures we don't match object attributes
194
+ assignment_regex = r"(?<!\.)(?<!\w)(\bfinal_answer)(\s*=)"
195
+ code = re.sub(assignment_regex, r"final_answer_variable\2", code)
196
+
197
+ # Pattern for replacing variable usage but not function calls
198
+ # Negative lookahead (?!\s*\() ensures we don't match function calls
199
+ # Negative lookbehind (?<!\.|\w) ensures we don't match object methods or other variables
200
+ variable_regex = r"(?<!\.)(?<!\w)(\bfinal_answer\b)(?!\s*\()"
201
+ code = re.sub(variable_regex, "final_answer_variable", code)
202
+ return code
203
+
204
+
205
+ def safer_eval(func: Callable):
206
+ """
207
+ Decorator to make the evaluation of a function safer by checking its return value.
208
+
209
+ Args:
210
+ func: Function to make safer.
211
+
212
+ Returns:
213
+ Callable: Safer function with return value check.
214
+ """
215
+
216
+ @wraps(func)
217
+ def _check_return(
218
+ expression,
219
+ state,
220
+ static_tools,
221
+ custom_tools,
222
+ authorized_imports=BASE_BUILTIN_MODULES,
223
+ ):
224
+ result = func(expression, state, static_tools, custom_tools, authorized_imports=authorized_imports)
225
+ if "*" not in authorized_imports:
226
+ if isinstance(result, ModuleType):
227
+ if result.__name__ not in authorized_imports:
228
+ raise InterpreterError(f"Forbidden access to module: {result.__name__}")
229
+ elif isinstance(result, dict) and result.get("__spec__"):
230
+ if result["__name__"] not in authorized_imports:
231
+ raise InterpreterError(f"Forbidden access to module: {result['__name__']}")
232
+ elif isinstance(result, (FunctionType, BuiltinFunctionType)):
233
+ for qualified_function_name in DANGEROUS_FUNCTIONS:
234
+ module_name, function_name = qualified_function_name.rsplit(".", 1)
235
+ if (
236
+ function_name not in static_tools
237
+ and result.__name__ == function_name
238
+ and result.__module__ == module_name
239
+ ):
240
+ raise InterpreterError(f"Forbidden access to function: {function_name}")
241
+ return result
242
+
243
+ return _check_return
244
+
245
+
246
+ def evaluate_attribute(
247
+ expression: ast.Attribute,
248
+ state: Dict[str, Any],
249
+ static_tools: Dict[str, Callable],
250
+ custom_tools: Dict[str, Callable],
251
+ authorized_imports: List[str],
252
+ ) -> Any:
253
+ if expression.attr.startswith("__") and expression.attr.endswith("__"):
254
+ raise InterpreterError(f"Forbidden access to dunder attribute: {expression.attr}")
255
+ value = evaluate_ast(expression.value, state, static_tools, custom_tools, authorized_imports)
256
+ return getattr(value, expression.attr)
257
+
258
+
259
+ def evaluate_unaryop(
260
+ expression: ast.UnaryOp,
261
+ state: Dict[str, Any],
262
+ static_tools: Dict[str, Callable],
263
+ custom_tools: Dict[str, Callable],
264
+ authorized_imports: List[str],
265
+ ) -> Any:
266
+ operand = evaluate_ast(expression.operand, state, static_tools, custom_tools, authorized_imports)
267
+ if isinstance(expression.op, ast.USub):
268
+ return -operand
269
+ elif isinstance(expression.op, ast.UAdd):
270
+ return operand
271
+ elif isinstance(expression.op, ast.Not):
272
+ return not operand
273
+ elif isinstance(expression.op, ast.Invert):
274
+ return ~operand
275
+ else:
276
+ raise InterpreterError(f"Unary operation {expression.op.__class__.__name__} is not supported.")
277
+
278
+
279
+ def evaluate_lambda(
280
+ lambda_expression: ast.Lambda,
281
+ state: Dict[str, Any],
282
+ static_tools: Dict[str, Callable],
283
+ custom_tools: Dict[str, Callable],
284
+ authorized_imports: List[str],
285
+ ) -> Callable:
286
+ args = [arg.arg for arg in lambda_expression.args.args]
287
+
288
+ def lambda_func(*values: Any) -> Any:
289
+ new_state = state.copy()
290
+ for arg, value in zip(args, values):
291
+ new_state[arg] = value
292
+ return evaluate_ast(
293
+ lambda_expression.body,
294
+ new_state,
295
+ static_tools,
296
+ custom_tools,
297
+ authorized_imports,
298
+ )
299
+
300
+ return lambda_func
301
+
302
+
303
+ def evaluate_while(
304
+ while_loop: ast.While,
305
+ state: Dict[str, Any],
306
+ static_tools: Dict[str, Callable],
307
+ custom_tools: Dict[str, Callable],
308
+ authorized_imports: List[str],
309
+ ) -> None:
310
+ iterations = 0
311
+ while evaluate_ast(while_loop.test, state, static_tools, custom_tools, authorized_imports):
312
+ for node in while_loop.body:
313
+ try:
314
+ evaluate_ast(node, state, static_tools, custom_tools, authorized_imports)
315
+ except BreakException:
316
+ return None
317
+ except ContinueException:
318
+ break
319
+ iterations += 1
320
+ if iterations > MAX_WHILE_ITERATIONS:
321
+ raise InterpreterError(f"Maximum number of {MAX_WHILE_ITERATIONS} iterations in While loop exceeded")
322
+ return None
323
+
324
+
325
+ def create_function(
326
+ func_def: ast.FunctionDef,
327
+ state: Dict[str, Any],
328
+ static_tools: Dict[str, Callable],
329
+ custom_tools: Dict[str, Callable],
330
+ authorized_imports: List[str],
331
+ ) -> Callable:
332
+ source_code = ast.unparse(func_def)
333
+
334
+ def new_func(*args: Any, **kwargs: Any) -> Any:
335
+ func_state = state.copy()
336
+ arg_names = [arg.arg for arg in func_def.args.args]
337
+ default_values = [
338
+ evaluate_ast(d, state, static_tools, custom_tools, authorized_imports) for d in func_def.args.defaults
339
+ ]
340
+
341
+ # Apply default values
342
+ defaults = dict(zip(arg_names[-len(default_values) :], default_values))
343
+
344
+ # Set positional arguments
345
+ for name, value in zip(arg_names, args):
346
+ func_state[name] = value
347
+
348
+ # Set keyword arguments
349
+ for name, value in kwargs.items():
350
+ func_state[name] = value
351
+
352
+ # Handle variable arguments
353
+ if func_def.args.vararg:
354
+ vararg_name = func_def.args.vararg.arg
355
+ func_state[vararg_name] = args
356
+
357
+ if func_def.args.kwarg:
358
+ kwarg_name = func_def.args.kwarg.arg
359
+ func_state[kwarg_name] = kwargs
360
+
361
+ # Set default values for arguments that were not provided
362
+ for name, value in defaults.items():
363
+ if name not in func_state:
364
+ func_state[name] = value
365
+
366
+ # Update function state with self and __class__
367
+ if func_def.args.args and func_def.args.args[0].arg == "self":
368
+ if args:
369
+ func_state["self"] = args[0]
370
+ func_state["__class__"] = args[0].__class__
371
+
372
+ result = None
373
+ try:
374
+ for stmt in func_def.body:
375
+ result = evaluate_ast(stmt, func_state, static_tools, custom_tools, authorized_imports)
376
+ except ReturnException as e:
377
+ result = e.value
378
+
379
+ if func_def.name == "__init__":
380
+ return None
381
+
382
+ return result
383
+
384
+ # Store original AST, source code, and name
385
+ new_func.__ast__ = func_def
386
+ new_func.__source__ = source_code
387
+ new_func.__name__ = func_def.name
388
+
389
+ return new_func
390
+
391
+
392
+ def evaluate_function_def(
393
+ func_def: ast.FunctionDef,
394
+ state: Dict[str, Any],
395
+ static_tools: Dict[str, Callable],
396
+ custom_tools: Dict[str, Callable],
397
+ authorized_imports: List[str],
398
+ ) -> Callable:
399
+ custom_tools[func_def.name] = create_function(func_def, state, static_tools, custom_tools, authorized_imports)
400
+ return custom_tools[func_def.name]
401
+
402
+
403
+ def evaluate_class_def(
404
+ class_def: ast.ClassDef,
405
+ state: Dict[str, Any],
406
+ static_tools: Dict[str, Callable],
407
+ custom_tools: Dict[str, Callable],
408
+ authorized_imports: List[str],
409
+ ) -> type:
410
+ class_name = class_def.name
411
+ bases = [evaluate_ast(base, state, static_tools, custom_tools, authorized_imports) for base in class_def.bases]
412
+ class_dict = {}
413
+
414
+ for stmt in class_def.body:
415
+ if isinstance(stmt, ast.FunctionDef):
416
+ class_dict[stmt.name] = evaluate_ast(stmt, state, static_tools, custom_tools, authorized_imports)
417
+ elif isinstance(stmt, ast.Assign):
418
+ for target in stmt.targets:
419
+ if isinstance(target, ast.Name):
420
+ class_dict[target.id] = evaluate_ast(
421
+ stmt.value,
422
+ state,
423
+ static_tools,
424
+ custom_tools,
425
+ authorized_imports,
426
+ )
427
+ elif isinstance(target, ast.Attribute):
428
+ class_dict[target.attr] = evaluate_ast(
429
+ stmt.value,
430
+ state,
431
+ static_tools,
432
+ custom_tools,
433
+ authorized_imports,
434
+ )
435
+ else:
436
+ raise InterpreterError(f"Unsupported statement in class body: {stmt.__class__.__name__}")
437
+
438
+ new_class = type(class_name, tuple(bases), class_dict)
439
+ state[class_name] = new_class
440
+ return new_class
441
+
442
+
443
+ def evaluate_augassign(
444
+ expression: ast.AugAssign,
445
+ state: Dict[str, Any],
446
+ static_tools: Dict[str, Callable],
447
+ custom_tools: Dict[str, Callable],
448
+ authorized_imports: List[str],
449
+ ) -> Any:
450
+ def get_current_value(target: ast.AST) -> Any:
451
+ if isinstance(target, ast.Name):
452
+ return state.get(target.id, 0)
453
+ elif isinstance(target, ast.Subscript):
454
+ obj = evaluate_ast(target.value, state, static_tools, custom_tools, authorized_imports)
455
+ key = evaluate_ast(target.slice, state, static_tools, custom_tools, authorized_imports)
456
+ return obj[key]
457
+ elif isinstance(target, ast.Attribute):
458
+ obj = evaluate_ast(target.value, state, static_tools, custom_tools, authorized_imports)
459
+ return getattr(obj, target.attr)
460
+ elif isinstance(target, ast.Tuple):
461
+ return tuple(get_current_value(elt) for elt in target.elts)
462
+ elif isinstance(target, ast.List):
463
+ return [get_current_value(elt) for elt in target.elts]
464
+ else:
465
+ raise InterpreterError("AugAssign not supported for {type(target)} targets.")
466
+
467
+ current_value = get_current_value(expression.target)
468
+ value_to_add = evaluate_ast(expression.value, state, static_tools, custom_tools, authorized_imports)
469
+
470
+ if isinstance(expression.op, ast.Add):
471
+ if isinstance(current_value, list):
472
+ if not isinstance(value_to_add, list):
473
+ raise InterpreterError(f"Cannot add non-list value {value_to_add} to a list.")
474
+ current_value += value_to_add
475
+ else:
476
+ current_value += value_to_add
477
+ elif isinstance(expression.op, ast.Sub):
478
+ current_value -= value_to_add
479
+ elif isinstance(expression.op, ast.Mult):
480
+ current_value *= value_to_add
481
+ elif isinstance(expression.op, ast.Div):
482
+ current_value /= value_to_add
483
+ elif isinstance(expression.op, ast.Mod):
484
+ current_value %= value_to_add
485
+ elif isinstance(expression.op, ast.Pow):
486
+ current_value **= value_to_add
487
+ elif isinstance(expression.op, ast.FloorDiv):
488
+ current_value //= value_to_add
489
+ elif isinstance(expression.op, ast.BitAnd):
490
+ current_value &= value_to_add
491
+ elif isinstance(expression.op, ast.BitOr):
492
+ current_value |= value_to_add
493
+ elif isinstance(expression.op, ast.BitXor):
494
+ current_value ^= value_to_add
495
+ elif isinstance(expression.op, ast.LShift):
496
+ current_value <<= value_to_add
497
+ elif isinstance(expression.op, ast.RShift):
498
+ current_value >>= value_to_add
499
+ else:
500
+ raise InterpreterError(f"Operation {type(expression.op).__name__} is not supported.")
501
+
502
+ # Update the state: current_value has been updated in-place
503
+ set_value(
504
+ expression.target,
505
+ current_value,
506
+ state,
507
+ static_tools,
508
+ custom_tools,
509
+ authorized_imports,
510
+ )
511
+
512
+ return current_value
513
+
514
+
515
+ def evaluate_boolop(
516
+ node: ast.BoolOp,
517
+ state: Dict[str, Any],
518
+ static_tools: Dict[str, Callable],
519
+ custom_tools: Dict[str, Callable],
520
+ authorized_imports: List[str],
521
+ ) -> bool:
522
+ if isinstance(node.op, ast.And):
523
+ for value in node.values:
524
+ if not evaluate_ast(value, state, static_tools, custom_tools, authorized_imports):
525
+ return False
526
+ return True
527
+ elif isinstance(node.op, ast.Or):
528
+ for value in node.values:
529
+ if evaluate_ast(value, state, static_tools, custom_tools, authorized_imports):
530
+ return True
531
+ return False
532
+
533
+
534
+ def evaluate_binop(
535
+ binop: ast.BinOp,
536
+ state: Dict[str, Any],
537
+ static_tools: Dict[str, Callable],
538
+ custom_tools: Dict[str, Callable],
539
+ authorized_imports: List[str],
540
+ ) -> Any:
541
+ # Recursively evaluate the left and right operands
542
+ left_val = evaluate_ast(binop.left, state, static_tools, custom_tools, authorized_imports)
543
+ right_val = evaluate_ast(binop.right, state, static_tools, custom_tools, authorized_imports)
544
+
545
+ # Determine the operation based on the type of the operator in the BinOp
546
+ if isinstance(binop.op, ast.Add):
547
+ return left_val + right_val
548
+ elif isinstance(binop.op, ast.Sub):
549
+ return left_val - right_val
550
+ elif isinstance(binop.op, ast.Mult):
551
+ return left_val * right_val
552
+ elif isinstance(binop.op, ast.Div):
553
+ return left_val / right_val
554
+ elif isinstance(binop.op, ast.Mod):
555
+ return left_val % right_val
556
+ elif isinstance(binop.op, ast.Pow):
557
+ return left_val**right_val
558
+ elif isinstance(binop.op, ast.FloorDiv):
559
+ return left_val // right_val
560
+ elif isinstance(binop.op, ast.BitAnd):
561
+ return left_val & right_val
562
+ elif isinstance(binop.op, ast.BitOr):
563
+ return left_val | right_val
564
+ elif isinstance(binop.op, ast.BitXor):
565
+ return left_val ^ right_val
566
+ elif isinstance(binop.op, ast.LShift):
567
+ return left_val << right_val
568
+ elif isinstance(binop.op, ast.RShift):
569
+ return left_val >> right_val
570
+ else:
571
+ raise NotImplementedError(f"Binary operation {type(binop.op).__name__} is not implemented.")
572
+
573
+
574
+ def evaluate_assign(
575
+ assign: ast.Assign,
576
+ state: Dict[str, Any],
577
+ static_tools: Dict[str, Callable],
578
+ custom_tools: Dict[str, Callable],
579
+ authorized_imports: List[str],
580
+ ) -> Any:
581
+ result = evaluate_ast(assign.value, state, static_tools, custom_tools, authorized_imports)
582
+ if len(assign.targets) == 1:
583
+ target = assign.targets[0]
584
+ set_value(target, result, state, static_tools, custom_tools, authorized_imports)
585
+ else:
586
+ expanded_values = []
587
+ for tgt in assign.targets:
588
+ if isinstance(tgt, ast.Starred):
589
+ expanded_values.extend(result)
590
+ else:
591
+ expanded_values.append(result)
592
+
593
+ for tgt, val in zip(assign.targets, expanded_values):
594
+ set_value(tgt, val, state, static_tools, custom_tools, authorized_imports)
595
+ return result
596
+
597
+
598
+ def set_value(
599
+ target: ast.AST,
600
+ value: Any,
601
+ state: Dict[str, Any],
602
+ static_tools: Dict[str, Callable],
603
+ custom_tools: Dict[str, Callable],
604
+ authorized_imports: List[str],
605
+ ) -> None:
606
+ if isinstance(target, ast.Name):
607
+ if target.id in static_tools:
608
+ raise InterpreterError(f"Cannot assign to name '{target.id}': doing this would erase the existing tool!")
609
+ state[target.id] = value
610
+ elif isinstance(target, ast.Tuple):
611
+ if not isinstance(value, tuple):
612
+ if hasattr(value, "__iter__") and not isinstance(value, (str, bytes)):
613
+ value = tuple(value)
614
+ else:
615
+ raise InterpreterError("Cannot unpack non-tuple value")
616
+ if len(target.elts) != len(value):
617
+ raise InterpreterError("Cannot unpack tuple of wrong size")
618
+ for i, elem in enumerate(target.elts):
619
+ set_value(elem, value[i], state, static_tools, custom_tools, authorized_imports)
620
+ elif isinstance(target, ast.Subscript):
621
+ obj = evaluate_ast(target.value, state, static_tools, custom_tools, authorized_imports)
622
+ key = evaluate_ast(target.slice, state, static_tools, custom_tools, authorized_imports)
623
+ obj[key] = value
624
+ elif isinstance(target, ast.Attribute):
625
+ obj = evaluate_ast(target.value, state, static_tools, custom_tools, authorized_imports)
626
+ setattr(obj, target.attr, value)
627
+
628
+
629
+ def evaluate_call(
630
+ call: ast.Call,
631
+ state: Dict[str, Any],
632
+ static_tools: Dict[str, Callable],
633
+ custom_tools: Dict[str, Callable],
634
+ authorized_imports: List[str],
635
+ ) -> Any:
636
+ if not isinstance(call.func, (ast.Call, ast.Lambda, ast.Attribute, ast.Name, ast.Subscript)):
637
+ raise InterpreterError(f"This is not a correct function: {call.func}).")
638
+
639
+ func, func_name = None, None
640
+
641
+ if isinstance(call.func, ast.Call):
642
+ func = evaluate_ast(call.func, state, static_tools, custom_tools, authorized_imports)
643
+ elif isinstance(call.func, ast.Lambda):
644
+ func = evaluate_ast(call.func, state, static_tools, custom_tools, authorized_imports)
645
+ elif isinstance(call.func, ast.Attribute):
646
+ obj = evaluate_ast(call.func.value, state, static_tools, custom_tools, authorized_imports)
647
+ func_name = call.func.attr
648
+ if not hasattr(obj, func_name):
649
+ raise InterpreterError(f"Object {obj} has no attribute {func_name}")
650
+ func = getattr(obj, func_name)
651
+ elif isinstance(call.func, ast.Name):
652
+ func_name = call.func.id
653
+ if func_name in state:
654
+ func = state[func_name]
655
+ elif func_name in static_tools:
656
+ func = static_tools[func_name]
657
+ elif func_name in custom_tools:
658
+ func = custom_tools[func_name]
659
+ elif func_name in ERRORS:
660
+ func = ERRORS[func_name]
661
+ else:
662
+ raise InterpreterError(
663
+ f"It is not permitted to evaluate other functions than the provided utils or functions defined/imported in previous code (tried to execute {call.func.id})."
664
+ )
665
+ elif isinstance(call.func, ast.Subscript):
666
+ func = evaluate_ast(call.func, state, static_tools, custom_tools, authorized_imports)
667
+ if not callable(func):
668
+ raise InterpreterError(f"This is not a correct function: {call.func}).")
669
+ func_name = None
670
+
671
+ args = []
672
+ for arg in call.args:
673
+ if isinstance(arg, ast.Starred):
674
+ args.extend(evaluate_ast(arg.value, state, static_tools, custom_tools, authorized_imports))
675
+ else:
676
+ args.append(evaluate_ast(arg, state, static_tools, custom_tools, authorized_imports))
677
+
678
+ kwargs = {
679
+ keyword.arg: evaluate_ast(keyword.value, state, static_tools, custom_tools, authorized_imports)
680
+ for keyword in call.keywords
681
+ }
682
+
683
+ if func_name == "super":
684
+ if not args:
685
+ if "__class__" in state and "self" in state:
686
+ return super(state["__class__"], state["self"])
687
+ else:
688
+ raise InterpreterError("super() needs at least one argument")
689
+ cls = args[0]
690
+ if not isinstance(cls, type):
691
+ raise InterpreterError("super() argument 1 must be type")
692
+ if len(args) == 1:
693
+ return super(cls)
694
+ elif len(args) == 2:
695
+ instance = args[1]
696
+ return super(cls, instance)
697
+ else:
698
+ raise InterpreterError("super() takes at most 2 arguments")
699
+ elif func_name == "print":
700
+ state["_print_outputs"] += " ".join(map(str, args)) + "\n"
701
+ return None
702
+ else: # Assume it's a callable object
703
+ if (inspect.getmodule(func) == builtins) and inspect.isbuiltin(func) and (func not in static_tools.values()):
704
+ raise InterpreterError(
705
+ f"Invoking a builtin function that has not been explicitly added as a tool is not allowed ({func_name})."
706
+ )
707
+ return func(*args, **kwargs)
708
+
709
+
710
+ def evaluate_subscript(
711
+ subscript: ast.Subscript,
712
+ state: Dict[str, Any],
713
+ static_tools: Dict[str, Callable],
714
+ custom_tools: Dict[str, Callable],
715
+ authorized_imports: List[str],
716
+ ) -> Any:
717
+ index = evaluate_ast(subscript.slice, state, static_tools, custom_tools, authorized_imports)
718
+ value = evaluate_ast(subscript.value, state, static_tools, custom_tools, authorized_imports)
719
+ try:
720
+ return value[index]
721
+ except (KeyError, IndexError, TypeError) as e:
722
+ error_message = f"Could not index {value} with '{index}': {type(e).__name__}: {e}"
723
+ if isinstance(index, str) and isinstance(value, Mapping):
724
+ close_matches = difflib.get_close_matches(index, list(value.keys()))
725
+ if len(close_matches) > 0:
726
+ error_message += f". Maybe you meant one of these indexes instead: {str(close_matches)}"
727
+ raise InterpreterError(error_message) from e
728
+
729
+
730
+ def evaluate_name(
731
+ name: ast.Name,
732
+ state: Dict[str, Any],
733
+ static_tools: Dict[str, Callable],
734
+ custom_tools: Dict[str, Callable],
735
+ authorized_imports: List[str],
736
+ ) -> Any:
737
+ if name.id in state:
738
+ return state[name.id]
739
+ elif name.id in static_tools:
740
+ return static_tools[name.id]
741
+ elif name.id in custom_tools:
742
+ return custom_tools[name.id]
743
+ elif name.id in ERRORS:
744
+ return ERRORS[name.id]
745
+ close_matches = difflib.get_close_matches(name.id, list(state.keys()))
746
+ if len(close_matches) > 0:
747
+ return state[close_matches[0]]
748
+ raise InterpreterError(f"The variable `{name.id}` is not defined.")
749
+
750
+
751
+ def evaluate_condition(
752
+ condition: ast.Compare,
753
+ state: Dict[str, Any],
754
+ static_tools: Dict[str, Callable],
755
+ custom_tools: Dict[str, Callable],
756
+ authorized_imports: List[str],
757
+ ) -> bool | object:
758
+ result = True
759
+ left = evaluate_ast(condition.left, state, static_tools, custom_tools, authorized_imports)
760
+ for i, (op, comparator) in enumerate(zip(condition.ops, condition.comparators)):
761
+ op = type(op)
762
+ right = evaluate_ast(comparator, state, static_tools, custom_tools, authorized_imports)
763
+ if op == ast.Eq:
764
+ current_result = left == right
765
+ elif op == ast.NotEq:
766
+ current_result = left != right
767
+ elif op == ast.Lt:
768
+ current_result = left < right
769
+ elif op == ast.LtE:
770
+ current_result = left <= right
771
+ elif op == ast.Gt:
772
+ current_result = left > right
773
+ elif op == ast.GtE:
774
+ current_result = left >= right
775
+ elif op == ast.Is:
776
+ current_result = left is right
777
+ elif op == ast.IsNot:
778
+ current_result = left is not right
779
+ elif op == ast.In:
780
+ current_result = left in right
781
+ elif op == ast.NotIn:
782
+ current_result = left not in right
783
+ else:
784
+ raise InterpreterError(f"Unsupported comparison operator: {op}")
785
+
786
+ if current_result is False:
787
+ return False
788
+ result = current_result if i == 0 else (result and current_result)
789
+ left = right
790
+ return result
791
+
792
+
793
+ def evaluate_if(
794
+ if_statement: ast.If,
795
+ state: Dict[str, Any],
796
+ static_tools: Dict[str, Callable],
797
+ custom_tools: Dict[str, Callable],
798
+ authorized_imports: List[str],
799
+ ) -> Any:
800
+ result = None
801
+ test_result = evaluate_ast(if_statement.test, state, static_tools, custom_tools, authorized_imports)
802
+ if test_result:
803
+ for line in if_statement.body:
804
+ line_result = evaluate_ast(line, state, static_tools, custom_tools, authorized_imports)
805
+ if line_result is not None:
806
+ result = line_result
807
+ else:
808
+ for line in if_statement.orelse:
809
+ line_result = evaluate_ast(line, state, static_tools, custom_tools, authorized_imports)
810
+ if line_result is not None:
811
+ result = line_result
812
+ return result
813
+
814
+
815
+ def evaluate_for(
816
+ for_loop: ast.For,
817
+ state: Dict[str, Any],
818
+ static_tools: Dict[str, Callable],
819
+ custom_tools: Dict[str, Callable],
820
+ authorized_imports: List[str],
821
+ ) -> Any:
822
+ result = None
823
+ iterator = evaluate_ast(for_loop.iter, state, static_tools, custom_tools, authorized_imports)
824
+ for counter in iterator:
825
+ set_value(
826
+ for_loop.target,
827
+ counter,
828
+ state,
829
+ static_tools,
830
+ custom_tools,
831
+ authorized_imports,
832
+ )
833
+ for node in for_loop.body:
834
+ try:
835
+ line_result = evaluate_ast(node, state, static_tools, custom_tools, authorized_imports)
836
+ if line_result is not None:
837
+ result = line_result
838
+ except BreakException:
839
+ break
840
+ except ContinueException:
841
+ continue
842
+ else:
843
+ continue
844
+ break
845
+ return result
846
+
847
+
848
+ def evaluate_listcomp(
849
+ listcomp: ast.ListComp,
850
+ state: Dict[str, Any],
851
+ static_tools: Dict[str, Callable],
852
+ custom_tools: Dict[str, Callable],
853
+ authorized_imports: List[str],
854
+ ) -> List[Any]:
855
+ def inner_evaluate(generators: List[ast.comprehension], index: int, current_state: Dict[str, Any]) -> List[Any]:
856
+ if index >= len(generators):
857
+ return [
858
+ evaluate_ast(
859
+ listcomp.elt,
860
+ current_state,
861
+ static_tools,
862
+ custom_tools,
863
+ authorized_imports,
864
+ )
865
+ ]
866
+ generator = generators[index]
867
+ iter_value = evaluate_ast(
868
+ generator.iter,
869
+ current_state,
870
+ static_tools,
871
+ custom_tools,
872
+ authorized_imports,
873
+ )
874
+ result = []
875
+ for value in iter_value:
876
+ new_state = current_state.copy()
877
+ if isinstance(generator.target, ast.Tuple):
878
+ for idx, elem in enumerate(generator.target.elts):
879
+ new_state[elem.id] = value[idx]
880
+ else:
881
+ new_state[generator.target.id] = value
882
+ if all(
883
+ evaluate_ast(if_clause, new_state, static_tools, custom_tools, authorized_imports)
884
+ for if_clause in generator.ifs
885
+ ):
886
+ result.extend(inner_evaluate(generators, index + 1, new_state))
887
+ return result
888
+
889
+ return inner_evaluate(listcomp.generators, 0, state)
890
+
891
+
892
+ def evaluate_setcomp(
893
+ setcomp: ast.SetComp,
894
+ state: Dict[str, Any],
895
+ static_tools: Dict[str, Callable],
896
+ custom_tools: Dict[str, Callable],
897
+ authorized_imports: List[str],
898
+ ) -> Set[Any]:
899
+ result = set()
900
+ for gen in setcomp.generators:
901
+ iter_value = evaluate_ast(gen.iter, state, static_tools, custom_tools, authorized_imports)
902
+ for value in iter_value:
903
+ new_state = state.copy()
904
+ set_value(
905
+ gen.target,
906
+ value,
907
+ new_state,
908
+ static_tools,
909
+ custom_tools,
910
+ authorized_imports,
911
+ )
912
+ if all(
913
+ evaluate_ast(if_clause, new_state, static_tools, custom_tools, authorized_imports)
914
+ for if_clause in gen.ifs
915
+ ):
916
+ element = evaluate_ast(
917
+ setcomp.elt,
918
+ new_state,
919
+ static_tools,
920
+ custom_tools,
921
+ authorized_imports,
922
+ )
923
+ result.add(element)
924
+ return result
925
+
926
+
927
+ def evaluate_try(
928
+ try_node: ast.Try,
929
+ state: Dict[str, Any],
930
+ static_tools: Dict[str, Callable],
931
+ custom_tools: Dict[str, Callable],
932
+ authorized_imports: List[str],
933
+ ) -> None:
934
+ try:
935
+ for stmt in try_node.body:
936
+ evaluate_ast(stmt, state, static_tools, custom_tools, authorized_imports)
937
+ except Exception as e:
938
+ matched = False
939
+ for handler in try_node.handlers:
940
+ if handler.type is None or isinstance(
941
+ e,
942
+ evaluate_ast(handler.type, state, static_tools, custom_tools, authorized_imports),
943
+ ):
944
+ matched = True
945
+ if handler.name:
946
+ state[handler.name] = e
947
+ for stmt in handler.body:
948
+ evaluate_ast(stmt, state, static_tools, custom_tools, authorized_imports)
949
+ break
950
+ if not matched:
951
+ raise e
952
+ else:
953
+ if try_node.orelse:
954
+ for stmt in try_node.orelse:
955
+ evaluate_ast(stmt, state, static_tools, custom_tools, authorized_imports)
956
+ finally:
957
+ if try_node.finalbody:
958
+ for stmt in try_node.finalbody:
959
+ evaluate_ast(stmt, state, static_tools, custom_tools, authorized_imports)
960
+
961
+
962
+ def evaluate_raise(
963
+ raise_node: ast.Raise,
964
+ state: Dict[str, Any],
965
+ static_tools: Dict[str, Callable],
966
+ custom_tools: Dict[str, Callable],
967
+ authorized_imports: List[str],
968
+ ) -> None:
969
+ if raise_node.exc is not None:
970
+ exc = evaluate_ast(raise_node.exc, state, static_tools, custom_tools, authorized_imports)
971
+ else:
972
+ exc = None
973
+ if raise_node.cause is not None:
974
+ cause = evaluate_ast(raise_node.cause, state, static_tools, custom_tools, authorized_imports)
975
+ else:
976
+ cause = None
977
+ if exc is not None:
978
+ if cause is not None:
979
+ raise exc from cause
980
+ else:
981
+ raise exc
982
+ else:
983
+ raise InterpreterError("Re-raise is not supported without an active exception")
984
+
985
+
986
+ def evaluate_assert(
987
+ assert_node: ast.Assert,
988
+ state: Dict[str, Any],
989
+ static_tools: Dict[str, Callable],
990
+ custom_tools: Dict[str, Callable],
991
+ authorized_imports: List[str],
992
+ ) -> None:
993
+ test_result = evaluate_ast(assert_node.test, state, static_tools, custom_tools, authorized_imports)
994
+ if not test_result:
995
+ if assert_node.msg:
996
+ msg = evaluate_ast(assert_node.msg, state, static_tools, custom_tools, authorized_imports)
997
+ raise AssertionError(msg)
998
+ else:
999
+ # Include the failing condition in the assertion message
1000
+ test_code = ast.unparse(assert_node.test)
1001
+ raise AssertionError(f"Assertion failed: {test_code}")
1002
+
1003
+
1004
+ def evaluate_with(
1005
+ with_node: ast.With,
1006
+ state: Dict[str, Any],
1007
+ static_tools: Dict[str, Callable],
1008
+ custom_tools: Dict[str, Callable],
1009
+ authorized_imports: List[str],
1010
+ ) -> None:
1011
+ contexts = []
1012
+ for item in with_node.items:
1013
+ context_expr = evaluate_ast(item.context_expr, state, static_tools, custom_tools, authorized_imports)
1014
+ if item.optional_vars:
1015
+ state[item.optional_vars.id] = context_expr.__enter__()
1016
+ contexts.append(state[item.optional_vars.id])
1017
+ else:
1018
+ context_var = context_expr.__enter__()
1019
+ contexts.append(context_var)
1020
+
1021
+ try:
1022
+ for stmt in with_node.body:
1023
+ evaluate_ast(stmt, state, static_tools, custom_tools, authorized_imports)
1024
+ except Exception as e:
1025
+ for context in reversed(contexts):
1026
+ context.__exit__(type(e), e, e.__traceback__)
1027
+ raise
1028
+ else:
1029
+ for context in reversed(contexts):
1030
+ context.__exit__(None, None, None)
1031
+
1032
+
1033
+ def get_safe_module(raw_module, authorized_imports, visited=None):
1034
+ """Creates a safe copy of a module or returns the original if it's a function"""
1035
+ # If it's a function or non-module object, return it directly
1036
+ if not isinstance(raw_module, ModuleType):
1037
+ return raw_module
1038
+
1039
+ # Handle circular references: Initialize visited set for the first call
1040
+ if visited is None:
1041
+ visited = set()
1042
+
1043
+ module_id = id(raw_module)
1044
+ if module_id in visited:
1045
+ return raw_module # Return original for circular refs
1046
+
1047
+ visited.add(module_id)
1048
+
1049
+ # Create new module for actual modules
1050
+ safe_module = ModuleType(raw_module.__name__)
1051
+
1052
+ # Copy all attributes by reference, recursively checking modules
1053
+ for attr_name in dir(raw_module):
1054
+ try:
1055
+ attr_value = getattr(raw_module, attr_name)
1056
+ except (ImportError, AttributeError) as e:
1057
+ # lazy / dynamic loading module -> INFO log and skip
1058
+ logger.info(
1059
+ f"Skipping import error while copying {raw_module.__name__}.{attr_name}: {type(e).__name__} - {e}"
1060
+ )
1061
+ continue
1062
+ # Recursively process nested modules, passing visited set
1063
+ if isinstance(attr_value, ModuleType):
1064
+ attr_value = get_safe_module(attr_value, authorized_imports, visited=visited)
1065
+
1066
+ setattr(safe_module, attr_name, attr_value)
1067
+
1068
+ return safe_module
1069
+
1070
+
1071
+ def check_module_authorized(module_name, authorized_imports):
1072
+ if "*" in authorized_imports:
1073
+ return True
1074
+ else:
1075
+ module_path = module_name.split(".")
1076
+ # ["A", "B", "C"] -> ["A", "A.B", "A.B.C"]
1077
+ module_subpaths = [".".join(module_path[:i]) for i in range(1, len(module_path) + 1)]
1078
+ return any(subpath in authorized_imports for subpath in module_subpaths)
1079
+
1080
+
1081
+ def evaluate_import(expression, state, authorized_imports):
1082
+ if isinstance(expression, ast.Import):
1083
+ for alias in expression.names:
1084
+ if check_module_authorized(alias.name, authorized_imports):
1085
+ raw_module = import_module(alias.name)
1086
+ state[alias.asname or alias.name] = get_safe_module(raw_module, authorized_imports)
1087
+ else:
1088
+ raise InterpreterError(
1089
+ f"Import of {alias.name} is not allowed. Authorized imports are: {str(authorized_imports)}"
1090
+ )
1091
+ return None
1092
+ elif isinstance(expression, ast.ImportFrom):
1093
+ if check_module_authorized(expression.module, authorized_imports):
1094
+ raw_module = __import__(expression.module, fromlist=[alias.name for alias in expression.names])
1095
+ module = get_safe_module(raw_module, authorized_imports)
1096
+ if expression.names[0].name == "*": # Handle "from module import *"
1097
+ if hasattr(module, "__all__"): # If module has __all__, import only those names
1098
+ for name in module.__all__:
1099
+ state[name] = getattr(module, name)
1100
+ else: # If no __all__, import all public names (those not starting with '_')
1101
+ for name in dir(module):
1102
+ if not name.startswith("_"):
1103
+ state[name] = getattr(module, name)
1104
+ else: # regular from imports
1105
+ for alias in expression.names:
1106
+ if hasattr(module, alias.name):
1107
+ state[alias.asname or alias.name] = getattr(module, alias.name)
1108
+ else:
1109
+ raise InterpreterError(f"Module {expression.module} has no attribute {alias.name}")
1110
+ else:
1111
+ raise InterpreterError(
1112
+ f"Import from {expression.module} is not allowed. Authorized imports are: {str(authorized_imports)}"
1113
+ )
1114
+ return None
1115
+
1116
+
1117
+ def evaluate_dictcomp(
1118
+ dictcomp: ast.DictComp,
1119
+ state: Dict[str, Any],
1120
+ static_tools: Dict[str, Callable],
1121
+ custom_tools: Dict[str, Callable],
1122
+ authorized_imports: List[str],
1123
+ ) -> Dict[Any, Any]:
1124
+ result = {}
1125
+ for gen in dictcomp.generators:
1126
+ iter_value = evaluate_ast(gen.iter, state, static_tools, custom_tools, authorized_imports)
1127
+ for value in iter_value:
1128
+ new_state = state.copy()
1129
+ set_value(
1130
+ gen.target,
1131
+ value,
1132
+ new_state,
1133
+ static_tools,
1134
+ custom_tools,
1135
+ authorized_imports,
1136
+ )
1137
+ if all(
1138
+ evaluate_ast(if_clause, new_state, static_tools, custom_tools, authorized_imports)
1139
+ for if_clause in gen.ifs
1140
+ ):
1141
+ key = evaluate_ast(
1142
+ dictcomp.key,
1143
+ new_state,
1144
+ static_tools,
1145
+ custom_tools,
1146
+ authorized_imports,
1147
+ )
1148
+ val = evaluate_ast(
1149
+ dictcomp.value,
1150
+ new_state,
1151
+ static_tools,
1152
+ custom_tools,
1153
+ authorized_imports,
1154
+ )
1155
+ result[key] = val
1156
+ return result
1157
+
1158
+
1159
+ def evaluate_delete(
1160
+ delete_node: ast.Delete,
1161
+ state: Dict[str, Any],
1162
+ static_tools: Dict[str, Callable],
1163
+ custom_tools: Dict[str, Callable],
1164
+ authorized_imports: List[str],
1165
+ ) -> None:
1166
+ """
1167
+ Evaluate a delete statement (del x, del x[y]).
1168
+
1169
+ Args:
1170
+ delete_node: The AST Delete node to evaluate
1171
+ state: The current state dictionary
1172
+ static_tools: Dictionary of static utils
1173
+ custom_tools: Dictionary of custom utils
1174
+ authorized_imports: List of authorized imports
1175
+ """
1176
+ for target in delete_node.targets:
1177
+ if isinstance(target, ast.Name):
1178
+ # Handle simple variable deletion (del x)
1179
+ if target.id in state:
1180
+ del state[target.id]
1181
+ else:
1182
+ raise InterpreterError(f"Cannot delete name '{target.id}': name is not defined")
1183
+ elif isinstance(target, ast.Subscript):
1184
+ # Handle index/key deletion (del x[y])
1185
+ obj = evaluate_ast(target.value, state, static_tools, custom_tools, authorized_imports)
1186
+ index = evaluate_ast(target.slice, state, static_tools, custom_tools, authorized_imports)
1187
+ try:
1188
+ del obj[index]
1189
+ except (TypeError, KeyError, IndexError) as e:
1190
+ raise InterpreterError(f"Cannot delete index/key: {str(e)}")
1191
+ else:
1192
+ raise InterpreterError(f"Deletion of {type(target).__name__} targets is not supported")
1193
+
1194
+
1195
+ @safer_eval
1196
+ def evaluate_ast(
1197
+ expression: ast.AST,
1198
+ state: Dict[str, Any],
1199
+ static_tools: Dict[str, Callable],
1200
+ custom_tools: Dict[str, Callable],
1201
+ authorized_imports: List[str] = BASE_BUILTIN_MODULES,
1202
+ ):
1203
+ """
1204
+ Evaluate an abstract syntax tree using the content of the variables stored in a state and only evaluating a given
1205
+ set of functions.
1206
+
1207
+ This function will recurse through the nodes of the tree provided.
1208
+
1209
+ Args:
1210
+ expression (`ast.AST`):
1211
+ The code to evaluate, as an abstract syntax tree.
1212
+ state (`Dict[str, Any]`):
1213
+ A dictionary mapping variable names to values. The `state` is updated if need be when the evaluation
1214
+ encounters assignments.
1215
+ static_tools (`Dict[str, Callable]`):
1216
+ Functions that may be called during the evaluation. Trying to change one of these static_tools will raise an error.
1217
+ custom_tools (`Dict[str, Callable]`):
1218
+ Functions that may be called during the evaluation. These static_tools can be overwritten.
1219
+ authorized_imports (`List[str]`):
1220
+ The list of modules that can be imported by the code. By default, only a few safe modules are allowed.
1221
+ If it contains "*", it will authorize any import. Use this at your own risk!
1222
+ """
1223
+ if state.setdefault("_operations_count", {"counter": 0})["counter"] >= MAX_OPERATIONS:
1224
+ raise InterpreterError(
1225
+ f"Reached the max number of operations of {MAX_OPERATIONS}. Maybe there is an infinite loop somewhere in the code, or you're just asking too many calculations."
1226
+ )
1227
+ state["_operations_count"]["counter"] += 1
1228
+ common_params = (state, static_tools, custom_tools, authorized_imports)
1229
+ if isinstance(expression, ast.Assign):
1230
+ # Assignment -> we evaluate the assignment which should update the state
1231
+ # We return the variable assigned as it may be used to determine the final result.
1232
+ return evaluate_assign(expression, *common_params)
1233
+ elif isinstance(expression, ast.AugAssign):
1234
+ return evaluate_augassign(expression, *common_params)
1235
+ elif isinstance(expression, ast.Call):
1236
+ # Function call -> we return the value of the function call
1237
+ return evaluate_call(expression, *common_params)
1238
+ elif isinstance(expression, ast.Constant):
1239
+ # Constant -> just return the value
1240
+ return expression.value
1241
+ elif isinstance(expression, ast.Tuple):
1242
+ return tuple((evaluate_ast(elt, *common_params) for elt in expression.elts))
1243
+ elif isinstance(expression, (ast.ListComp, ast.GeneratorExp)):
1244
+ return evaluate_listcomp(expression, *common_params)
1245
+ elif isinstance(expression, ast.DictComp):
1246
+ return evaluate_dictcomp(expression, *common_params)
1247
+ elif isinstance(expression, ast.SetComp):
1248
+ return evaluate_setcomp(expression, *common_params)
1249
+ elif isinstance(expression, ast.UnaryOp):
1250
+ return evaluate_unaryop(expression, *common_params)
1251
+ elif isinstance(expression, ast.Starred):
1252
+ return evaluate_ast(expression.value, *common_params)
1253
+ elif isinstance(expression, ast.BoolOp):
1254
+ # Boolean operation -> evaluate the operation
1255
+ return evaluate_boolop(expression, *common_params)
1256
+ elif isinstance(expression, ast.Break):
1257
+ raise BreakException()
1258
+ elif isinstance(expression, ast.Continue):
1259
+ raise ContinueException()
1260
+ elif isinstance(expression, ast.BinOp):
1261
+ # Binary operation -> execute operation
1262
+ return evaluate_binop(expression, *common_params)
1263
+ elif isinstance(expression, ast.Compare):
1264
+ # Comparison -> evaluate the comparison
1265
+ return evaluate_condition(expression, *common_params)
1266
+ elif isinstance(expression, ast.Lambda):
1267
+ return evaluate_lambda(expression, *common_params)
1268
+ elif isinstance(expression, ast.FunctionDef):
1269
+ return evaluate_function_def(expression, *common_params)
1270
+ elif isinstance(expression, ast.Dict):
1271
+ # Dict -> evaluate all keys and values
1272
+ keys = (evaluate_ast(k, *common_params) for k in expression.keys)
1273
+ values = (evaluate_ast(v, *common_params) for v in expression.values)
1274
+ return dict(zip(keys, values))
1275
+ elif isinstance(expression, ast.Expr):
1276
+ # Expression -> evaluate the content
1277
+ return evaluate_ast(expression.value, *common_params)
1278
+ elif isinstance(expression, ast.For):
1279
+ # For loop -> execute the loop
1280
+ return evaluate_for(expression, *common_params)
1281
+ elif isinstance(expression, ast.FormattedValue):
1282
+ # Formatted value (part of f-string) -> evaluate the content and format it
1283
+ value = evaluate_ast(expression.value, *common_params)
1284
+ # Early return if no format spec
1285
+ if not expression.format_spec:
1286
+ return value
1287
+ # Apply format specification
1288
+ format_spec = evaluate_ast(expression.format_spec, *common_params)
1289
+ return format(value, format_spec)
1290
+ elif isinstance(expression, ast.If):
1291
+ # If -> execute the right branch
1292
+ return evaluate_if(expression, *common_params)
1293
+ elif hasattr(ast, "Index") and isinstance(expression, ast.Index):
1294
+ return evaluate_ast(expression.value, *common_params)
1295
+ elif isinstance(expression, ast.JoinedStr):
1296
+ return "".join([str(evaluate_ast(v, *common_params)) for v in expression.values])
1297
+ elif isinstance(expression, ast.List):
1298
+ # List -> evaluate all elements
1299
+ return [evaluate_ast(elt, *common_params) for elt in expression.elts]
1300
+ elif isinstance(expression, ast.Name):
1301
+ # Name -> pick up the value in the state
1302
+ return evaluate_name(expression, *common_params)
1303
+ elif isinstance(expression, ast.Subscript):
1304
+ # Subscript -> return the value of the indexing
1305
+ return evaluate_subscript(expression, *common_params)
1306
+ elif isinstance(expression, ast.IfExp):
1307
+ test_val = evaluate_ast(expression.test, *common_params)
1308
+ if test_val:
1309
+ return evaluate_ast(expression.body, *common_params)
1310
+ else:
1311
+ return evaluate_ast(expression.orelse, *common_params)
1312
+ elif isinstance(expression, ast.Attribute):
1313
+ return evaluate_attribute(expression, *common_params)
1314
+ elif isinstance(expression, ast.Slice):
1315
+ return slice(
1316
+ evaluate_ast(expression.lower, *common_params) if expression.lower is not None else None,
1317
+ evaluate_ast(expression.upper, *common_params) if expression.upper is not None else None,
1318
+ evaluate_ast(expression.step, *common_params) if expression.step is not None else None,
1319
+ )
1320
+ elif isinstance(expression, ast.While):
1321
+ return evaluate_while(expression, *common_params)
1322
+ elif isinstance(expression, (ast.Import, ast.ImportFrom)):
1323
+ return evaluate_import(expression, state, authorized_imports)
1324
+ elif isinstance(expression, ast.ClassDef):
1325
+ return evaluate_class_def(expression, *common_params)
1326
+ elif isinstance(expression, ast.Try):
1327
+ return evaluate_try(expression, *common_params)
1328
+ elif isinstance(expression, ast.Raise):
1329
+ return evaluate_raise(expression, *common_params)
1330
+ elif isinstance(expression, ast.Assert):
1331
+ return evaluate_assert(expression, *common_params)
1332
+ elif isinstance(expression, ast.With):
1333
+ return evaluate_with(expression, *common_params)
1334
+ elif isinstance(expression, ast.Set):
1335
+ return set((evaluate_ast(elt, *common_params) for elt in expression.elts))
1336
+ elif isinstance(expression, ast.Return):
1337
+ raise ReturnException(evaluate_ast(expression.value, *common_params) if expression.value else None)
1338
+ elif isinstance(expression, ast.Pass):
1339
+ return None
1340
+ elif isinstance(expression, ast.Delete):
1341
+ return evaluate_delete(expression, *common_params)
1342
+ else:
1343
+ # For now we refuse anything else. Let's add things as we need them.
1344
+ raise InterpreterError(f"{expression.__class__.__name__} is not supported.")
1345
+
1346
+
1347
+ class FinalAnswerException(Exception):
1348
+ def __init__(self, value):
1349
+ self.value = value
1350
+
1351
+
1352
+ def evaluate_python_code(
1353
+ code: str,
1354
+ static_tools: Optional[Dict[str, Callable]] = None,
1355
+ custom_tools: Optional[Dict[str, Callable]] = None,
1356
+ state: Optional[Dict[str, Any]] = None,
1357
+ authorized_imports: List[str] = BASE_BUILTIN_MODULES,
1358
+ max_print_outputs_length: int = DEFAULT_MAX_LEN_OUTPUT,
1359
+ ):
1360
+ """
1361
+ Evaluate a python expression using the content of the variables stored in a state and only evaluating a given set
1362
+ of functions.
1363
+
1364
+ This function will recurse through the nodes of the tree provided.
1365
+
1366
+ Args:
1367
+ code (`str`):
1368
+ The code to evaluate.
1369
+ static_tools (`Dict[str, Callable]`):
1370
+ The functions that may be called during the evaluation. These can also be agents in a multiagent setting.
1371
+ These utils cannot be overwritten in the code: any assignment to their name will raise an error.
1372
+ custom_tools (`Dict[str, Callable]`):
1373
+ The functions that may be called during the evaluation.
1374
+ These utils can be overwritten in the code: any assignment to their name will overwrite them.
1375
+ state (`Dict[str, Any]`):
1376
+ A dictionary mapping variable names to values. The `state` should contain the initial inputs but will be
1377
+ updated by this function to contain all variables as they are evaluated.
1378
+ The print outputs will be stored in the state under the key "_print_outputs".
1379
+ """
1380
+ try:
1381
+ expression = ast.parse(code)
1382
+ except SyntaxError as e:
1383
+ raise InterpreterError(
1384
+ f"Code parsing failed on line {e.lineno} due to: {type(e).__name__}\n"
1385
+ f"{e.text}"
1386
+ f"{' ' * (e.offset or 0)}^\n"
1387
+ f"Error: {str(e)}"
1388
+ )
1389
+
1390
+ if state is None:
1391
+ state = {}
1392
+ static_tools = static_tools.copy() if static_tools is not None else {}
1393
+ custom_tools = custom_tools if custom_tools is not None else {}
1394
+ result = None
1395
+ state["_print_outputs"] = PrintContainer()
1396
+ state["_operations_count"] = {"counter": 0}
1397
+
1398
+ if "final_answer" in static_tools:
1399
+ previous_final_answer = static_tools["final_answer"]
1400
+
1401
+ def final_answer(answer, structured_product=None): # Using 'answer' as the argument like in the original function
1402
+ raise FinalAnswerException(previous_final_answer(answer, structured_product))
1403
+
1404
+ static_tools["final_answer"] = final_answer
1405
+
1406
+ try:
1407
+ for node in expression.body:
1408
+ result = evaluate_ast(node, state, static_tools, custom_tools, authorized_imports)
1409
+ state["_print_outputs"].value = truncate_content(
1410
+ str(state["_print_outputs"]), max_length=max_print_outputs_length
1411
+ )
1412
+ is_final_answer = False
1413
+ return result, is_final_answer
1414
+ except FinalAnswerException as e:
1415
+ state["_print_outputs"].value = truncate_content(
1416
+ str(state["_print_outputs"]), max_length=max_print_outputs_length
1417
+ )
1418
+ is_final_answer = True
1419
+ return e.value, is_final_answer
1420
+ except Exception as e:
1421
+ state["_print_outputs"].value = truncate_content(
1422
+ str(state["_print_outputs"]), max_length=max_print_outputs_length
1423
+ )
1424
+ raise InterpreterError(
1425
+ f"Code execution failed at line '{ast.get_source_segment(code, node)}' due to: {type(e).__name__}: {e}"
1426
+ )
1427
+
1428
+
1429
+ class PythonExecutor:
1430
+ pass
1431
+
1432
+
1433
+ class LocalPythonExecutor(PythonExecutor):
1434
+ def __init__(
1435
+ self,
1436
+ additional_authorized_imports: List[str],
1437
+ max_print_outputs_length: Optional[int] = None,
1438
+ ):
1439
+ self.custom_tools = {}
1440
+ self.state = {}
1441
+ self.max_print_outputs_length = max_print_outputs_length
1442
+ if max_print_outputs_length is None:
1443
+ self.max_print_outputs_length = DEFAULT_MAX_LEN_OUTPUT
1444
+ self.additional_authorized_imports = additional_authorized_imports
1445
+ self.authorized_imports = list(set(BASE_BUILTIN_MODULES) | set(self.additional_authorized_imports))
1446
+ # TODO: assert self.authorized imports are all installed locally
1447
+ self.static_tools = None
1448
+
1449
+ def __call__(self, code_action: str) -> Tuple[Any, str, bool]:
1450
+ output, is_final_answer = evaluate_python_code(
1451
+ code_action,
1452
+ static_tools=self.static_tools,
1453
+ custom_tools=self.custom_tools,
1454
+ state=self.state,
1455
+ authorized_imports=self.authorized_imports,
1456
+ max_print_outputs_length=self.max_print_outputs_length,
1457
+ )
1458
+ logs = str(self.state["_print_outputs"])
1459
+ return output, logs, is_final_answer
1460
+
1461
+ def send_variables(self, variables: dict):
1462
+ self.state.update(variables)
1463
+
1464
+ def send_tools(self, tools: Dict[str, Tool]):
1465
+ self.static_tools = {**tools, **BASE_PYTHON_TOOLS.copy()}
1466
+
1467
+
1468
+ __all__ = ["evaluate_python_code", "LocalPythonExecutor"]
src/aiagent/ui/amazon_gradio_theme.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from gradio.themes.base import Base
2
+ from gradio.themes.utils import colors
3
+
4
+
5
+ class AmazonTheme(Base):
6
+ def __init__(self):
7
+ super().__init__(
8
+ primary_hue=colors.orange,
9
+ secondary_hue=colors.gray,
10
+ font=["Arial", "sans-serif"],
11
+ font_mono=["Courier New", "monospace"]
12
+ )
13
+
14
+ self.set(
15
+ body_background_fill="#f3f3f3",
16
+ body_background_fill_dark="#f3f3f3",
17
+ border_color_primary="#ddd",
18
+ shadow_drop="0 2px 4px rgba(0,0,0,0.08)",
19
+ button_primary_background_fill="#34455c",
20
+ button_primary_background_fill_dark="#34455c",
21
+ button_primary_text_color="#ffffff",
22
+ button_primary_text_color_dark="#ffffff",
23
+ button_primary_background_fill_hover="#f5aa3b",
24
+ button_primary_background_fill_hover_dark="#f5aa3b",
25
+
26
+ body_text_color_dark="#000000",
27
+ block_background_fill_dark="#ffffff",
28
+ color_accent_soft_dark="#fff7ed",
29
+ background_fill_secondary_dark="#fafafa",
30
+
31
+ button_secondary_background_fill="#f5aa3b",
32
+ button_secondary_background_fill_dark="#f5aa3b",
33
+ button_secondary_background_fill_hover="#de952a",
34
+ button_secondary_background_fill_hover_dark="#de952a",
35
+ button_secondary_border_color="#ccc",
36
+ button_secondary_text_color="#473a25",
37
+ button_secondary_text_color_dark="#473a25",
38
+
39
+ button_border_width='0px',
40
+ # button_radius='8px',
41
+
42
+ # Champs de saisie (input)
43
+ input_background_fill="#fffff",
44
+ input_background_fill_dark="#fffff",
45
+ input_border_color="#ccc",
46
+ input_border_width="1px",
47
+ input_radius="6px",
48
+ input_shadow="0 1px 2px rgba(0, 0, 0, 0.1)",
49
+ input_padding="10px 14px",
50
+ input_text_size="16px",
51
+
52
+ # Liens
53
+ link_text_color="#007185",
54
+ link_text_color_hover="#C7511F",
55
+ link_text_color_dark="#007185",
56
+ link_text_color_hover_dark="#C7511F"
57
+ )
src/aiagent/ui/main_gradio.py ADDED
@@ -0,0 +1,480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ from typing import Optional
4
+ import pandas as pd
5
+ import json
6
+
7
+ from smolagents.agents import ActionStep, MultiStepAgent
8
+ from smolagents.memory import MemoryStep
9
+ from smolagents.utils import _is_package_available
10
+ from src.aiagent.utils.rending_method import cleaning_model_thinking
11
+
12
+ from src.aiagent.ui.amazon_gradio_theme import AmazonTheme
13
+
14
+ theme_amazon = AmazonTheme()
15
+
16
+
17
+ def pull_messages_from_step(
18
+ step_log: MemoryStep,
19
+ ):
20
+ """Extract ChatMessage objects from agent steps with proper nesting"""
21
+
22
+ if isinstance(step_log, ActionStep):
23
+ # Output the step number
24
+ step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else ""
25
+ yield step_number, "STEP_NUMBER"
26
+ # yield gr.ChatMessage(role="assistant", content=f"**{step_number}**")
27
+
28
+ # First yield the thought/reasoning from the LLM
29
+ if hasattr(step_log, "model_output") and step_log.model_output is not None:
30
+ # Clean up the LLM output
31
+ model_output = step_log.model_output.strip()
32
+ # Remove any trailing <end_code> and extra backticks, handling multiple possible formats
33
+ model_output = re.sub(r"```\s*<end_code>", "```", model_output) # handles ```<end_code>
34
+ model_output = re.sub(r"<end_code>\s*```", "```", model_output) # handles <end_code>```
35
+ model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output) # handles ```\n<end_code>
36
+ model_output = model_output.strip()
37
+
38
+ yield model_output, "STEP"
39
+
40
+ # Handle standalone errors but not from tool calls
41
+ elif hasattr(step_log, "error") and step_log.error is not None:
42
+
43
+ yield str(step_log.error), "ERROR"
44
+
45
+ # Calculate duration and token information
46
+ step_footnote = f"{step_number}"
47
+ if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
48
+ token_str = (
49
+ f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}"
50
+ )
51
+ step_footnote += token_str
52
+ if hasattr(step_log, "duration"):
53
+ step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
54
+ step_footnote += step_duration
55
+ step_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """
56
+
57
+ yield step_footnote, 'FOOTNOTE'
58
+
59
+
60
+ def stream_to_gradio(
61
+ agent,
62
+ task: str,
63
+ reset_agent_memory: bool = False,
64
+ additional_args: Optional[dict] = None,
65
+ ):
66
+ """Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages."""
67
+ if not _is_package_available("gradio"):
68
+ raise ModuleNotFoundError(
69
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
70
+ )
71
+
72
+ total_input_tokens = 0
73
+ total_output_tokens = 0
74
+
75
+ for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
76
+ # Track tokens if model provides them
77
+ if hasattr(agent.model, "last_input_token_count"):
78
+ total_input_tokens += agent.model.last_input_token_count
79
+ total_output_tokens += agent.model.last_output_token_count
80
+ if isinstance(step_log, ActionStep):
81
+ step_log.input_token_count = agent.model.last_input_token_count
82
+ step_log.output_token_count = agent.model.last_output_token_count
83
+
84
+ for message, status_code in pull_messages_from_step(
85
+ step_log,
86
+ ):
87
+ yield message, status_code
88
+
89
+ final_answer = step_log # Last log is the run's final_answer
90
+
91
+ yield final_answer, "FINAL"
92
+
93
+
94
+ def generate_product_cards(l_products):
95
+ cards = ""
96
+ for product in l_products:
97
+ details = ""
98
+ for feature in product.keys():
99
+ if feature not in ["product_name", "image_url", "product_link"]:
100
+ details += f"<li><b>{feature.capitalize()}:</b> {product[feature]}</li>"
101
+
102
+ image_link = product.get("image_url",
103
+ 'https://raw.githubusercontent.com/fmr-aeg/AiAgent_ecom/refs/heads/main/assets/no_image.png')
104
+ product_name = product.get("product_name", 'product name')
105
+ product_link = product.get("product_link", 'www.amazon.fr')
106
+
107
+ card = f"""
108
+ <div style='flex: 0 0 auto; width: 200px; border: 1px solid #ddd; border-radius: 10px; padding: 10px; box-shadow: 2px 2px 12px rgba(0,0,0,0.1); text-align: center; background: white; transition: transform 0.2s;'>
109
+ <a href="{product_link}" target="_blank" style="text-decoration: none; color: inherit;">
110
+ <img src="{image_link}" style='width: 100%; height: 250px; object-fit: scale-down; border-radius: 8px;' />
111
+ <h4 style='margin: 10px 0 5px;'>{product_name}</h4>
112
+ </a>
113
+ <ul style='list-style: none; padding: 0; font-size: 14px; text-align: left;'>{details}</ul>
114
+ </div>
115
+ """
116
+ cards += card
117
+ return f"<div style='display: flex; overflow-x: auto; gap: 16px; padding: 10px;'>{cards}</div>"
118
+
119
+
120
+ class GradioUI:
121
+ """A one-line interface to launch your agent in Gradio"""
122
+
123
+ def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
124
+ if not _is_package_available("gradio"):
125
+ raise ModuleNotFoundError(
126
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
127
+ )
128
+ self.agent = agent
129
+ self.file_upload_folder = file_upload_folder
130
+ self.cmt = cleaning_model_thinking(model_name='gemini/gemini-2.0-flash')
131
+ if self.file_upload_folder is not None:
132
+ if not os.path.exists(file_upload_folder):
133
+ os.mkdir(file_upload_folder)
134
+
135
+ def interact_with_agent(self, prompt, messages, memory_product):
136
+ import gradio as gr
137
+
138
+ messages.append(gr.ChatMessage(role="user", content=prompt))
139
+ yield messages, memory_product
140
+
141
+ for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
142
+
143
+ # if msg[1] == "STEP_NUMBER":
144
+ # messages.append(gr.ChatMessage(role="assistant", content=f"**{msg[0]}**"))
145
+
146
+ if msg[1] == "STEP":
147
+ preprocessed_message = self.cmt(msg[0])
148
+ messages.append(
149
+ gr.ChatMessage(role="assistant", content=preprocessed_message))
150
+
151
+ if msg[1] == "ERROR":
152
+ messages.append(
153
+ gr.ChatMessage(role="assistant", content=msg[0], metadata={"title": "💥 Error"}))
154
+
155
+ if msg[1] == "FOOTNOTE":
156
+ messages.append(
157
+ gr.ChatMessage(role="assistant", content=msg[0]))
158
+ messages.append(gr.ChatMessage(role="assistant", content="-----"))
159
+
160
+ if msg[1] == "FINAL":
161
+
162
+ final_answer = msg[0]
163
+
164
+ messages.append(
165
+ gr.ChatMessage(role="assistant", content=str(final_answer[0])))
166
+
167
+ if isinstance(final_answer[1], pd.DataFrame):
168
+ l_product = json.loads(final_answer[1].to_json(orient="records"))
169
+ html_product = generate_product_cards(l_product)
170
+ memory_product = html_product
171
+
172
+ elif isinstance(final_answer[1], list):
173
+ html_product = generate_product_cards(final_answer[1])
174
+ memory_product = html_product
175
+
176
+ yield messages, memory_product
177
+ yield messages, memory_product
178
+
179
+ def log_user_message(self, text_input):
180
+ return text_input, ""
181
+
182
+ def reset_agent(self):
183
+ self.agent.memory.reset()
184
+ self.agent.monitor.reset()
185
+
186
+ def pre_interaction_updates(self):
187
+ import gradio as gr
188
+ return (
189
+ gr.update(visible=False), # info row
190
+ gr.update(visible=False), # example row
191
+ gr.update(visible=True), # chatbot
192
+ gr.update(visible=True), # product_reco
193
+ gr.update(visible=True), # thinking_message
194
+ gr.update(visible=True), # column_reset
195
+ )
196
+
197
+ def post_interaction_updates(self):
198
+ import gradio as gr
199
+ return gr.update(visible=False) # hide thinking
200
+
201
+ def launch(self, **kwargs):
202
+ import gradio as gr
203
+
204
+ with gr.Blocks(theme=theme_amazon, fill_height=True) as demo:
205
+ stored_messages = gr.State([])
206
+ current_product = gr.State([])
207
+
208
+ with gr.Row(scale=1):
209
+ gr.Markdown('')
210
+
211
+ with gr.Column(scale=1, visible=False) as column_reset:
212
+ clear = gr.Button("Reset conversation", variant="primary")
213
+
214
+ with gr.Column(scale=30):
215
+ chatbot = gr.Chatbot(
216
+ label="🤖 AmazAgent",
217
+ show_label=False,
218
+ type="messages",
219
+ avatar_images=(
220
+ "assets/user_image.png",
221
+ "assets/logo_amazon_circle.png",
222
+ ),
223
+ resizeable=True,
224
+ scale=1,
225
+ visible=False
226
+ )
227
+
228
+ thinking_message = gr.Markdown("🤖 Let me think...", visible=False)
229
+ product_reco = gr.HTML(visible=False)
230
+ with gr.Row():
231
+ text_input = gr.Textbox(lines=1,
232
+ label="Chat Message",
233
+ show_label=False,
234
+ placeholder="How can I help you ?",
235
+ container=False,
236
+ scale=15)
237
+ search_button = gr.Button("🔍︎", scale=1, variant="secondary")
238
+
239
+ gr.HTML("""
240
+ <style>
241
+ .grid-container {
242
+ display: grid;
243
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
244
+ gap: 20px;
245
+ padding: 20px;
246
+ }
247
+
248
+ .gr-row {
249
+ align-items: stretch; /* étire les colonnes pour hauteur égale */
250
+ }
251
+
252
+ .card {
253
+ background-color: white;
254
+ border-radius: 10px;
255
+ box-shadow: 0 4px 8px rgba(0,0,0,0.1);
256
+ text-align: center;
257
+ padding: 16px;
258
+ display: flex;
259
+ flex-direction: column;
260
+ justify-content: space-between;
261
+ }
262
+
263
+ .card h3 {
264
+ font-size: 16px;
265
+ margin-bottom: 10px;
266
+ color: #fc0000;
267
+ }
268
+
269
+ .card h4 {
270
+ font-size: 12px;
271
+ margin-bottom: 10px;
272
+ color: #fc0000;
273
+ }
274
+
275
+ .card img {
276
+ max-width: 100%;
277
+ height: auto;
278
+ flex: auto;
279
+ object-fit: scale-down;
280
+ border-radius: 6px;
281
+ margin-bottom: 10px;
282
+ margin: auto;
283
+ }
284
+
285
+ .card .gr-button {
286
+ margin-top: auto;
287
+ width: 100%;
288
+ }
289
+
290
+ .info-box {
291
+ display: flex;
292
+ align-items: flex-start;
293
+ max-width: 100%;
294
+ background-color: #fff;
295
+ border-radius: 8px;
296
+ padding: 20px 24px;
297
+ box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
298
+ border-left: 6px solid #ffa41c;
299
+ margin: 20px auto;
300
+ }
301
+
302
+ .info-content {
303
+ flex: 1;
304
+ color: #000000;
305
+ }
306
+
307
+ .info-title {
308
+ font-size: 18px;
309
+ font-weight: 600;
310
+ margin-bottom: 10px;
311
+ color: #000000;
312
+ }
313
+
314
+ .info-text {
315
+ font-size: 15px;
316
+ line-height: 1.6;
317
+ margin-bottom: 12px;
318
+ }
319
+
320
+ .disclaimer {
321
+ font-size: 13px;
322
+ color: #fc0000;
323
+ }
324
+
325
+ .disclaimer b {
326
+ color: #fc0000;
327
+ }
328
+ </style>
329
+ """)
330
+
331
+ with gr.Row(elem_classes="info-box") as info_row:
332
+ gr.HTML(
333
+ """<div class="info-content">
334
+ <div class="info-title">About this assistant</div>
335
+ <div class="info-text">
336
+ Meet your smart shopping assistant — an AI agent that interacts directly with Amazon to guide you through your online shopping journey. It can reason, adapt to your feedback in real time, and curate the most relevant product selections for your needs. Think of it as your personal shopper, helping you find the best items effortlessly and efficiently.
337
+ </div>
338
+ <div class="disclaimer">
339
+ <b>Disclaimer:</b> This tool is not affiliated with Amazon or any of its subsidiaries. It simply uses publicly available data to assist you in your product search.
340
+ </div>
341
+ </div>"""
342
+ )
343
+
344
+ with gr.Row() as example_row:
345
+ with gr.Column(elem_classes="card"):
346
+ gr.HTML(
347
+ "<h3>Can you find similar products to this one and compare them for me, please?</h3>"
348
+ "<img src='gradio_api/file=assets/result_siege_auto.png' "
349
+ "alt='Image 2'>")
350
+ button_example2 = gr.Button("Explore this suggestion")
351
+ text_example2 = gr.Markdown(
352
+ "Can you find similar products to this one : https://www.amazon.fr/CYBEX-Solution-i-Fix-Pure-Black/dp/B0C58QGJNG/?th=1 and compare them for me, please?",
353
+ visible=False)
354
+ with gr.Column(elem_classes="card"):
355
+ gr.HTML(
356
+ "<h3>I'm hesitating between the S24 Ultra, the iPhone 16, and the Xiaomi 14 Ultra.</h3>"
357
+ "<img src='gradio_api/file=assets/phone_result_example.png' "
358
+ "alt='Image 3'>")
359
+ button_example3 = gr.Button("Run this prompt")
360
+ text_example3 = gr.Markdown(
361
+ "I'm hesitating between the S24 Ultra, the iPhone 16, and the Xiaomi 14 Ultra.",
362
+ visible=False)
363
+ with gr.Column(elem_classes="card"):
364
+ gr.HTML(
365
+ "<h3>Je cherche une robe noir pour un mariage qui a lieu le week-end de la semaine prochaine.</h3>"
366
+ "<img src='gradio_api/file=assets/black_dress_example.png' "
367
+ "alt='Image 1'>")
368
+ button_example1 = gr.Button("Start with this")
369
+ text_example1 = gr.Markdown(
370
+ "Je cherche une robe noir pour un mariage qui a lieu le week-end de la semaine prochaine",
371
+ visible=False)
372
+
373
+ # Enter case
374
+ text_input.submit(
375
+ self.log_user_message,
376
+ inputs=text_input,
377
+ outputs=[stored_messages, text_input],
378
+ ).then(
379
+ self.pre_interaction_updates,
380
+ inputs=None,
381
+ outputs=[info_row, example_row, chatbot, product_reco, thinking_message, column_reset]
382
+ ).then(
383
+ self.interact_with_agent,
384
+ inputs=[stored_messages, chatbot, current_product],
385
+ outputs=[chatbot, product_reco],
386
+ ).then(
387
+ self.post_interaction_updates,
388
+ inputs=None,
389
+ outputs=thinking_message,
390
+ )
391
+
392
+ # button search case
393
+ search_button.click(
394
+ self.log_user_message,
395
+ inputs=text_input,
396
+ outputs=[stored_messages, text_input],
397
+ ).then(
398
+ self.pre_interaction_updates,
399
+ inputs=None,
400
+ outputs=[info_row, example_row, chatbot, product_reco, thinking_message, column_reset]
401
+ ).then(
402
+ self.interact_with_agent,
403
+ inputs=[stored_messages, chatbot, current_product],
404
+ outputs=[chatbot, product_reco],
405
+ ).then(
406
+ self.post_interaction_updates,
407
+ inputs=None,
408
+ outputs=thinking_message,
409
+ )
410
+
411
+ # button example 1
412
+ button_example1.click(
413
+ self.log_user_message,
414
+ inputs=text_example1,
415
+ outputs=[stored_messages, text_example1],
416
+ ).then(
417
+ self.pre_interaction_updates,
418
+ inputs=None,
419
+ outputs=[info_row, example_row, chatbot, product_reco, thinking_message, column_reset]
420
+ ).then(
421
+ self.interact_with_agent,
422
+ inputs=[stored_messages, chatbot, current_product],
423
+ outputs=[chatbot, product_reco],
424
+ ).then(
425
+ self.post_interaction_updates,
426
+ inputs=None,
427
+ outputs=thinking_message,
428
+ )
429
+
430
+ # button example 2
431
+ button_example2.click(
432
+ self.log_user_message,
433
+ inputs=text_example2,
434
+ outputs=[stored_messages, text_example2],
435
+ ).then(
436
+ self.pre_interaction_updates,
437
+ inputs=None,
438
+ outputs=[info_row, example_row, chatbot, product_reco, thinking_message, column_reset]
439
+ ).then(
440
+ self.interact_with_agent,
441
+ inputs=[stored_messages, chatbot, current_product],
442
+ outputs=[chatbot, product_reco],
443
+ ).then(
444
+ self.post_interaction_updates,
445
+ inputs=None,
446
+ outputs=thinking_message,
447
+ )
448
+
449
+ # button example 3
450
+ button_example3.click(
451
+ self.log_user_message,
452
+ inputs=text_example3,
453
+ outputs=[stored_messages, text_example3],
454
+ ).then(
455
+ self.pre_interaction_updates,
456
+ inputs=None,
457
+ outputs=[info_row, example_row, chatbot, product_reco, thinking_message, column_reset]
458
+ ).then(
459
+ self.interact_with_agent,
460
+ inputs=[stored_messages, chatbot, current_product],
461
+ outputs=[chatbot, product_reco],
462
+ ).then(
463
+ self.post_interaction_updates,
464
+ inputs=None,
465
+ outputs=thinking_message,
466
+ )
467
+
468
+ clear.click(
469
+ self.reset_agent,
470
+ None,
471
+ None
472
+ ).then(
473
+ lambda: [None, None, None],
474
+ None,
475
+ [chatbot, current_product, product_reco])
476
+
477
+ demo.launch(debug=True, share=False, **kwargs)
478
+
479
+
480
+ __all__ = ["stream_to_gradio", "GradioUI"]
src/aiagent/utils/ecom_tools.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents import tool, Tool
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ import json
5
+ import pandas as pd
6
+ import re
7
+ from typing import Any, Optional
8
+
9
+
10
+ class ParserProductDescriptionWithGuideTool(Tool):
11
+ name = "parse_product_description_with_guide"
12
+ description = (
13
+ "Use this tool when you are given a *detailed product description* and asked to extract specific *product attributes*. "
14
+ "The tool takes two inputs: the raw product description and a list of target attributes "
15
+ "(e.g., 'dimensions', 'material', 'color', 'convertible', etc.). "
16
+ "It returns a structured JSON object containing the requested information, and always includes: "
17
+ "'product_name', 'image_url', and 'price', even if they are not explicitly requested. "
18
+ "If an attribute is not found in the description, it is marked as 'N/A'. "
19
+ "This tool is ideal for structuring product data from unstructured text."
20
+ )
21
+ inputs = {"product_description": {"type": "string",
22
+ "description": "The product description containing every information on the product"},
23
+ "product_feature": {"type": "array",
24
+ "description": "The list of feature that should be retrieve from product description"},
25
+ }
26
+ output_type = "string"
27
+
28
+ def __init__(self, model,
29
+ **kwargs):
30
+ super().__init__(**kwargs)
31
+ self.model = model
32
+ self.system_prompt = ("""You are an expert assistant in product information extraction.
33
+
34
+ Based on a *product description* provided by the user, your job is to identify and extract the *requested attributes*,
35
+ and organize them in a structured JSON format.
36
+
37
+ Your response must **always include at minimum** the following keys, even if they are not explicitly requested:
38
+ - "product_name"
39
+ - "image_url"
40
+ - "price"
41
+
42
+ For each requested attribute:
43
+ - If it is found in the description, provide its value.
44
+ - If it is missing, return `"N/A"` as the value.
45
+
46
+ Your final output must be a valid JSON object, using the exact attribute names as keys.
47
+
48
+ Example:
49
+ If the description is about a sofa and the requested attributes are ["dimension", "color", "material", "convertible"],
50
+ your output should look like this:
51
+
52
+ {
53
+ "product_name": "Oslo 3-seater Sofa",
54
+ "image_url": "https://...",
55
+ "price": "€499",
56
+ "dimension": "200x90x85 cm",
57
+ "color": "Light grey",
58
+ "material": "Fabric and wood",
59
+ "convertible": "Yes"
60
+ }
61
+
62
+ Be precise, structured, and always do your best to help the customer understand the product clearly.""")
63
+
64
+ def _preprocessing_message(self, product_description, feature_list):
65
+ messages = [{"role": "system",
66
+ "content": [{"type": "text", "text": self.system_prompt}]},
67
+ {"role": "user",
68
+ "content": [{"type": "text", "text": product_description},
69
+ {"type": "text", "text": f"retrieve the following features : {feature_list}"}]}
70
+ ]
71
+ return messages
72
+
73
+ def forward(self, product_description: str, product_feature: list[str]):
74
+ messages = self._preprocessing_message(product_description, product_feature)
75
+ model_output = self.model(messages, response_format={"type": "json_object"}).content
76
+
77
+ return json.loads(model_output)
78
+
79
+
80
+ class GetProductDescriptionTool(Tool):
81
+ name = "get_product_description"
82
+ description = ("tool that retrieve the product description and the price of a product from Amazon.com, "
83
+ "all information is condensed into a raw character string")
84
+ inputs = {"product_url": {"type": "string",
85
+ "description": "The url link of the product on Amazon.com"}}
86
+
87
+ output_type = "string"
88
+
89
+ def __init__(self):
90
+ super().__init__()
91
+ self.headers = {
92
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
93
+ "Accept-Language": "en-US,en;q=0.9"
94
+ }
95
+
96
+
97
+ @staticmethod
98
+ def _clean_product_url(product_url: str) -> str:
99
+ pattern = r"(https://www\.amazon\.[a-z.]+/[^/]+/dp/[^/]+)"
100
+ match = re.search(pattern, product_url)
101
+
102
+ return match.group(0)
103
+
104
+ def forward(self, product_url: str) -> str:
105
+
106
+ product_url = self._clean_product_url(product_url)
107
+ try:
108
+ response = requests.get(product_url, headers=self.headers)
109
+ response.raise_for_status()
110
+
111
+ soup = BeautifulSoup(response.text, 'html.parser')
112
+
113
+ preprocessed_html = ""
114
+
115
+ # Extraction de la description
116
+ product_title = soup.find("div", id="titleSection")
117
+ product_img = soup.find('div', id='imgTagWrapperId')
118
+ product_description = soup.find("div", id="productDescription")
119
+ alt_description = soup.find("div", id="feature-bullets")
120
+ seller_description = soup.find("div", id="aplus")
121
+ price = soup.find('span', class_='a-offscreen')
122
+
123
+ if product_title:
124
+ preprocessed_html += "-- product title -- \n"
125
+ preprocessed_html += product_title.get_text().strip() + '\n\n'
126
+
127
+ if product_img:
128
+ preprocessed_html += "-- image url -- \n"
129
+ preprocessed_html += product_img.find('img')['src'] + '\n\n'
130
+
131
+ if product_description:
132
+ preprocessed_html += "-- product description by Website -- \n"
133
+ preprocessed_html += product_description.get_text(strip=True) + '\n\n'
134
+
135
+ if alt_description:
136
+ preprocessed_html += "-- additional description -- \n"
137
+ preprocessed_html += alt_description.get_text(strip=True) + '\n\n'
138
+
139
+ if seller_description:
140
+ preprocessed_html += "-- product description by Seller -- \n"
141
+ preprocessed_html += seller_description.get_text(strip=True) + '\n\n'
142
+
143
+ if price:
144
+ preprocessed_html += "-- price of the product --\n"
145
+ preprocessed_html += price.get_text()
146
+
147
+ return preprocessed_html
148
+
149
+ except requests.exceptions.RequestException as e:
150
+ return f"Error : {str(e)}"
151
+
152
+
153
+ @tool
154
+ def search_on_amazon(keyword: str) -> list[dict]:
155
+ """
156
+ function to retrieve a list of products resulting from a search on the amazon search engine. For all these products,
157
+ it also retrieve the image url, the product price and the hypothetical delivery date.
158
+
159
+ Args:
160
+ keyword: the keyword to search for in the search engine
161
+
162
+ Returns:
163
+ a list containing one json per product with the following three keys :
164
+ - product_name : title of the product
165
+ - image_url : url of the product's image
166
+ - product_link : url of the product page
167
+ - product_price : the price of the product
168
+ - delivery_date : information on delivery date
169
+ """
170
+
171
+ headers = {
172
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
173
+ 'Accept-Language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7',
174
+ 'Accept-Encoding': 'gzip, deflate, br',
175
+ 'Connection': 'keep-alive',
176
+ 'Upgrade-Insecure-Requests': '1',
177
+ }
178
+
179
+ url = f"https://www.amazon.fr/s?k={keyword.replace(' ', '+')}" # Could be adapted for other countries
180
+
181
+ response = requests.get(url, headers=headers)
182
+
183
+ if response.status_code != 200:
184
+ print("Error during page loading", response.status_code)
185
+
186
+ # Parsing using beautifulSoup
187
+ soup = BeautifulSoup(response.text, 'html.parser')
188
+
189
+ products = []
190
+ product_elements = soup.find_all('div', role='listitem') # Getting only organic product
191
+
192
+ for product in product_elements[:10]: # limited to top 10 products
193
+ product_json = dict()
194
+
195
+ tag_sponsorised = product.find('span', class_='puis-label-popover-default')
196
+
197
+ if tag_sponsorised:
198
+ continue
199
+
200
+ title_element = product.find('h2')
201
+ image_element = product.find('img', class_='s-image')
202
+ link_element = product.find('a', class_='a-link-normal')
203
+ price_element = product.find("span", class_='a-offscreen')
204
+ delivery_element = product.find('div', {"data-cy": "delivery-recipe"})
205
+
206
+ if title_element:
207
+ product_json['product_name'] = title_element.get_text()
208
+
209
+ if image_element:
210
+ product_json['image_url'] = image_element.get('src')
211
+
212
+ if link_element:
213
+ product_json['product_link'] = 'https://www.amazon.fr' + link_element['href']
214
+
215
+ if price_element:
216
+ product_json['price'] = price_element.get_text().replace("\\xa0", " ").replace("\xa0", " ")
217
+
218
+ if delivery_element:
219
+ product_json['delivery_date'] = delivery_element.get_text()
220
+
221
+ products.append(product_json)
222
+
223
+ return products
224
+
225
+
226
+ class CompareProductTool(Tool):
227
+ name = "compare_product"
228
+ description = (
229
+ "Generate a comparison table (as a pandas DataFrame) from a list of structured product dictionaries."
230
+ "This function is used when product data is already structured (e.g., extracted via another tool)"
231
+ "and the goal is to present selected features in a clear tabular format for comparison."
232
+ )
233
+
234
+ inputs = {"list_product_element": {"type": "array",
235
+ "description": """List of products as dictionaries,
236
+ there must necessarily have the key product_name and price
237
+ (e.g., [{'product_name': 'Product 1', 'price': 500, 'Screen': '15"', 'Processor': 'Intel i5'}, {'product_name': 'Product 2', 'price': 600, 'Screen': '17"', 'Processor': 'Intel i7'}])"""}
238
+ }
239
+ output_type = "any"
240
+
241
+ def __init__(self, model,
242
+ **kwargs):
243
+ super().__init__(**kwargs)
244
+ self.model = model
245
+
246
+ def _clean_product_info(self, product_description: dict):
247
+ messages = [{"role": "system",
248
+ "content": ("Tu es un super assistant très fort pour resumer et structurer des json."
249
+ "Je vais te fournir un json et tu vas faire en sorte qu'aucune valeur de clef soit superieur à 50 characère."
250
+ "Tu as le droit de resumer pour conserver que les informations principales mais tu nas pas le droit de toucher les champs qui sont des urls, tu les rends tel quel sans les affecter."
251
+ "Ne change pas la structure du json, il ne doit pas manquer de clef qui étaient presentent initialement ni etre renommé"
252
+ "concernant les champs de livraison, je veux que tu ne conserve que la date la plus courte de livraison sous le format jour mois")},
253
+ {"role": "user", "content": f"met moi en forme ce json stp : {product_description}"}]
254
+ model_output = self.model(messages, response_format={"type": "json"}).content
255
+
256
+ model_output = re.sub(r"^```(?:json)?\n|\n```$", "", model_output.strip())
257
+ return json.loads(model_output)
258
+
259
+ def forward(self, list_product_element: list[dict]):
260
+ for product_index in range(len(list_product_element)):
261
+ list_product_element[product_index] = self._clean_product_info(list_product_element[product_index])
262
+
263
+ return pd.DataFrame(list_product_element)
264
+
265
+
266
+ class FilterProduct(Tool):
267
+ name = "filter_product"
268
+ description = (
269
+ "Filter a list of products based on a user-defined condition."
270
+ """The condition is expressed in natural language (e.g., "must be delivered before May 10", "price under €300", etc.)."""
271
+ )
272
+
273
+ inputs = {
274
+ "list_product_element": {
275
+ "type": "array",
276
+ "description": "List of products in the form of dictionaries. Example: [{'product_name': 'A', 'price': 100, 'delivery_date': '5 May'}]"
277
+ },
278
+ "condition": {
279
+ "type": "string",
280
+ "description": "Natural language condition to be met (e.g., 'must be delivered before May 10')."
281
+ }
282
+ }
283
+
284
+ output_type = "array"
285
+
286
+ def __init__(self, model, **kwargs):
287
+ super().__init__(**kwargs)
288
+ self.model = model
289
+
290
+ def _check_condition_with_llm(self, product: dict, condition: str) -> bool:
291
+ messages = [
292
+ {"role": "system", "content": (
293
+ "Tu es un assistant chargé d'évaluer si un produit respecte une condition utilisateur."
294
+ "Tu vas recevoir un produit sous forme de dictionnaire, et une condition."
295
+ "Tu dois répondre uniquement par 'oui' ou 'non' (sans autre explication), selon que le produit satisfait la condition ou non en t'aidant des differents champs du dictionnaire."
296
+ "La réponse doit être exactement 'oui' ou 'non', en minuscules."
297
+ )},
298
+ {"role": "user", "content": f"Produit : {product}\n Condition : {condition}"}
299
+ ]
300
+
301
+ result = self.model(messages).content.strip().lower()
302
+ return result == "oui"
303
+
304
+ def forward(self, list_product_element: list[dict], condition: str):
305
+ filtered_products = []
306
+
307
+ for product in list_product_element:
308
+ try:
309
+ if self._check_condition_with_llm(product, condition):
310
+ filtered_products.append(product)
311
+ except Exception as e:
312
+ # Log ou passer en silence
313
+ continue
314
+
315
+ return filtered_products
316
+
317
+
318
+ class FinalAnswerTool(Tool):
319
+ name = "final_answer"
320
+ description = "Provides a final answer to the given problem and a pd.dataframe corresponding to the recommended product if necessary"
321
+ inputs = {"answer": {"type": "any", "description": "The final answer to the problem"},
322
+ "structured_product": {"type": "object",
323
+ "description": "optional products recommended in a structured format",
324
+ "nullable": True}, }
325
+ output_type = "any"
326
+
327
+ def forward(self, answer: Any, structured_product: Optional[object] = None) -> (Any, Any):
328
+ return answer, structured_product
src/aiagent/utils/rending_method.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from litellm import completion
2
+
3
+
4
+ class cleaning_model_thinking:
5
+ def __init__(self, model_name: str):
6
+ self.model_name = model_name
7
+
8
+ self.system_message = [{
9
+ "role": "system",
10
+ "content": ("You are an assistant that helps explain the reasoning or actions of an AI agent to end users. "
11
+ "You translate either 'Thought' steps or blocks of code into clear, natural language that a "
12
+ "non-technical user can understand. "
13
+ "Each response must be a **single, precise, user-facing sentence** that keeps the **key "
14
+ "intent of the block**. "
15
+ "Avoid vague summaries like 'help you decide' or 'comparing products' — be specific about "
16
+ "what the AI is doing."
17
+ "Always speaks in the first person singular")
18
+ }]
19
+
20
+ @staticmethod
21
+ def formalize_message_block(thinking_bloc: str):
22
+ message = [{
23
+ "role": "user",
24
+ "content": (f"Here is a block from an AI agent that helps users compare products on Amazon. "
25
+ f"Please summarize exactly what the AI is doing in one short and clear sentence, without "
26
+ f"using any technical terms or code.\n\n "
27
+ f"Block:\n:\n\n {thinking_bloc}")
28
+ }]
29
+
30
+ return message
31
+
32
+ def __call__(self, thinking_bloc):
33
+ user_message = self.formalize_message_block(thinking_bloc)
34
+
35
+ res = completion(
36
+ model=self.model_name,
37
+ messages=self.system_message + user_message)
38
+
39
+ return res.choices[0].message.content