// education & ai

LLM 외부 도구 연동 (Function Calling과 에이전트)

**함수 호출(Function Calling)**은 LLM이 직접 대답할 수 없는 실시간 데이터(날씨, 주가, DB 조회, 외부 API)가 필요할 때, 어떤 파이썬 함수를 호출해야 하는지 스스로 판단하여 매개변수 JSON을 반환하는 기술입니다.


1. Function Calling & Agent 용어 사전 (Glossary)


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)을 받도록 설계해야 합니다.

🎓 DAVHAVE AI & 모바일 개발 마스터링

AI 및 마스터 가이드 수강 중 도움이 필요하시거나 사내 AI 교육 및 에이전트 도입 컨설팅이 필요하신가요?

AI 마스터 문의하기 →
https://davhave.com/education/ai/claude/ch08-function-calling-and-tools
← 이전 레슨RAG 시스템의 설계와 최적화 다음 레슨 →다중 에이전트 협력 시스템