문심일언 대규모 모델의 함수 호출 기능 활용 사례

대규모 언어 모델에서 '함수 호출'은 두 가지 맥락에서 사용됩니다:

  • 내부 함수 호출: 모델 자체가 입력을 처리하고 예측을 생성하기 위해 내부적으로 수행하는 연산. 이는 모델 아키텍처의 일부로, 일반 사용자에게는 보이지 않습니다.
  • 외부 API 호출: 모델이 외부 시스템과 상호작용할 수 있도록 설계된 경우. 예를 들어, 데이터베이스 조회, 이미지 처리 서비스 실행, 외부 정보 수집 등에 대한 요청을 자동으로 전달할 수 있습니다.

이번 실습에서는 문심일언(ERNIE-Bot) 모델을 활용해 외부 서비스와의 함수 호출 기능을 구현합니다. 목표는 사용자의 자연어 입력을 분석해 관광지 추천 및 예약 작업을 자동화하는 것입니다.

1. 환경 설정

먼저, 백도 인공지능 클라우드 플랫폼에서 제공하는 SDK를 설치합니다:

pip install qianfan

다음으로, 백도 인공지능 콘솔에서 애플리케이션 키(앱키)와 시크릿 키를 발급받아야 합니다.

2. 기능 요구사항

사용자가 다음과 같은 요청을 입력하면:

"서울 영등포구 주변 5킬로미터 이내의 관광지를 추천해줘"

모델은 다음 정보를 파싱하여 attractionRecommend 함수를 호출해야 합니다:

  • 위치: 서울 영등포구
  • 거리: 5000미터

또한, 사용자가:

"그럼 광화문 광장에 가기로 하자"

라고 입력하면, 모델은 attractionReservation 함수를 호출해 예약을 진행해야 합니다.

3. 코드 구현

import qianfan
import re
from pprint import pprint
import json

# 프롬프트 로드
with open('prompt_template.txt', encoding='utf-8') as f:
raw_prompt = f.read()

# 외부 함수 정의
def attraction_recommend(params):
location = params.get("location", "")
distance = params.get("expect_distance", 5000)
# 실제 서비스 연동 로직 또는 데이터베이스 검색 가능
return {
"recommended_attractions": [
{"name": "광화문광장", "distance": 1200},
{"name": "국립중앙박물관", "distance": 2300}
],
"message": f"{location} 근처 {distance}m 이내의 추천 명소입니다."
}

def attraction_reservation(params):
attraction_name = params.get("attraction", "")
# 실제 예약 시스템 연동
return {
"status": "success",
"booking_id": "BK20240517001",
"message": f"'{attraction_name}'에 대한 예약이 완료되었습니다."
}

def execute_function_call(prompt):
print(f"사용자 입력: {prompt}")

model_name = "ERNIE-Bot"
print("=" * 35, f"모델 {model_name} 응답", "=" * 35)

# 모델 호출
response = qianfan.ChatCompletion().do(
model=model_name,
messages=[{"role": "user", "content": prompt}],
temperature=0.0,
functions=[
{
"name": "attraction_recommend",
"description": "지정된 위치 주변의 관광지를 추천합니다.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "주소 정보 (시/도/구 포함)"},
"expect_distance": {"type": "integer", "description": "최대 거리 (단위: 미터)"}
},
"required": ["location"]
},
"responses": {
"type": "object",
"properties": {
"recommended_attractions": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"distance": {"type": "integer"}
}
}
},
"message": {"type": "string"}
}
}
},
{
"name": "attraction_reservation",
"description": "지정된 관광지에 대해 예약을 진행합니다.",
"parameters": {
"type": "object",
"properties": {
"attraction": {"type": "string", "description": "예약할 관광지 이름"}
},
"required": ["attraction"]
},
"responses": {
"type": "object",
"properties": {
"status": {"type": "string"},
"booking_id": {"type": "string"},
"message": {"type": "string"}
}
}
}
]
)

pprint(response)

# 함수 호출 파싱 및 실행
if 'function_call' in response['body']:
func_name = response['body']['function_call']['name']
args = response['body']['function_call']['arguments']

result = eval(func_name)(args)
print("\n함수 실행 결과:")
print(json.dumps(result, ensure_ascii=False, indent=2))

print("\n" + "=" * 35 + " 처리 완료 " + "=" * 35 + "\n")

# 프롬프트 세분화 및 처리
prompt_sections = re.split(r"----", raw_prompt)

for section in prompt_sections:
if section.strip():
execute_function_call(section.strip())

태그: 문심일언 ERNIE-Bot qianfan 함수 호출 API 연동

7월 20일 16:28에 게시됨