함수 호출(Function Calling) 구현

함수 호출(Function Calling) 구현

Function Calling

Function Calling은 대규모 언어 모델(LLM)이 외부 API와 연동하여 실제 작업을 수행할 수 있게 하는 기능입니다. 이 가이드에서는 Function Calling의 개념부터 실전 예시까지 알아보겠습니다.

목차

  • Function Calling 개념
  • OpenAI Function Calling
  • Claude Tool Use
  • 실전 예시
  • 모벸 예시 vs 실전 예시

1. Function Calling 개념

Function Calling은 LLM이 특정 함수를 호출하여 외부 시스템과 상호작용하는 방법입니다.

작동 원리

  1. 요청: 사용자가 질문을 합니다
  2. 추론: LLM이 질문을 분석하고 어떤 함수를 호출해야 할지 결정합니다
  3. 함수 호출: LLM이 함수 이름과 파라미터를 반환합니다
  4. 실행: 애플리케이션이 실제 함수를 호출합니다
  5. 응답: 함수의 결과를 다시 LLM에 전달하여 최종 응답을 생성합니다

장점

  • 실시 데이터 접근: 외부 API에서 실시간 정보를 가져올 수 있습니다
  • 자동화: 복잡한 작업을 자동으로 수행할 수 있습니다
  • 유연한 통합: 여러 API를 유연하게 통합할 수 있습니다

2. OpenAI Function Calling

OpenAI의 Function Calling은 표준화된 형식을 제공합니다.

함수 정의

import OpenAI from "openai";

client = OpenAI(api_key="your-api-key")

# 함수 정의
functions = [
  {
    "name": "get_weather",
    "description": "특정 도시의 날씨를 가져옵니다",
    "parameters": {
      "type": "object",
      "properties": {
        "location": {
          "type": "string",
          "description": "도시 이름 (예: 서울, 부산)"
        },
        "unit": {
          "type": "string",
          "enum": ["celsius", "fahrenheit"],
          "description": "온도 단위"
        }
      },
      "required": ["location"]
    }
  }
]

함수 호출 요청

response = client.chat.completions.create(
  model="gpt-4o",
  messages=[
    {"role": "system", "content": "당신은 도움이 되는 어시스턴트입니다."},
    {"role": "user", "content": "서울의 날씨는 어때요?"}
  ],
  functions=functions,
  function_call="auto"
)

함수 실행 및 응답

# 함수 호출 확인
function_call = response.choices[0].message.function_call

if function_call:
  # 함수 파라미터 추출
  import json
  function_args = json.loads(function_call.arguments)
  location = function_args.get("location")
  
  # 실제 함수 호출
  weather_data = get_weather(location)  # 외부 함수
  
  # 응답 생성
  second_response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
      {"role": "system", "content": "당신은 도움이 되는 어시스턴트입니다."},
      {"role": "user", "content": "서울의 날씨는 어때요?"},
      {"role": "function", "name": "get_weather", "content": json.dumps(weather_data)},
      {"role": "system", "content": f"서울의 날씨: {weather_data}"}
    ]
  )
  
  print(second_response.choices[0].message.content)

3. Claude Tool Use

Anthropic의 Claude는 Tool Use 형식을 제공합니다.

툴 정의

import anthropic

client = anthropic.Anthropic(api_key="your-api-key")

# 툴 정의
tools = [
  {
    "name": "search_database",
    "description": "데이터베이스에서 정보를 검색합니다",
    "input_schema": {
      "type": "object",
      "properties": {
        "query": {
          "type": "string",
          "description": "검색어"
        }
      },
      "required": ["query"]
    }
  }
]

툴 사용 요청

response = client.messages.create(
  model="claude-3-5-sonnet-20240229",
  max_tokens=1024,
  tools=tools,
  messages=[
    {"role": "user", "content": "최신 기사에서 AI 관련 기사를 찾아줘"}
  ]
)

4. 실전 예시

이메일 발송 시스템

functions = [
  {
    "name": "send_email",
    "description": "이메일을 발송합니다",
    "parameters": {
      "type": "object",
      "properties": {
        "to": {"type": "string", "description": "받는 사람 이메일"},
        "subject": {"type": "string", "description": "제목"},
        "body": {"type": "string", "description": "이메일 본문"}
      },
      "required": ["to", "subject", "body"]
    }
  }
]

response = client.chat.completions.create(
  model="gpt-4o",
  messages=[
    {"role": "user", "content": "john@example.com에게 회의 초대장을 보내줘"}
  ],
  functions=functions,
  function_call="auto"
)

캘린더 예약

functions = [
  {
    "name": "book_calendar",
    "description": "캘린더에 일정을 추가합니다",
    "parameters": {
      "type": "object",
      "properties": {
        "title": {"type": "string", "description": "이벤트 제목"},
        "start": {"type": "string", "description": "시작 시간 (ISO 8601)"},
        "end": {"type": "string", "description": "종료 시간 (ISO 8601)"}
      },
      "required": ["title", "start", "end"]
    }
  }
]

response = client.chat.completions.create(
  model="gpt-4o",
  messages=[
    {"role": "user", "content": "내일 오후 2시부터 3시까지 팀 회의 잡아줘"}
  ],
  functions=functions,
  function_call="auto"
)

5. 모벨 예시 vs 실전 예시

항목 모벨 예시 실전 예시
함수 복잡도 간단한 파라미터 여러 API 호출 복합
에러 처리 기본 에러 핸들링 재시도 및 폴백 전략
성능 최적화 단일 API 호출 병렬 API 호출
보안 고려 기본 권한 확인 Rate Limiting 및 인증

결론

Function Calling은 LLM을 더 강력하게 만드는 핵심 기술입니다. 실제 앱에 적용하여 사용자 경험을 극대화하세요!

  • Function Calling 개념 이해
  • OpenAI Function Calling
  • Claude Tool Use
  • 실전 예시 적용

다음으로는 AI 보안 및 가이드라인에 대해 알아보겠습니다! 🛡️