brunch
매거진 NCP AI

Lab 5 . Function calling API

by Master Seo

1. API 호출 실습 코드 다운로드



2

f unction calling API 호출


import

requests

API_KEY = KEY

REQUEST_ID =

"

url =

"https://clovastudio.stream.ntruss.com/testapp/v3/chat completions/HCX DASH 002"

headers = {

" Authorization": f "Bearer {API_

"X NCP CLOVASTUDIO REQUEST ID"ID": REQUEST_

"Content Type"Type": "application/

}

data = {

" messages":

" content": 내일 서울 날씨 어때

" role": "

" tools":

" type": "

" function":

" description": 날씨를 알려줄 수 있는 도구

" name": "get_

" parameters":

" type": "

" properties":

" location":

" description": 서울 , 대전 , 부산 등의 도시 이름

" type": "

" unit":

" type": "

" enum": [" celsius", "

" date":


" description": "2025 03 21 같은 형태의 날짜 문자열 . 날씨를 알고 싶은 날짜

" type": "

" required": ["

" toolChoice": "

}

response = requests.post(url, headers=headers, json=data)

result = response.json()



3

. 다중 tool 구성한 코드 실행


import

os

import

json

import

requests

from

datetime import datetime

API_KEY = KEY

REQUEST_ID =

"

API_URL =

"https://clovastudio.stream.ntruss.com/testapp/v3/chat completions/HCX DASH 002"

HEADERS = {

" Authorization": f "Bearer {API_

"X NCP CLOVASTUDIO REQUEST ID"ID": REQUEST_

"Content Type"Type": "application/

}

#

메뉴별 가격표 예시

MENU_PRICES = {

대형 피자 "": 25000

중형 피자 "": 18000

콜라 "": 2000

사이다 "": 2000

치즈스틱 "": 5000

}

def

get_menu_price args : dict

get_menu_price 툴이 호출되었을 때 실행됩니다


args: {"item_name": " 대형 피자

반환 : {"item_name": "...", "unit_price":

item = args.get( get("item_

price = MENU_PRICES.get(item)

if price is None

return

"item_ name":

"unit_ price": None

" error": f "'"'{ item}' 메뉴를 찾을 수 없습니다

return

"item_ name":

"unit_ price": price

def

create_order args : dict

create_order 툴이 호출되었을 때 실행됩니다

args: {

"items": [{"name": "...", "quantity": 3},

"delivery_address":

"delivery_date": "YYYY MM DD",

"notes":

반환 : 주문 요약 정보 (

items = args[ args["items

order_items = []

total_amount = 0

# 각 아이템별 가격 조회 및 소계 계산

for it in items:

name = it[ it["

qty = it[ it["

# 가격 조회

price_info = get_menu_price({ price({"item_ name":

unit_price = price_info.get( get("unit_

subtotal = unit_price * qty if unit_price is not None else 0

order_items.append({

" name":

" quantity":


int (datetime.utcnow().

"delivery_ address": args["delivery_

"delivery_ date": args["delivery_

" notes": args. get("

" items": order_

"total_ amount": total_amount

return order_summary

def

main

# 1) 사용자 입력

user_input = input � 요청을 입력하세요 :

# 2) 모델 호출 payload

payload = {

" messages":

{{" role": " system", " content": 사용자의 요청에 맞는 툴을 호출하여 처리합니다 . 정의되지 않은 툴 요청 시 안

내 메시지를 출력합니다

{{" role": " user", " content": user_

" tools":

" type": "

" function":

" name": "create_

" description": 자연어 주문 요청을 구조화된 JSON 으로 변환합니다

" parameters":

" type": "

" properties":

" items": {" type": " array", " items": {" type": " object", " properties": {" name": {" type": " string"},

" quantity": {" type": " integer"}}, " required": [" name", "

"delivery_ address": {" type": "

"delivery_ date": {" type": "

" notes": {" type": "

" required": [" items", "delivery_ address", "delivery_



" type": "

" function":

" name": "get_menu_

" description": 피자 나 콜라 메뉴의 현재 가격을 조회합니다

" parameters":

" type": "

" properties": {"item_ name": {" type": " string", " description": 메뉴 이름

" required": ["item_

" toolChoice": "

# 3) API 요청

response = requests.post(API_URL, headers=HEADERS, json=payload)

response.raise_for_status()

result = response.json()

# 4) toolC alls 처리

tool_calls = result[ result[" result"][][" message"]. get(" toolCalls",

if not tool_calls:

print ❌ 호출할 수 없는 tool 입니다

return

for call in tool_calls:

fn_name = call[ call[" function"][]["

fn_args = call[ call[" function"][]["

if fn_name == "create_

output = create_order(fn_args)

elif fn_name == "get_menu_

output = get_menu_price(fn_args)

else

output = { {" error": f 해당 tool 을 호출할 수 없습니다 : '{fn_

print f n � {fn_ 호출 결과

print (json.dumps(output, ensure_ False , 2


if

__ == "__

main()



K EY 정보 변경 후 아래 예시 입력 후 적절한 tool 이 호출되는지 확인

◼ 예시 중형 피자와 대형피자

◼ 예시 3 개의 대형 피자와 2 개의 콜라를 8 월 1 일에 강남 N 타워 로 배달해 주세요 . 로비에 놔두시면 됩니다

◼ 예시 비행기 가격 조회




7. Tool 을 활용한 팟캐스트 음성 제작 데모 페이지 구성




데모 영상 보기


실습코드



A I API 신청 및 등록

해당 서비스는 비용이 발생함



Services > AI NAVER API > AI NAVER API 선택 후 +Application 등록 선택

◼ A pplication 이름 : AITEST

⚫ Service 선택

◼ C LOVA : CLOVA Speech Recognition , CLOVA Voice

◼ NAVER : All


서비스 환경 등록 > Web 서비스 : http://ai.edu.co m 입력 후 하단의 등록 ’ 버튼 클릭

⚫ 인증정보 클릭



다음 정보 기록


인증 정보 생성 : .env 파일 생성


HCX_API_KEY=" KEY

HCX_REQUEST_ID=" ID

NAVER_CLIENT_ID=" AI API KEY

NAVER_CLIENT_SECRET=" AI API SECRET



10. 패키지 설치

pip install load_dotenv

pip install AudioSegment

sudo apt install ffmpeg




11. 실습 코드 실행

Streamlit run audio_tts.py








매거진의 이전글Lab4. Langchain 연동