Semantic Kernel과 C#.NET을 활용한 대형 언어 모델 함수 호출 구현

GPT-4에서의 함수 호출 구현 방법

함수 정의

실행 가능한 함수를 정의합니다. 예시: 위치 기반 날씨 정보 조회


def fetch_weather_data(city, scale='Celsius'):
    # 실제 날씨 정보 조회 로직
    return {"city": city, "temp": "24", "scale": scale, "status": "맑음"}

함수 메타데이터 구성

모델이 함수를 이해할 수 있도록 설명 정보 제공


func_metadata = [
    {
        "name": "fetch_weather_data",
        "description": "특정 도시의 현재 날씨 정보 조회",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "도시 이름"},
                "scale": {
                    "type": "string",
                    "enum": ["Celsius", "Fahrenheit"],
                    "description": "온도 단위, 기본값은 섭씨"
                }
            },
            "required": ["city"]
        }
    }
]

모델 통신 및 실행 처리


import openai
import json

openai.api_key = 'API_KEY'

def query_model(messages, functions):
    response = openai.ChatCompletion.create(
        model="gpt-4-0613",
        messages=messages,
        functions=functions,
        function_call="auto"
    )
    return response

user_query = {"role": "user", "content": "서울의 현재 날씨는 어떨까요?"}
model_response = query_model([user_query], func_metadata)

함수 실행 및 응답 처리


response_data = model_response["choices"][0]["message"]

if "function_call" in response_data:
    func_name = response_data["function_call"]["name"]
    arguments = json.loads(response_data["function_call"]["arguments"])
    
    if func_name == "fetch_weather_data":
        result = fetch_weather_data(
            city=arguments.get("city"),
            scale=arguments.get("scale", "Celsius")
        )
        
        followup_messages = [
            user_query,
            response_data,
            {"role": "function", "name": func_name, "content": json.dumps(result)}
        ]
        final_output = query_model(followup_messages, func_metadata)
        print(final_output["choices"][0]["message"]["content"])
else:
    print(response_data["content"])

Semantic Kernel과 C#.NET 통합

계산기 플러그인 구현 예시


using Microsoft.SemanticKernel;

public class MathOperations
{
    [KernelFunction("multiply_values")]
    public int Multiply(int first, int second)
    {
        return first * second;
    }
}

커널 초기화 및 함수 실행


using Microsoft.SemanticKernel.Connectors.OpenAI;

var kernel = Kernel.CreateBuilder()
    .AddOpenAIChatCompletion(
        "gpt-4-turbo",
        "API_KEY"
    )
    .Build();

var mathPlugin = kernel.ImportPluginFromObject(new MathOperations(), "MathPlugin");

var computationResult = await kernel.InvokeAsync(
    "MathPlugin", 
    "multiply_values", 
    new() {{ "first", 7 }, { "second", 8 }}
);

Console.WriteLine($"실행 결과: {computationResult}");

동작 원리

  • Semantic Kernel은 .NET 메서드를 플러그인으로 노출
  • [KernelFunction] 속성이 호출 가능 함수로 등록
  • ImportPluginFromObject()로 플러그인 커널에 추가
  • InvokeAsync()로 매개변수와 함께 함수 실행

태그: function-calling semantic-kernel csharp dotnet gpt-4

5월 31일 03:43에 게시됨