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}'.")

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
      }
    }),
)"