google-gemini / generative-ai-python

The official Python library for the Google Gemini API
https://pypi.org/project/google-generativeai/
Apache License 2.0
1.58k stars 314 forks source link

Response.text raises an exception when only a function call is returned #532

Closed JeremyEastham closed 1 month ago

JeremyEastham commented 2 months ago

Description of the bug:

The GenerateContentResponse.text property sometimes raises an exception when no text is returned from the API. The documentation states that this property is equivalent to response.candidates[0].content.parts[0].text, but accessing that property does not always raise an exception when response.text does. One of these cases is when the model responds by calling a function without any text, which leads to an error when parsing the parts list.

Actual vs expected behavior:

Minimal example:

import google.generativeai as genai

def my_tool():
    pass

genai.configure( api_key = ... )
model = genai.GenerativeModel( model_name = "gemini-1.5-flash", tools = [ my_tool ] )
chat = model.start_chat()
response = chat.send_message( "I'm trying to test my tool. Please call it for me." )
assert response.candidates[0].content.parts[0].text == "" # Succeeds
print( response.text ) # Expected: "" or None

# Traceback (most recent call last):
#   File "C:\Users\...\bug.py", line 13, in <module>
#     print( response.text ) # Expected: "" or None
#            ^^^^^^^^^^^^^
#   File "C:\Users\...\venv\Lib\site-packages\google\generativeai\types\generation_types.py", line 465, in text
#     part_type = protos.Part.pb(part).whichOneof("data")
#                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# AttributeError: whichOneof. Did you mean: 'WhichOneof'?

Any other information you'd like to share?

Related Issues:

Gunand3043 commented 2 months ago

Hi @JeremyEastham , Since you haven't set the parameter 'enable_automatic_function_calling=True', you will need to manually call the function by yourself to get the generated text response. For reference please check the link.

github-actions[bot] commented 1 month ago

Marking this issue as stale since it has been open for 14 days with no activity. This issue will be closed if no further activity occurs.

github-actions[bot] commented 1 month ago

This issue was closed because it has been inactive for 28 days. Please post a new issue if you need further assistance. Thanks!