Add endpoint to update session state
Currently, there's no official way to externally trigger a state update for a given session via the FastAPI cli. For use cases where session state needs to be updated outside of a user-generated message (e.g., programmatic changes based on UI selections, time-based triggers, external data), it would be very useful to expose a dedicated endpoint for this.
Proposed endpoint:
import time
from fastapi.responses import JSONResponse
from ..events.event_actions import EventActions
@app.post(
"/apps/{app_name}/users/{user_id}/sessions/{session_id}/state",
response_model_exclude_none=True,
)
def update_session_state(
app_name: str,
user_id: str,
session_id: str,
state_changes: dict[str, Any],
) -> JSONResponse:
try:
logger.info(f"Updating session state for app='{app_name}', user='{user_id}', session='{session_id}'")
logger.debug(f"State changes to apply: {state_changes}")
session = get_session(app_name, user_id, session_id)
logger.debug(f"Retrieved session: {session.id if session else 'None'}")
actions_with_update = EventActions(state_delta=state_changes)
system_event = Event(
invocation_id="inv_login_update",
author="system",
actions=actions_with_update,
timestamp=time.time()
)
session_service.append_event(session, system_event)
return JSONResponse(
status_code=200,
content={"message": "Session state updated successfully."}
)
except Exception as e:
logger.exception("Failed to update session state")
raise HTTPException(status_code=500, detail=str(e))
Tested and confirmed working:
API call:
curl -X 'POST' \
'http://localhost:8080/apps/agent/users/1/sessions/191/state' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{"dummy": "modified"}'
Response:
{
"message": "Session state updated successfully."
}
After checking the session state, the update was correctly applied.
Use cases:
- Enable frontend or external tools to patch session state dynamically
- Support admin overrides, onboarding flows, and progressive profile enrichment
- Avoids the need to trigger a message just to change state
Hi @triangle-z , now that we support update the state through the AgentRun (see: https://github.com/google/adk-python/commit/3f9f773d9b5fcca343e32f76f6d5677b7cf4c327). You can send state update along with the chat message
Hi @triangle-z , now that we support update the state through the AgentRun (see: https://github.com/google/adk-python/commit/3f9f773d9b5fcca343e32f76f6d5677b7cf4c327). You can send state update along with the chat message
Clicking on commit hash makes it seem like the code to allow stateDeltas to be sent were removed. Tried to make a run call on version 1.9.0 with stateDelta and this was not working. Could we get an example curl request where this is working and state is updated?
Hi @MiguelHuerta88 , the change for state_delta is still there (https://github.com/google/adk-python/blob/v.1.9.0/src/google/adk/cli/adk_web_server.py#L160).
In adk web, you can send the state_delta along with your chat message in the chat box when you click on the 3 dot button.
In FastAPI you just send the update inside the AgentRunRequest.
Example request body:
{
"appName": "my app",
"userId": "user",
"sessionId": "abc",
"newMessage": {
"parts": [
{
"text": "Hello"
}
],
"role": "user"
},
"stateDelta": {
"key": "value"
}
}
@DeanChensj thanks for the quick reply. I just retested again and it was working as expected when using run_sse. I was trying to use run endpoint. That might've been what I did wrong
What if you just want to update the stateDelta but not have the agent generate a response? There's an API for VertexAISessionService and it'll be good if there's a consistent API on local development as well -- otherwise, we're just creating a lot of branching between local dev and using Agents Engine.
Hi, thanks for the replies about possible solutions, but in official doc there is this example:
Sessions store the state and event history for a specific user's interaction with an agent.
Create or Update a Session Creates a new session or updates an existing one. If a session with the given IDs already exists, its state will be overwritten with the new state provided.
Method: POST Path: /apps/{app_name}/users/{user_id}/sessions/{session_id} Request Body
{ "state": { "key1": "value1", "key2": 42 } } Example Request
curl -X POST http://localhost:8000/apps/my_sample_agent/users/u_123/sessions/s_abc
-H "Content-Type: application/json"
-d '{"state": {"visit_count": 5}}'
Currently, if I try this example, I will get "Session already exist:" error, according to this logic
Going forward, I would either expect to:
- not get this error, and updated state
- separate endpoint for state updates
My use-case: I want to store custom session title there and other meta info about session that isn't supported out of the box
Looking forward for your response @DeanChensj
Hello everyone, is there some updates on this issue ? We're working on a similar use case with my team, and I'd love to contribute. @NazariiShvets even if you could make it work, your exemple doesn't fit our needs : we have several agents running, and by updating the whole state, we could possibly fall into race conditions and potentially override fields we don't want to change.
A simple proposal is to allow session service to be passed to the get_fast_api_app instead of uri only.
(https://github.com/google/adk-python/blob/831e2e6d4d3dbd56fe553ba1bba759588f1b7658/src/google/adk/cli/fast_api.py#L56)
This is how we're doing right now:
- instantiate a session service object elsewhere in our code
- create our own endpoint to handle state management with the same process showed by the author.
- pass the uri of the session service to
get_fast_api_app.
It's not optimal because there are two session service objects, and this is not working for InMemorySessionService as there is no uri associated.
What do you think ? I can send the PR this week as I have some free time right now.
Hi, thanks for the replies about possible solutions, but in official doc there is this example:
Sessions store the state and event history for a specific user's interaction with an agent. Create or Update a Session Creates a new session or updates an existing one. If a session with the given IDs already exists, its state will be overwritten with the new state provided. Method: POST Path: /apps/{app_name}/users/{user_id}/sessions/{session_id} Request Body { "state": { "key1": "value1", "key2": 42 } } Example Request curl -X POST http://localhost:8000/apps/my_sample_agent/users/u_123/sessions/s_abc -H "Content-Type: application/json" -d '{"state": {"visit_count": 5}}'
Currently, if I try this example, I will get "Session already exist:" error, according to this logic
Going forward, I would either expect to:
- not get this error, and updated state
- separate endpoint for state updates
My use-case: I want to store custom session title there and other meta info about session that isn't supported out of the box
Looking forward for your response @DeanChensj
Any update on this? I keep getting Session already exists
If you pass the 'stateDelta' object, the session state will change.
It is now supported https://github.com/google/adk-python/blob/4f85e86fc3915f0e67312a39fe22451968d4f1b1/src/google/adk/cli/adk_web_server.py#L818