함수 호출(function calling)은 대규모 언어 모델(LLM)의 능력을 확장하고 특정 작업을 수행하는 강력한 메커니즘이다. LLM은 사용자의 입력을 분석하고, 적절한 함수를 선택하여 필요한 매개변수와 함께 호출한다. 이 과정을 통해 LLM은 실시간 데이터 검색, 계산 수행, 외부 시스템과의 상호작용 등 다양한 작업을 수행할 수 있다. 함수 호출은 LLM의 자연어 처리 능력과 구조화된 작업 수행 능력을 결합하여, 더 정확하고 맥락에 맞는 응답을 생성한다.

함수 호출의 주요 장점은 유연성과 확장성에 있다. 개발자는 특정 도메인이나 사용 사례에 맞는 사용자 정의 함수를 정의할 수 있으며, 이를 통해 LLM의 기능을 크게 확장할 수 있다. 예를 들어, 날씨 정보 검색, 데이터베이스 쿼리, 예약 시스템 접근 등 다양한 기능을 LLM에 통합할 수 있다.

JSON 출력

함수 호출을 JSON 형식으로 구조화하는 것은 데이터의 일관성과 해석의 용이성을 크게 향상시킨다. JSON은 인간과 기계 모두가 쉽게 읽고 이해할 수 있는 형식으로, 복잡한 데이터 구조를 명확하게 표현할 수 있어, 특히 다양한 유형의 정보를 포함하는 함수 호출에서 매우 유용하며, 파라미터의 이름과 값을 명확히 연결하여 오류의 가능성을 줄인다.

또한, JSON을 사용한 함수 호출은 시스템 간의 상호 운용성을 크게 향상시킨다. 많은 프로그래밍 언어와 플랫폼이 JSON을 기본적으로 지원하기 때문에, 다양한 환경에서 쉽게 통합될 수 있다. 웹 기반 애플리케이션이나 마이크로서비스 아키텍처에서 중요하며, API 통신의 표준으로 자리 잡았다. 결과적으로, JSON을 통한 함수 호출은 개발 과정을 간소화하고, 시스템의 유지보수성과 확장성을 향상시키는 데 크게 기여한다.

헬로월드

함수 호출 헬로월드 프로그램은 OpenAI의 GPT 모델을 사용하여 간단한 인사 기능을 구현했다. 프로그램은 먼저 hello_world라는 함수를 정의하고, 이 함수의 설명을 OpenAI API에 제공한 다음, 사용자의 입력을 API에 전송하면, GPT 모델이 이를 해석하여 적절한 함수 호출을 결정한다. API가 hello_world 함수 호출을 요청하면, 프로그램은 이 함수를 실행하여 개인화된 인사말을 생성하고 출력합니다.

코드
from openai import OpenAI
import os
from dotenv import load_dotenv
import json

load_dotenv()

client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))


# 간단한 함수 정의
def hello_world(name):
    return f"안녕하세요, {name}님!"


# OpenAI에 제공할 함수 설명
functions = [
    {
        "name": "hello_world",
        "description": "이름을 받아 인사말을 반환하는 함수",
        "parameters": {
            "type": "object",
            "properties": {"name": {"type": "string", "description": "사용자의 이름"}},
            "required": ["name"],
        },
    }
]

# OpenAI API 호출
response = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[{"role": "user", "content": "내 이름은 홍길동이야. 인사해줘."}],
    functions=functions,
    function_call="auto",
)

# 응답 처리 및 함수 실행
message = response.choices[0].message
if message.function_call:
    function_args = json.loads(message.function_call.arguments)
    result = hello_world(function_args["name"])
    print(result)
안녕하세요, 홍길동님!

날씨 API

날씨 API 호출 코드는 OpenAI의 GPT 모델과 OpenWeatherMap API를 결합하여 사용자의 날씨 관련 질문에 답한다. 먼저 OpenWeatherMap API를 사용하여 특정 도시의 날씨 정보를 가져오는 get_weather 함수를 정의했다. 그 다음 이 함수의 설명을 OpenAI API에 제공하고, 사용자의 자연어 입력을 처리하도록 GPT 모델에 요청했다. GPT 모델은 사용자의 질문을 해석하여 적절한 도시 이름을 추출하고 get_weather 함수를 호출했다. 마지막으로 함수의 반환값을 출력하여 사용자에게 현재 날씨 정보를 제공했다. 이 과정을 통해 자연어 처리와 실시간 데이터 조회를 결합한 실용적인 AI 애플리케이션의 기본 구조를 구현했다.

코드
from openai import OpenAI
import requests
import os
from dotenv import load_dotenv

# 환경 변수 로드
load_dotenv()

# OpenAI 및 OpenWeatherMap API 키 설정
openai_api_key = os.getenv("OPENAI_API_KEY")
weather_api_key = os.getenv("OPENWEATHER_API_KEY")

# OpenAI 클라이언트 초기화
client = OpenAI(api_key=openai_api_key)

