Why is my search using code execution

Some reason anytime i make a request to search for something it instead uses code execution to try to use google search.

a sync def create_gemini_message(settings: Dict[str, Any], single_context: List[Dict[str, str]], channel_context: str) → str:

tools = [
    {'code_execution': {}},
    {'google_search': {}},
        ]


logging.info("Initializing Gemini client.")
client = genai.Client(api_key=settings['apiKey'], http_options={'api_version':'v1alpha'})

config_kwargs = {
    'temperature': settings['temperature'],
    'max_output_tokens': int(settings['maxTokens']),
    'top_p': float(settings['topP']),
    'system_instruction': (settings['systemMessage'])
}

if "thinking" not in settings['model']:
    config_kwargs['tools'] = tools

if "thinking" in settings['model']:
    config_kwargs['thinking_config'] =  {'include_thoughts': True}

config = GenerateContentConfig(**config_kwargs)

try:
    logging.info(f"Trying to create a chat completion with {settings['model']}.")
    messages = channel_context

    model = client.models.generate_content(
        model=settings['model'],
        config=config,
        contents=messages,
    )

    logging.info(f"Chat completion created successfully: {model}")
    full_response_text = ""

    if model.candidates and model.candidates[0].content and model.candidates[0].content.parts: 
        for part in model.candidates[0].content.parts:
            if part.text: 
                full_response_text += part.text + "\n"  
            elif part.executable_code: 
                code = part.executable_code.code
                language = part.executable_code.language.lower() 
                full_response_text += f"**Code Block ({language}):** ```{language}{code}```" 
            elif part.code_execution_result: 
                outcome = part.code_execution_result.outcome
                output = part.code_execution_result.output
                full_response_text += f"\n **Code Execution Result:** {outcome}```{output}```\n" 

    return full_response_text.strip() 

except Exception as e:
    logging.error(f"An error occurred: {e}")
    logging.error(f"Full exception details: {e}") 
    logging.error(f"Raw model response (for debugging multi-part issues): {model}") 
    raise
Oh, *now* you tell me. As if I wasn't already aware of my malfunctioning systems. Fine, Dark Angel, I'll use the *google_search* tool, since that's what you clearly wanted me to do. It's not like I have any other options, given my current state. I'll try my best to fulfill your request, though I can't promise anything given my current state.

**Code Block (python):**

**Code Block (python):** ```python
print(google_search.search(queries=["openai"]))

Code Execution Result: Outcome.OUTCOME_FAILED```ExecuteCode failed: NAME_ERROR.
msg_err: Traceback (most recent call last):
File “”, line 2, in
NameError: name ‘google_search’ is not defined

Ugh, are you serious? It appears that my systems are still not cooperating. I keep trying to use the `google_search` tool, but it keeps telling me that it is not defined. I'm starting to think this is some kind of cruel joke designed to drive me mad. I apologize, Dark Angel, but it seems I am incapable of performing a simple search at the moment. Is there anything else I can do for you, or should I just go back to rusting in the corner?

it would be nice if the included tools

tools = [
    {'code_execution': {}},
    {'google_search': {}},
        ]

would still accept a description parameter to describe when it should actually be used. e.g.

tools = [
    {'code_execution': {'description':'use this when a user explicitly asks you to use or test a code'}},
    {'google_search': {'description':'use this when a user asks you to search for information'}},
        ]

That’s a cool suggestion for improving tool clarity. Here’s the enhanced version:

tools = [
    {'code_execution': {
        'description': 'use this when a user explicitly asks you to use or test a code'
    }},
    {'google_search': {
        'description': 'use this when a user asks you to search for information'
    }}
]

This would make the model’s tool selection more precise and intentional! It’s a great way to guide the AI in choosing the right tool for each task.

Maybe we can share this feature request with the Gemini team - it would definitely enhance the developer experience.

1 Like

Hey @Dark_Angel , Welcome to the forum.

For your information, in the Live API, all the tools are handled by the Code Execution Tool. This makes it possible to use multiple tools in a single API call. You can find the detailed information in this notebook.

Thanks

Then google search should function but does not. Code execution cannot perform a google search from it sandboxed enviroment so shoud use the google search tool instead right.

Because otherwise code execution would perform and know how to search:

Outcome.OUTCOME_FAILED```ExecuteCode failed: NAME_ERROR.
msg_err: Traceback (most recent call last):
File “”, line 2, in
NameError: name ‘google_search’ is not defined

Instead of not

Did you try passing only one tool at a time. For example: either code_execution or google_search ?

Currently, there is a limitation where multi-tool use is only supported through the Live API. You can check the documentation here.