잡다한글

ChatGPT API 업데이트 & Function calling 기능 지원

Jonghyuk Baek 2023. 6. 20. 00:43

Introduction

https://openai.com/blog/function-calling-and-other-api-updates

 

 

Function calling and other API updates

We’re announcing updates including more steerable API models, function calling capabilities, longer context, and lower prices.

openai.com

 

 

최근에 ChatGPT API 업데이트에 대한 글이 OpenAI 블로그에 올라왔는데 (6월 13일자), 오늘은 해당 내용에 대해 간략하게 정리해 보고자 한다.

 


 

주요한 변경 내용은 다음과 같다.

  • Function calling (함수 호출) 기능 제공
  • 기존 대비 4배 분량의 컨텍스트를 처리할 수 있는 gpt-3.5-turbo 모델의 16k 컨텍스트 버전 제공
  • gpt-3.5-turbo 모델의 가격 25% 인하
  • 최신 임베딩 모델의 가격 75% 인하
  • 기존 gpt-3.5-turbo-0301 모델과 gpt-4-0314 모델의 deprecation 예고

 

gpt-3.5-turbo-16k

 

https://openai.com/pricing

 

기존의 4K 컨텍스트의 4배 분량을 처리할 수 있는 16K 모델이 추가되었다. 다만 유의할 점은 4K 모델에 비해서 같은 토큰 수 대비 정확히 2배의 가격을 보여준다.

다만 기존에 3.5 버전을 사용하면서 입출력 길이 제한이 꽤 불편했던 것을 생각하면, 이 가격을 내더라도 사용하고자 하는 수요가 있지 않을까 싶다.

 

API cost reduction

 

https://openai.com/pricing

 

gpt-3.5-turbo 4K 모델 기준 입출력 $0.002/1K tokens 에서 입력 $0.0015/1K tokens / 출력 $0.002/1K tokens 으로 가격이 변경되었다. 입력 쪽에만 25% 금액 인하가 적용되었다.

임베딩 모델 쪽에서는 Ada v2 임베딩 모델의 가격이 $0.0004/1K tokens 에서 $0.0001/1K tokens 으로 75% 가격이 인하되었다. 다른 모델의 경우 이전과 동일한 것으로 보인다.

 

Function calling

이번 업데이트의 가장 핫한 주제다!

모델이 API 호출 입력으로부터 함수 호출 시점을 파악해 내고, 함수 호출에 필요한 파라미터 등의 정보를 JSON 형태로 내보낼 수 있게 된다. 즉 ChatGPT API 호출을 통해 원하는 함수를 적절한 인자와 함께 호출 하는 것이 가능하다는 뜻이다.

 

OpenAI 블로그의 예시를 옮겨오자면, 이 기능은 다음과 같은 느낌으로 적용할 수 있다.

 

"Email Anya to see if she wants to get coffee next Friday"

의 쿼리를 이용해

send_email(to: string, body: string)

위와 같은 형태의 함수를 호출한다던지,

 

“Who are my top ten customers this month?”

와 같은 질문을

get_customers_by_revenue(start_date: string, end_date: string, limit: int)

처럼 다른 API 호출로 연결하는 것이 가능하다.

 

원하는 API를 손쉽게 자연어 기반의 명령어로 호출할 수 있게 되었다는 점에서 의미가 있다.

 

gpt-4-0613gpt-3.5-turbo-0613 모델에서 사용이 가능하다고 하며, 이 두 모델은 입력에 따라 함수의 호출 여부를 탐지해 낼 수 있도록 fine-tune 되어 있다고 한다.

 

도큐멘테이션에서 제공하는 기본적인 작동 흐름을 보여주는 예시를 함께 첨부한다.

import openai
import json


# Example dummy function hard coded to return the same weather
# In production, this could be your backend API or an external API
def get_current_weather(location, unit="fahrenheit"):
    """Get the current weather in a given location"""
    weather_info = {
        "location": location,
        "temperature": "72",
        "unit": unit,
        "forecast": ["sunny", "windy"],
    }
    return json.dumps(weather_info)


def run_conversation():
    # Step 1: send the conversation and available functions to GPT
    messages = [{"role": "user", "content": "What's the weather like in Boston?"}]
    functions = [
        {
            "name": "get_current_weather",
            "description": "Get the current weather 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": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
            },
        }
    ]
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo-0613",
        messages=messages,
        functions=functions,
        function_call="auto",  # auto is default, but we'll be explicit
    )
    response_message = response["choices"][0]["message"]

    # Step 2: check if GPT wanted to call a function
    if response_message.get("function_call"):
        # Step 3: call the function
        # Note: the JSON response may not always be valid; be sure to handle errors
        available_functions = {
            "get_current_weather": get_current_weather,
        }  # only one function in this example, but you can have multiple
        function_name = response_message["function_call"]["name"]
        fuction_to_call = available_functions[function_name]
        function_args = json.loads(response_message["function_call"]["arguments"])
        function_response = fuction_to_call(
            location=function_args.get("location"),
            unit=function_args.get("unit"),
        )

        # Step 4: send the info on the function call and function response to GPT
        messages.append(response_message)  # extend conversation with assistant's reply
        messages.append(
            {
                "role": "function",
                "name": function_name,
                "content": function_response,
            }
        )  # extend conversation with function response
        second_response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo-0613",
            messages=messages,
        )  # get a new response from GPT where it can see the function response
        return second_response


print(run_conversation())

 

더 자세하게 알고 싶다면 공식 도큐멘테이션을 참고해 보자.

 


아래는 참고할 만한 페이지들이다.

References

ChatGPT Documentation - Function calling

https://platform.openai.com/docs/guides/gpt/function-calling

Function calling and other API updates

https://openai.com/blog/function-calling-and-other-api-updates

OpenAI Pricing

https://openai.com/pricing

 

 

 

반응형