def get_weather(city):
    """OpenWeatherMap API를 사용하여 날씨 정보를 가져오는 함수"""
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    params = {"q": city, "appid": weather_api_key, "units": "metric"}  # 섭씨 온도 사용
    response = requests.get(base_url, params=params)
    if response.status_code == 200:
        data = response.json()
        weather_desc = data["weather"][0]["description"]
        temp = data["main"]["temp"]
        return f"{city}의 현재 날씨는 {weather_desc}이며, 기온은 {temp}°C 입니다."
    else:
        return "날씨 정보를 가져오는데 실패했습니다."


# OpenAI에 제공할 함수 설명
functions = [
    {
        "name": "get_weather",
        "description": "특정 도시의 현재 날씨 정보를 가져오는 함수",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "날씨를 알고싶은 도시 이름"}
            },
            "required": ["city"],
        },
    }
]

# 사용자 입력 처리 및 함수 호출
user_input = "속초시 오늘 날씨 어때?"
response = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[{"role": "user", "content": user_input}],
    functions=functions,
    function_call="auto",
)

# 응답 처리 및 함수 실행
message = response.choices[0].message
if message.function_call:
    function_args = eval(message.function_call.arguments)
    result = get_weather(function_args["city"])
    print(result)
else:
    print(message.content)
날씨 정보를 가져오는데 실패했습니다.

랭체인 도구

함수 호출은 특정 GPT 모형에 특화된 반면 랭체인 도구는 특정 GPT 모형에 종속되지 않는다.

코드
from langchain.agents import Tool
from langchain.agents import AgentType
from langchain.memory import ConversationBufferMemory
from langchain.chat_models import ChatOpenAI
from langchain.agents import initialize_agent
from langchain.tools import DuckDuckGoSearchRun
import os
from dotenv import load_dotenv

load_dotenv()

# OpenAI API 키 설정
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")

# ChatOpenAI 모델 초기화
llm = ChatOpenAI(temperature=0)

# DuckDuckGo 검색 도구 초기화
search = DuckDuckGoSearchRun()

# 도구 정의
tools = [
    Tool(
        name="DuckDuckGo Search",
        func=search.run,
        description="useful for when you need to answer questions about current events or the current state of the world",
    )
]

# 메모리 초기화
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)

# 에이전트 초기화
agent = initialize_agent(
    tools,
    llm,
    agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION,
    verbose=True,
    memory=memory,
)

# 에이전트 실행
response = agent.run("What's the latest news about SpaceX?")
print(response)
C:\Users\statkclee\AppData\Roaming\Python\Python312\site-packages\langchain\agents\json_chat\base.py:22: SyntaxWarning: invalid escape sequence '\ '
  """Create an agent that uses JSON to format its logic, build for Chat Models.
C:\Users\statkclee\AppData\Roaming\Python\Python312\site-packages\langchain_core\_api\deprecation.py:119: LangChainDeprecationWarning: The class `ChatOpenAI` was deprecated in LangChain 0.0.10 and will be removed in 0.3.0. An updated version of the class exists in the langchain-openai package and should be used instead. To use it run `pip install -U langchain-openai` and import as `from langchain_openai import ChatOpenAI`.
  warn_deprecated(
C:\Users\statkclee\AppData\Roaming\Python\Python312\site-packages\langchain_core\_api\deprecation.py:119: LangChainDeprecationWarning: The function `initialize_agent` was deprecated in LangChain 0.1.0 and will be removed in 0.3.0. Use Use new agent constructor methods like create_react_agent, create_json_agent, create_structured_chat_agent, etc. instead.
  warn_deprecated(
C:\Users\statkclee\AppData\Roaming\Python\Python312\site-packages\langchain_core\_api\deprecation.py:119: LangChainDeprecationWarning: The method `Chain.run` was deprecated in langchain 0.1.0 and will be removed in 0.3.0. Use invoke instead.
  warn_deprecated(


> Entering new AgentExecutor chain...
```json
{
    "action": "DuckDuckGo Search",
    "action_input": "latest news about SpaceX"
}
```
Observation: Breaking space news, the latest updates on rocket launches, skywatching events and more! ... SpaceX traced the cause of the leak to a crack in a line for a pressure sensor in the liquid-oxygen ... Agency officials said the next launch of a SpaceX Crew Dragon spacecraft, the ninth mission by SpaceX to take four astronauts for a six-month stay at the space station, or Crew-9, is scheduled for ... About 5 miles (8 kilometers) south of the crowds, SpaceX's massive Starship vehicle lifted off this morning (March 14) at 9:25 a.m. EDT (1325 GMT) from the company's manufacturing and test launch ... 阅读简体中文版 閱讀繁體中文版. SpaceX's launch of its mammoth Starship rocket on Thursday accomplished a set of ambitious goals that Elon Musk, the company's chief executive, had ... SpaceX. Today was nothing short of extraordinary. As per the plan, the Starship rocket has successfully returned to Earth on its fourth test flight, landing in the Indian Ocean. It's a major step ...
Thought:```json
{
    "action": "Final Answer",
    "action_input": "SpaceX has been making headlines with recent achievements, including the successful launch and return of the Starship rocket on its fourth test flight, landing in the Indian Ocean."
}
```

> Finished chain.
SpaceX has been making headlines with recent achievements, including the successful launch and return of the Starship rocket on its fourth test flight, landing in the Indian Ocean.