다음을 통해 공유


의미 체계 커널 플러그 인을 사용하여 에이전트 구성

중요합니다

이 기능은 릴리스 후보 단계에 있습니다. 이 단계의 기능은 거의 완전하고 일반적으로 안정적이지만 전체 일반 공급에 도달하기 전에 약간의 개선 또는 최적화가 필요할 수 있습니다.

의미 체계 커널의 함수 및 플러그 인

함수 호출은 개발자가 사용자 지정 기능을 추가하고 AI 애플리케이션의 기능을 확장할 수 있는 강력한 도구입니다. 의미 체계 커널 플러그 인 아키텍처는 함수 호출을 지원하는 유연한 프레임워크를 제공합니다. Agent의 경우, 플러그인함수 호출 통합은 이 기본적인 의미 체계 커널 기능을 기반으로 합니다.

구성이 완료되면, 에이전트는 마치 어떤 사용 예에서도 그렇듯이, 사용 가능한 함수 Agent Framework를 호출할 시기와 방법을 선택합니다.

에이전트에 플러그 인 추가

에서 사용할 수 있는 Agent은 해당 Kernel 내에서 관리됩니다. 이 설정을 사용하면 각 Agent 사용자가 특정 역할에 따라 고유한 기능에 액세스할 수 있습니다.

플러그인Kernel에 만들기 전이나 후에 Agent 추가할 수 있습니다. 플러그 인을 초기화하는 프로세스는 의미 체계 커널 구현에 사용되는 것과 동일한 패턴을 따르며 AI 기능 관리에 일관성과 사용 편의성을 제공합니다.

비고

ChatCompletionAgent의 경우, 함수 호출 모드를 명시적으로 사용하도록 설정해야 합니다. OpenAIAssistant 에이전트는 항상 자동 함수 호출을 기반으로 합니다.

// Factory method to produce an agent with a specific role.
// Could be incorporated into DI initialization.
ChatCompletionAgent CreateSpecificAgent(Kernel kernel, string credentials)
{
    // Clone kernel instance to allow for agent specific plug-in definition
    Kernel agentKernel = kernel.Clone();

    // Import plug-in from type
    agentKernel.ImportPluginFromType<StatelessPlugin>();

    // Import plug-in from object
    agentKernel.ImportPluginFromObject(new StatefulPlugin(credentials));

    // Create the agent
    return
        new ChatCompletionAgent()
        {
            Name = "<agent name>",
            Instructions = "<agent instructions>",
            Kernel = agentKernel,
            Arguments = new KernelArguments(
                new OpenAIPromptExecutionSettings()
                {
                    FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
                })
        };
}

플러그인을 사용하여 ChatCompletionAgent를 만드는 방법에는 두 가지가 있습니다.

방법 1: 생성자를 통해 플러그 인 지정

플러그 인 목록을 생성자에 직접 전달할 수 있습니다.

from semantic_kernel.agents import ChatCompletionAgent

# Create the Chat Completion Agent instance by specifying a list of plugins
agent = ChatCompletionAgent(
    service=AzureChatCompletion(),
    instructions="<instructions>",
    plugins=[SamplePlugin()]
)

팁 (조언)

기본적으로 자동 함수 호출은 사용하도록 설정됩니다. 사용하지 않도록 설정하려면 생성자에서 function_choice_behavior 인수를 function_choice_behavior=FunctionChoiceBehavior.Auto(auto_invoke=False)으로 설정합니다. 이 설정을 사용하면 플러그 인이 모델로 브로드캐스트되지만 자동으로 호출되지는 않습니다. 실행 설정이 AI 서비스 구성에서 지정한 service_id 또는 ai_model_id와 동일한 경우, 실행 설정에 정의된 함수 호출 동작(KernelArguments 통해)이 생성자에 설정된 함수 선택 동작보다 우선합니다.

방법 2: 수동으로 커널 구성

생성자를 통해 커널을 제공하지 않으면 모델 유효성 검사 중에 커널이 자동으로 만들어집니다. 전달된 모든 플러그 인이 우선적으로 적용되고 커널에 추가됩니다. 커널의 상태를 보다 세밀하게 제어하려면 다음 단계를 수행합니다.

from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, AzureChatPromptExecutionSettings
from semantic_kernel.functions import KernelFunctionFromPrompt
from semantic_kernel.kernel import Kernel

# Create the instance of the Kernel
kernel = Kernel()

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

# Get the AI Service settings
settings = kernel.get_prompt_execution_settings_from_service_id()

# Configure the function choice behavior to auto invoke kernel functions
settings.function_choice_behavior = FunctionChoiceBehavior.Auto()

# Add the Plugin to the Kernel
kernel.add_plugin(SamplePlugin(), plugin_name="<plugin name>")

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

팁 (조언)

