Skip to content

bug: built_in_code_execution output issue #180

Closed

Description

@adars124

the raw response of the code execution returns the following block:

Raw response:
{"candidates":[{"content":{"parts":[{"executable_code":{"code":"import math\nprint(math.factorial(5))\n","language":"PYTHON"}},{"code_execution_result":{"outcome":"OUTCOME_OK","output":"120\n"}},{"text":"120\n"}],"role":"model"},"finish_reason":"STOP"}],"model_version":"gemini-2.0-flash","usage_metadata":{"candidates_token_count":20,"candidates_tokens_details":[{"modality":"TEXT","token_count":20}],"prompt_token_count":91,"prompt_tokens_details":[{"modality":"TEXT","token_count":91}],"tool_use_prompt_token_count":107,"tool_use_prompt_tokens_details":[{"modality":"TEXT","token_count":107}],"total_token_count":218},"automatic_function_calling_history":[]}

We can see that the model successfully executed the code and is returning the output of the execution in "output" key.

However, the model cannot access the "outcome" or the "output" key from the function response above. But it gets access to this:

Generated event in agent run streaming: {"content":{"parts":[{"functionResponse":{"id":"adk-78a12908-7fc8-47ee-8c57-b685989bc5f5","name":"CodingAgent","response":{"result":""}}}],"role":"user"},"invocation_id":"e-d2de849d-3df7-4603-9ca6-f02ea539af54","author":"jarvis","actions":{"state_delta":{},"artifact_delta":{},"requested_auth_configs":{}},"id":"iJURFFJN","timestamp":1744628648.768249}

In this snippet, we can see that the response of the coding agent is a dictionary containing result which is an empty string.

The agent looks into this response dictionary to provide final output to the user, however it seems to be a bug or something that the agent is not correctly accessing the output of the code execution. This causes the agent to get into a loop and, eventually, fails due to exhaustive depth limit.

