Поделиться через


Изучение семантического ядра ChatCompletionAgent

Подсказка

Подробная документация по API, связанная с этим обсуждением, доступна по адресу:

Подсказка

Подробная документация по API, связанная с этим обсуждением, доступна по адресу:

Подсказка

Подробная документация по API, связанная с этим обсуждением, доступна по адресу:

Завершение чата в семантическом ядре

Завершение чата — это основной протокол взаимодействия на основе чата с моделью искусственного интеллекта, в которой журнал чата поддерживается и представлен модели с каждым запросом. Службы ИИ семантического ядра предлагают единую платформу для интеграции возможностей завершения чата различных моделей ИИ.

С помощью ChatCompletionAgent можно использовать любую из этих служб ИИ для создания ответов, адресуется ли пользователю или другому агенту.

Подготовка среды разработки

Чтобы продолжить разработку ChatCompletionAgent, настройте среду разработки с соответствующими пакетами.

Добавьте пакет Microsoft.SemanticKernel.Agents.Core в проект:

dotnet add package Microsoft.SemanticKernel.Agents.Core --prerelease

Установите пакет semantic-kernel.

pip install semantic-kernel

Это важно

В зависимости от того, какая служба ИИ используется в составе ChatCompletionAgent, может потребоваться установить дополнительные пакеты. Проверьте необходимые дополнительные сведения на следующей странице

<dependency>
    <groupId>com.microsoft.semantic-kernel</groupId>
    <artifactId>semantickernel-agents-core</artifactId>
    <version>[LATEST]</version>
</dependency>

Создание ChatCompletionAgent

ChatCompletionAgent фундаментально основан на службах искусственного интеллекта . Таким образом, создание ChatCompletionAgent начинается с создания экземпляра Kernel, содержащего одну или несколько служб завершения чата, а затем созданием экземпляра агента с ссылкой на этот экземпляр Kernel.

// Initialize a Kernel with a chat-completion service
IKernelBuilder builder = Kernel.CreateBuilder();

builder.AddAzureOpenAIChatCompletion(/*<...configuration parameters>*/);

Kernel kernel = builder.Build();

// Create the agent
ChatCompletionAgent agent =
    new()
    {
        Name = "SummarizationAgent",
        Instructions = "Summarize user input",
        Kernel = kernel
    };

Существует два способа создания ChatCompletionAgent:

1. Предоставление службы завершения чата напрямую

from semantic_kernel.agents import ChatCompletionAgent

# Create the agent by directly providing the chat completion service
agent = ChatCompletionAgent(
    service=AzureChatCompletion(),  # your chat completion service instance
    name="<agent name>",
    instructions="<agent instructions>",
)

2. Сначала создав ядро, добавив к нему службу, а затем предоставив ядро

# Define the kernel
kernel = Kernel()

# Add the chat completion service to the kernel
kernel.add_service(AzureChatCompletion())

# Create the agent using the kernel
agent = ChatCompletionAgent(
  kernel=kernel, 
  name="<agent name>", 
  instructions="<agent instructions>",
)

Первый метод полезен, если у вас уже есть служба завершения чата. Второй метод является полезным, если требуется ядро, которое управляет несколькими службами или дополнительными функциями.

// Initialize a Kernel with a chat-completion service
var chatCompletion = OpenAIChatCompletion.builder()
        .withOpenAIAsyncClient(client) // OpenAIAsyncClient with configuration parameters
        .withModelId(MODEL_ID)
        .build();

var kernel = Kernel.builder()
        .withAIService(ChatCompletionService.class, chatCompletion)
        .build();

// Create the agent
var agent = ChatCompletionAgent.builder()
        .withKernel(kernel)
        .build();

Выбор службы ИИ

Использование семантического ядра служб ИИ напрямую не отличается от того, как ChatCompletionAgent поддерживает возможность выбора сервиса с помощью селектора. Селектор службы определяет, какую службу ИИ выбрать, когда в Kernel содержится более одной.

Замечание

Если существует несколько служб ИИ и не предоставляется селектор службы, для агента применяется та же логика по умолчанию, которую вы найдете при использовании служб ИИ за пределами Agent Framework

