Multi-Turn Conversations

Learn how to create agents that maintain context across conversation turns.

Calculator Multi-Turn Example

In this example, by using the session_id parameter, the agent can refer back to the context of previous run(s) and maintain context across several conversation turns.


Info: An agent run is the process of an agent running one or more tasks based on its defined rules and instructions. In a conversation (also called a session), each time a user takes a turn (like asking a question or giving a command), it's called an "agent run". During this run, the agent might need to take several steps (like using different tools or making several calculations) to complete the task and respond to the user. So, one user turn = one agent run, which can involve several steps to get the final answer.

calculator_multi_turns.py

from oci.addons.adk import Agent, AgentClient
from oci.addons.adk.tool.prebuilt import CalculatorToolkit

def main():

    client = AgentClient(
        auth_type="api_key",
        profile="DEFAULT",
        region="us-chicago-1"
    )

    agent = Agent(
        client=client,
        agent_endpoint_id="ocid1.genaiagentendpoint...",
        instructions="You perform calculations using tools provided.",
        tools=[CalculatorToolkit()]
    )

    agent.setup()

    # First turn (here we start a new session)
    input = "What is the square root of 256?"
    response = agent.run(input, max_steps=3)
    response.pretty_print()

    # Second turn (here we use the same session from last run)
    input = "do the same thing for 81"
    response = agent.run(input, session_id=response.session_id, max_steps=3)
    response.pretty_print()

if __name__ == "__main__":
    main()

Let's break down the example: 1. First Turn: The agent processes the initial user query for calculating the square root. 2. Session ID: After the first response, the session_id from that response is captured. 3. Second Turn: When the user asks do the same thing for 81, the agent understands the context because the session_id is passed to the second call. 4. Without the session_id, the agent wouldn't understand what "the same thing" refers to.

How It Works

When you don't pass the session_id parameter, the run will start a new session.

When you pass the session_id parameter, the run will reuse the specified session, rather than creating a new session.

A session maintains the context of the run that starts the session, as well as any runs that use the same session_id.