MCPcopy Create free account
hub / github.com/Alibaba-NLP/DeepResearch / PythonInterpreter

Class PythonInterpreter

inference/tool_python.py:29–150  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

27
28@register_tool('PythonInterpreter', allow_overwrite=True)
29class PythonInterpreter(BaseToolWithFileAccess):
30 name = "PythonInterpreter"
31 description = 'Execute Python code in a sandboxed environment. Use this to run Python code and get the execution results.\n**Make sure to use print() for any output you want to see in the results.**\nFor code parameters, use placeholders first, and then put the code within <code></code> XML tags, such as:\n<tool_call>\n{"purpose": <detailed-purpose-of-this-tool-call>, "name": <tool-name>, "arguments": {"code": ""}}\n<code>\nHere is the code.\n</code>\n</tool_call>\n'
32
33 parameters = {
34 "type": "object",
35 "properties": {
36 "code": {
37 "type": "string",
38 "description": "The Python code to execute. Must be provided within <code></code> XML tags. Remember to use print() statements for any output you want to see.",
39 }
40 },
41 "required": ["code"],
42 }
43
44 def __init__(self, cfg: Optional[Dict] = None):
45 super().__init__(cfg)
46 # self.summary_mapping = SummaryMapping()
47
48 @property
49 def args_format(self) -> str:
50 fmt = self.cfg.get('args_format')
51 if fmt is None:
52 if has_chinese_chars([self.name_for_human, self.name, self.description, self.parameters]):
53 fmt = 'The input for this tool should be a Markdown code block.'
54
55 else:
56 fmt = 'Enclose the code within triple backticks (`) at the beginning and end of the code.'
57 return fmt
58
59 def observation(self, tool: dict, tool_dict: dict, tool_results, empty_mode: bool=False, readpage: bool=False, max_observation_length: int=None, tokenizer=None):
60 print('test')
61 assert isinstance(tool_results, str), f"result of python code should be str, instead of {type(tool_results)}. {tool_results}"
62 return tool_results
63
64 @property
65 def function(self) -> dict:
66 return {
67 'name': self.name,
68 'description': self.description,
69 'parameters': self.parameters,
70 }
71
72 def call(self, params, files= None, timeout = 50, **kwargs) -> str:
73 try:
74 code=params
75 last_error = None
76 for attempt in range(8):
77 try:
78 # Randomly sample an endpoint for each attempt
79 endpoint = random.choice(SANDBOX_FUSION_ENDPOINTS)
80 print(f"Attempt {attempt + 1}/5 using endpoint: {endpoint}")
81
82 code_result = run_code(RunCodeRequest(code=code, language='python', run_timeout=timeout), max_attempts=1, client_timeout=timeout, endpoint=endpoint)
83 print("[Python] Code Result", code_result)
84 result = []
85 if code_result.run_result.stdout:
86 result.append(f"stdout:\n{code_result.run_result.stdout}")

Callers 1

react_agent.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected