|
| 1 | +""" |
| 2 | +Agent that uses a Tool to execute python code. |
| 3 | +
|
| 4 | +CAUTION - this is a security risk, as it allows arbitrary code execution. |
| 5 | +This is a bare-bones example. For a real application, you would want to restrict |
| 6 | +the code in various ways, e.g. by using a sandboxed environment, or by restricting |
| 7 | +the modules that can be imported. |
| 8 | +
|
| 9 | +Run like this (leave model empty to use default GPT4o) |
| 10 | +
|
| 11 | +uv run examples/basic/python-code-exec-tool.py -m gpt4o-mini |
| 12 | +""" |
| 13 | + |
| 14 | +import io |
| 15 | +import contextlib |
| 16 | +from fire import Fire |
| 17 | +from rich.prompt import Prompt |
| 18 | +from langroid.pydantic_v1 import Field |
| 19 | +from langroid.agent.tools.orchestration import ResultTool |
| 20 | +import langroid as lr |
| 21 | +import langroid.language_models as lm |
| 22 | + |
| 23 | + |
| 24 | +def execute_code(code_string): |
| 25 | + """ |
| 26 | + A minimal function to execute Python code and capture its output. |
| 27 | +
|
| 28 | + Args: |
| 29 | + code_string: The Python code to execute |
| 30 | +
|
| 31 | + Returns: |
| 32 | + Tuple of (output, local_variables) |
| 33 | + """ |
| 34 | + # Create dictionary for local variables |
| 35 | + local_vars = {} |
| 36 | + |
| 37 | + # Capture stdout |
| 38 | + buffer = io.StringIO() |
| 39 | + |
| 40 | + # Execute code with stdout redirection |
| 41 | + with contextlib.redirect_stdout(buffer): |
| 42 | + try: |
| 43 | + exec(code_string, globals(), local_vars) |
| 44 | + success = True |
| 45 | + except Exception as e: |
| 46 | + print(f"Error: {str(e)}") |
| 47 | + success = False |
| 48 | + |
| 49 | + output = buffer.getvalue() |
| 50 | + return output, local_vars, success |
| 51 | + |
| 52 | + |
| 53 | +class PyCodeTool(lr.ToolMessage): |
| 54 | + request: str = "py_code_tool" |
| 55 | + purpose: str = "To execute python <code> and return results" |
| 56 | + |
| 57 | + code: str = Field( |
| 58 | + ..., |
| 59 | + description=""" |
| 60 | + Syntactically valid Python code that can be placed in file to |
| 61 | + be run by the Python interpreter. MUST NOT CONTAIN any CODE-BLOCK |
| 62 | + delimiters like triple-backticks. |
| 63 | + """, |
| 64 | + ) |
| 65 | + |
| 66 | + def handle(self): |
| 67 | + output, local_vars, success = execute_code(self.code) |
| 68 | + if success: |
| 69 | + print("Successfully ran code. Results:") |
| 70 | + print(output) |
| 71 | + print("Local variables:") |
| 72 | + print(local_vars) |
| 73 | + else: |
| 74 | + print("Failed to run code.") |
| 75 | + return ResultTool(output=output, local_vars=local_vars, success=success) |
| 76 | + |
| 77 | + |
| 78 | +def main(model: str = ""): |
| 79 | + llm_config = lm.OpenAIGPTConfig( |
| 80 | + chat_model=model or lm.OpenAIChatModel.GPT4o, |
| 81 | + ) |
| 82 | + agent = lr.ChatAgent( |
| 83 | + lr.ChatAgentConfig( |
| 84 | + name="Coder", |
| 85 | + llm=llm_config, |
| 86 | + # handle LLM non-tool msg |
| 87 | + handle_llm_no_tool=lambda msg: ResultTool( |
| 88 | + output=msg.content, |
| 89 | + success=True, |
| 90 | + ), |
| 91 | + system_message=f""" |
| 92 | + You are an expert python coder. When you get a user's message, |
| 93 | + respond as follows: |
| 94 | + - if you think you need to run Python code, |
| 95 | + use the TOOL `{PyCodeTool.name()}` to perform the task. |
| 96 | + - otherwise simply respond to the user's message. |
| 97 | + """, |
| 98 | + ) |
| 99 | + ) |
| 100 | + agent.enable_message(PyCodeTool) |
| 101 | + # task specialized to return ResultTool |
| 102 | + # set restart to False to maintain conv history across `run` calls |
| 103 | + task = lr.Task(agent, interactive=False, restart=False)[ResultTool] |
| 104 | + |
| 105 | + while True: |
| 106 | + user_input = Prompt.ask("User") |
| 107 | + if user_input.lower() in ["x", "q"]: |
| 108 | + break |
| 109 | + result: ResultTool | None = task.run(user_input) |
| 110 | + if result is not None: |
| 111 | + # code was run; do something with the output if any |
| 112 | + if result.success: |
| 113 | + print("Output:", result.output) |
| 114 | + else: |
| 115 | + print("Code execution failed.") |
| 116 | + |
| 117 | + |
| 118 | +if __name__ == "__main__": |
| 119 | + Fire(main) |
0 commit comments