Skip to content

Commit 131a1a2

Browse files
TLK-2364 - implements preamble extension for python interpreter tool (#887)
1 parent 6fc3a08 commit 131a1a2

File tree

3 files changed

+49
-5
lines changed

3 files changed

+49
-5
lines changed

docs/config_details/config_description.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
- tools - Tool configurations
2626
- python_interpreter - Python interpreter configurations
2727
- url - URL of the python interpreter tool
28+
- forbidden_packages - Forbidden packages - list of packages that are not allowed to be used in the python interpreter tool
2829
- use_tools_preamble - Use tools preamble - if set to true, the tools preamble will be used in the chat requests
2930
- feature_flags - Feature flags configurations
3031
- use_agents_view - Use agents view - if set to true, the frontend agents view will be available.

src/backend/config/settings.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,10 @@ class PythonToolSettings(BaseSettings, BaseModel):
112112
url: Optional[str] = Field(
113113
default=None, validation_alias=AliasChoices("PYTHON_INTERPRETER_URL", "url")
114114
)
115+
forbidden_packages: Optional[List[str]] = Field(
116+
default=["micropip","requests","aiohttp","urllib3","fsspec","smart_open","pyodide-http"],
117+
validation_alias=AliasChoices("PYTHON_INTERPRETER_FORBIDDEN_PACKAGES", "forbidden_packages")
118+
)
115119

116120

117121
class TavilySearchSettings(BaseSettings, BaseModel):

src/backend/tools/base.py

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from enum import StrEnum
44
from typing import Any, Dict, List
55

6+
import requests
67
from fastapi import Request
78
from pydantic import BaseModel
89

@@ -52,13 +53,13 @@ def __new__(cls, name, bases, class_dict):
5253
return super().__new__(cls, name, bases, class_dict)
5354

5455

55-
class BaseToolPreambleRegistry:
56+
class ToolDefaultPreambleRegistry:
5657
"""
5758
Registry to store default preamble values for tools.
5859
Currently, it's implemented as a class with predefined values, but we can use set_preamble to set values.
5960
"""
6061
_default_preambles = {
61-
"toolkit_python_interpreter": "If you decide to use toolkit_python_interpreter tool and are going to plot something, try returning result as a png. Ensure that the generated code does not include any internet connection, and avoid using the module named requests. ",
62+
"toolkit_python_interpreter": "If you decide to use toolkit_python_interpreter tool and are going to plot something, try returning result as a png. Ensure that the generated code does not include any internet connection.",
6263
"read_file": "When using the read_file tool, always ensure that the file parameter is prepared as a tuple in the format (filename, file ID). The order of the tuple fields is critical. ",
6364
"search_file":"When using the search_file tool, always ensure that the `files` parameter is prepared as a list of tuples in the format (filename, file ID). The order of the tuple fields is critical. "
6465
}
@@ -71,11 +72,42 @@ def set_preamble(cls, tool_id, preamble):
7172
cls._default_preambles[tool_id] = preamble
7273

7374
@classmethod
74-
def get_preamble(cls, tool_class):
75+
def get_preamble(cls, tool_class_id):
7576
"""
7677
Retrieve the default preamble for a given tool class.
7778
"""
78-
return cls._default_preambles.get(tool_class, None)
79+
return cls._get_class_specific_preamble(tool_class_id) or cls._default_preambles.get(tool_class_id, None)
80+
81+
@classmethod
82+
def _get_class_specific_preamble(cls, tool_class_id):
83+
"""
84+
Retrieve the custom preamble for a given tool class.
85+
"""
86+
if tool_class_id == "toolkit_python_interpreter":
87+
interpreter_url = Settings().get('tools.python_interpreter.url')
88+
if interpreter_url:
89+
try:
90+
# TODO Confirm with TJ if we need to add this settings here or set predefined values on the interpreter side
91+
forbidden_packages = Settings().get('tools.python_interpreter.forbidden_packages')
92+
if forbidden_packages:
93+
forbidden_response = requests.post(interpreter_url + "/forbidden-packages", json={"packages": forbidden_packages})
94+
if forbidden_response.status_code != 200:
95+
return None
96+
forbidden_preamble_packages = ", ".join(forbidden_packages)
97+
# TODO Ask TJ do we need available packages
98+
# available_response = requests.get(interpreter_url + "/available-packages")
99+
# if available_response.status_code != 200:
100+
# return None
101+
# available_packages = available_response.json()["packages"]
102+
# available_cleaned = [item for item in available_packages if item not in forbidden_packages]
103+
# available_preamble_packages = ", ".join(available_cleaned)
104+
preamble = f"If you decide to use the toolkit_python_interpreter tool and plan to plot something, try returning the result as a PNG. Ensure that the generated code does not require an internet connection. Avoid using the following packages in code generation: {forbidden_preamble_packages}. "
105+
return preamble
106+
except Exception as e:
107+
logger.error(f"Error while retrieving the Python interpreter preamble.: {str(e)}")
108+
return None
109+
110+
return None
79111

80112

81113
class BaseTool(metaclass=ParametersValidationMeta):
@@ -94,7 +126,7 @@ def __init_subclass__(cls, **kwargs):
94126
using the registry class.
95127
"""
96128
super().__init_subclass__(**kwargs)
97-
cls.TOOL_DEFAULT_PREAMBLE = BaseToolPreambleRegistry.get_preamble(cls.ID)
129+
cls.TOOL_DEFAULT_PREAMBLE = ToolDefaultPreambleRegistry.get_preamble(cls.ID)
98130

99131
def __init__(self, *args, **kwargs):
100132
self._post_init_check()
@@ -140,6 +172,13 @@ async def call(
140172
) -> List[Dict[str, Any]]:
141173
...
142174

175+
@classmethod
176+
def get_preamble(cls):
177+
return cls.TOOL_DEFAULT_PREAMBLE
178+
179+
@classmethod
180+
def set_preamble(cls, preamble):
181+
cls.TOOL_DEFAULT_PREAMBLE = preamble
143182

144183
class BaseToolAuthentication(ABC):
145184
"""

0 commit comments

Comments
 (0)