함수1.py

Google Gemini Function Calling (함수 호출) 구현


개요

항목 내용
기능 LLM이 외부 함수를 호출하는 기능
사용 사례 계산기, API 호출, DB 조회 등
핵심 LLM이 “언제” 함수를 호출할지 판단

Function Calling 흐름

사용자 질문: "8765432 + 1234567은?"
         ↓
┌─────────────────────────────┐
│  1. LLM이 질문 분석         │
│  → "계산이 필요하다" 판단    │
│  → simple_add 함수 호출 요청 │
└─────────────┬───────────────┘
              ↓
┌─────────────────────────────┐
│  2. 로컬에서 함수 실행      │
│  → simple_add(8765432, ...)  │
│  → 결과: 9999999            │
└─────────────┬───────────────┘
              ↓
┌─────────────────────────────┐
│  3. 결과를 LLM에 전달       │
│  → LLM이 자연어 응답 생성   │
└─────────────────────────────┘

전체 소스 코드

import json
from google import genai
from google.genai import types

# --- 설정 ---
MyKey = "YOUR_GEMINI_API_KEY"
MODEL_NAME = 'gemini-2.5-flash'

try:
    client = genai.Client(api_key=MyKey)
except Exception as e:
    print(f"클라이언트 초기화 오류: {e}")
    client = None

# 💡 1. 모델이 호출할 수 있는 함수 정의
def simple_add(a: int, b: int) -> str:
    """
    두 정수 a와 b를 더한 결과를 반환하는 외부 계산기 도구입니다.
    """
    result = a + b
    return json.dumps({"sum": result})

def calculate_tax(money: int) -> str:
    """
    소득(money)을 받아서 원천징수액(3.3%)을 계산합니다.
    """
    result = money - money * 0.033
    return json.dumps({"base": money, "tax": money * 0.033, "sum": result})

# 💡 2. 함수 매핑 딕셔너리
AVAILABLE_FUNCTIONS = {
    "simple_add": simple_add,
    "calculate_tax": calculate_tax
}

# 3. 함수 호출을 처리하는 메인 로직
def run_function_calling(user_query: str):
    if not client:
        print("클라이언트 초기화 실패")
        return

    print("=" * 50)
    print(f"사용자 입력: {user_query}")

    # 4. 모델에게 제공할 함수 목록
    tools = [simple_add, calculate_tax]

    # 5. 사용자 질문
    messages = [{"role": "user", "parts": [types.Part(text=user_query)]}]

    # 6. 모델에게 요청 (함수 호출 여부 자율 판단)
    response = client.models.generate_content(
        model=MODEL_NAME,
        contents=messages,
        config=types.GenerateContentConfig(tools=tools)
    )

    # 7. 모델이 함수 호출을 요청했는지 확인
    if response.function_calls:
        function_call = response.function_calls[0]
        function_name = function_call.name
        function_args = dict(function_call.args)

        print(f"\n**AI 요청:** '{function_name}' 함수 호출 (인수: {function_args})")

        # 8. 실제 함수 실행
        function_to_call = AVAILABLE_FUNCTIONS.get(function_name)
        tool_response_json = function_to_call(**function_args)

        print(f"   **함수 실행 결과:** {tool_response_json}")

        # 9. 함수 결과를 모델에게 전달
        messages.append(response.candidates[0].content)
        messages.append(
            types.Content(
                role='tool',
                parts=[
                    types.Part.from_function_response(
                        name=function_name,
                        response={"result": tool_response_json}
                    )
                ]
            )
        )

        # 10. 최종 답변 요청
        final_response = client.models.generate_content(
            model=MODEL_NAME,
            contents=messages,
        )

        print(f"\n✅ **최종 AI 답변:** {final_response.text.strip()}")

    else:
        print(f"\n**AI 응답:** 함수 호출 없이 바로 답변")
        print(response.text.strip())

# --- 실행 예제 ---

# 예제 1: 계산 (함수 호출 발생)
query1 = "외부 계산기로 8765432와 1234567을 더해줘"
run_function_calling(query1)

print("\n" + "=" * 50)

# 예제 2: 세금 계산 (함수 호출 발생)
query2 = "내 소득이 1000000원일 때 원천징수액을 계산해줘"
run_function_calling(query2)

print("\n" + "=" * 50)

# 예제 3: 일반 질문 (함수 호출 없음)
query3 = "태양계 행성의 수는 몇 개야?"
run_function_calling(query3)

핵심 개념

1. 함수 정의

함수는 docstring으로 용도를 설명해야 LLM이 언제 호출할지 판단:

def simple_add(a: int, b: int) -> str:
    """두 정수를 더하는 외부 계산기입니다."""
    return json.dumps({"sum": a + b})

2. 함수 목록 제공

tools = [simple_add, calculate_tax]

response = client.models.generate_content(
    model=MODEL_NAME,
    contents=messages,
    config=types.GenerateContentConfig(tools=tools)
)

3. 함수 호출 확인

if response.function_calls:
    function_call = response.function_calls[0]
    function_name = function_call.name      # "simple_add"
    function_args = dict(function_call.args) # {"a": 8765432, "b": 1234567}

실행 예시

==================================================
사용자 입력: 외부 계산기로 8765432와 1234567을 더해줘

**AI 요청:** 'simple_add' 함수 호출 (인수: {'a': 8765432, 'b': 1234567})
   **함수 실행 결과:** {"sum": 9999999}

✅ **최종 AI 답변:** 8765432와 1234567을 더한 결과는 9,999,999입니다!

==================================================
사용자 입력: 태양계 행성의 수는 몇 개야?

**AI 응답:** 함수 호출 없이 바로 답변
태양계에는 8개의 행성이 있습니다: 수성, 금성, 지구, 화성...

사용 사례

사례 함수 예시
계산 덧셈, 단위 변환, 세금 계산
검색 날씨 API, 주가 조회, DB 검색
외부 시스템 이메일 발송, 일정 등록