別再付高價:教學示範如何建立自主 AI 智能體,搜尋並預訂最便宜的醫療檢查
Stop Overpaying: Build an Autonomous AI Agent to Find and Book the Cheapest Medical Exams
這篇教學示範如何以 GPT-4、Playwright、Celery 和 Redis 建立自主 AI 智能體,搜尋並預訂價格最低的醫療檢查。系統以 GPT-4o 從網頁擷取檢查資料,再比較價格及預約選項。提交預約前,智能體會透過 Slack 或 Telegram 通知用戶確認。
Healthcare costs are notoriously opaque. One hospital might charge $500 for an MRI, while a clinic three blocks away charges $1,200. Manually checking every portal, comparing schedules, and clicking through tedious forms is a soul-crushing task. But what if you could delegate this entire workflow to a closed-loop AI Agent?
In this tutorial, we are diving deep into AI Agents, Playwright automation, and LLM-driven web scraping. We will build a system that uses GPT-4 to "think," Playwright to "act," and Celery with Redis to handle the heavy lifting of background task processing. By the end of this guide, you’ll have a blueprint for an autonomous agent capable of navigating complex medical portals to save you time and money. 🚀
The Architecture: How the Agent "Thinks" and "Acts"
Before we write a single line of code, we need to understand the data flow. We aren't just writing a scraper; we are building a closed-loop system. The agent takes a goal (e.g., "Find an MRI under $600 next Tuesday"), explores the web, extracts data, makes a decision, and executes an action.
graph TD
A[User Request] --> B[Celery Task Queue]
B --> C[AI Agent Worker]
C --> D{Playwright Browser}
D --> E[Platform A: Search & Scrape]
D --> F[Platform B: Search & Scrape]
E --> G[LLM Data Extraction]
F --> G
G --> H[Comparison Engine]
H --> I{Best Option Found?}
I -- Yes --> J[Auto-Booking Workflow]
I -- No --> K[Notify User / Retry]
J --> L[Confirmation Email]
subgraph Infrastructure
B
C
end
subgraph Logic
G
H
end
Prerequisites
To follow along, you'll need the following stack:
- Playwright: For headless browser automation (handling SPAs and Shadow DOMs).
- GPT-4 (OpenAI API): The "brain" that parses unstructured HTML and decides which buttons to click.
- Redis: Our message broker.
- Celery: To handle long-running asynchronous tasks without blocking the UI.
Step 1: Setting Up the Brain (LLM Parser)
Traditional scrapers break when a CSS class changes. Our agent uses GPT-4 to interpret the page structure dynamically. We use Pydantic to ensure the agent returns structured data.
from pydantic import BaseModel
from openai import OpenAI
client = OpenAI()
class ExamOption(BaseModel):
provider_name: str
price: float
available_date: str
booking_url: str
def parse_page_content(html_snippet: str, query: str):
"""
Uses GPT-4o to extract specific medical exam data from messy HTML.
"""
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a medical data extractor. Extract exam options into JSON."},
{"role": "user", "content": f"Context: {html_snippet}\n\nQuery: Find {query}"}
],
response_format={"type": "json_object"}
)
return response.choices[0].message.content
Step 2: The Eyes and Hands (Playwright)
We use Playwright to navigate to medical portals. Since many portals use heavy JavaScript, we wait for network idleness before capturing the state.
import asyncio
from playwright.async_api import async_playwright
async def search_medical_portal(url: str, exam_name: str):
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
# Navigate to the portal
await page.goto(url)
# Human-like interaction: Type search query
await page.fill('input[placeholder="Search exams..."]', exam_name)
await page.press('input[placeholder="Search exams..."]', "Enter")
# Wait for results to load
await page.wait_for_load_state("networkidle")
# Grab the inner text of the results container
content = await page.inner_html('.results-container')
await browser.close()
return content
Step 3: Scaling with Celery & Redis
Searching 10 different platforms takes time. We don't want the user waiting on a loading spinner. We offload this to Celery.
from celery import Celery
app = Celery('medical_agent', broker='redis://localhost:6379/0')
@app.task
def run_autonomous_booking_flow(user_id, exam_type, max_price):
# 1. Scrape multiple sources in parallel (simplified here)
raw_html = asyncio.run(search_medical_portal("https://health-portal.com", exam_type))
# 2. Extract data via LLM
data = parse_page_content(raw_html, exam_type)
# 3. Logic: Compare and find the cheapest
# (Implementation of comparison logic...)
# 4. Trigger Booking
if data['price'] <= max_price:
print(f"💰 Found a deal! Booking {exam_type} at {data['provider_name']}")
# Call booking function...
🥑 Level Up Your AI Infrastructure
Building a local prototype is easy, but moving AI Agents into production requires handling rate limits, proxy rotation, and sophisticated prompt engineering.
For more production-ready patterns, advanced agentic workflows, and deep dives into AI orchestration, check out the official WellAlly Tech Blog. They provide excellent resources on scaling LLM applications and securing autonomous agents in highly regulated industries like healthcare.
Step 4: Closing the Loop (Auto-Booking)
The "Closed-Loop" part means the agent doesn't just report—it acts. Once a candidate is found, the agent navigates to the booking_url, fills in the user's encrypted profile data (stored in Redis), and submits the form.
Note on Safety: Always implement a "Human-in-the-loop" (HITL) step for financial transactions. Our agent sends a Slack/Telegram notification with a "Confirm Booking" button before final submission.
Conclusion
By combining Playwright for navigation and GPT-4 for semantic understanding, we've moved past brittle regex-based scraping into the era of Autonomous AI Agents. This system can adapt to UI changes, handle complex searches, and ultimately perform tasks that previously required hours of human clicking.
Key Takeaways:
- Use LLMs for parsing, not for navigation logic (keep logic in Python).
- State Management is key—Redis is your best friend for tracking agent progress.
- Respect Robots.txt and implement delays to avoid being flagged.
What will you automate next? Let me know in the comments! 👇
來源:DEV Community · dev.to