**함수 호출(Function Calling)**은 LLM이 직접 대답할 수 없는 실시간 데이터(날씨, 주가, DB 조회, 외부 API)가 필요할 때, 어떤 파이썬 함수를 호출해야 하는지 스스로 판단하여 매개변수 JSON을 반환하는 기술입니다.
1. Function Calling & Agent 용어 사전 (Glossary)
- Function Calling: LLM이 질문을 분석하여 미리 정의된 도구(Tools) 목록 중 필요한 함수 이름과 전달 인자(Arguments)를 도출해내는 기능입니다.
- AI Agent (자율 AI 에이전트): 스스로 목표(Goal)를 이해하고, 계획(Plan)을 세우며, 주도적으로 도구를 호출해 결과를 종합하는 지능형 시스템입니다.
- ReAct Framework (Reasoning + Acting): "생각(Thought) -> 행동(Action) -> 관찰(Observation)"의 루프를 반복하여 문제를 해결하는 에이전트 핵심 아키텍처입니다.
2. 파이썬 Function Calling 풀 루프 구현 코드
import json
# 1. 실제 실행될 파이썬 외부 함수 정의
def get_stock_price(ticker):
prices = {"AAPL": "$225.50", "NVDA": "$130.20", "005930.KS": "75,000원"}
return json.dumps({"ticker": ticker, "price": prices.get(ticker, "알수없음")})
# 2. LLM에 바인딩할 도구 명세서(Tools) 정의
tools = [{
"type": "function",
"function": {
"name": "get_stock_price",
"description": "주식 티커 심볼을 받아 현재 실시간 주가를 조회합니다.",
"parameters": {
"type": "object",
"properties": {
"ticker": {"type": "string", "description": "주식 티커 (예: AAPL, NVDA)"}
},
"required": ["ticker"]
}
}
}]
# 3. 1차 API 호출 (LLM이 함수 호출 필요성을 판단)
messages = [{"role": "user", "content": "엔비디아(NVDA) 현재 주가 좀 알려줘"}]
response = client.chat.completions.create(model="gpt-4o-mini", messages=messages, tools=tools)
tool_call = response.choices[0].message.tool_calls[0]
print(f"AI의 판단: {tool_call.function.name} 함수를 인자 {tool_call.function.arguments} 로 호출할 것.")
# 4. 실제 파이썬 함수 실행 후 2차 API 호출로 최종 답변 완성
args = json.loads(tool_call.function.arguments)
result_json = get_stock_price(args["ticker"])
messages.append(response.choices[0].message) # AI의 tool_call 요청 저장
messages.append({"role": "tool", "tool_call_id": tool_call.id, "content": result_json})
final_response = client.chat.completions.create(model="gpt-4o-mini", messages=messages)
print("최종 응답:", final_response.choices[0].message.content)
3. 자주 묻는 질문 (Q&A)
Q. LLM이 무한히 루프를 돌며 나쁜 함수를 실행할 위험은 없나요?
A. 에이전트 구축 시 최대 도구 실행 횟수(예: max_iterations=5) 제약 조건을 걸어야 하며, 데이터 삭제/결제 같은 위험한 함수 실행 전에는 사람의 승인(Human-in-the-loop)을 받도록 설계해야 합니다.