IKernelBuilder builder = Kernel.CreateBuilder();

// Initialize multiple chat-completion services.
builder.AddAzureOpenAIChatCompletion(/*<...service configuration>*/, serviceId: "service-1");
builder.AddAzureOpenAIChatCompletion(/*<...service configuration>*/, serviceId: "service-2");

Kernel kernel = builder.Build();

ChatCompletionAgent agent =
    new()
    {
        Name = "<agent name>",
        Instructions = "<agent instructions>",
        Kernel = kernel,
        Arguments = // Specify the service-identifier via the KernelArguments
          new KernelArguments(
            new OpenAIPromptExecutionSettings() 
            { 
              ServiceId = "service-2" // The target service-identifier.
            })
    };
from semantic_kernel.connectors.ai.open_ai import (
    AzureChatCompletion,
    AzureChatPromptExecutionSettings,
)

# Define the Kernel
kernel = Kernel()

# Add the AzureChatCompletion AI Service to the Kernel
kernel.add_service(AzureChatCompletion(service_id="service1"))
kernel.add_service(AzureChatCompletion(service_id="service2"))

settings = AzureChatPromptExecutionSettings(service_id="service2")

# Create the agent
agent = ChatCompletionAgent(
  kernel=kernel, 
  name="<agent name>", 
  instructions="<agent instructions>",
  arguments=KernelArguments(settings=settings)
)

Функция в настоящее время недоступна в Java.

Общение с ChatCompletionAgent

Общение с вашим ChatCompletionAgent основано на экземпляре ChatHistory, не отличающемся от взаимодействия со службой ИИ завершения чата.

Вы можете просто вызвать агент с помощью сообщения пользователя.

// Define agent
ChatCompletionAgent agent = ...;

// Generate the agent response(s)
await foreach (ChatMessageContent response in agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "<user input>")))
{
  // Process agent response(s)...
}

Вы также можете использовать AgentThread, чтобы поговорить с вашим агентом. Здесь мы используем ChatHistoryAgentThread.

Объект ChatHistoryAgentThread через свой конструктор может также принимать необязательный объект ChatHistory в качестве входных данных при возобновлении предыдущей беседы. (не отображается)

// Define agent
ChatCompletionAgent agent = ...;

AgentThread thread = new ChatHistoryAgentThread();

// Generate the agent response(s)
await foreach (ChatMessageContent response in agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "<user input>"), thread))
{
  // Process agent response(s)...
}

Существует несколько способов общения с ChatCompletionAgent.

Проще всего позвонить и ожидать get_response:

# Define agent
agent = ChatCompletionAgent(...)

# Generate the agent response
response = await agent.get_response(messages="user input")
# response is an `AgentResponseItem[ChatMessageContent]` object

Если вы хотите, чтобы агент сохранял историю бесед между вызовами, вы можете передать ему ChatHistoryAgentThread следующим образом:


# Define agent
agent = ChatCompletionAgent(...)

# Generate the agent response(s)
response = await agent.get_response(messages="user input")

# Generate another response, continuing the conversation thread from the first response.
response2 = await agent.get_response(messages="user input", thread=response.thread)
# process agent response(s)

invoke Вызов метода возвращает значение AsyncIterableAgentResponseItem[ChatMessageContent].

# Define agent
agent = ChatCompletionAgent(...)

# Define the thread
thread = ChatHistoryAgentThread()

# Generate the agent response(s)
async for response in agent.invoke(messages="user input", thread=thread):
  # process agent response(s)

ChatCompletionAgent также поддерживает потоковую передачу, в которой метод invoke_stream возвращает объект типа AsyncIterableStreamingChatMessageContent.

# Define agent
agent = ChatCompletionAgent(...)

# Define the thread
thread = ChatHistoryAgentThread()

# Generate the agent response(s)
async for response in agent.invoke_stream(messages="user input", thread=thread):
  # process agent response(s)
ChatCompletionAgent agent = ...;

// Generate the agent response(s)
agent.invokeAsync(new ChatMessageContent<>(AuthorRole.USER, "<user input>")).block();

