건강 자동화: GPT-4 함수 호출 및 Google Calendar를 활용한 AI 의료 에이전트 구축

발행: (2026년 1월 20일 오전 09:45 GMT+9)
8 min read
원문: Dev.to

I’m happy to translate the article for you, but I’ll need the full text you’d like translated. Could you please paste the content (excluding the source line you’ve already provided) here? Once I have it, I’ll keep the source line unchanged and translate the rest into Korean while preserving all formatting, markdown, and technical terms.

소개

우리 모두 그런 경험이 있습니다: 몸이 좀 안 좋지만, 구식 병원 포털을 헤매거나 20분 동안 대기하면서 진료 예약을 잡는 생각만으로도 또 다른 증상이 생기는 느낌이죠.

“허리 아래쪽에 날카로운 통증이 있어요. 다음 주 화요일 오후에 정형외과 전문의를 찾아 주세요.” 라고 말만 하면, 똑똑한 AI 에이전트가 나머지를 처리한다면 어떨까요?

이 튜토리얼에서는 헬스케어 에이전트 컨트롤러를 구축합니다. OpenAI Function Calling, AI 에이전트, 그리고 Google Calendar API를 활용하여 다음과 같은 시스템을 만들 것입니다:

  1. 자연어 요청을 이해합니다.
  2. 의사 일정 정보를 조회합니다.
  3. 개인 일정과 교차 확인합니다.
  4. 예약을 완료합니다 – 모두 깔끔한 FastAPI 백엔드를 통해 이루어집니다.

이것이 바로 헬스케어 자동화와 개인 맞춤형 AI 비서의 미래입니다.

아키텍처 개요

신뢰할 수 있는 에이전트를 구축하려면 **“Brain”(LLM)**과 “Hands”(API) 사이에 명확한 분리를 해야 합니다. 아래는 데이터 흐름 다이어그램입니다.

sequenceDiagram
    participant User
    participant FastAPI as API_Gateway
    participant OpenAI as GPT-4o_(Brain)
    participant GCal as Google_Calendar_API_(Hands)

    User->>FastAPI: "Book a dentist for next Monday morning"
    FastAPI->>OpenAI: Prompt + Tools Definition
    OpenAI->>OpenAI: Analyze Intent & Extract Date/Type
    OpenAI-->>FastAPI: Call Function: search_doctors(specialty, date)
    FastAPI->>GCal: GET /events (Check slots)
    GCal-->>FastAPI: Returns Available Slots
    FastAPI->>OpenAI: "Found 10:00 AM and 11:30 AM"
    OpenAI-->>FastAPI: Call Function: create_appointment(time)
    FastAPI->>GCal: POST /events (Book it!)
    GCal-->>FastAPI: Confirmation
    FastAPI-->>User: "Success! You're booked for 10:00 AM."

사전 요구 사항

항목필요한 이유
OpenAI API KeyGPT‑4o(함수 호출 가능) 접근을 위해.
Google Cloud ConsoleGoogle Calendar API를 활성화하고 credentials.json을 다운로드합니다.
FastAPI & Uvicorn백엔드용 웹 서버.
python‑dotenv환경 변수를 안전하게 관리합니다.

Note: 함수 호출을 사용하면 GPT‑4가 코드에 정의한 함수의 인자를 설명할 수 있습니다. 우리는 두 가지 도구를 정의할 것입니다: 하나는 가용성을 가져오고, 다른 하나는 이벤트를 생성합니다.

1️⃣ 도구 정의 (tools.py)

# tools.py
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_calendar_availability",
            "description": "Check if a specific time slot is free on the doctor's calendar",
            "parameters": {
                "type": "object",
                "properties": {
                    "start_time": {
                        "type": "string",
                        "description": "ISO‑8601 formatted start time"
                    },
                    "end_time": {
                        "type": "string",
                        "description": "ISO‑8601 formatted end time"
                    },
                },
                "required": ["start_time", "end_time"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "book_appointment",
            "description": "Create a new calendar event for the medical appointment",
            "parameters": {
                "type": "object",
                "properties": {
                    "summary": {
                        "type": "string",
                        "description": "Reason for the visit (e.g., 'Orthopedic consult')"
                    },
                    "start_time": {"type": "string"},
                    "end_time": {"type": "string"},
                },
                "required": ["summary", "start_time", "end_time"],
            },
        },
    },
]

2️⃣ Google Calendar용 헬퍼 함수

간략히 말하면 OAuth2 흐름을 이미 완료했고 service 객체가 준비되어 있다고 가정합니다.

# gcal_helper.py
from googleapiclient.discovery import build

def create_appointment(summary: str, start_time: str, end_time: str):
    """
    Insert a new event into the authenticated user's primary calendar.
    """
    event = {
        "summary": summary,
        "start": {"dateTime": start_time, "timeZone": "UTC"},
        "end":   {"dateTime": end_time,   "timeZone": "UTC"},
    }
    # `service` should be a pre‑authenticated Google Calendar service instance.
    return service.events().insert(calendarId="primary", body=event).execute()

3️⃣ FastAPI 엔드포인트 (main.py)

# main.py
import os
import json
from fastapi import FastAPI
from openai import OpenAI
from tools import tools
from gcal_helper import create_appointment

app = FastAPI()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

@app.post("/schedule")
async def handle_medical_request(user_input: str):
    """
    Receive a natural‑language request, let the LLM decide which tool to call,
    and execute the corresponding function.
    """
    # 1️⃣ Send request to OpenAI
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": user_input}],
        tools=tools,
        tool_choice="auto",
    )

    message = response.choices[0].message

    # 2️⃣ Did the model request a function call?
    if message.tool_calls:
        for tool_call in message.tool_calls:
            if tool_call.function.name == "book_appointment":
                args = json.loads(tool_call.function.arguments)
                result = create_appointment(
                    summary=args["summary"],
                    start_time=args["start_time"],
                    end_time=args["end_time"],
                )
                return {"status": "success", "data": result}

    # If no tool call, ask the user for clarification
    return {"status": "clarification_needed", "message": message.content}

4️⃣ Production Considerations

  • HIPAA compliance – 데이터가 저장 중 및 전송 중에 암호화하고, 접근을 제한하며, 로그를 감사합니다.
  • Retrieval‑Augmented Generation (RAG) – 정확한 조언을 위해 의료 지식 베이스를 통합합니다.
  • State management – 다중 턴 대화를 처리합니다 (예: 날짜/시간 확인).

프로덕션 준비가 된 에이전트 패턴에 대해 더 자세히 알아보려면 WellAlly Blog(프롬프트 인젝션 방지, 다중 에이전트 오케스트레이션 등에 대한 전문 가이드)를 참고하세요.

다음 단계

기능설명
개인 캘린더 확인제안된 약속이 사용자의 기존 회의와 겹치지 않는지 확인합니다.
Twilio SMS 통합예약 후 확인 문자(또는 알림)를 보냅니다.
전문의 검색 도구전문의, 위치, 보험 등으로 의사를 찾기 위해 로컬 데이터베이스 또는 외부 API를 조회합니다.
오류 처리 및 재시도API 오류, 속도 제한, 모호한 사용자 입력을 우아하게 처리합니다.
테스트 및 CI/CD단위/통합 테스트를 추가하고 Docker/Kubernetes로 배포를 자동화합니다.

🎉 이제 최소한의 기능적인 의료 에이전트 컨트롤러를 구축했습니다!

GPT‑4의 추론 능력과 OpenAI Function Calling의 구조적 신뢰성을 결합함으로써, 지루한 관리 작업을 원활한 대화로 바꾸었습니다. 계속해서 반복하고 파이프라인을 안전하게 만들면, 몇 마디 말만으로 환자들이 예약을 잡을 수 있는 프로덕션 급 AI 어시스턴스를 갖게 될 것입니다.

전문의 검색을 강화하기 위해 의료 디렉터리 API 또는 다른 데이터 소스를 사용하세요.

헬스케어나 생산성을 위한 AI 에이전트를 만들고 있나요? 아래에 댓글을 남기거나 레포지토리를 공유해주세요—여러분이 이 패턴을 어떻게 구현하고 있는지 보고 싶습니다!

Back to Blog

관련 글

더 보기 »

기술은 구원자가 아니라 촉진자다

왜 사고의 명확성이 사용하는 도구보다 더 중요한가? Technology는 종종 마법 스위치처럼 취급된다—켜기만 하면 모든 것이 개선된다. 새로운 software, ...

에이전틱 코딩에 입문하기

Copilot Agent와의 경험 나는 주로 GitHub Copilot을 사용해 인라인 편집과 PR 리뷰를 수행했으며, 대부분의 사고는 내 머리로 했습니다. 최근 나는 t...