医疗预约助手后端

一个基于FastAPI的生产就绪后端,利用Groq托管的LLaMA-3.1模型和MCP风格编排层,为AI驱动的医疗预约助手提供支持。

  • by Akerfeldt669
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 Akerfeldt669/medical-mcp-server

使用说明

医疗预约助理-后端

用于人工智能医疗预约助理的生产就绪FastAPI后端,使用 Groq托管的LLaMA-3.1模型 带着一个 MCP风格编排层.

🏗️ 建筑一瞥

┌─────────────────────────────────────────────────────────────────┐
│                    User Application Layer                       │
│              (Web UI, Mobile App, or CLI Client)                │
└────────────────────────┬────────────────────────────────────────┘
                         │ HTTP/JSON
                         ↓
┌─────────────────────────────────────────────────────────────────┐
│                   FastAPI Web Server                            │
│              (backend/main.py - HTTP Routes)                    │
├─────────────────────────────────────────────────────────────────┤
│ POST /chat              ← Main conversation endpoint            │
│ GET  /health            ← System health check                   │
│ GET  /doctors           ← List available doctors                │
│ GET  /appointments/...  ← View/manage appointments              │
└────────────────────────┬────────────────────────────────────────┘
                         │
                         ↓
┌─────────────────────────────────────────────────────────────────┐
│         MCP Server Layer (Intent Detection & Routing)           │
│              (backend/mcp/server.py & intents.py)               │
├─────────────────────────────────────────────────────────────────┤
│ • Detects user intent (BOOK, VIEW, EDIT, CANCEL, GREET)        │
│ • Routes requests to handlers                                  │
│ • Manages conversation context                                 │
│ • Controls all service calls (never calls LLM directly)         │
└─────────────┬──────────────────────┬──────────────────────┬─────┘
              │                      │                      │
         Book Intent            View Intent            Cancel Intent
              │                      │                      │
              ↓                      ↓                      ↓
        ┌──────────────┐    ┌──────────────┐    ┌──────────────────┐
        │              │    │              │    │                  │
        │ Extract with │    │ Service Load │    │ Service Delete   │
        │ Groq LLaMA   │    │ from JSON    │    │ in JSON          │
        │              │    │              │    │                  │
        └──────┬───────┘    └──────┬───────┘    └────────┬─────────┘
               │                   │                     │
               ↓                   ↓                     ↓
        ┌──────────────────────────────────────────────────────────┐
        │    Services Layer (Business Logic & File Operations)     │
        │                                                          │
        │  • CalendarService - Check availability                 │
        │  • AppointmentService - CRUD operations                 │
        │  • All JSON file writes happen HERE ONLY                │
        └──────────────────────┬───────────────────────────────────┘
                               │
                               ↓
                    ┌────────────────────────┐
                    │  Persistent Storage    │
                    │ (backend/data/)        │
                    │ appointments.json      │
                    │  (JSON file)           │
                    └────────────────────────┘

🔑 主要特点

✅ LLaMA做什么(只读)

  • 🧠 自然语言理解
  • 📝 实体提取(姓名、日期、时间、医生、原因)
  • 💬 专业响应生成
  • ❌ 不写入文件或数据库

✅ 服务内容(WRITE)

  • 📅 日历可用性检查
  • 📋 预约CRUD操作
  • 💾 JSON文件持久性
  • 🔐 通过MCP控制访问

📋 快速开始

1.获取Groq API密钥

# Visit https://console.groq.com
# Generate API key in console

2.配置环境

cp .env.example .env
# Edit .env and add GROQ_API_KEY

3.安装并运行

pip install -r requirements.txt
cd backend
python main.py

4.测试

curl http://localhost:8000/health

看 GROQ_SETUP.md 有关详细的设置说明。

📁 项目结构

backend/
├── main.py                      # FastAPI application
├── config.py                    # Configuration management (NEW)
├── mcp/
│   ├── intents.py              # Intent detection
│   └── server.py               # MCP orchestration
├── llm/
│   └── groq_client.py          # Groq LLaMA client
├── services/
│   ├── appointment_service.py  # Appointment CRUD
│   └── calendar_service.py     # Availability checking
└── data/
    └── appointments.json       # Persistent storage

docs/
├── GROQ_SETUP.md              # Groq setup guide (NEW)
├── ARCHITECTURE.md            # Detailed architecture
├── BACKEND_README.md          # API documentation
└── QUICKSTART.md              # Quick start guide

🔄 数据流示例

用户:“明天下午2点预约史密斯医生”

1. HTTP Request arrives
   ├── POST /chat
   ├── user_id: "patient001"
   └── message: "Book an appointment with Dr. Smith..."

2. MCP Server
   ├── detect_intent() → Intent.BOOK
   ├── confidence: 0.95
   └── route to: _handle_booking()

3. Groq LLaMA (READ-ONLY)
   ├── Input: "Book an appointment with Dr. Smith..."
   ├── Task: Extract entities
   └── Output: {
   │       "name": null,  # Not in message
   │       "date": "2025-12-25",
   │       "time": "14:00",
   │       "doctor_name": "Dr. Smith",
   │       "reason": null
   │   }

4. Handler checks required fields
   ├── missing: ["name", "reason"]
   └── Response: "I need your name and reason..."

