다음을 통해 공유


의미 체계 커널 시작

몇 단계만 수행하면 Python, .NET 또는 Java에서 의미 체계 커널을 사용하여 첫 번째 AI 에이전트를 빌드할 수 있습니다. 이 가이드에서는 다음 방법을 보여 드립니다.

  • 필요한 패키지 설치
  • AI를 사용하여 앞뒤로 대화 만들기
  • AI 에이전트에게 코드를 실행할 수 있는 기능 제공
  • 즉석에서 AI 만들기 계획 보기

SDK 설치

의미 체계 커널에는 여러 NuGet 패키지를 사용할 수 있습니다. 그러나 대부분의 시나리오에서는 일반적으로 .Microsoft.SemanticKernel

다음 명령을 사용하여 설치할 수 있습니다.

dotnet add package Microsoft.SemanticKernel

Nuget 패키지의 전체 목록은 지원되는 언어 문서를 참조하세요.

Python 패키지에 액세스하기 SemanticKernel 위한 지침은 여기에서 확인할 수 있습니다. 다음과 같이 쉽습니다.

pip install semantic-kernel

전자 필기장 빠르게 시작

Python 또는 C# 개발자인 경우 Notebook을 빠르게 시작할 수 있습니다. 이러한 Notebook은 의미 체계 커널을 사용하여 AI 에이전트를 빌드하는 방법에 대한 단계별 가이드를 제공합니다.

의미 체계 커널 Notebook

시작하려면 다음 단계를 수행합니다.

  1. 의미 체계 커널 리포지토리 복제
  2. Visual Studio Code에서 리포지토리 열기
  3. _/python/samples/getting_started로 이동합니다.
  4. 00-getting-started.ipynb를 열어 환경 설정 및 첫 번째 AI 에이전트 만들기를 시작하세요!

시작하려면 다음 단계를 수행합니다.

  1. 의미 체계 커널 리포지토리 복제
  2. Visual Studio Code에서 리포지토리 열기
  3. _/dotnet/Notebook으로 이동합니다.
  4. 00-getting-started.ipynb를 열어 환경 설정 및 첫 번째 AI 에이전트 만들기를 시작하세요!

첫 번째 콘솔 앱 작성

// Import packages
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;

// Create a kernel with Azure OpenAI chat completion
var builder = Kernel.CreateBuilder().AddAzureOpenAIChatCompletion(modelId, endpoint, apiKey);

// Add enterprise components
builder.Services.AddLogging(services => services.AddConsole().SetMinimumLevel(LogLevel.Trace));

// Build the kernel
Kernel kernel = builder.Build();
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();

// Add a plugin (the LightsPlugin class is defined below)
kernel.Plugins.AddFromType<LightsPlugin>("Lights");

// Enable planning
OpenAIPromptExecutionSettings openAIPromptExecutionSettings = new() 
{
    ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions
};

// Create a history store the conversation
var history = new ChatHistory();

// Initiate a back-and-forth chat
string? userInput;
do {
    // Collect user input
    Console.Write("User > ");
    userInput = Console.ReadLine();

    // Add user input
    history.AddUserMessage(userInput);

    // Get the response from the AI
    var result = await chatCompletionService.GetChatMessageContentAsync(
        history,
        executionSettings: openAIPromptExecutionSettings,
        kernel: kernel);

    // Print the results
    Console.WriteLine("Assistant > " + result);

    // Add the message from the agent to the chat history
    history.AddMessage(result.Role, result.Content ?? string.Empty);
} while (userInput is not null)
import asyncio

from semantic_kernel import Kernel
from semantic_kernel.functions import kernel_function
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.connectors.ai.function_call_behavior import FunctionCallBehavior
from semantic_kernel.connectors.ai.chat_completion_client_base import ChatCompletionClientBase
from semantic_kernel.contents.chat_history import ChatHistory
from semantic_kernel.functions.kernel_arguments import KernelArguments

from semantic_kernel.connectors.ai.open_ai.prompt_execution_settings.azure_chat_prompt_execution_settings import (
    AzureChatPromptExecutionSettings,
)

async def main():
    # Initialize the kernel
    kernel = Kernel()

    # Add Azure OpenAI chat completion
    kernel.add_service(AzureChatCompletion(
        deployment_name="your_models_deployment_name",
        api_key="your_api_key",
        base_url="your_base_url",
    ))

    # Set the logging level for  semantic_kernel.kernel to DEBUG.
    logging.basicConfig(
        format="[%(asctime)s - %(name)s:%(lineno)d - %(levelname)s] %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )
    logging.getLogger("kernel").setLevel(logging.DEBUG)

    # Add a plugin (the LightsPlugin class is defined below)
    kernel.add_plugin(
        LightsPlugin(),
        plugin_name="Lights",
    )

    chat_completion : AzureChatCompletion = kernel.get_service(type=ChatCompletionClientBase)

    # Enable planning
    execution_settings = AzureChatPromptExecutionSettings(tool_choice="auto")
    execution_settings.function_call_behavior = FunctionCallBehavior.EnableFunctions(auto_invoke=True, filters={})

    # Create a history of the conversation
    history = ChatHistory()

    # Initiate a back-and-forth chat
    userInput = None
    while True:
        # Collect user input
        userInput = input("User > ")

        # Terminate the loop if the user says "exit"
        if userInput == "exit":
            break

        # Add user input to the history
        history.add_user_message(userInput)

        # Get the response from the AI
        result = (await chat_completion.get_chat_message_contents(
            chat_history=history,
            settings=execution_settings,
            kernel=kernel,
            arguments=KernelArguments(),
        ))[0]

        # Print the results
        print("Assistant > " + str(result))

        # Add the message from the agent to the chat history
        history.add_message(result)

# Run the main function
if __name__ == "__main__":
    asyncio.run(main())

다음 전후 채팅은 본체에 표시되는 것과 유사해야 합니다. 함수 호출은 AI가 백그라운드에서 플러그 인을 활용하는 방법을 보여주기 위해 아래에 추가되었습니다.

역할 메시지
🔵사용자 조명을 설정/해제하세요.
🔴도우미(함수 호출) LightsPlugin.GetState()
🟢도구 off
🔴도우미(함수 호출) LightsPlugin.ChangeState(true)
🟢도구 on
🔴도우미 이제 빛이 켜집니다.

위의 코드에 대한 자세한 내용을 이해하려면 다음 섹션에서 자세히 알아봅니다.

코드 이해

의미 체계 커널을 사용하여 엔터프라이즈 앱 빌드를 더 쉽게 시작할 수 있도록 커널을 만들고 이를 사용하여 AI 서비스와 상호 작용하는 프로세스를 안내하는 단계별 안내를 만들었습니다.

의미 체계 커널 Python 맵

의미 체계 커널 DotNET 맵

다음 섹션에서는 1, 2, 3, 4, 6, 910단계를 진행하여 위의 샘플의 압축을 풀겠습니다. AI 서비스에 의해 구동되고 코드를 실행할 수 있는 간단한 에이전트를 빌드하는 데 필요한 모든 것.

  1. 패키지 가져오기
  2. AI 서비스 추가
  3. 엔터프라이즈 구성 요소
  4. 커널 빌드
  5. 메모리 추가(건너뛰기)
  6. 플러그 인 추가
  7. 커널 인수 만들기(건너뛰기)
  8. 프롬프트 만들기(건너뛰기)
  9. 계획
  10. Invoke

1) 패키지 가져오기

이 샘플에서는 먼저 다음 패키지를 가져와 시작했습니다.

using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
import asyncio

from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.connectors.ai.function_call_behavior import FunctionCallBehavior
from semantic_kernel.connectors.ai.chat_completion_client_base import ChatCompletionClientBase
from semantic_kernel.contents.chat_history import ChatHistory
from semantic_kernel.functions.kernel_arguments import KernelArguments

from semantic_kernel.connectors.ai.open_ai.prompt_execution_settings.azure_chat_prompt_execution_settings import (
    AzureChatPromptExecutionSettings,
)

2) AI 서비스 추가

그 후 커널의 가장 중요한 부분인 사용하려는 AI 서비스를 추가합니다. 이 예제에서는 커널 작성기에서 Azure OpenAI 채팅 완료 서비스를 추가했습니다.

참고 항목

이 예제에서는 Azure OpenAI를 사용했지만 다른 채팅 완료 서비스를 사용할 수 있습니다. 지원되는 서비스의 전체 목록을 보려면 지원되는 언어 문서를 참조하세요. 다른 서비스를 만드는 데 도움이 필요한 경우 AI 서비스 문서를 참조하세요. OpenAI 또는 Azure OpenAI 모델을 서비스로 사용하는 방법에 대한 지침을 찾을 수 있습니다.

// Create kernel
var builder = Kernel.CreateBuilder()
builder.AddAzureOpenAIChatCompletion(modelId, endpoint, apiKey);
# Initialize the kernel
kernel = Kernel()

# Add Azure OpenAI chat completion
kernel.add_service(AzureChatCompletion(
    deployment_name="your_models_deployment_name",
    api_key="your_api_key",
    base_url="your_base_url",
))

3) 엔터프라이즈 서비스 추가

의미 체계 커널을 사용할 때의 주요 이점 중 하나는 엔터프라이즈급 서비스를 지원한다는 것입니다. 이 샘플에서는 AI 에이전트를 디버그하는 데 도움이 되도록 로깅 서비스를 커널에 추가했습니다.

builder.Services.AddLogging(services => services.AddConsole().SetMinimumLevel(LogLevel.Trace)); 
import logging

# Set the logging level for  semantic_kernel.kernel to DEBUG.
logging.basicConfig(
    format="[%(asctime)s - %(name)s:%(lineno)d - %(levelname)s] %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)
logging.getLogger("kernel").setLevel(logging.DEBUG)

4) 커널 빌드 및 서비스 검색

서비스가 추가되면 커널을 빌드하고 나중에 사용할 수 있도록 채팅 완료 서비스를 검색합니다.

Kernel kernel = builder.Build();

// Retrieve the chat completion service
var chatCompletionService = kernel.Services.GetRequiredService<IChatCompletionService>();

커널이 구성되면 나중에 사용할 수 있도록 채팅 완료 서비스를 검색합니다.

참고 항목

Python에서는 커널을 명시적으로 빌드할 필요가 없습니다. 대신 커널 개체에서 직접 서비스에 액세스할 수 있습니다.

chat_completion : AzureChatCompletion = kernel.get_service(type=ChatCompletionClientBase)

6) 플러그 인 추가

플러그 인을 사용하면 AI 에이전트가 코드를 실행하여 외부 원본에서 정보를 검색하거나 작업을 수행할 수 있습니다. 위의 예제에서는 AI 에이전트가 전구와 상호 작용할 수 있는 플러그 인을 추가했습니다. 아래에서는 이 플러그 인을 만드는 방법을 보여 드리겠습니다.

네이티브 플러그 인 만들기

아래에서 네이티브 플러그 인을 만드는 것은 새 클래스를 만드는 것만큼 간단하다는 것을 알 수 있습니다.

이 예제에서는 전구를 조작할 수 있는 플러그 인을 만들었습니다. 간단한 예제이지만 이 플러그 인은 두 가지 모두를 지원하는 방법을 빠르게 보여 줍니다.

  1. AI 에이전트에 전구 상태를 제공하여 RAG(검색 보강 세대)
  2. 또한 AI 에이전트가 전구를 켜거나 끌 수 있도록 하여 작업 자동화 를 수행합니다.

사용자 고유의 코드에서 유사한 결과를 얻기 위해 외부 서비스 또는 API와 상호 작용하는 플러그 인을 만들 수 있습니다.

using System.ComponentModel;
using Microsoft.SemanticKernel;

public class LightsPlugin
{
   // Mock data for the lights
   private readonly List<LightModel> lights = new()
   {
      new LightModel { Id = 1, Name = "Table Lamp", IsOn = false },
      new LightModel { Id = 2, Name = "Porch light", IsOn = false },
      new LightModel { Id = 3, Name = "Chandelier", IsOn = true }
   };

   [KernelFunction("get_lights")]
   [Description("Gets a list of lights and their current state")]
   [return: Description("An array of lights")]
   public async Task<List<LightModel>> GetLightsAsync()
   {
      return lights
   }

   [KernelFunction("change_state")]
   [Description("Changes the state of the light")]
   [return: Description("The updated state of the light; will return null if the light does not exist")]
   public async Task<LightModel?> ChangeStateAsync(int id, bool isOn)
   {
      var light = lights.FirstOrDefault(light => light.Id == id);

      if (light == null)
      {
         return null;
      }

      // Update the light with the new state
      light.IsOn = isOn;

      return light;
   }
}

public class LightModel
{
   [JsonPropertyName("id")]
   public int Id { get; set; }

   [JsonPropertyName("name")]
   public string Name { get; set; }

   [JsonPropertyName("is_on")]
   public bool? IsOn { get; set; }
}
from typing import Annotated
from semantic_kernel.functions import kernel_function

class LightsPlugin:
    lights = [
        {"id": 1, "name": "Table Lamp", "is_on": False},
        {"id": 2, "name": "Porch light", "is_on": False},
        {"id": 3, "name": "Chandelier", "is_on": True},
    ]

    @kernel_function(
        name="get_lights",
        description="Gets a list of lights and their current state",
    )
    def get_state(
        self,
    ) -> Annotated[str, "the output is a string"]:
        """Gets a list of lights and their current state."""
        return self.lights

    @kernel_function(
        name="change_state",
        description="Changes the state of the light",
    )
    def change_state(
        self,
        id: int,
        is_on: bool,
    ) -> Annotated[str, "the output is a string"]:
        """Changes the state of the light."""
        for light in self.lights:
            if light["id"] == id:
                light["is_on"] = is_on
                return light
        return None

커널에 플러그 인 추가

플러그 인을 만든 후에는 AI 에이전트가 액세스할 수 있도록 커널에 추가할 수 있습니다. 샘플에서는 커널에 LightsPlugin 클래스를 추가했습니다.

// Add the plugin to the kernel
kernel.Plugins.AddFromType<LightsPlugin>("Lights");
# Add the plugin to the kernel
kernel.add_plugin(
    LightsPlugin(),
    plugin_name="Lights",
)

9) 계획

의미 체계 커널은 대부분의 LLM의 네이티브 기능인 함수 호출을 활용하여 계획을 제공합니다. 함수 호출을 사용하면 LLM이 특정 함수를 요청(또는 호출)하여 사용자의 요청을 충족할 수 있습니다. 그런 다음 의미 체계 커널은 요청을 코드베이스의 적절한 함수로 마샬링하고 AI 에이전트가 최종 응답을 생성할 수 있도록 결과를 LLM에 다시 반환합니다.

자동 함수 호출을 사용하도록 설정하려면 먼저 의미 체계 커널이 AI 에이전트가 요청할 때 커널의 함수를 자동으로 호출하도록 적절한 실행 설정을 만들어야 합니다.

OpenAIPromptExecutionSettings openAIPromptExecutionSettings = new() 
{
    ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions
};
execution_settings = AzureChatPromptExecutionSettings(tool_choice="auto")
execution_settings.function_call_behavior = FunctionCallBehavior.EnableFunctions(auto_invoke=True, filters={})

10) 호출

마지막으로 플러그 인을 사용하여 AI 에이전트를 호출합니다. 샘플 코드는 비 스트리밍 응답을 생성하는 방법을 보여 주지만 메서드를 사용하여 GetStreamingChatMessageContentAsync 스트리밍 응답을 생성할 수도 있습니다.

// Create chat history
var history = new ChatHistory();

// Get the response from the AI
var result = await chatCompletionService.GetChatMessageContentAsync(
    history,
    executionSettings: openAIPromptExecutionSettings,
    kernel: kernel
);
# Create a history of the conversation
history = ChatHistory()

# Get the response from the AI
result = (await chat_completion.get_chat_message_contents(
    chat_history=history,
    settings=execution_settings,
    kernel=kernel,
    arguments=KernelArguments(),
))[0]

다음 단계

이 가이드에서는 AI 서비스와 상호 작용하고 코드를 실행할 수 있는 간단한 AI 에이전트를 빌드하여 의미 체계 커널을 빠르게 시작하는 방법을 알아보았습니다. 더 많은 예제를 보고 더 복잡한 AI 에이전트를 빌드하는 방법을 알아보려면 심층 샘플을 확인하세요.