함수 호출 생성형 AI 사용기

Digitalization

함수 호출 생성형 AI 는 주어진 프롬프트로 내가 정의한 함수에 대한 입력을 맥락에 맞도록 자동적으로 만들어 주는 fine tuning된 생성형 AI입니다.

최근 생성형 AI에 대한 기대감은 예전 인터넷이 발명된 시기와 비교될 정도로 뜨겁습니다.

인터넷은 정보에 대한 무제한 접근성과 전세계를 대상으로 24시간 서로 사람들을 연결하게 만들어 새로운 산업혁명에 비견될 만큼의 생산성을 이끌어 내었습니다.

전 세계는 생성형 AI가 이와 비슷한 경제적 효과를 끌어내리라는 기대감에 가득 차 있습니다.

생성형 AI 돈이 되나요?

Money

ChatGPT가 세상에 처음 등장했을때 사람들은 인공지능의 마법과 같은 답변에 모두 깜짝 놀랐습니다.

그러나 과연 이러한 ChatGPT와 같은 생성형 AI를 통해 어떻게 돈을 벌 수 있는지에 대한 명쾌한 답은 아직 없는 상태입니다.

ChatGPT, 클로드같은 서비스들은 무료 버젼과 프로 버젼이 제공하는 서비스의 등급 나누기를 통해 유료가입자를 확보합니다.

생성형 AI를 통해 제품을 혁신한 좋은 사례는 어도비사가 아닐까 합니다.

함수 호출 생성형 AI 란 무엇인가요?

python function

함수 호출 생성형 AI 는 사용자가 자기가 가지고 있는 프롬프트와 이 프롬프트를 기반으로 자신이 얻고자 하는 정보에 대한 입력과 조작과정을 정의한 함수를 입력으로 받습니다.

그리고 이러한 입력을 기반으로 함수와 프롬프트의 맥락을 이해하고 함수의 입력에 필요한 파라미터들에 대입될 값들을 프롬프트에서 찾아내어 스트링으로 표현해 줍니다.

사용을 해 본 함수 호출 생성형 AI는 NexusFlow 사의 NexusRaven-V2-13B 입니다. 어떤 Model을 Foundation model로 사용했는지는 공개하지 않고 있습니다.

함수 호출 생성형 AI 사용 예

생성형 AI를 사용하여 함수 호출과 이를 위한 파라미터 값 결정 자동화를 위하여 아래와 같은 code set을 정의합니다.

import requests
def get_weather_data(coordinates):
    """
    Fetches weather data from the Open-Meteo API for the given latitude and longitude.

    Args:
    coordinates (tuple): The latitude of the location.

    Returns:
    float: The current temperature in the coordinates you've asked for
    """
    latitude, longitude = coordinates
    base_url = "https://api.open-meteo.com/v1/forecast"
    params = {
        "latitude": latitude,
        "longitude": longitude,
        "current": "temperature_2m,wind_speed_10m",
        "hourly": "temperature_2m,relative_humidity_2m,wind_speed_10m"
    }

    response = requests.get(base_url, params=params)
    if response.status_code == 200:
        print (f"""Temperature in C: {response.json()["current"]["temperature_2m"]}""")
    else:
        return {"error": "Failed to fetch data, status code: {}".format(response.status_code)}

def get_coordinates_from_city(city_name):
    """
    Fetches the latitude and longitude of a given city name using the Maps.co Geocoding API.

    Args:
    city_name (str): The name of the city.

    Returns:
    tuple: The latitude and longitude of the city.
    """
    base_url = "https://geocode.maps.co/search"
    params = {"q": city_name}

    response = requests.get(base_url, params=params)
    if response.status_code == 200:
        data = response.json()
        if data:
            # Assuming the first result is the most relevant
            return data[0]["lat"], data[0]["lon"]
        else:
            return {"error": "No data found for the given city name."}
    else:
        return {"error": "Failed to fetch data, status code: {}".format(response.status_code)}

최선의 결과를 얻기 위해서는 Python docstring format에 맞도록 함수가 하는 일과 arguement 그리고 return값을 상세히 써 주어야 Raven이 user prompt와 맞추어 정확한 함수 호출을 만들어 냅니다.

그리고 prompt로는 아래와 같은 텍스트를 준비합니다.

RAVEN_PROMPT = \
'''
Function:
def get_weather_data(coordinates):
    """
    Fetches weather data from the Open-Meteo API for the given latitude and longitude.

    Args:
    coordinates (tuple): The latitude of the location.

    Returns:
    float: The current temperature in the coordinates you've asked for
    """

Function:
def get_coordinates_from_city(city_name):
    """
    Fetches the latitude and longitude of a given city name using the Maps.co Geocoding API.

    Args:
    city_name (str): The name of the city.

    Returns:
    tuple: The latitude and longitude of the city.
    """

User Query: {query}<human_end>
'''

QUESTION = "Whats's the weather like in Seattle right now?"

Huggingface에는 다음과 같은 API endpoint가 공개되어 있습니다.

# Now, let's prompt Raven!
API_URL = "http://nexusraven.nexusflow.ai"
headers = {
        "Content-Type": "application/json"
}
def query(payload):
	"""
	Sends a payload to a TGI endpoint.
	"""
	import requests
	response = requests.post(API_URL, headers=headers, json=payload)
	return response.json()

def query_raven(prompt):
	"""
	This function sends a request to the TGI endpoint to get Raven's function call.
	This will not generate Raven's justification and reasoning for the call, to save on latency.
	"""
	import requests
	output = query({
		"inputs": prompt,
		"parameters" : {"temperature" : 0.001, "stop" : ["<bot_end>"], "do_sample" : False, "max_new_tokens" : 2000, "return_full_text" : False}})
	call = output[0]["generated_text"].replace("Call:", "").strip()
	return call

def query_raven_with_reasoning(prompt):
	"""
	This function sends a request to the TGI endpoint to get Raven's function call AND justification for the call
	"""
	import requests
	output = query({
		"inputs": prompt,
		"parameters" : {"temperature" : 0.001, "do_sample" : False, "max_new_tokens" : 2000, "return_full_text" : False}})
	call = output[0]["generated_text"].replace("Call:", "").strip()
	return call

위의 Raven과 통신하기 위한 함수들과 예제로 준비한 prompt를 사용하여 Raven에 질의를 하면 아래와 같은 답변 text를 얻을 수 있고 해당 text는 예상한 바와 같이 곧바로 실행 가능한 Python script가 됩니다.

get_weather_data(coordinates=get_coordinates_from_city(city_name='Seattle'))

멋집니다! Raven은 현재 Python code를 다룰 수 있도록 fine tuning된 LLM입니다.

당연히 function call을 사용하므로 우리가 흔히 사용하는 REST API도 임의의 python code로 API call을 한 번 싸주게 되면 API call도 문제 없이 수행 할 수 있습니다.

아래는 Huggingface내 NexusFlow의 demo URL 에서

“I would like to meet my daughter at Blue Bottle Coffeeshop an have some cup of coffee. After coffee, I would like to take a walk alongside Market street and drop by bycicle store. It would be great if we can rent 2 byclcles and take a ride to nearby Costco mall.”

와 같은 입력을 주었을때 최종 생성되는 이미지입니다.

Google map에 필요한 API들과 그에 해당하는 parameter set들을 보여 줍니다.

가능한 사용 예

라우터 무선 기지국 전송 장비등 많은 네트워크 장비들은 별도의 구성을 위한 파라미터들이 필요합니다.

심지어는 이런 파라미터들을 인터넷이나 다른 표준 단체에서 표준화하여 다른 제조사간 연동에 필요한 규약을 정하기도 합니다.

기본적으로 장비 측면에서 제공되어야 하는 데이터 뿐만 아니라 해당 장비에서 지원하는 특수 기능을 활성화 하는 경우 해당 기능에 필요한 별도의 데이터를 구성해야 하는 경우가 있습니다.

다행히 이런 데이터 구성을 위하여 Netconf YANG등 별도의 프로토콜과 데이터를 지원하는 경우가 많습니다.

이런 Network 장비 provisioning절차는 High level design부터 Low level design까지 많은 단계와 공수를 거쳐 완성됩니다.

만약 Raven과 같은 function call을 지원하는 LLM들이 좀 더 다양해 져서 Netwotk provisioning과 같은 단순하지만 많은 장비에 대해 벌어지는 작업들에 대한 구성 작업을 지원하게 된다면 큰 생산성 향상의 결과를 가져 올 수 있을 것 같다라는 생각을 해 보았습니다.

Similar Posts

Leave a Reply