Skip to content

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

Closed

Description

@momo-tuannguyen12

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

Activity

  1. added
    core
    on Jun 23, 2025
  2. momo-tuannguyen12 commented on Jun 23, 2025

    @momo-tuannguyen12
    Author

    Any more information, feel free to ask me provide.

  3. calvingiles commented on Jun 23, 2025

    @calvingiles
    Contributor

    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

  4. calvingiles commented on Jun 23, 2025

    @calvingiles
    Contributor

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

  5. momo-tuannguyen12 commented on Jun 23, 2025

    @momo-tuannguyen12
    Author

    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.

  6. calvingiles commented on Jun 23, 2025

    @calvingiles
    Contributor

    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.

  7. momo-tuannguyen12 commented on Jun 24, 2025

    @momo-tuannguyen12
    Author

    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

  8. hangfei commented on Jun 24, 2025

    @hangfei
    Collaborator

    Could you provide a minimal example to reproduce this?

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

  9. added
    need attention
    on Jun 24, 2025
  10. tgallant commented on Jun 25, 2025

    @tgallant

    @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 841e10a

    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.

  11. added theissue type on Jul 2, 2025
  12. seanzhou1023 commented on Jul 7, 2025

    @seanzhou1023
    Collaborator

    please provide the agent codes and steps to reproduce.

  13. seanzhou1023 commented on Jul 7, 2025

    @seanzhou1023
    Collaborator

    @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

    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.

  14. momo-tuannguyen12 commented on Jul 18, 2025

    @momo-tuannguyen12
    Author

    @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 :-)

  15. PaveLuchkov commented on Jul 20, 2025

    @PaveLuchkov

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

coreneed attention

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions