自动化你的健康:构建具备 GPT-4 函数调用和 Google Calendar 的 AI 医疗代理

发布: (2026年1月20日 GMT+8 08:45)
6 min read
原文: Dev.to

Source: Dev.to

请提供您希望翻译的完整文本(除代码块和 URL 之外),我将按照要求保持原有的 Markdown 格式并将内容翻译成简体中文。

介绍

我们都有过这种经历:身体不舒服,但想到要在笨拙的医院门户上操作,或者在电话线上等上 20 分钟才能预约医生,这种感觉就像又添了一个症状。

如果你只需要说,“我下背部有剧痛,帮我找一位下周二下午有空的骨科专家”,然后让智能 AI 代理处理剩下的事,会怎样?

在本教程中,我们将构建一个 Healthcare Agent Controller。通过利用 OpenAI Function CallingAI agentsGoogle Calendar API,我们将创建一个系统,实现以下功能:

  1. 理解自然语言请求。
  2. 查询医生的可预约时间。
  3. 与你的个人日程进行交叉对照。
  4. 完成预约——全部通过一个简洁的 FastAPI 后端完成。

这就是医疗自动化和个性化 AI 助手的未来。

架构概览

要构建可靠的代理,我们需要在 “大脑”(LLM)和 “手”(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 密钥访问 GPT‑4o(具备函数调用能力)。
Google Cloud 控制台启用 Google Calendar API 并下载 credentials.json
FastAPI 与 Uvicorn后端的 Web 服务器。
python‑dotenv安全管理环境变量。

注意: 函数调用允许 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 – encrypt data at rest and in transit, restrict access, and audit logs.
  • Retrieval‑Augmented Generation (RAG) – integrate a medical knowledge base for accurate advice.
  • State management – handle multi‑turn conversations (e.g., confirming date/time).

For a deeper dive into production‑ready agent patterns, see the WellAlly Blog (specialized guides on prompt‑injection prevention, multi‑agent orchestration, etc.).

下一步

功能描述
Personal Calendar Check确认拟议的预约不会与用户已有的会议冲突。
Twilio SMS Integration在预订后发送确认短信(或提醒)。
Specialist Lookup Tool查询本地数据库或外部 API,以按专科、地点、保险等查找医生。
Error‑Handling & Retries优雅地处理 API 失败、速率限制和模糊的用户输入。
Testing & CI/CD添加单元/集成测试,并使用 Docker/Kubernetes 自动化部署。

🎉 您已经构建了一个最小的、功能完整的医疗代理控制器!

通过将 GPT‑4 的推理能力与 OpenAI 函数调用的结构可靠性相结合,我们将繁琐的行政任务转变为流畅的对话。继续迭代,确保管道安全,您将拥有一个可投入生产的 AI 助手,只需几句话即可帮助患者预约。

使用医疗目录 API 或其他数据源来丰富专家查询功能。

您是在为医疗或生产力构建 AI 代理吗?在下方留言或分享您的仓库——我很想看到您是如何实现这些模式的!

Back to Blog

相关文章

阅读更多 »

Rapg:基于 TUI 的密钥管理器

我们都有这种经历。你加入一个新项目,首先听到的就是:“在 Slack 的置顶消息里查找 .env 文件”。或者你有多个 .env …

技术是赋能者,而非救世主

为什么思考的清晰度比你使用的工具更重要。Technology 常被视为一种魔法开关——只要打开,它就能让一切改善。新的 software,...

踏入 agentic coding

使用 Copilot Agent 的经验 我主要使用 GitHub Copilot 进行 inline edits 和 PR reviews,让我的大脑完成大部分思考。最近我决定 t...