ValueError: ("Invalid operation: The `response.text` quick accessor requires the response to contain a valid `Part`, but none were returned

I am a Gemini API beginner user, and I am trying to get descriptions of animals that are in a csv file (One animal per row). With the code below, I am getting the error from the title. If I remove the .text from the line “animal_info[‘description’] = response”, it works perfectly.

def generate_descriptions(input_csv, output_csv):
    model = genai.GenerativeModel(
        "gemini-1.5-flash",
        system_instruction="You are a volunteer at an animal shelter. Write a description for an animal in the shelter to help it get adopted. Make your responses in one paragraph.",
    )
    with open(input_csv, 'r', encoding='utf-8') as infile, open(output_csv, 'w', newline='',encoding='utf-8') as outfile:
        reader = csv.DictReader(infile)
        fieldnames = reader.fieldnames + ['description']
        writer = csv.DictWriter(outfile, fieldnames=fieldnames)
        writer.writeheader()

        for animal_info in reader:
            response = model.generate_content(
                generation_config=genai.types.GenerationConfig(
                    max_output_tokens=250,
                    temperature=1.25,
                ),
                contents=f"Write an engaging, informative description for a {animal_info['animal_type']} named {animal_info['name']}. It is {animal_info['age']} years old, {animal_info['color']}, and has been in the shelter for {animal_info['months_in_shelter']} months. Its behavior is {animal_info['behavior']}, its health is {animal_info['health']}, and it is vaccinated: {animal_info['vaccinated']}. Target audience: {animal_info['target_audience']}.",
            )
            response = response.text.strip()
            animal_info['description'] = response
            writer.writerow(animal_info)
            print(f"Generated description for {animal_info['name']}.")
    print(f"Descriptions generated and saved to '{output_csv}'.")
1 Like

Hi @JeffTheNinja57 . Welcome to the forum!

The Value error you are getting represents response doesn’t contain any valid parts. This can happen due to several potential reasons like the Older SDK version or temporary issues with the Gemini API.

Try upgrading your SDK using : pip install --upgrade google-generativeai

Also, Integrate exception handling in your code :

for animal_info in reader:
    try:
        response = model.generate_content(
            generation_config=genai.types.GenerationConfig(
                max_output_tokens=250,
                temperature=1.25,
            ),
            contents= --your prompt--
        
        # Check if the response has content
        if response.parts:
            description = response.text
            animal_info['description'] = description.strip()
        else:
            animal_info['description'] = "No description generated"
        
    except Exception as e:
        print(f"Error generating description for {animal_info['name']}: {str(e)}")
        animal_info['description'] = f"Error: {str(e)}"

    --your code--

If you still get any issue, please feel free to reach out.

Hi,

Thanks a lot for the response! I have had a separate issue, kind of connected to the first one:

For a lot of the datapoints the generator does not work due to safety concerns. I do not know how to set the thresholds to HIGH, as I do not think safety should be a concern.

for example: (the first line is the header and the 2nd is supposed to be the first line of datapoints)

animal_type,name,age,color,months_in_shelter,behavior,health,vaccinated,target_audience,description
dog,Bella,3,black,12,"friendly, energetic",excellent,True,families,"response:
GenerateContentResponse(
    done=True,
    iterator=None,
    result=protos.GenerateContentResponse({
      ""candidates"": [
        {
          ""finish_reason"": ""SAFETY"",
          ""index"": 0,
          ""safety_ratings"": [
            {
              ""category"": ""HARM_CATEGORY_SEXUALLY_EXPLICIT"",
              ""probability"": ""MEDIUM""
            },
            {
              ""category"": ""HARM_CATEGORY_HATE_SPEECH"",
              ""probability"": ""NEGLIGIBLE""
            },
            {
              ""category"": ""HARM_CATEGORY_HARASSMENT"",
              ""probability"": ""NEGLIGIBLE""
            },
            {
              ""category"": ""HARM_CATEGORY_DANGEROUS_CONTENT"",
              ""probability"": ""NEGLIGIBLE""
            }
          ]
        }
      ],
      ""usage_metadata"": {
        ""prompt_token_count"": 89,
        ""total_token_count"": 89
      }
    }),
)"

Hi @JeffTheNinja57

The issue you are getting is due to safety concerns. Change you safety settings to BLOCK_NONE and try to run the code again.

Thanks

Unfortunately, in case that you run into a SAFETY block the candidate in the response doesn’t contain part elements. The text property is a shortcut only, and therefore points at NULL. Hence it’s not working. You would need a check prior to accessing the text property to handle this. Check the FinishReason value to get more details.

In my Gemini SDK for .NET I implemented it more gracious. Feedback to the Google team has been submitted, too.

	public string? Text
    {
        get
        {
            if (Candidates?.FirstOrDefault()?.FinishReason is
                FinishReason.MaxTokens or
                FinishReason.Safety or
                FinishReason.Recitation or
                FinishReason.Other)
                return string.Empty;
            return Candidates?.FirstOrDefault()?.Content?.Parts.FirstOrDefault()?.Text;
        }
    }