Hello, community and Google team!
I’ve encountered an issue with the Gemini API that I’ve been trying to resolve. I had previously determined the problem using a code fix, but the actual cause of the error differed from my fix before.
After further testing and research, I discovered that the error occurs when you provide two, four, six, or other even number of user turns. For instance:
user: Hi.
user: Please run the test function.
model: Ok. (RUN THE TEST FUNCTION)
<ERROR 400>
As we understand, the role
of a Content Object should be either user
, model
, or function
. However, the error message suggests Please ensure that function call turns come immediately after a user turn or after a function response turn.
This implies the model shouldn’t call functions after a model turn.
So, why does the error occur when the previous turn is a role: "user"
turn? I suspect that the Gemini API may not use the value of role
to identify user and model contents. Instead, it uses the index of the content. Therefore, the first content would be user
, the second would be model
, and the third would be user
again.
As a result, the Gemini API might interpret the previous example like this:
user: Hi.
model: Please run the test function.
user: Ok. (RUN THE TEST FUNCTION)
<ERROR 400>
Notice that the Gemini API doesn’t verify if the function is called by the model; it only checks the functionCall
part.
This also explains why the model shouldn’t call functions after a model turn. It might be perceived as the user calling a function.
By the way, if you try to trigger this error in AI Studio, it won’t work because AI Studio automatically creates two user messages into one Content
but in two Part
s.
I believe this is a bug in the Gemini API that needs to be fixed. Alternatively, if the API is designed to use the content index instead of role
, it should provide a clearer error message, such as User turn should be used at the start or immediately after a model turn.
As another proof, I got the following contents:
[
{
"role": "user",
"parts": [
{
"text": "hi."
}
]
},
{
"role": "user",
"parts": [
{
"text": "Hello, nice to meet you."
}
]
},
{
"role": "user",
"parts": [
{
"text": "Repeat the previous message you say."
}
]
},
{
"parts": [
{
"text": "Hello, nice to meet you.\n"
}
],
"role": "model"
}
]