검색
검색
노트 검색
회원가입로그인

새로 나온 ChatGPT API Function calling 사용법

page thumbnail

ChatGPT API 의 gpt-3.5-turbo-0613 이나 gpt-4-0613 버전에서 함수 호출 (function calling)을 사용할 수 있습니다.

기존의 messages 외에 functions 라는 파라미터가 생겼는데 여기에 함수 관련 정보를 보내서 ChatGPT가 이를 처리할 수 있는 형태입니다.

작동 방식은 다음과 같습니다.

  1. functions 에 작동하기를 원하는 함수(내부 함수 또는 외부 API 함수)의 관련 정보를 넣어서 보낸다.

  2. ChatGPT가 messages의 맥락을 바탕으로 함수 호출을 할지 말지의 의도와 관련 정보(함수 이름, 변수)를 답변한다.

  3. ChatGPT의 함수 호출 의도가 있다면 ChatGPT가 답변한 변수들을 바탕으로 (messages에서 추출된 정보) 함수를 호출한다. (함수를 호출하는 것은 ChatGPT가 아니고 우리가 해야 합니다.)

  4. 함수의 결과값을 추가해 다시 API를 호출한다. ChatGPT는 이를 바탕으로 최종 답변을 생성한다.

조금 복잡해 보이기는 한데 1. 함수를 호출해야 하는 상황을 자동으로 파악하고 (intention) 이 때 2. 우리가 함수 실행 결과를 첨부해 두 번째 요청 (second request)을 보내면 ChatGPT가 처리하는 방식이라고 보시면 됩니다. ChatGPT 플러그인과 작동 방식이 거의 유사하네요.

코드와 함께 설명을 드릴게요. 자바스크립트로 작성했습니다. app.js 를 다음과 같이 수정해 주세요.

import { Configuration, OpenAIApi } from "openai";
import dotenv from "dotenv";
dotenv.config();

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});

// 실행 할 함수 (내부 함수나 외부 API 등이 가능합니다.)
function get_current_weather(location, unit = "fahrenheit") {
  const weather_info = {
    location: location,
    temperature: 75,
    unit: unit,
    forecast: ["sunny", "windy"],
  };
  return weather_info;
}

let messages = [{ role: "user", content: "What's the weather like in Seoul?" }];

const openai = new OpenAIApi(configuration);
const chat = await openai.createChatCompletion({
  model: "gpt-3.5-turbo-0613", // 0613 버전에서 함수 호출이 가능합니다.
  messages: messages,
  // 함수 관련 정보를 functions에 같이 보내줍니다. (JSON 형태면 OK)
  functions: [
    {
      name: "get_current_weather",
      description: "Get the current weather information in a given location",
      parameters: {
        type: "object",
        properties: {
          location: {
            type: "string",
            description: "The city and state, e.g. San Francisco, CA",
          },
          unit: {
            type: "string",
            enum: ["fahrenheit", "celsius"],
          },
        },
        required: ["location"],
      },
    },
  ],
  function_call: "auto", // 함수 실행 여부를 자동으로 판단합니다.
  // 함수 실행을 원하지 않고 일반적인 답변을 원하면 none 으로 설정합니다.
});

console.log(chat.data.choices[0]);
// 이런 식으로 ChatGPT가 함수를 실행해야 하는 상황이면 function_call 응답을 줍니다.
// {
//   index: 0,
//   message: {
//     role: 'assistant',
//     content: null,
//     function_call: {
//       name: 'get_current_weather',
//       arguments: '{\n  "location": "Seoul"\n}'
//     }
//   },
//   finish_reason: 'function_call'
// }

const response_message = chat.data.choices[0]["message"];
//     role: 'assistant',
//     content: null,
//     function_call: {
//       name: 'get_current_weather',
//       arguments: '{\n  "location": "Seoul"\n}'
//     }

// second request
if (response_message.function_call) {
  // ChatGPT의 함수 호출 의도가 있다면 관련 정보 (함수 이름, 변수) 를 추출하여 함수를 실행합니다.
  const args = JSON.parse(response_message.function_call.arguments);
  const function_response = get_current_weather(args.location, args.unit);
  // {
  //   location: 'Seoul',
  //   temperature: 75,
  //   unit: 'fahrenheit',
  //   forecast: [ 'sunny', 'windy' ]
  // }
  messages.push(response_message); // 함수 실행 의도를 다음에 보낼 메시지에 추가합니다. (assistant)
  messages.push({
    role: "function",
    name: response_message.function_call.name,
    content: JSON.stringify(function_response),
  }); // 함수 호출 결과를 다음에 보낼 메시지에 첨부합니다.

  const second_response = await openai.createChatCompletion({
    model: "gpt-3.5-turbo-0613",
    messages: messages,
  });
  console.log(second_response.data.choices[0], "second response");
  // {
  //   index: 0,
  //   message: {
  //     role: 'assistant',
  //     content: 'The current weather in Seoul is sunny with a temperature of 75 degrees Fahrenheit. It is also quite windy.'
  //   },
  //   finish_reason: 'stop'
  // } second response
}

이런 식으로 서울의 날씨를 대답할 수 있게 됩니다. ChatGPT API에 명시적인 도구를 쥐어줄 수 있다고 보시면 됩니다.

이를 활용하여 다양한 기능들을 붙일 수 있을 것 같습니다. 예를 들어 이메일 쓰기, 블로그 포스팅하기, 구매하기 등이 있습니다. 물론 중요한 행동일 경우에는 사용자의 확인을 받는 로직을 추가하는 것이 필요할 것 같습니다.

한번 function calling 기능을 사용해 보면서 이해해 보세요.

공식 문서 : https://platform.openai.com/docs/guides/gpt/function-calling

function 파라미터 공식 레퍼런스 문서 : https://platform.openai.com/docs/api-reference/chat/create#chat/create-functions

공유하기
url 복사하기
카카오로 공유하기
트위터로 공유하기
페이스북 공유하기