OAuth2/OpenAPI not working with subsequent tool calls
Describe the bug
I tried to get user-auth working with an OpenAPI toolset based on this documentation.
The initial user query causes multiple sequential openapi tool calls, the first triggering the authorization flow.
After the adk_request_credential function response was provided with the authorization code following things happen:
- The execution of the first tool call triggering the authorization is resumed
- The authorization code is exchanged against an token
- The API call succeeds
- The next tool call tries to exchange the authorization code against a token, resulting in the error below
- The API call fails
- The tool calls end up in endless loop, starting over resuming of the triggering tool which now fails again
Failed to exchange OAuth2 tokens: invalid_grant: The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.
I tried the flow via dev-ui, as well as via CLI with the provided helper functions.
To summarize: After resuming the execution, the first tool call is able to see the authorization code and get a token correctly. Every subsequent tool call does not see the token, rather only the authorization code and tries to fetch a token again which fails.
The problem does not appear when the initial user query is written in a way that it causes a single tool call.
My assumption is that this has to do with how session state is persisted and loaded.
To Reproduce Steps to reproduce the behavior:
- Follow this documentation
- Use authentication with 2 consecutive tool calls
Expected behavior
I would expect that the second tool call to use the same oauth token as retrieved by the first tool call.
Screenshots
No screenshots available yet.
Desktop (please complete the following information):
- Linux
- Python 3.11.2
- ADK version 1.6.1 (also tried on
a4baa35b847266f1efd7a497b3a36b8220e3eb3a)
Model Information:
- gemini-2.0-flash
Can confirm that we are also facing this bug, even when authentication succeeds.
My reproduction set up is:
- Make sure that the user is not authenticated, create an agent with OpenAPI toolkit
- Query the agent with a query that needs at least 2 tools to succeed
- After successful authentication, the first tool that prompted the authentication pop up will be called over an over again in a loop.
Tracing the code as far as I can, looks like the culprit is located here: https://github.com/google/adk-python/blob/main/src/google/adk/auth/auth_preprocessor.py#L108
@seanzhou1023 I haven't created a working reproducible example, but here is some information on the sequence of Event that is triggering the bug, let me know if it's helpful or if you need more context:
- Event 0, author 'user': user query "what are my open tickets?"
- Event 1, author 'agent': LLM function call "get_user_id". Tool ID
adk-6d2f2261-a090-4b80-881d-37a295f972aa - Event 2, author 'agent': ADK function call "adk_request_credentials" (injected via
functions.generate_auth_event). Tool IDadk-e9cef455-2275-46e8-90aa-471b2a80e725 - Event 3, author 'agent': Function response
pending:Truewith "Needs your authorization to access your data" - Event 4, author 'agent': LLM response "I need you to authorize"
-- End of first run, now the user authorizes via browser pop-up, and a new BaseLlmFlow._run_one_step_async starts, ending up in auth_preprocessor.py after a few more event yields ---
- Event 5, author 'user': Function response for "adk_request_credentials" with oauth tokens
- Event 6, author 'agent': Tool function response for "get_user_id"
- Event 7, author 'agent': LLM function call "get_open_tickets"
- Event 8, author 'agent': Tool function response for "get_open_tickets"
So, because adk_request_credentials with ID adk-e9cef455-2275-46e8-90aa-471b2a80e725 is part of our event history, and because its function_call_id points to get_user_id with ID adk-6d2f2261-a090-4b80-881d-37a295f972aa, we will resolve get_user_id once more as a tool to resume and start invoking it again, starting the infinite loop inside _AuthLlmRequestProcessor.run_async.
Why this only happens when there are 2 (or more) tools, I don't know yet.
Using adk version 1.4.1
@arryon thanks for confirming. I ended up debugging in the exact same spot.
I did some more digging and tried to understand how authentication is handled on other places. It seems that this area is currently being reworked (hence the @experimental).
From what I see, there are 2 paths for authentication:
- The
_AuthLlmRequestProcessor->AuthHandlerwhich is relevant for our case with theOpenAPIToolset/RestAPITool - The
AuthenticatedFunctionTool->CredentialManagerwhich is relevant for theAuthenticatedFunctionTool
Both paths call similar functions underneath, but only the latter is using the newly introduced CredentialService and takes a seemingly more structured approach to the problem , see get_auth_credential.
I have no good ideas how to proceed with this.
Edit: I did try 2 subsequent AuthenticatedFunctionTools to see if this would fix the issue. It does not, unfortunately. Still, it tries to exchange oauth code against a token multiple times and runs in an infinite loop.
Same problem here, thought I was going crazy.. +1
Some more info on the _AuthLlmRequestProcessor.
The implementation consists of 2 loops, both going through the events backwards:
The important part is the second one: It skips the latest event. All earlier events are used for picking tools_to_resume. As soon as there is an event after the tool call which caused the authentication, the endless loop occurs.
I tried different scenarios:
Does loop: - Authenticated Function - Non -uthenticated Function
Does not loop: - Non-Authenticated Function - Authenticated Function
So I tried to come up with a solution for a better condition when not to resume a tool:
@@ -75,8 +75,15 @@ class _AuthLlmRequestProcessor(BaseLlmRequestProcessor):
if not request_euc_function_call_ids:
return
+ seen_responses = set()
for i in range(len(events) - 2, -1, -1):
event = events[i]
+
+ # remember what not to resume
+ for response in event.get_function_responses():
+ if not response.id in event.actions.requested_auth_configs:
+ seen_responses.add(response.id)
+
# looking for the system long running request euc function call
function_calls = event.get_function_calls()
if not function_calls:
@@ -87,6 +94,8 @@ class _AuthLlmRequestProcessor(BaseLlmRequestProcessor):
for function_call in function_calls:
if function_call.id not in request_euc_function_call_ids:
continue
+ if function_call.id in seen_responses:
+ continue
args = AuthToolArguments.model_validate(function_call.args)
tools_to_resume.add(args.function_call_id)
This seems to work at first sight, but I have no idea if this is actually correct. Someone familiar with the code should be able to come up with a better condition I guess.
Having the exact same issue in ADK version 1.8.0 as well.
Same problem on 1.10.0
@kautsig @arryon thanks for reporting the issue. Do you have the agent codes for us to reproduce ? for the two API call, are they share the same auth_scheme and auth_credential ?
I tried to condense it down to the most basic example I could build.
The toolset consists of 2 API calls:
- The first one to retrieve person id based on name
- The second one which retrieves person details based on the person id
Note: OAuth URLs, client id and client secret have been removed.
import datetime
from zoneinfo import ZoneInfo
from google.adk.agents import Agent
from google.adk.auth.auth_credential import AuthCredential, AuthCredentialTypes, OAuth2Auth
from google.adk.auth.auth_schemes import OpenIdConnectWithConfig
from google.adk.models.lite_llm import LiteLlm
from google.adk.tools.openapi_tool.openapi_spec_parser.openapi_toolset import OpenAPIToolset
openapi_spec_string = """
{
"openapi": "3.0.0",
"servers": [{"url": "http://localhost:9123"}],
"paths": {
"/id": {
"get": {
"summary": "Based on a person name returns the person id.",
"operationId": "id",
"description": "Based on a person name returns the person id.",
"parameters": [
{"name": "id", "in": "query", "schema": { "type": "string" }, "description": "person name"}
],
"responses": {
"200": {
"description": "person id",
"content": { "application/json": { "schema": { "type": "string" } } }
}
}
}
},
"/details": {
"get": {
"summary": "Based on a person ID, retrieve the person details.",
"operationId": "details",
"description": "The person details",
"parameters": [
{"name": "id", "in": "query", "schema": { "type": "string" }, "description": "the person details"}
],
"responses": {
"200": {
"description": "the person details"
}
}
}
}
}
}
"""
auth_scheme = OpenIdConnectWithConfig(
authorization_endpoint="...",
token_endpoint="...",
scopes=['openid']
)
auth_credential = AuthCredential(
auth_type=AuthCredentialTypes.OPEN_ID_CONNECT,
oauth2=OAuth2Auth(
client_id="...",
client_secret="...",
)
)
toolset = OpenAPIToolset(
spec_str=openapi_spec_string,
spec_str_type='json',
auth_scheme=auth_scheme,
auth_credential=auth_credential,
)
root_agent = Agent(
name="person_agent",
model=LiteLlm(model="openai/gemini-2.0-flash"),
description=(
"Agent to provide person information."
),
instruction=(
"You are a helpful agent who can provide person information."
"Don't ask for ID's retrieve them by name."
),
tools=[toolset],
)
Here an example conversation. The dev-ui will not recieve any updates from that point on:
In the agent output the message:
The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client
This is repeated all over again which is a symptom of the infinite loop.
Let me know if this is sufficient for you to reproduce.
For completeness, these are the API functions:
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/id", func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if len(auth) == 0 {
fmt.Printf("%+v\n", "no auth header") // output for debug
w.WriteHeader(http.StatusUnauthorized)
return
}
fmt.Printf("%+v\n", r.Header.Get("Authorization")) // output for debug
fmt.Fprintf(w, "1937123120")
})
http.HandleFunc("/details", func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if len(auth) == 0 {
fmt.Printf("%+v\n", "no auth header") // output for debug
w.WriteHeader(http.StatusUnauthorized)
return
}
fmt.Printf("%+v\n", r.Header.Get("Authorization")) // output for debug
fmt.Fprintf(w, "The person likes cats.")
})
log.Fatal(http.ListenAndServe(":9123", nil))
}
@seanzhou1023 I hope the example works for reproducing it. Let me know if I can do something in addition to get this fixed.
Hi @kautsig thanks for the information :) One thing I don't understand is that when you said, In the agent output the message:
The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client
what do you mean by agent output the mesage ? where did it output the message ? you also mentioned The dev-ui will not recieve any updates from that point on, so the message was on the console ? it's the console log of adk web ?
meanwhile could you run adk web with --log_level DEBUG and attach the full console log (with sensitive information redacted) ?
thanks :)
also one thing I don't quite understand, from the screenshot, the first api call also failed / stucked ? but the original issue mentioned that only the send api call will fail. Does the behavior of the issue change recently?
BTW, for the original issue:
1. The execution of the first tool call triggering the authorization is resumed
2. The authorization code is exchanged against an token
3. The API call succeeds
4. The next tool call tries to exchange the authorization code against a token, resulting in the error below
5. The API call fails
6. The tool calls end up in endless loop, starting over resuming of the triggering tool which now fails again
how did second API call trigger ? did you ask some additional question to the agent between 3 & 4 to trigger the second tool call ? and did the web UI popup a new window for you to go through oauth flow for the second tool call ?
Another thing you can try is that , I noticed you are using LiteLlm(model="openai/gemini-2.0-flash") as the model, you can directly specify a str gemini-2.0-flash as the model instead of using LiteLlm. But this seems not relevant to the problem.
Also Google API toolset use the exactly the same interface : https://github.com/google/adk-python/blob/3bc2d77b4d180e9c42b30d4d1ce580aa75abe501/src/google/adk/tools/google_api_tool/google_api_toolset.py#L93
could you compare your codes with it ?
I tested this sample agent : https://github.com/google/adk-python/tree/main/contributing/samples/oauth_calendar_agent
which uses the CalendarToolset (https://github.com/google/adk-python/blob/3bc2d77b4d180e9c42b30d4d1ce580aa75abe501/src/google/adk/tools/google_api_tool/google_api_toolsets.py#L59) that extends the the GoogleApiToolset.
It worked well for me. I'm doubting whether it's som problem with your auth server ?
in this sample, list calendar event is a separate tool, just ignore it. get calendar event and update calendar event are both from same CalendarToolset instance. as you can see those tools are successfully invoked in sequence.
what do you mean by agent output the mesage ? where did it output the message ? you also mentioned The dev-ui will not recieve any updates from that point on, so the message was on the console ? it's the console log of adk web ?
Console log of adk web, yes.
meanwhile could you run adk web with --log_level DEBUG and attach the full console log (with sensitive information redacted) ?
I will try to do that, but need a bit of time to provide the result to ensure it's cleaned properly.
also one thing I don't quite understand, from the screenshot, the first api call also failed / stucked ? but the original issue mentioned that only the send api call will fail. Does the behavior of the issue change recently?
The first api call succeeds, the agent resumes execution based on the result and triggers a the necessary subsequent tool call immediately. The chat ui does not receive an update any more, because this run never finishes.
how did second API call trigger ? did you ask some additional question to the agent between 3 & 4 to trigger the second tool call ? and did the web UI popup a new window for you to go through oauth flow for the second tool call ?
The second call triggers synchonously as a result of the response of the first one. No additional questions asked. Thats why I structured the test tools in a way the outcome of one needs to be used as input of the other: person name -> get person id -> get person details.
Another thing you can try is that , I noticed you are using LiteLlm(model="openai/gemini-2.0-flash") as the model, you can directly specify a str gemini-2.0-flash as the model instead of using LiteLlm. But this seems not relevant to the problem
I will have a look at that...
Also Google API toolset use the exactly the same interface: could you compare your codes with it ?
In your example, your initial prompt does not cause an immediate subsequent tool call after the oauth flow. You could try to immediately prompt the agent to remove someone from the meeting at 10 without getting the event details first. If my understanding is correct, this should trigger the problem, because I would expect the agent to call google_calendar_events_update as a result of the google_calendar_events_get response.
@kautsig thank you so much for your quick response. Now I totally understand the issue :) Do appreciate it. I know the root cause, I will fix it.
@kautsig please try the fix and feel free to reopen if you still see issues.
@seanzhou1023 I see you released the fix already. I upgraded my test project to google-adk==1.13.0, but no success. The infinite loop still occurs (exact same setup as described in https://github.com/google/adk-python/issues/1944#issuecomment-3183024665).
@arryon does the fix work for you?
I will have a look at the points above, as well as the test assertions introduced in the fix.
Sorry, I made a mistake. The fix is not part of 1.13. I tried with main and the problem is fixed. Thanks a lot @seanzhou1023 !