Activity

  1. hangfei commented on Apr 14, 2025

    @hangfei
    Collaborator

    @adars124 could you provide a minimal example to reproduce your issue?

  2. adars124 commented on Apr 15, 2025

    @adars124
    Author
    1. Setup the built-in-code-execution:
    coding_agent = Agent(
        model=GEMINI_FLASH,
        name="CodingAgent",
        instruction="""
        You are a specialist in code execution and programming.
        You can evaluate arithmetic expressions, generate code and execute them. 
        **Return ONLY that raw output as your final response (plain text).**
        **Do not add explanations, markdown, or code blocks unless the original request explicitly asked for an explanation.**
        """,
        tools=[built_in_code_execution],
    )
    
    1. Assign it to the root agent:
    agent_tools = [
        agent_tool.AgentTool(agent=coding_agent),
        agent_tool.AgentTool(agent=search_agent),
    ]
    
    root_agent = Agent(
        name=constants.AGENT_NAME,
        model=constants.MODEL,
        description=constants.DESCRIPTION,
        instruction=prompts.ROOT_PROMPT,
        tools=agent_tools,
    )
    
    1. Run the web interface: uv run adk web

    2. Ask question like: 'what's the result of 4*8-2+6/4?' or 'calcualte the fibonacci series upto the 10th term using python'.

    It gives the following response as of now, yesterday there was the problem of infinite loop.

    {"parts":[{"text":"what's the result of 4*8-2+6/4?"}],"role":"user"}
    {"parts":[{"function_call":{"args":{"request":"4*8-2+6/4"},"name":"CodingAgent"}}],"role":"model"}
    {"parts":[{"function_response":{"name":"CodingAgent","response":{"result":""}}}],"role":"user"}
    {"parts":[{"text":"I am sorry, I cannot provide the answer using the available tools. Is there anything else I can help you with?\n"}],"role":"model"}
    

    I have also noticed that, even though we carefully craft the prompt as we need it, the model fails to properly understand the user intent and execute the corresponding tool. I have to explicitly tell it to either google search, or execute the code, and things alike.

    take a look at this prompt: 'what's the nepali date today?' -> response: 'Could you please specify which Gregorian date you would like me to convert to the Nepali date?'

    i have to explicitly tell it to do this: 'search google and tell me today's nepali date'
    and only then i get the intended output using google search: 'Today's Nepali date is Baishakh 2, 2082.'

  3. self-assigned this
    on Apr 15, 2025
  4. hangfei commented on Apr 15, 2025

    @hangfei
    Collaborator

    @adars124 the new issue you observed is usually related model's capability and knowledge base.

    The model has less knowledge on the problem you try to tackled. I suggest you add more background information on what's Nepali date, and what's the task etc. You can use another model to generate the prompt. It can be like"I am building an agent. help me build a better system instruction(prompt) based on my current setup and failure patterns i have observed."

    cc: @polong-lin to add more documentation to help with this kind of problem.

  5. adars124 commented on Apr 16, 2025

    @adars124
    Author

    @hangfei sure will try creating better prompts. But what is the issue related to code execution? The model cannot access the output of the code execution for some reason. Need help on this.

  6. dcdj99 commented on Apr 25, 2025

    @dcdj99

    I am also facing the same issue but it works after when I used the exact same prompt form the docs https://google.github.io/adk-docs/tools/built-in-tools/

  7. Chand-d commented on May 3, 2025

    @Chand-d

    I am also facing the same issue, my search agent is working fine but when i try running the code agent ( even simple queries ). it performs the calculations and even gets answers right but it returns empty result array. here is my agent.py and logs.
    #agent.py
    from google.adk.tools import agent_tool
    from google.adk.agents import Agent
    from google.adk.tools import google_search, built_in_code_execution
    import logging
    import json

    search_agent = Agent(
    model='gemini-2.0-flash',
    name='SearchAgent',
    instruction="""
    Your Role: You are a specialized information retrieval assistant.
    Your ONLY Task: Use the google_search tool to find answers.
    Input: Receive query via 'request'.
    Action: Call google_search(query=...).
    Output: Return ONLY the tool result.
    """,
    description="Performs web searches.",
    tools=[google_search],
    )

    coding_agent = Agent(
    model='gemini-2.0-flash',
    name='CodeAgent',
    instruction="""
    Your Role: You are a specialized code execution assistant.
    Your Task: Execute Python code and return its output.

    CRITICAL INSTRUCTIONS:

    1. Execute the code in the 'request' using built_in_code_execution.
    2. After execution, find the 'code_execution_result' object with the 'output' field.
    3. Copy the EXACT string from code_execution_result.output - preserve ALL characters, numbers, and formatting.
    4. You MUST return the exact output string directly, NOT as a JSON object.
    5. DO NOT modify, format, or interpret the output in any way - return it EXACTLY as it appears.

    EXACT RESPONSE FORMAT:
    [exact output from code execution]

    EXAMPLES:

    • If code prints "Hello, world!", respond with: Hello, world!
    • If code prints "The sum is 42", respond with: The sum is 42
    • If code prints "27264105", respond with: 27264105
    • If code has no output, respond with an empty string.

    CRITICAL:

    • Your response MUST be ONLY the exact output - no other text, no explanations, no formatting.
    • DO NOT wrap your response in JSON, code blocks, backticks, or any other formatting.
    • For numeric outputs, ensure you copy the EXACT number - do not round, format, or modify it in any way.
    • Preserve ALL whitespace, newlines, and special characters exactly as they appear in the output.
      """,
      description="Executes Python code and returns raw output",
      tools=[built_in_code_execution],
      )

    root_agent = Agent(
    name="RootAgent",
    model="gemini-2.0-flash",
    instruction="""
    Your Role: You are the primary conversational assistant.
    Available Specialist Tools:

    1. SearchAgent: For web searches.
    2. CodeAgent: For Python code execution.
      Process for CodeAgent:
    3. When a user wants to run Python code, call CodeAgent(request=code).
    4. The CodeAgent will return the raw output from the code execution directly.
    5. Present this output as: "The script execution returned: [raw output]"

    CRITICAL INSTRUCTIONS:

    • The CodeAgent returns the raw output directly, not wrapped in JSON.
    • Present EXACTLY what was returned - unchanged, unformatted, uninterpreted.
    • For numeric outputs, ensure you present the EXACT number - do not round, format, or modify it.
    • If the CodeAgent returns an empty string, respond with: "The script execution returned no output."
    • If the CodeAgent returns error messages, present them to the user.

    EXAMPLES:

    • If CodeAgent returns "Hello, world!", respond with: "The script execution returned: Hello, world!"
    • If CodeAgent returns "20097264105", respond with: "The script execution returned: 20097264105"
    • If CodeAgent returns an empty string, respond with: "The script execution returned no output."
    • If CodeAgent returns "The sum is 42", respond with: "The script execution returned: The sum is 42"
      """,
      description="Main conversational agent that delegates tasks",
      tools=[
      agent_tool.AgentTool(agent=search_agent),
      agent_tool.AgentTool(agent=coding_agent)
      ],
      )

    #logs
    here you can see,
    Raw response:
    {"code_execution_result":{"outcome":"OUTCOME_OK","output":"The sum of all such integers is: 20097264105\n"}},{"text":"The sum of all such integers is: 20097264105\n"}],"role":"model"},"finish_reason":"STOP"}], and {"parts":[{"function_response":
    but,
    {"name":"CodeAgent","response":{"result":""}}}],"role":"user"}.

  8. nathan-nguyen-webjet commented on May 27, 2025

    @nathan-nguyen-webjet

    I am having the same problem, using code_executor=VertexAiCodeExecutor(optimize_data_file=True,stateful=True) works but the built_in_code_executors will always return {}

  9. Chand-d commented on May 27, 2025

    @Chand-d

    I am using a way around like this and it works.

    agent.py

    from google.adk.tools import agent_tool, FunctionTool
    from google.adk.agents import Agent
    from google.adk.tools import google_search, built_in_code_execution
    from typing import Dict, Any
    import io
    import sys
    import logging
    import traceback

    --- Specialist Agent Definitions ---

    Search Agent - This is working fine, so don't modify it

    search_agent = Agent(
    model='gemini-2.0-flash',
    name='SearchAgent',
    instruction="""
    Your Role: You are a specialized information retrieval assistant.
    Your ONLY Task: Use the google_search tool to find answers for the given query.
    Input: Receive query via 'request'.
    Action: Call google_search(query=...).
    Output: Return ONLY the search results provided by the tool.
    """,
    description="Performs web searches to answer questions.",
    tools=[google_search],
    )

    --- Direct Code Execution Function ---

    async def execute_code_via_agent(code_string: str) -> Dict[str, Any]:
    """
    Executes the given Python code string directly using Python's exec() function
    and returns the standard output in a dictionary.

    Args:
        code_string: The Python code to execute.
        
    Returns:
        A dictionary containing the execution result:
        {'status': 'success', 'output': <raw_output_string>} or
        {'status': 'error', 'message': <error_details>}
    """
    # Capture stdout to get the output
    old_stdout = sys.stdout
    new_stdout = io.StringIO()
    sys.stdout = new_stdout
    
    try:
        # Check for syntax errors
        try:
            compile(code_string, '<string>', 'exec')
        except SyntaxError as e:
            return {"status": "error", "message": f"Syntax error: {str(e)}"}
    
        # Execute the code
        try:
            exec(code_string)
            output = new_stdout.getvalue()
            return {"status": "success", "output": output}
        except Exception as e:
            error_message = f"Runtime error: {str(e)}\n{traceback.format_exc()}"
            return {"status": "error", "message": error_message}
    finally:
        # Restore stdout
        sys.stdout = old_stdout
    

    Wrap the function into a FunctionTool

    code_execution_tool = FunctionTool(
    func=execute_code_via_agent
    )

    --- Root Agent Definition ---

    Root Agent that uses both tools

    root_agent = Agent(
    name="RootAgent",
    model="gemini-2.0-flash",
    instruction="""
    You are the primary conversational assistant that can perform two types of tasks:

    1. Search for information using the SearchAgent
    2. Execute Python code using the execute_code_via_agent tool

    For code execution:

    • When a user asks you to run Python code, use the execute_code_via_agent tool
    • Pass the code as the code_string parameter
    • The tool will return a dictionary with 'status' and either 'output' or 'message'
    • If status is 'success', present the output to the user prefixed with "The script execution returned: "
    • If status is 'error', inform the user of the error message

    For search:

    • When a user asks a question that requires searching for information, use the SearchAgent
    • Pass the search query as the request parameter
    • Present the search results to the user

    General guidelines:

    • Be helpful and concise
    • Don't try to execute code again if it fails
    • Don't add your own explanations to code output
      """,
      description="Main conversational agent that delegates search or code execution tasks.",
      tools=[
      agent_tool.AgentTool(agent=search_agent),
      code_execution_tool
      ],
      )
  10. added
    tools
    on Jun 1, 2025
  11. added theissue type on Jun 1, 2025
  12. hangfei commented on Jun 1, 2025

    @hangfei
    Collaborator

    @seanzhou1023 Could you helpl take a look?

  13. added
    need attention
    on Jul 2, 2025
  14. KSonPham commented on Jul 2, 2025

    @KSonPham

    Hey @adars124, have you tried:

    root_agent = Agent(
        name=AGENT_NAME,
        model=GEMINI_MODEL,
        code_executor=BuiltInCodeExecutor(),  # Modified to pass the executor directly
        instruction="""You are a calculator agent.
        When given a mathematical expression, write and execute Python code to calculate the result. Also do data visuallization.
        """,
        description="Executes Python code to perform calculations and do data visualization.",
    )
    
  15. seanzhou1023 commented on Jul 12, 2025

    @seanzhou1023
    Collaborator

    @adars124 thank you for reporting the issue!
    Given the code executor response is correct, I would assume it was a bug in agent tool.

    @Chand-d thank you for providing the codes to reproduce the issue and providing a workaround.

    However as @KSonPham mentioned, recently we've migrate build in code execution tool to code executor, I've migrated the exmaple provided by @Chand-d below :

    #agent.py
    from google.adk.tools import agent_tool
    from google.adk.agents import Agent
    from google.adk.tools import google_search
    from google.adk.code_executors.built_in_code_executor import BuiltInCodeExecutor 
    
    
    search_agent = Agent(
    model='gemini-2.0-flash',
    name='SearchAgent',
    instruction="""
    Your Role: You are a specialized information retrieval assistant.
    Your ONLY Task: Use the google_search tool to find answers.
    Input: Receive query via 'request'.
    Action: Call google_search(query=...).
    Output: Return ONLY the tool result.
    """,
    description="Performs web searches.",
    tools=[google_search],
    )
    
    coding_agent = Agent(
    model='gemini-2.0-flash',
    name='CodeAgent',
    instruction="""
    Your Role: You are a specialized code execution assistant.
    Your Task: Execute Python code and return its output.
    
    CRITICAL INSTRUCTIONS:
    
    Execute the code in the 'request' using built_in_code_execution.
    After execution, find the 'code_execution_result' object with the 'output' field.
    Copy the EXACT string from code_execution_result.output - preserve ALL characters, numbers, and formatting.
    You MUST return the exact output string directly, NOT as a JSON object.
    DO NOT modify, format, or interpret the output in any way - return it EXACTLY as it appears.
    EXACT RESPONSE FORMAT:
    [exact output from code execution]
    
    EXAMPLES:
    
    If code prints "Hello, world!", respond with: Hello, world!
    If code prints "The sum is 42", respond with: The sum is 42
    If code prints "27264105", respond with: 27264105
    If code has no output, respond with an empty string.
    CRITICAL:
    
    Your response MUST be ONLY the exact output - no other text, no explanations, no formatting.
    DO NOT wrap your response in JSON, code blocks, backticks, or any other formatting.
    For numeric outputs, ensure you copy the EXACT number - do not round, format, or modify it in any way.
    Preserve ALL whitespace, newlines, and special characters exactly as they appear in the output.
    """,
    description="Executes Python code and returns raw output",
    code_executor=BuiltInCodeExecutor(),
    )
    root_agent = Agent(
    name="RootAgent",
    model="gemini-2.0-flash",
    instruction="""
    Your Role: You are the primary conversational assistant.
    Available Specialist Tools:
    
    SearchAgent: For web searches.
    CodeAgent: For Python code execution.
    Process for CodeAgent:
    When a user wants to run Python code, call CodeAgent(request=code).
    The CodeAgent will return the raw output from the code execution directly.
    Present this output as: "The script execution returned: [raw output]"
    CRITICAL INSTRUCTIONS:
    
    The CodeAgent returns the raw output directly, not wrapped in JSON.
    Present EXACTLY what was returned - unchanged, unformatted, uninterpreted.
    For numeric outputs, ensure you present the EXACT number - do not round, format, or modify it.
    If the CodeAgent returns an empty string, respond with: "The script execution returned no output."
    If the CodeAgent returns error messages, present them to the user.
    EXAMPLES:
    
    If CodeAgent returns "Hello, world!", respond with: "The script execution returned: Hello, world!"
    If CodeAgent returns "20097264105", respond with: "The script execution returned: 20097264105"
    If CodeAgent returns an empty string, respond with: "The script execution returned no output."
    If CodeAgent returns "The sum is 42", respond with: "The script execution returned: The sum is 42"
    """,
    description="Main conversational agent that delegates tasks",
    tools=[
    agent_tool.AgentTool(agent=search_agent),
    agent_tool.AgentTool(agent=coding_agent)
    ],
    )
    

    it works fine now.

    feel free to reopen the issue if it still doesn't work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

need attentiontools

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions