与代理进行多轮次对话

本教程步骤演示如何与代理进行多轮次对话,其中代理是在 Azure OpenAI 聊天完成服务上构建的。

重要

代理框架支持多种不同类型的代理。 本教程使用基于聊天完成服务的代理,但所有其他代理类型都以相同的方式运行。 有关其他代理类型以及如何构造它们的详细信息,请参阅 Agent Framework 用户指南

先决条件

有关先决条件和创建代理,请参阅本教程中的 “创建并运行简单代理 ”步骤。

使用多轮对话运行代理

软件代理是无状态的,并且不会在每次调用之间内部维护任何状态。 若要与代理进行多轮次对话,需要创建一个对象来保存会话状态,并在运行该对象时将此对象传递给代理。

若要创建聊天状态对象,请在代理实例上调用 GetNewThread 该方法。

AgentThread thread = agent.GetNewThread();

然后,可以将此线程对象以及用户输入一起传递给代理实例上的 RunAsyncRunStreamingAsync 方法。

Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", thread));
Console.WriteLine(await agent.RunAsync("Now add some emojis to the joke and tell it in the voice of a pirate's parrot.", thread));

这将保持呼叫之间的聊天状态,代理在响应新输入时能够引用会话中的先前输入和响应消息。

重要

服务的类型 AIAgent 将确定会话历史记录的存储方式。 例如,使用 ChatCompletion 服务时,聊天历史记录存储在 AgentThread 对象中,并在每次调用时发送到服务。 另一方面,使用 Azure AI 代理服务时,对话历史记录存储在 Azure AI 代理服务中,并且每次调用时仅向服务发送对会话的引用。

单个代理处理多个对话

可以通过创建多个对象来与同一代理实例进行多个 AgentThread 独立对话。 然后,可以使用这些线程来维护每个会话的单独聊天状态。 这些对话将相互完全独立,因为代理不会在内部维护任何状态。

AgentThread thread1 = agent.GetNewThread();
AgentThread thread2 = agent.GetNewThread();
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", thread1));
Console.WriteLine(await agent.RunAsync("Tell me a joke about a robot.", thread2));
Console.WriteLine(await agent.RunAsync("Now add some emojis to the joke and tell it in the voice of a pirate's parrot.", thread1));
Console.WriteLine(await agent.RunAsync("Now add some emojis to the joke and tell it in the voice of a robot.", thread2));

使用多轮对话运行代理

软件代理是无状态的,并且不会在每次调用之间内部维护任何状态。 若要与代理进行多轮次对话,需要创建一个对象来保存会话状态,并在运行该对象时将此对象传递给代理。

若要创建聊天状态对象,请在代理实例上调用 get_new_thread() 该方法。

thread = agent.get_new_thread()

然后,可以将此线程对象以及用户输入一起传递给代理实例上的 runrun_stream 方法。

async def main():
    result1 = await agent.run("Tell me a joke about a pirate.", thread=thread)
    print(result1.text)

    result2 = await agent.run("Now add some emojis to the joke and tell it in the voice of a pirate's parrot.", thread=thread)
    print(result2.text)

asyncio.run(main())

这将保持呼叫之间的聊天状态,代理在响应新输入时能够引用会话中的先前输入和响应消息。

重要

代理使用的服务类型将确定会话历史记录的存储方式。 例如,使用聊天完成服务时,聊天历史记录存储在 AgentThread 对象中,并在每次调用时发送到服务。 另一方面,使用 Azure AI 代理服务时,对话历史记录存储在 Azure AI 代理服务中,并且每次调用时仅向服务发送对会话的引用。

单个代理处理多个对话

可以通过创建多个对象来与同一代理实例进行多个 AgentThread 独立对话。 然后,可以使用这些线程来维护每个会话的单独聊天状态。 这些对话将相互完全独立,因为代理不会在内部维护任何状态。

async def main():
    thread1 = agent.get_new_thread()
    thread2 = agent.get_new_thread()

    result1 = await agent.run("Tell me a joke about a pirate.", thread=thread1)
    print(result1.text)

    result2 = await agent.run("Tell me a joke about a robot.", thread=thread2)
    print(result2.text)

    result3 = await agent.run("Now add some emojis to the joke and tell it in the voice of a pirate's parrot.", thread=thread1)
    print(result3.text)

    result4 = await agent.run("Now add some emojis to the joke and tell it in the voice of a robot.", thread=thread2)
    print(result4.text)

asyncio.run(main())

后续步骤