Skip to content

Should we use the same namespace for locals and globals in UnsafeLocalCodeExecutor? #295

@abhishm

Description

@abhishm

Issue

Please see this part of UnsafeLocalCodeExecutor.

globals_ = {}
locals_ = {}
stdout = io.StringIO()
with redirect_stdout(stdout):
  exec(code_execution_input.code, globals_, locals_)
output = stdout.getvalue()
coding_agent = Agent(
    name = "coding_agent",
    description = "Agent for handling coding requests",
    model = "gemini-2.0-flash",
    instruction="""You are a coding agent. You can execute code to help users answers some simple questions.""",
    code_executor=UnsafeLocalCodeExecutor(),
    # planner=PlanReActPlanner(),
    # planner=BuiltInPlanner(thinking_config=types.ThinkingConfig(includeThoughts=True)),
    output_key="code_output"
)

Because of separate locals() and globals(), the below code returned by LLM fails

Image

Solution

Change this part of UnsafeLocalCodeExecutor
as below.

namespace = {}
stdout = io.StringIO()
with redirect_stdout(stdout):
  exec(code_execution_input.code, globals=namespace, locals=namespace)
output = stdout.getvalue()

Please see here for explanation.

Metadata

Metadata

Assignees

Labels

tools[Component] This issue is related to tools

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions