File + Code execution causes 500 internal error

I’m having issues when using code execution together with files.
It works correctly in AI studio, but I get errors via the API.

Anyone else run into this issue?

This is my payload:

{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "fileData": {
            "fileUri": "https://generativelanguage.googleapis.com/v1beta/files/SECRET",
            "mimeType": "text/csv"
          }
        }
      ]
    },
    {
      "role": "user",
      "parts": [
        {
          "text": "Calculate the sum of the column 'effect'."
        }
      ]
    }
  ],
  "tools": [
    {
      "codeExecution": {}
    }
  ],
  "generationConfig": {
    "temperature": 1,
    "topK": 40,
    "topP": 0.95,
    "maxOutputTokens": 8192,
    "responseMimeType": "text/plain"
  }
}

I only get this response:

{
  "error": {
    "code": 500,
    "message": "Internal error encountered.",
    "status": "INTERNAL"
  }
}
1 Like

Hi,

Welcome to the forum.

Did you to merge the two parts into one array? The API does not consume two consecutive roles of user in a single request but expects alternating roles of user and model.

Your payload should look like this.

{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "Calculate the sum of the column 'effect'."
        },
        {
          "fileData": {
            "fileUri": "https://generativelanguage.googleapis.com/v1beta/files/SECRET",
            "mimeType": "text/csv"
          }
        }
      ]
    }
  ],
  "tools": [
    {
      "codeExecution": {}
    }
  ],
  "generationConfig": {
    "temperature": 1,
    "topK": 40,
    "topP": 0.95,
    "maxOutputTokens": 8192,
    "responseMimeType": "text/plain"
  }
}

Also, counter check whether your MIME type is an accepted one. If not sure, use text/plain instead.

Cheers.

I am encountering the same issue as Fredrik_Nordell and this does not solve the issue. I am using Gemini Flash 2.0.

I am submitting a list of contents in Python, where each content alternates between user and assistant. Even a single user content element with two parts, where the first part is file data pointing to a “text/plain” file in Google Files (with just the word “Hey” in it) and the second part is a message asking the model to describe what is in the file, will cause the API to fail with a 500 internal server error.

This seems to be a fundamental error with Google’s API rather than a user error.

Hi there,

Interesting, here is a working JSON payload from my test cases I’m running for the Gemini SDK for .NET

{
  "model" : "models/gemini-2.0-flash",
  "contents" : [ {
    "role" : "user",
    "parts" : [ {
      "text" : "Transcribe this audio into english texts. Break the text into small logical segments. Include punctuation where appropriate. Timestamps should have milli-second level accuracy.\n\nOutput the segments in the SRT format:\n\nsubtitle_id\nstart_time \\u2192 end_time\ncontent"
    }, {
      "fileData" : {
        "fileUri" : "https://generativelanguage.googleapis.com/v1beta/files/nf5m6c59czbf",
        "mimeType" : "audio/mpeg"
      }
    } ]
  } ]
}

This gets processed and comes back as HTTP 200.

Let me quickly check with CodeExecution and GenerationConfig.

Hi again,

I took the OP’s initial post as reference and created a test case for my Gemini SDK for .NET regarding CodeExecution and it worked as expected.

First, I created a CSV file with sample data using Gemini Code Assist with the following prompt: "Generate sample data in CSV format using the following columns: date, temperature, effect. The column “effect” is an integer value "

And then replayed the same options and configuration parameters to create the payload like this:

{
  "model" : "models/gemini-2.0-flash",
  "contents" : [ {
    "role" : "user",
    "parts" : [ {
      "text" : "Calculate the sum of the column 'effect'."
    }, {
      "fileData" : {
        "fileUri" : "https://generativelanguage.googleapis.com/v1beta/files/t6it3a0icapu",
        "mimeType" : "text/csv"
      }
    } ]
  } ],
  "generationConfig" : {
    "temperature" : 1,
    "topP" : 0.95,
    "topK" : 40,
    "maxOutputTokens" : 8192,
    "responseMimeType" : "text/plain"
  },
  "tools" : [ {
    "codeExecution" : { }
  } ]
}

So, now comes the very interesting part! The request depends on the model.

  • models/gemini-1.5-flash = HTTP 200
  • models/gemini-2.0-flash = HTTP 500
  • models/gemini-2.0-flash-thinking-exp = HTTP 200
  • models/gemini-2.0-pro-exp = HTTP 200

I assume this should probably be escalated to the team, @GUNAND_MAYANGLAMBAM

BTW, here’s the code execution part in Python generated and run by Gemini 2.0 Flash Thinking.

import pandas as pd

df = pd.read_csv('input_file_0.csv')
print(df.head())

         date  temperature  effect
0  2024-01-01           25       1
1  2024-01-02           32       2
2  2024-01-03           18       1
3  2024-01-04           10       0
4  2024-01-05            5      -1

import pandas as pd

df = pd.read_csv('input_file_0.csv')
effect_sum = df['effect'].sum()
print(f'Sum of the effect column: {effect_sum}')

Sum of the effect column: 14

The sum of the 'effect' column is 14.

Cheers

1 Like

Hey jkirstaetter, thanks for taking the effort to replicate the problem. I have also come to the conclusion that the issue only occurs when code execution is enabled; the same query with the same parts without code execution succeeds.

Does anything in particular have to be done to escalate it to the team?

Hi

I already tagged Gunand hoping he escalates to the team.
Otherwise, file an issue here: https://issuetracker.google.com

Cheers

1 Like

Maybe tagging @Vishal could help here? :slight_smile:

Hey, thanks for raising the issue. I have also tested with all other models, and it seems like there is some issue with gemini-2.0-flash.

I have escalated the issue.

Thanks.

3 Likes

Thanks for everyone’s reply! This got put into my spam-folder :slight_smile:

It seems like there’s a slight change from last week, since now I get this error instead:

{
  "error": {
    "code": 400,
    "message": "File https://generativelanguage.googleapis.com/v1beta/files/wx5ulupyy73i not exist in the Gemini API.",
    "status": "INVALID_ARGUMENT"
  }
}

Hi @Fredrik_Nordell

Well, files uploaded to File API have a lifetime of 48 hours only and are deleted automatically.

Cheers.

Thanks! Though I get this even if I just uploaded the file.

(sorry for late reply)

If I manually go to the file I have the following status:

{
  "name": "files/kf4f65u8han",
  "mimeType": "application/json",
  "sizeBytes": "20991",
  "createTime": "2025-03-04T07:44:03.622406Z",
  "updateTime": "2025-03-04T07:44:03.622406Z",
  "expirationTime": "2025-03-06T07:44:03.473004224Z",
  "sha256Hash": "MDZiNDlkYjg4NjM4OGJhODhlZWZlOGE5ZjVmNDQwMDUyNGI5ZmRjNzk5NGE4ZTM2NTg4ZDk0MDkwMDU0OTNiOQ==",
  "uri": "https://generativelanguage.googleapis.com/v1beta/files/kf4f65u8han",
  "state": "ACTIVE",
  "source": "UPLOADED"
}

The issue seems to be fixed. Let me know if you are still facing the issue

I still have an issue with 400 error, please tell me if you can see any obvious errors in my code.
I’ve tried with ensuring that the file is fully uploaded and accessible, but with the same error.

Let me provide a full example of my test code:

#!/bin/bash
set -euo pipefail

# Replace with your actual API key
API_KEY=""

# Define the single file and its MIME type.
FILE="test.csv"
MIME_TYPE="text/csv"

# Verify the file exists.
if [[ ! -f "$FILE" ]]; then
  echo "Error: File '$FILE' not found."
  exit 1
fi

# Calculate file size in bytes.
NUM_BYTES=$(wc -c < "$FILE")
echo "Uploading $FILE ($NUM_BYTES bytes, MIME type: $MIME_TYPE)..."

# Upload the file and capture the response.
RESPONSE=$(curl -s "https://generativelanguage.googleapis.com/upload/v1beta/files?key=${API_KEY}" \
  -H "X-Goog-Upload-Command: start, upload, finalize" \
  -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
  -H "Content-Type: application/json" \
  -d "{\"file\": {\"display_name\": \"${FILE}\"}}" \
  --data-binary "@${FILE}")

# Parse the file URI from the response.
FILE_URI=$(echo "$RESPONSE" | jq -r '.file.uri')
if [[ "$FILE_URI" == "null" || -z "$FILE_URI" ]]; then
  echo "Error: Failed to retrieve file URI. Response: $RESPONSE"
  exit 1
fi

# Define the file URI as FILE_URI_0 (as in the original sample).
export FILE_URI_0="${FILE_URI}"
echo "Uploaded file URI: $FILE_URI_0"

# Prepare the JSON payload with two separate content objects.
PAYLOAD=$(cat <<EOF
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "fileData": {
            "fileUri": "${FILE_URI_0}",
            "mimeType": "text/csv"
          }
        }
      ]
    },
    {
      "role": "user",
      "parts": [
        {
          "text": "Calculate the sum of the effect column"
        }
      ]
    }
  ],
  "generationConfig": {
    "temperature": 1,
    "topK": 40,
    "topP": 0.95,
    "maxOutputTokens": 8192,
    "responseMimeType": "text/plain"
  }
}
EOF
)

echo "Payload:"
echo "$PAYLOAD" | jq '.'

# Send the generateContent request.
echo "Sending generateContent request..."
curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${API_KEY}" \
  -H 'Content-Type: application/json' \
  -d "$PAYLOAD"

echo "Done."

With the following csv:

date,effect,spend
2023-01-01, 100, 50
2023-02-01, 150, 100
2023-03-01, 100, 50

I get the following response:

