How to Integrate Next.js for healthcare with Vercel AI SDK for AI agents

By Cyprian AaronsUpdated 2026-04-21
next-js-for-healthcarevercel-ai-sdkai-agentsnextjs-for-healthcare

Combining Next.js for healthcare with Vercel AI SDK gives you a clean path to build patient-facing AI agents that can reason over clinical workflows, route requests, and return structured responses inside a modern web app. The useful pattern here is simple: Next.js for healthcare handles the app layer and healthcare-specific UI/workflow concerns, while Vercel AI SDK handles model orchestration, tool calling, and streaming responses.

Prerequisites

  • Python 3.10+
  • Node.js 18+ for the Next.js app
  • A Next.js project already set up
  • Access to the Vercel AI SDK in your Next.js app
  • A healthcare backend or mock service exposing patient/workflow endpoints
  • Environment variables configured:
    • OPENAI_API_KEY or another supported model key
    • NEXT_PUBLIC_API_BASE_URL
  • Familiarity with:
    • createAI
    • useChat
    • streamText
    • generateText

Integration Steps

  1. Create the healthcare API contract

    Start by defining the backend endpoints your agent will call. In healthcare systems, keep the contract narrow: patient lookup, appointment status, medication reminders, and triage routing.

    from dataclasses import dataclass
    from typing import Any, Dict
    
    @dataclass
    class HealthcareAPI:
        base_url: str
    
        def get_patient_summary(self, patient_id: str) -> Dict[str, Any]:
            # Replace with requests.get(...) in production
            return {
                "patient_id": patient_id,
                "name": "Jane Doe",
                "risk_level": "moderate",
                "last_visit": "2026-03-12",
                "open_tasks": ["lab review", "refill request"]
            }
    
        def create_triage_ticket(self, payload: Dict[str, Any]) -> Dict[str, Any]:
            # Replace with requests.post(...) in production
            return {
                "ticket_id": "triage_12345",
                "status": "queued",
                "payload": payload
            }
    
  2. Expose a server-side agent endpoint in Next.js

    In the Next.js route handler, use Vercel AI SDK’s streamText to call the model and wire tools that hit your healthcare API. This is where the agent becomes useful instead of just chatty.

    import os
    import json
    from typing import Any, Dict
    
    # Pseudocode-style Python showing the integration shape.
    # In the actual Next.js route handler you'll implement this in TypeScript,
    # but this demonstrates the API flow clearly.
    
    from vercel_ai_sdk import stream_text  # conceptual import for mapping intent
    
    class AgentTools:
        def __init__(self, api):
            self.api = api
    
        def get_patient_summary(self, args: Dict[str, Any]) -> Dict[str, Any]:
            return self.api.get_patient_summary(args["patient_id"])
    
        def create_triage_ticket(self, args: Dict[str, Any]) -> Dict[str, Any]:
            return self.api.create_triage_ticket(args)
    
    async def handle_agent_request(messages):
        result = stream_text(
            model="gpt-4.1-mini",
            messages=messages,
            tools={
                "get_patient_summary": {
                    "description": "Fetch a patient summary by ID",
                    "parameters": {"patient_id": {"type": "string"}}
                },
                "create_triage_ticket": {
                    "description": "Create a triage ticket for clinical review",
                    "parameters": {
                        "patient_id": {"type": "string"},
                        "reason": {"type": "string"},
                        "urgency": {"type": "string"}
                    }
                }
            }
        )
        return result
    
  3. Connect the agent to your healthcare service layer

    Keep business logic outside the model call. The model decides which tool to use; your service layer does the actual data access and validation. That keeps PHI handling deterministic.

    from pydantic import BaseModel, Field
    
    class TriageRequest(BaseModel):
        patient_id: str = Field(..., min_length=1)
        reason: str = Field(..., min_length=5)
        urgency: str = Field(default="medium")
    
    class HealthcareAgentService:
        def __init__(self, api):
            self.api = api
    
        def run_triage(self, request_data: dict) -> dict:
            req = TriageRequest(**request_data)
            ticket = self.api.create_triage_ticket(req.model_dump())
            return {
                "message": f"Triage ticket created: {ticket['ticket_id']}",
                "status": ticket["status"]
            }
    
  4. Use Vercel AI SDK on the client with streaming chat

    On the frontend side of your Next.js app for healthcare, use useChat so clinicians or patients see streaming output as soon as it’s available. The client should never talk directly to protected healthcare APIs.

    # Conceptual Python representation of client/server separation.
    # The actual client hook is used in Next.js/React code.
    
    class ChatSession:
        def __init__(self):
            self.endpoint = "/api/agent"
    
        def send_message(self, text: str) -> dict:
            payload = {
                "messages": [{"role": "user", "content": text}]
            }
            return {
                "endpoint": self.endpoint,
                "payload": payload,
                "expected_transport": "streaming"
            }
    
    session = ChatSession()
    print(session.send_message("Summarize patient P123 and open a triage ticket if needed"))
    
  5. Add guardrails for healthcare data

    Don’t let the model freewheel over PHI. Enforce authorization checks before tool execution and redact sensitive fields before returning results to the UI.

     from typing import Dict
    
     class GuardedHealthcareAPI(HealthcareAPI):
         def authorize(self, user_role: str) -> None:
             if user_role not in {"clinician", "care_coordinator"}:
                 raise PermissionError("Unauthorized access")
    
         def safe_patient_summary(self, user_role: str, patient_id: str) -> Dict[str, Any]:
             self.authorize(user_role)
             data = self.get_patient_summary(patient_id)
             return {
                 "patient_id": data["patient_id"],
                 "risk_level": data["risk_level"],
                 "last_visit": data["last_visit"],
                 # omit direct identifiers unless required by policy
             }
    

Testing the Integration

Use a simple end-to-end smoke test that validates tool routing and response shaping.

from pprint import pprint

api = HealthcareAPI(base_url="https://health.example.com")
service = HealthcareAgentService(api)

result = service.run_triage({
    "patient_id": "P123",
    "reason": "Patient reports worsening shortness of breath after discharge",
    "urgency": "high"
})

pprint(result)

Expected output:

{'message': 'Triage ticket created: triage_12345', 'status': 'queued'}

If you want one more check at the agent layer, verify that a message requesting a summary triggers get_patient_summary and returns a structured answer instead of raw model text.

Real-World Use Cases

  • Patient intake agents that collect symptoms, summarize history, and create triage tickets for nurses.
  • Care coordination assistants that pull appointment status and medication tasks into one workflow.
  • Prior authorization helpers that assemble clinical context before handing off to human review.

Keep learning

By Cyprian Aarons, AI Consultant at Topiax.

Want the complete 8-step roadmap?

Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.

Get the Starter Kit

Related Guides