커널에 서비스를 추가할 때 service_id이 지정되지 않으면 기본값은 default입니다. 커널에서 여러 AI 서비스를 구성할 때 인수를 사용하여 service_id 구분하는 것이 좋습니다. 이렇게 하면 특정 service_id 에 대한 실행 설정을 검색하고 해당 설정을 원하는 서비스에 연결할 수 있습니다.

var chatCompletion = OpenAIChatCompletion.builder()
    .withModelId("<model-id>")
    .withOpenAIAsyncClient(new OpenAIClientBuilder()
            .credential(new AzureKeyCredential("<api-key>"))
            .endpoint("<endpoint>")
            .buildAsyncClient())
    .build();

Kernel kernel = Kernel.builder()
    .withAIService(ChatCompletionService.class, chatCompletion)
    .withPlugin(KernelPluginFactory.createFromObject(new SamplePlugin(), "<plugin name>"))
    .build();

var agent = ChatCompletionAgent.builder()
    .withKernel(kernel)
    .withName("<agent name>")
    .withInstructions("<agent instructions>")
    .build();

에이전트에 함수 추가

플러그 인은 함수 호출을 구성하는 가장 일반적인 방법입니다. 그러나 프롬프트 함수를 포함하여 개별 함수를 독립적으로 제공할 수도 있습니다.

// Factory method to product an agent with a specific role.
// Could be incorporated into DI initialization.
ChatCompletionAgent CreateSpecificAgent(Kernel kernel)
{
    // Clone kernel instance to allow for agent specific plug-in definition
    Kernel agentKernel = kernel.Clone();

    // Create plug-in from a static function
    var functionFromMethod = agentKernel.CreateFunctionFromMethod(StatelessPlugin.AStaticMethod);

    // Create plug-in from a prompt
    var functionFromPrompt = agentKernel.CreateFunctionFromPrompt("<your prompt instructions>");

    // Add to the kernel
    agentKernel.ImportPluginFromFunctions("my_plugin", [functionFromMethod, functionFromPrompt]);

    // Create the agent
    return
        new ChatCompletionAgent()
        {
            Name = "<agent name>",
            Instructions = "<agent instructions>",
            Kernel = agentKernel,
            Arguments = new KernelArguments(
                new OpenAIPromptExecutionSettings()
                {
                    FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
                })
        };
}
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, AzureChatPromptExecutionSettings
from semantic_kernel.functions import KernelFunctionFromPrompt
from semantic_kernel.kernel import Kernel

# Create the instance of the Kernel
kernel = Kernel()

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

# Create the AI Service settings
settings = AzureChatPromptExecutionSettings()

# Configure the function choice behavior to auto invoke kernel functions
settings.function_choice_behavior = FunctionChoiceBehavior.Auto()

# Add the Plugin to the Kernel
kernel.add_function(
    plugin_name="<plugin_name>",
    function=KernelFunctionFromPrompt(
        function_name="<function_name>",
        prompt="<your prompt instructions>",
    )
)

# Create the agent
agent = ChatCompletionAgent(
    kernel=kernel,
    name=<agent name>,
    instructions=<agent instructions>,
    arguments=KernelArguments(settings=settings),
)
var chatCompletion = OpenAIChatCompletion.builder()
    .withModelId("<model-id>")
    .withOpenAIAsyncClient(new OpenAIClientBuilder()
            .credential(new AzureKeyCredential("<api-key>"))
            .endpoint("<endpoint>")
            .buildAsyncClient())
    .build();

// Create function from method
var functionFromMethod = KernelFunction.createFromMethod(SamplePlugin.class.getMethod("method"), new SamplePlugin());

// Create function from prompt
var functionFromPrompt = KernelFunction.createFromPrompt("<your prompt instructions>");

// Create the kernel with a plugin from the two functions
Kernel kernel = Kernel.builder()
    .withAIService(ChatCompletionService.class, chatCompletion)
    .withPlugin(KernelPluginFactory.createFromFunctions("SamplePlugin", List.of(functionFromMethod, functionFromPrompt)))
    .build();

InvocationContext invocationContext = InvocationContext.builder()
    .withFunctionChoiceBehavior(FunctionChoiceBehavior.auto(true))
    .build();

// Create the agent
var agent = ChatCompletionAgent.builder()
    .withKernel(kernel)
    .withName("<agent name>")
    .withInstructions("<agent instructions>")
    .withInvocationContext(invocationContext)
    .build();

에이전트 함수 호출에 대한 제한 사항

ChatCompletionAgent을(를) 직접 호출할 때 모든 함수 선택 기능이 지원됩니다. 그러나 사용 중인 OpenAIAssistant경우 현재 자동 함수 호출 만 사용할 수 있습니다.

사용 방법

함수 호출을 사용하는 엔드 투 엔드 예제는 다음을 참조하세요.

다음 단계