5. If all fields present:
   ├── CalendarService.check_availability()
   │   └── Available? → true
   ├── AppointmentService.book_appointment()
   │   └── Writes to JSON
   └── Return confirmation

6. Response to User
   └── "✓ Appointment booked! ID: apt123..."

🚀 API终点

POST/聊天(主对话)

curl -X POST http://localhost:8000/chat \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "patient001",
    "message": "I want to book an appointment with Dr. Smith on December 27 at 10 AM"
  }'

GET/健康(状态检查)

curl http://localhost:8000/health

GET/医生(列出医生)

curl http://localhost:8000/doctors

GET/约会/{user_id}(查看约会)

curl http://localhost:8000/appointments/patient001

GET/预约/{医生}/可用(查看可用性)

curl "http://localhost:8000/appointments/Dr.%20Smith/available?date=2025-12-27"

⚙️ 配置

中的所有设置 backend/config.py:

# Groq Settings
GROQ_API_KEY = "gsk_..."          # From .env
GROQ_MODEL = "llama-3.1-70b-versatile"  # LLaMA model
GROQ_TEMPERATURE = 0.3            # Deterministic responses
GROQ_MAX_TOKENS = 500             # Response length

# Server
HOST = "0.0.0.0"
PORT = 8000
DEBUG = False

# Storage
DATA_DIR = "backend/data"
APPOINTMENTS_FILE = "backend/data/appointments.json"

🔐 MCP设计模式

为什么选择MCP?

MCP(模型上下文协议)风格的编排确保:

  1. 明确区分关注点

    • MCP:仅用于意图检测
    • LLM:仅限于NLP任务
    • 服务:仅限业务逻辑
  2. LLM安全

    • LLM从不访问文件
    • LLM从不访问数据库
    • LLM只返回结构化数据
  3. 可靠性

    • 无隐性副作用
    • 显式控制流
    • 易于测试和调试

📊 预约数据示例

{
  "id": "apt001",
  "name": "John Smith",
  "phone": "user001",
  "email": "john@example.com",
  "date": "2025-12-27",
  "time": "10:00",
  "doctor_name": "Dr. Smith",
  "reason": "General checkup",
  "status": "confirmed",
  "created_at": "2025-12-24T10:30:00",
  "updated_at": null,
  "cancelled_at": null,
  "notes": "Optional notes"
}

🧪 测试

单元测试意图检测

from backend.mcp.intents import IntentDetector, Intent

detector = IntentDetector()
intent, confidence = detector.detect("Book an appointment")
assert intent == Intent.BOOK
assert confidence > 0.2

Groq客户端单元测试

from backend.llm.groq_client import GroqLLMClient
from backend.config import config

client = GroqLLMClient(config=config)
result = client.extract_appointment_details("Book with Dr. Smith on Jan 1")
assert result["doctor_name"] == "Dr. Smith"

集成测试全流程

curl -X POST http://localhost:8000/chat \
  -H "Content-Type: application/json" \
  -d '{"user_id": "test", "message": "Hello"}'

🐛 故障排除

“未设置GROQ_API_KEY环境变量”

# Set environment variable
export GROQ_API_KEY="your_key_here"
# Or create .env file
cp .env.example .env
# Edit .env with your key

本地主机上的“连接被拒绝”:8000

# Make sure server is running
python backend/main.py

# Check port is available
lsof -i :8000  # macOS/Linux
netstat -ano | findstr :8000  # Windows

Groq的反应缓慢

首次请求时正常(冷启动)。Groq通常在1-2秒内做出反应。 检查API配额:https://console.groq.com/usage

🚢 部署

码头工人

FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY backend/ .
ENV GROQ_API_KEY=${GROQ_API_KEY}
CMD ["python", "main.py"]

Heroku

heroku create medical-assistant
heroku config:set GROQ_API_KEY="gsk_..."
git push heroku main

AWS Lambda

请参阅BACKEND_README.md中的部署文档

📚 文档

🛠️ 技术栈

  • 框架:FastAPI(Python)
  • LLM:Groq主持的LLaMA-3.1-70b
  • 服务器:乌维科恩(ASGI)
  • 数据验证:Pydantic
  • 存储:JSON文件(开发版)/PostgreSQL(生产版)
  • 环境:python dotenv

📈 演出

  • 意图检测:~10ms
  • Groq API调用:1-2秒
  • 服务操作:<50ms
  • 总请求时间:1.5-2.5秒

🔜 后续步骤

  1. ✅ 获取Groq API密钥(请参见Groq_SETUP.md)
  2. ✅ 配置.env文件
  3. ✅ 运行后端: python backend/main.py
  4. ✅ 带有curl的测试端点
  5. ⏳ 构建前端(网络/移动UI)
  6. ⏳ 迁移到PostgreSQL进行生产
  7. ⏳ 添加身份验证和速率限制
  8. ⏳ 部署到生产环境

📞 支持

  • Groq文件:https://docs.groq.com
  • FastAPI文档:https://fastapi.tiangolo.com
  • 电子邮件:ayoubaknouche666@gmail.com

👤 作者


准备好开始了吗? → See GROQ_SETUP.md 有关详细的设置说明。