Delete Sessions

Proactively delete a session for better privacy and scalability.

The ADK uses a session to track the context of of a run, including supporting multi-turn conversations and local function tool invocations.

If you don't explicitly delete a session, the session is deleted automatically after its time-to-live (TTL) expires. The default TTL is 24 hours. However, this behavior might not suit your use case. For example, for privacy reasons you might want to delete a session immediately after the conversation ends.

Or your agent supports a large number of concurrent users, in which case you might want to delete sessions proactively to free up resources. An agent can have at at most 800 sessions per default quota, so to avoid hitting this limit, you can proactively delete sessions if your application can decide when a session is no longer needed.

Python

def main():

    agent = Agent(
        client=client,
        agent_endpoint_id="ocid1.genaiagentendpoint...",
        instructions="You are a helpful assistant that can perform calculations.",
        tools=[CalculatorToolkit()]
    )

    agent.setup()

    input = "What is the square root of 81?"
    response = agent.run(input)

    # You explicitly delete the session used by the last run
    agent.delete_session(response.session_id)

if __name__ == "__main__":
    main()

Java

public static void main(String[] args) throws Exception {
    Agent agent = Agent.builder()
        .client(agentClient)
        .agentEndpointId(AGENT_ENDPOINT_ID)
        .instructions("You perform calculations using tools provided.")
        .tools(Arrays.asList(new SimpleCalculatorToolkit()))
        .build();

    agent.setup()

    final String input = "What is the square root of 475695037565?";
    RunResponse response = agent.run(input);

    agent.deleteSession(response.getSessionId());
}

Alternatively, you can delete the session after the run completes by setting delete_session=True in the run method.

Python

def main():

    # Ask ADK to auto delete the session after the run completes
    response = agent.run(input, delete_session=True)

if __name__ == "__main__":
    main()

Java

public static void main(String[] args) throws Exception {
    final RunOptions runOptions = RunOptions.builder().deleteSession(true).build();
    RunResponse response = agent.run(input, runOptions);
}