Uploading test.csv (   20934 bytes, MIME type: text/csv)...
Uploaded file URI: https://generativelanguage.googleapis.com/v1beta/files/brcxbdn87y8
Payload:
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "fileData": {
            "fileUri": "https://generativelanguage.googleapis.com/v1beta/files/brcxbdn87y8",
            "mimeType": "text/csv"
          }
        }
      ]
    },
    {
      "role": "user",
      "parts": [
        {
          "text": "Calculate the sum of the effect column"
        }
      ]
    }
  ],
  "generationConfig": {
    "temperature": 1,
    "topK": 40,
    "topP": 0.95,
    "maxOutputTokens": 8192,
    "responseMimeType": "text/plain"
  }
}
Sending generateContent request...
{
  "error": {
    "code": 400,
    "message": "File https://generativelanguage.googleapis.com/v1beta/files/brcxbdn87y8 not exist in the Gemini API.",
    "status": "INVALID_ARGUMENT"
  }
}
Done.

Hello @Fredrik_Nordell

Yes, the “obvious” error is in your final payload. :smile_cat:

It is not allowed to have two or more consecutive Content objects with the same role.
See my previous post and merge your text and fileData parts into a single Content object with role user.

# Prepare the JSON payload with two separate content objects. BAD REQUEST!
# Prepare the JSON payload with two Part objects. OK!
PAYLOAD=$(cat <<EOF
{
  "contents": [ {
      "role": "user",
      "parts": [ {
          "fileData": {
            "fileUri": "${FILE_URI_0}",
            "mimeType": "text/csv"
          }
        },
        {
          "text": "Calculate the sum of the effect column"
        } ]
    } ],
  "generationConfig": {
    "temperature": 1,
    "topK": 40,
    "topP": 0.95,
    "maxOutputTokens": 8192,
    "responseMimeType": "text/plain"
  }
}
EOF
)

In case that you want to use multiple Content objects then you have to alternate between the roles of user and model.

# Prepare the JSON payload with multiple Content objects using alternating roles. OK!
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "fileData": {
            "fileUri": "https://generativelanguage.googleapis.com/v1beta/files/brcxbdn87y8",
            "mimeType": "text/csv"
          }
        }
      ]
    },
    {
      "role": "model",
      "parts": [
        {
          "text": "OK"
        }
      ]
    },
    {
      "role": "user",
      "parts": [
        {
          "text": "Calculate the sum of the effect column"
        }
      ]
    }
  ],
  "generationConfig": {
    "temperature": 1,
    "topK": 40,
    "topP": 0.95,
    "maxOutputTokens": 8192,
    "responseMimeType": "text/plain"
  }
}

Hope this helps.

Cheers.

@jkirstaetter but it’s a bit strange since in AIstudio when you click on “get code” you get it as two separate parts.

And it seems like I get the same error if I provide 2 parts objects.

PAYLOAD=$(cat <<EOF
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "fileData": {
            "fileUri": "https://generativelanguage.googleapis.com/v1beta/files/2ug1y4bnlkgj",
            "mimeType": "text/csv"
          }
        },
        {
          "text": "Calculate the sum of the effect column."
        }
      ]
    }
  ],
  "tools": [
    {
      "codeExecution": {}
    }
  ],
  "generationConfig": {
    "temperature": 1,
    "topK": 40,
    "topP": 0.95,
    "maxOutputTokens": 8192,
    "responseMimeType": "text/plain"
  }
}
EOF
)

And I get an error when I provide a model part:

PAYLOAD=$(cat <<EOF
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "fileData": {
            "fileUri": "https://generativelanguage.googleapis.com/v1beta/files/2ug1y4bnlkgj",
            "mimeType": "text/csv"
          }
        }
      ]
    },
    {
      "role": "model",
      "parts": [
        {
          "text": "OK"
        }
      ]
    },
    {
      "role": "user",
      "parts": [
        {
          "text": "Calculate the sum of the effect column"
        }
      ]
    }
  ],
  "tools": [
    {
      "codeExecution": {}
    }
  ],
  "generationConfig": {
    "temperature": 1,
    "topK": 40,
    "topP": 0.95,
    "maxOutputTokens": 8192,
    "responseMimeType": "text/plain"
  }
}
EOF
)

Thanks!

Hi @Fredrik_Nordell

Tried it with a different model?
As stated above that’s the payload I generate in my Gemini SDK for .NET and it works.

Maybe you build up your PAYLOAD from scratch and see when exactly the error occurs.

Cheers

Hi! @jkirstaetter

Yes, the gemini-2.0-flash-thinking-exp-01-21 model works fine, even with the multiparts. I’m only having this issue with “gemini-2.0-flash”

Thanks!

It’s also enough to remove the part containing the file to get a working response.
aka, removing this part:

        {
          "fileData": {
            "fileUri": "${FILE_URI}",
            "mimeType": "${MIME_TYPE}"
          }
        },

Finally, I found the issue now. I had the wrong content-type, which didn’t match the MIME_TYPE.

If I changed it to text/csv it’s working.

Thanks for the help everyone :slight_smile:

1 Like