### Execute Finite Python Code Source: https://github.com/fixed-ai/sandboxed-python/blob/main/README.md Demonstrates how to use the `execute_fpy` function to run Finite Python code within the sandboxed environment. Includes examples of basic printing and handling potential execution errors with custom error reporting. ```python from sandboxed_python import execute_fpy # Simple print statement execute_fpy(""" print("Hello, World!") """) # Complex expression with unpacking (starred expressions) try: execute_fpy(""" print([*{1, 2}, 3, *(4, 5), *{5: 1}]) "1" - "2" """) except FPyException as e: e.pretty_print() ``` -------------------------------- ### Using Sandboxed Python for Tool Calls Source: https://github.com/fixed-ai/sandboxed-python/blob/main/README.md Illustrates how Sandboxed Python can replace traditional tool calls by executing LLM-generated Python code. It shows how to add custom functions to the sandbox and retrieve results from it. ```python from sandboxed_python import execute_fpy, DefaultSecureSandbox class AgentTool: def __init__(self): self.sandbox = DefaultSecureSandbox() self.sandbox.add_function("query_db", self._query_db) # Custom tool def _query_db(self, query: str) -> list[dict]: # Simulate safe DB query return [{"result": "data"}] def call_tool(self, generated_code: str): try: execute_fpy(generated_code, sandbox=self.sandbox) # Access sandbox variables for results return self.sandbox.get_var("result") except Exception as e: return {"error": str(e)} # LLM can parse and retry # Agent usage agent = AgentTool() llm_generated_code = """ result = query_db("SELECT * FROM users") print(result) """ result = agent.call_tool(llm_generated_code) ``` -------------------------------- ### Customizing PySandbox for Agent Integration Source: https://github.com/fixed-ai/sandboxed-python/blob/main/README.md Demonstrates subclassing PySandbox to create a custom sandbox environment. This includes defining custom logic for function calls, method calls, variable access, and output display, tailored for agent needs. ```python from sandboxed_python import ( PySandbox, SourceLocation, execute_fpy, Undef, undef, FPyVal, # you can also use `typing.Any`... ) import typing class MySandbox(PySandbox): def __init__(self): self.variables: dict[str, FPyVal] = {} self.location: SourceLocation | None = None def get_location(self) -> SourceLocation | None: return self.location def set_location(self, location: SourceLocation) -> None: self.location = location def func_call( self, func_name: str, args: list[FPyVal], location: SourceLocation ) -> FPyVal: # Custom implementation: e.g., only allow 'len' if func_name == "len" and len(args) == 1: return len(args[0]) if func_name == "print": print(*args) return raise Exception(f"Function {func_name} not allowed") def method_call( self, subject: FPyVal, method_name: str, args: list[FPyVal], location: SourceLocation, ) -> FPyVal: # Custom implementation: e.g., allow str.upper if isinstance(subject, str) and method_name == "upper": return subject.upper() raise Exception(f"Method {method_name} not allowed on {type(subject)}") def get_var(self, name: str) -> FPyVal | Undef: return self.variables.get(name, Undef.undef) def set_var(self, name: str, value: FPyVal | Undef) -> None: if isinstance(value, Undef): self.variables.pop(name, None) else: self.variables[name] = value # type: ignore def list_vars(self) -> typing.Iterable[str]: return self.variables.keys() def display(self, value: FPyVal) -> None: print(f"[Custom Output] {value!r}") def exception_to_message(self, exception: Exception) -> str: return str(exception) # Usage sandbox = MySandbox() execute_fpy("print(len('hello'))", sandbox=sandbox) ``` -------------------------------- ### Safe Exception Handling in FPy Source: https://github.com/fixed-ai/sandboxed-python/blob/main/README.md Demonstrates how to access exception details in FPy, which provides a dictionary with safe, string-only keys instead of direct exception object access. This is a deviation from CPython for security reasons. ```python try: 1 / 0 except Exception as e: print(e['type']) # Outputs: 'ZeroDivisionError' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.