Вы также можете использовать AgentThread, чтобы поговорить с вашим агентом. Здесь мы используем ChatHistoryAgentThread.

Объект ChatHistoryAgentThread также может приниматься ChatHistory в качестве входных данных через его конструктор, если возобновить предыдущую беседу. (не отображается)

// Define agent
ChatCompletionAgent agent = ...;

AgentThread thread = new ChatHistoryAgentThread();

// Generate the agent response(s)
agent.invokeAsync(new ChatMessageContent<>(AuthorRole.USER, "<user input>"), thread).block();

Обработка промежуточных сообщений с помощью ChatCompletionAgent

Семантические ядра ChatCompletionAgent предназначены для вызова агента, выполняющего запросы пользователей или вопросы. Во время вызова агент может использовать инструменты для получения окончательного ответа. Чтобы получить доступ к промежуточным сообщениям, созданным во время этого процесса, вызывающие могут предоставить функцию обратного вызова, которая обрабатывает экземпляры FunctionCallContent или FunctionResultContent.

Документация по обратному вызову для ChatCompletionAgent будет доступна в ближайшее время.

Настройка обратного вызова on_intermediate_message в agent.invoke(...) или agent.invoke_stream(...) позволяет вызывающему объекту получать промежуточные сообщения, создаваемые в процессе формирования окончательного ответа агента.

import asyncio
from typing import Annotated

from semantic_kernel.agents.chat_completion.chat_completion_agent import ChatCompletionAgent, ChatHistoryAgentThread
from semantic_kernel.connectors.ai.open_ai.services.azure_chat_completion import AzureChatCompletion
from semantic_kernel.contents import FunctionCallContent, FunctionResultContent
from semantic_kernel.contents.chat_message_content import ChatMessageContent
from semantic_kernel.functions import kernel_function


# Define a sample plugin for the sample
class MenuPlugin:
    """A sample Menu Plugin used for the concept sample."""

    @kernel_function(description="Provides a list of specials from the menu.")
    def get_specials(self) -> Annotated[str, "Returns the specials from the menu."]:
        return """
        Special Soup: Clam Chowder
        Special Salad: Cobb Salad
        Special Drink: Chai Tea
        """

    @kernel_function(description="Provides the price of the requested menu item.")
    def get_item_price(
        self, menu_item: Annotated[str, "The name of the menu item."]
    ) -> Annotated[str, "Returns the price of the menu item."]:
        return "$9.99"


# This callback function will be called for each intermediate message
# Which will allow one to handle FunctionCallContent and FunctionResultContent
# If the callback is not provided, the agent will return the final response
# with no intermediate tool call steps.
async def handle_intermediate_steps(message: ChatMessageContent) -> None:
    for item in message.items or []:
        if isinstance(item, FunctionCallContent):
            print(f"Function Call:> {item.name} with arguments: {item.arguments}")
        elif isinstance(item, FunctionResultContent):
            print(f"Function Result:> {item.result} for function: {item.name}")
        else:
            print(f"{message.role}: {message.content}")


async def main() -> None:
    agent = ChatCompletionAgent(
        service=AzureChatCompletion(),
        name="Assistant",
        instructions="Answer questions about the menu.",
        plugins=[MenuPlugin()],
    )

    # Create a thread for the agent
    # If no thread is provided, a new thread will be
    # created and returned with the initial response
    thread: ChatHistoryAgentThread = None

    user_inputs = [
        "Hello",
        "What is the special soup?",
        "How much does that cost?",
        "Thank you",
    ]

    for user_input in user_inputs:
        print(f"# User: '{user_input}'")
        async for response in agent.invoke(
            messages=user_input,
            thread=thread,
            on_intermediate_message=handle_intermediate_steps,
        ):
            print(f"# {response.role}: {response}")
            thread = response.thread


if __name__ == "__main__":
    asyncio.run(main())

Ниже приведен пример выходных данных из процесса вызова агента:

User: 'Hello'
AuthorRole.ASSISTANT: Hi there! How can I assist you today?
User: 'What is the special soup?'
Function Call:> MenuPlugin-get_specials with arguments: {}
Function Result:> 
        Special Soup: Clam Chowder
        Special Salad: Cobb Salad
        Special Drink: Chai Tea
        for function: MenuPlugin-get_specials
AuthorRole.ASSISTANT: The special soup today is Clam Chowder. Would you like to know anything else from the menu?
User: 'How much does that cost?'
Function Call:> MenuPlugin-get_item_price with arguments: {"menu_item":"Clam Chowder"}
Function Result:> $9.99 for function: MenuPlugin-get_item_price
AuthorRole.ASSISTANT: The Clam Chowder costs $9.99. Would you like to know more about the menu or anything else?
User: 'Thank you'
AuthorRole.ASSISTANT: You're welcome! If you have any more questions, feel free to ask. Enjoy your day!

Функция в настоящее время недоступна в Java.

Декларативная спецификация

В ближайшее время будет представлена документация по использованию декларативных спецификаций.

Это важно

Эта функция находится на экспериментальном этапе. Функции на этом этапе находятся в стадии разработки и могут измениться перед переходом к этапу предварительного просмотра или релиз-кандидата.

Из декларативной спецификации на YAML можно непосредственно создать экземпляр ChatCompletionAgent. Этот подход позволяет определить основные свойства агента, инструкции и доступные функции (подключаемые модули) в структурированном и переносном виде. С помощью YAML можно описать имя агента, описание, запрос инструкции, набор инструментов и параметры модели в одном документе, что упрощает аудит и воспроизводимость конфигурации агента.

Замечание

Все средства или функции, указанные в декларативном YAML, уже должны существовать в экземпляре ядра во время создания агента. Загрузчик агента не создает новые функции из спецификации; Вместо этого он ищет указанные подключаемые модули и функции по их идентификаторам в ядре. Если необходимый подключаемый модуль или функция отсутствует в ядре, во время создания агента возникает ошибка.

Пример: Создание ChatCompletionAgent из спецификации YAML.

import asyncio
from typing import Annotated

from semantic_kernel import Kernel
from semantic_kernel.agents import AgentRegistry, ChatHistoryAgentThread
from semantic_kernel.agents.chat_completion.chat_completion_agent import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.functions import kernel_function

# Define a plugin with kernel functions
class MenuPlugin:
    @kernel_function(description="Provides a list of specials from the menu.")
    def get_specials(self) -> Annotated[str, "Returns the specials from the menu."]:
        return """
        Special Soup: Clam Chowder
        Special Salad: Cobb Salad
        Special Drink: Chai Tea
        """

    @kernel_function(description="Provides the price of the requested menu item.")
    def get_item_price(
        self, menu_item: Annotated[str, "The name of the menu item."]
    ) -> Annotated[str, "Returns the price of the menu item."]:
        return "$9.99"

# YAML spec for the agent
AGENT_YAML = """
type: chat_completion_agent
name: Assistant
description: A helpful assistant.
instructions: Answer the user's questions using the menu functions.
tools:
  - id: MenuPlugin.get_specials
    type: function
  - id: MenuPlugin.get_item_price
    type: function
model:
  options:
    temperature: 0.7
"""

USER_INPUTS = [
    "Hello",
    "What is the special soup?",
    "What does that cost?",
    "Thank you",
]

async def main():
    kernel = Kernel()
    kernel.add_plugin(MenuPlugin(), plugin_name="MenuPlugin")

    agent: ChatCompletionAgent = await AgentRegistry.create_from_yaml(
        AGENT_YAML, kernel=kernel, service=OpenAIChatCompletion()
    )

    thread: ChatHistoryAgentThread | None = None

    for user_input in USER_INPUTS:
        print(f"# User: {user_input}")
        response = await agent.get_response(user_input, thread=thread)
        print(f"# {response.name}: {response}")
        thread = response.thread

    await thread.delete() if thread else None

if __name__ == "__main__":
    asyncio.run(main())

Эта функция недоступна.

Инструкции

Полный пример для ChatCompletionAgentсм. здесь:

Дальнейшие шаги