adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

Error INVALID_ARGUMENT: Please ensure that function call turn comes immediately after a user turn or after a function response turn

Open momo-tuannguyen12 opened this issue 1 year ago • 12 comments

Describe the bug INVALID_ARGUMENT. {'error': {'code': 400, 'message': 'Please ensure that function call turn comes immediately after a user turn or after a function response turn.', 'status': 'INVALID_ARGUMENT'}}

User turn: [{message: "Help me", role: "user"] Model turn: [{message: "How I can help you today", role: "user"] // why agent response but role is "user"

When I got above error, I see the role is "user" instead of "model"

The error occurs RANDOMLY

Desktop (please complete the following information):

  • Python version(python -V): 3.10
  • ADK version(pip show google-adk): 1.2.1

Additional context I use remote mysql database session

momo-tuannguyen12 avatar Jun 23 '25 02:06 momo-tuannguyen12

Any more information, feel free to ask me provide.

momo-tuannguyen12 avatar Jun 23 '25 03:06 momo-tuannguyen12

~I have been investigating issues of this nature for some time, and came to the conclusion that this is, in some instances, an issue with the way the_ContentLlmRequestProcessor handles multiple function responses. I have created some test cases and a fix in #1582 .~

~Can you have a look at the branch on my fork to see if this addresses the issues for you?~

~calvingiles:bug/fix-function-parts-rewriting~

calvingiles avatar Jun 23 '25 03:06 calvingiles

Apologies - reading the details of your bug this looks unrelated actually - you have no function calls involved in your scenario. Disregard my above comment.

calvingiles avatar Jun 23 '25 03:06 calvingiles

Apologies - reading the details of your bug this looks unrelated actually - you have no function calls involved in your scenario. Disregard my above comment.

I send request -> Agent handle -> call tool -> success -> tool return response to agent Agent write to session but the role is "user", then the error above occurs.

momo-tuannguyen12 avatar Jun 23 '25 04:06 momo-tuannguyen12

Interesting. It is probably worth sharing more detailed steps that you took when this occurred. Also, if you can increase the logging verbosity it may give you more information to use when tracking this down.

calvingiles avatar Jun 23 '25 08:06 calvingiles

Contents: {"parts":[{"function_call":{"args":{"agent_name":"ai_assistant_agent"},"name":"transfer_to_agent"}}],"role":"model"} {"parts":[{"function_response":{"name":"transfer_to_agent","response":{"result":null}}}],"role":"user"} {"parts":[{"text":"['tuan.nguyen12: @BotGymD đọc nội dung trong này dùm tao https://static.momocdn.net/app/json/utilities/simContentV08.json']"}],"role":"user"} {"parts":[{"text":"For context:"},{"text":"[ai_assistant_agent] said: Ê thằng khứa kia, mày đưa tao cái link rồi kêu tao đọc thì tao cũng chịu chết thôi. Tao đâu có tay chân mà click vô đó đọc được. 🙄\n\nMày có muốn tao thử tìm xem cái file JSON đó nó nói về cái gì không? Hoặc nếu mày có nội dung của nó thì quăng đây tao xem thử coi có gì hay ho không. Chứ đưa mỗi cái link không thì tao bó tay chấm com rồi."}],"role":"user"} #------> why role user? {"parts":[{"text":"['tuan.nguyen12: @BotGymD tao quăng cái link nè https://static.momocdn.net/app/json/utilities/simContentV08.json']"}],"role":"user"} # retry 1 {"parts":[{"text":"['tuan.nguyen12: @BotGymD tao quăng cái link nè https://static.momocdn.net/app/json/utilities/simContentV08.json']"}],"role":"user"} # retry 1 {"parts":[{"text":"['tuan.nguyen12: @BotGymD tao quăng cái link nè https://static.momocdn.net/app/json/utilities/simContentV08.json']"}],"role":"user"} # retry 1

Functions: transfer_to_agent: {'agent_name': {'type': <Type.STRING: 'STRING'>}}

INFO:google_genai.models:AFC is enabled with max remote calls: 10. INFO:httpx:HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-04-17:generateContent "HTTP/1.1 400 Bad Request" 2025-06-24 13:40:36 - ERROR - backend.app.agents.reasoning_agent - Reasoning error (attempt 3/3): 400 INVALID_ARGUMENT. {'error': {'code': 400, 'message': 'Please ensure that function call turn comes immediately after a user turn or after a function response turn.', 'status': 'INVALID_ARGUMENT'}}

Please ignore logic of retrying in "Reasoning error (attempt 3/3)"

@calvingiles


Valid turns ontents: {"parts":[{"text":"['tuan.nguyen12: @BotGymD tao quăng cái link nè https://static.momocdn.net/app/json/utilities/simContentV08.json']"}],"role":"user"} {"parts":[{"text":"For context:"},{"text":"[reasoning_agent] called tool transfer_to_agent with parameters: {'agent_name': 'ai_assistant_agent'}"}],"role":"user"} {"parts":[{"text":"For context:"},{"text":"[reasoning_agent] transfer_to_agent tool returned result: {'result': None}"}],"role":"user"} {"parts":[{"text":"Tao thấy cái link mầy quăng rồi đó. Giờ mầy muốn tao làm gì với cái link này? Nói nghe coi, thằng khứa."}],"role":"model"} # -----> MODEL {"parts":[{"text":"['tuan.nguyen12: @BotGymD đọc nội dung trong link đó đi']"}],"role":"user"} {"parts":[{"text":"Thằng khứa này láo, bắt tao đọc link nữa! Tao nói mầy nghe, tao là AI, không có tay có mắt mà click vô link đọc như mầy được.\n\nNhưng mà... nếu mầy máu, tao có thể thử "ngó" qua cái link đó bằng cách tìm kiếm trên internet coi nó là cái gì. Mầy có muốn tao tìm kiếm thông tin chuyên sâu hơn về nội dung cái link này trên internet không? Tao có thể cung cấp thông tin cập nhật và chi tiết hơn cho mầy. Chịu không?"}],"role":"model"} # -----> MODEL

momo-tuannguyen12 avatar Jun 24 '25 06:06 momo-tuannguyen12

Could you provide a minimal example to reproduce this?

Could you switch to in-memory session to see if the issue persists?

hangfei avatar Jun 24 '25 20:06 hangfei

@hangfei @seanzhou1023

I have also encountered this same exception.

I have an analysis I'd like to share.

In our case we are using MySQL as the session backend.

In the database the "timestamp" for an event is a mysql DATETIME() object. This type of object only has precision up to a second.

In the problematic cases the user message event and the tool call event take place in the same second.

That means they will have the same timestamp in the db.

That means when the events are ordered by timestamp they aren't always going to be in the correct order.

When events are in an incorrect order, that is when we get the INVALID_ARGUMENT exception.

Running this against the db fixed the problem. We are not getting the INVALID_ARGUMENT exception anymore after this.

ALTER TABLE events MODIFY COLUMN timestamp DATETIME(6);

This command updates the timestamp column to have microsecond precision.

I see this commit is already present in the repo which implements the fix https://github.com/google/adk-python/commit/841e10ae353e0b1b3d020a26d6cac6f37981550e

In our case we initially set up our db prior to this fix being in place so our db was just in a bad state.

tgallant avatar Jun 25 '25 22:06 tgallant

please provide the agent codes and steps to reproduce.

seanzhou1023 avatar Jul 07 '25 23:07 seanzhou1023

@tgallant thank you so much for the investigation. I think what you mentioned totally make sense.

@momo-tuannguyen12 the role issue you noticed is as expected, this happens after we did agent transfer , we try to convert contents generated by other agent (before agent transfer) from user perspective to improve agent quality. e.g. if agent A said "I'm a good boy", and then transfer to agent B, we will construct the history/contents for agent B like below : User said, "For context, agent A said : 'I'm a good boy'. " see https://github.com/google/adk-python/blob/bf39c006102ef3f01e762e7bb744596a4589f171/src/google/adk/flows/llm_flows/contents.py#L232 for details. That's not the root cause of the issue. What @tgallant mentioned above is the root cause. please verify and reopen the issue if you found something different.

seanzhou1023 avatar Jul 07 '25 23:07 seanzhou1023

@tgallant thank you so much for the investigation. I think what you mentioned totally make sense.

@momo-tuannguyen12 the role issue you noticed is as expected, this happens after we did agent transfer , we try to convert contents generated by other agent (before agent transfer) from user perspective to improve agent quality. e.g. if agent A said "I'm a good boy", and then transfer to agent B, we will construct the history/contents for agent B like below : User said, "For context, agent A said : 'I'm a good boy'. " see

adk-python/src/google/adk/flows/llm_flows/contents.py

Line 232 in bf39c00

filtered_events.append( for details. That's not the root cause of the issue. What @tgallant mentioned above is the root cause. please verify and reopen the issue if you found something different.

Thanks, I just update DATETIME field in event table. I will reopen this issue if the error occurs again :-)

momo-tuannguyen12 avatar Jul 18 '25 07:07 momo-tuannguyen12

I encouraged with the same issue. Have an agent that simply creates events in calendar.

CreateAgent = Agent(
    name="CrateActionAgent",
    model=blueprint,
    instruction=prompt.Actions,
    output_key='actions_made',
    after_agent_callback=after_actions,
    include_contents='none',
    tools = [calendarCreateTool],
    planner=thinkging()
)

If I exclude contents it raises me with error after receiving tool result and evaluation starts.

  File "/opt/anaconda3/envs/cii/lib/python3.11/site-packages/tenacity/asyncio/__init__.py", line 114, in __call__
    result = await fn(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/anaconda3/envs/cii/lib/python3.11/site-packages/google/genai/_api_client.py", line 1027, in _async_request_once
    await errors.APIError.raise_for_async_response(response)
  File "/opt/anaconda3/envs/cii/lib/python3.11/site-packages/google/genai/errors.py", line 155, in raise_for_async_response
    raise ClientError(status_code, response_json, response)
google.genai.errors.ClientError: 400 INVALID_ARGUMENT. {'error': {'code': 400, 'message': 'Please ensure that function call turn comes immediately after a user turn or after a function response turn.', 'status': 'INVALID_ARGUMENT'}}

But if I include content it goes on perfectly.

PaveLuchkov avatar Jul 20 '25 06:07 PaveLuchkov