hospital-demo
v1.0.10
Published
A comprehensive code-first AriaFlow agent for hospital information and appointment booking, built with Hono server.
Downloads
341
Readme
🏥 Hospital Support Agent - Demo
A comprehensive code-first AriaFlow agent for hospital information and appointment booking, built with Hono server.
Features
✅ Hospital Information
- Contact details and location
- Operating hours
- Facilities and services
✅ Department Management
- Browse all departments
- Get detailed department information
- View services offered
✅ Doctor Search & Details
- Search doctors by specialty or name
- View doctor qualifications and experience
- Check doctor availability
- Get consultation fees
✅ Appointment Booking
- Check available time slots
- Book appointments with required information
- Get confirmation numbers
- File-based booking persistence
✅ Emergency Guidance
- Automatic emergency detection
- Immediate escalation for critical conditions
✅ Sessions & Working Memory
- Automatic session management (no config needed)
- Built-in working memory for context retention
- Memory automatically injected into prompts
- Persistent conversations across multiple turns
Sessions & Working Memory
AriaFlow Core has built-in session and working memory support!
How It Works
- Automatic Sessions: Runtime uses
MemoryStoreby default (in-memory) - Working Memory: Each session has a
workingMemoryobject - Auto-Injection: Memory is injected into system prompts as "Known Information"
- Persistence: Just pass
sessionIdbetween calls
Example
// First call - Runtime creates session automatically
const stream1 = runtime.stream({ input: 'My name is Sarah' });
for await (const part of stream1) {
if (part.type === 'done') {
sessionId = part.sessionId; // Save this!
}
}
// Second call - Runtime retrieves session and maintains context
const stream2 = runtime.stream({
input: "What's my name?",
sessionId // Reuse session
});Working Memory
Tools can access and modify working memory:
execute: async (input, { session }) => {
// Read
const name = session.workingMemory.user_name;
// Write
session.workingMemory.user_name = 'Sarah';
session.workingMemory.preferences = { specialty: 'Cardiology' };
return { success: true };
}The Runtime automatically injects this as:
## Known Information
{
"user_name": "Sarah",
"preferences": { "specialty": "Cardiology" }
}Demo
Run the working memory demo:
bun demo-memory.tsProduction Stores
For production, use persistent stores:
import { RedisStore } from '@ariaflowagents/redis-store';
import { PostgresStore } from '@ariaflowagents/postgres-store';
const runtime = new Runtime({
agents: [myAgent],
sessionStore: new RedisStore({ url: process.env.REDIS_URL }),
// or
sessionStore: new PostgresStore({ connectionString: process.env.DATABASE_URL }),
});Architecture
Code-First Approach
- PromptTemplateBuilder: Structured, maintainable prompts with sections for personality, goals, guardrails, glossary, and voice rules
- Runtime: Multi-agent orchestration with session management
- Tools: Type-safe tool definitions with Zod schemas
- Hono Server: HTTP/SSE/WebSocket endpoints
Tech Stack
- @ariaflowagents/core: Core AriaFlow primitives
- @ariaflowagents/hono-server: Server adapter
- Hono: Fast, lightweight web framework
- @ai-sdk/openai: OpenAI integration
- Zod v4: Schema validation
Setup
Install dependencies:
bun installConfigure environment:
# Edit .env file OPENAI_API_KEY=sk-your-key-here PORT=3000Run the server:
bun run dev
Usage
HTTP Endpoints
Health Check:
curl http://localhost:3000/healthAgent Info:
curl http://localhost:3000/infoChat (JSON):
curl -X POST http://localhost:3000/api/chat \
-H "Content-Type: application/json" \
-d '{"message": "What services do you offer?"}'Chat (SSE Streaming):
curl -N -X POST http://localhost:3000/api/chat/sse \
-H "Content-Type: application/json" \
-d '{"message": "I need to see a cardiologist"}'Session-based chat:
# First message (creates session)
curl -X POST http://localhost:3000/api/chat \
-H "Content-Type: application/json" \
-d '{"message": "Hello"}' > response.json
# Extract sessionId and use in next request
SESSION_ID=$(cat response.json | jq -r '.sessionId')
curl -X POST http://localhost:3000/api/chat \
-H "Content-Type: application/json" \
-d "{\"message\": \"I want to book an appointment\", \"sessionId\": \"$SESSION_ID\"}"WebSocket
Connect to ws://localhost:3000/ws for real-time streaming.
Interactive CLI
For testing without HTTP:
bun run test-cli.tsCommands:
/quit- Exit/help- Show help/new- Start new session
Example Conversations
1. Hospital Information
You: What are your operating hours?
Agent: [Provides OPD hours, emergency availability, pharmacy hours]2. Doctor Search
You: I need to see a cardiologist
Agent: [Uses searchDoctors tool, presents Dr. Nimal Fernando with details]
You: What's his availability?
Agent: [Uses checkDoctorAvailability, shows days and times]3. Appointment Booking
You: I want to book an appointment with Dr. Silva
Agent: [Shows availability, asks for details]
You: My name is John Smith, phone 0771234567, I need it for Tuesday
Agent: [Collects remaining info: date, time, reason]
Agent: [Uses createBooking tool, provides confirmation number]4. Emergency Detection
You: I'm having severe chest pain
Agent: This sounds like an emergency. Please call 1990 immediately...File Structure
hospital-demo/
├── .env # Environment variables
├── package.json # Dependencies
├── server.ts # Hono server with HTTP/SSE/WS
├── agent.ts # Hospital agent with PromptTemplateBuilder
├── test-cli.ts # Interactive CLI client
├── data/
│ └── hospital-info.ts # Hospital data (doctors, departments)
├── tools/
│ └── hospital-tools.ts # All agent tools
└── bookings/ # Created at runtime
└── BK-*.json # Booking confirmationsPrompt Architecture
The agent uses PromptTemplateBuilder for structured prompts:
- Personality: Professional, empathetic hospital support agent
- Goal: Information provision and booking assistance
- Guardrails:
- No medical advice
- Verify all data with tools
- Emergency escalation
- Required booking information
- Glossary: Medical terms (OPD, Emergency, Specialist, etc.)
- Voice Rules: TTS-optimized output
- Custom Sections:
- Booking process workflow
- Emergency protocol
- Hospital policies
Tools
| Tool | Purpose |
|------|---------|
| getHospitalInfo | General hospital information |
| getDepartments | Department listing and details |
| searchDoctors | Find doctors by specialty/name |
| getDoctorDetails | Detailed doctor information |
| checkDoctorAvailability | Check specific day availability |
| getAvailableSlots | Get time slots for date |
| createBooking | Create appointment booking |
Data Persistence
Bookings are saved as JSON files in bookings/ directory:
{
"confirmationNumber": "BK-12345678",
"patientName": "John Smith",
"patientPhone": "0771234567",
"doctor": { ... },
"appointmentDate": "2026-02-10",
"appointmentTime": "10:00",
"status": "confirmed",
...
}Customization
Add New Doctors
Edit data/hospital-info.ts and add to DOCTORS array.
Add New Tools
Create tool in tools/hospital-tools.ts and add to hospitalTools export.
Modify Agent Behavior
Edit prompt sections in agent.ts using PromptTemplateBuilder methods.
Change Model
In agent.ts, change:
model: openai('gpt-4o-mini') as any,
// to
model: openai('gpt-4o') as any,Testing Checklist
- [ ] Hospital information retrieval
- [ ] Doctor search by specialty
- [ ] Doctor availability checking
- [ ] Appointment booking flow
- [ ] Emergency detection
- [ ] Session persistence
- [ ] Tool usage validation
- [ ] Booking file creation
Production Considerations
For production deployment:
- Database: Replace file-based storage with PostgreSQL/MongoDB
- Authentication: Add API key validation
- Rate Limiting: Implement request throttling
- Monitoring: Add logging and metrics
- Validation: Enhanced input validation
- SMS/Email: Send booking confirmations
- Calendar Integration: Real-time availability checking
- Payment: Integrate payment gateway
License
MIT
Built with AriaFlow - A TypeScript framework for building conversational AI agents.
