Chat API Documentation
Pyre Chat Widget - API Documentation & Technical Design
Overview
The Pyre Chat Widget is a fire safety assistant chatbot interface that integrates with Google’s Gemini AI API. It provides real-time fire safety advice, emergency response guidance, and interactive chat functionality through a modern, responsive web widget.
Architecture Diagram
┌─────────────────────────────────────────────────────────────────┐
│ Client Browser │
├─────────────────────────────────────────────────────────────────┤
│ ┌─────────────────┐ ┌─────────────────┐ ┌──────────────┐ │
│ │ HTML/CSS │ │ JavaScript │ │ File Upload │ │
│ │ Chat UI │◄──►│ Controller │◄──►│ Handler │ │
│ └─────────────────┘ └─────────────────┘ └──────────────┘ │
│ │ │
├────────────────────────────────┼────────────────────────────────┤
│ API Layer │
│ │ │
│ ┌─────────────────────────────▼─────────────────────────────┐ │
│ │ HTTP Request Handler │ │
│ │ • Authentication (API Key) │ │
│ │ • Request Formatting │ │
│ │ • Error Handling │ │
│ └─────────────────────────────┬─────────────────────────────┘ │
│ │ │
├────────────────────────────────┼────────────────────────────────┤
│ External Services │
│ │ │
│ ┌─────────────────────────────▼─────────────────────────────┐ │
│ │ Google Gemini 1.5 Flash API │ │
│ │ • Natural Language Processing │ │
│ │ • Context-Aware Responses │ │
│ │ • Fire Safety Knowledge Base │ │
│ └─────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
Technical Stack
Frontend Technologies
- HTML5: Semantic markup and structure
- CSS3: Modern styling with gradients, animations, and responsive design
- Vanilla JavaScript: DOM manipulation and API integration
- CSS Grid/Flexbox: Layout management
- CSS Animations: Smooth transitions and micro-interactions
Backend Integration
- Google Gemini 1.5 Flash API: AI-powered conversational interface
- RESTful API: HTTP-based communication
- JSON: Data exchange format
API Integration
Gemini API Configuration
// API Endpoint
const GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent";
// API Key (Should be environment variable in production)
const API_KEY = "AIzaSyBEBGbw7HfOZPhKHd2T3JJT0Vz1ZIYlAD0";
Request Structure
interface GeminiRequest {
contents: Array<{
parts: Array<{
text: string;
}>;
}>;
}
Response Structure
interface GeminiResponse {
candidates: Array<{
content: {
parts: Array<{
text: string;
}>;
};
}>;
}
Core Functions
1. Chat Toggle Management
function toggleChat(): void
- Purpose: Opens/closes the chat modal
- Side Effects: Updates UI state, focuses input field
- Dependencies: DOM elements (
chatModal
,chatToggle
)
2. Message Handling
async function sendToGeminiAPI(userMessage: string): Promise<string>
- Purpose: Sends user message to Gemini API and returns AI response
- Parameters:
userMessage
: User’s input text (max 500 characters)
- Returns: AI-generated response text
- Error Handling: Returns fallback message on API failure
3. UI Message Display
function addMessageToChat(message: string, isAI: boolean = false): void
- Purpose: Adds message bubble to chat interface
- Parameters:
message
: Text content to displayisAI
: Boolean indicating if message is from AI or user
- Side Effects: Updates DOM, auto-scrolls to bottom
4. File Upload Handler
function handleFileUpload(event: Event): void
- Purpose: Processes uploaded files (images/documents)
- Supported Types: Images (display preview), other files (show filename)
- Limitations: Visual display only, no file analysis
Prompt Engineering
System Prompt Structure
The AI assistant is configured with a comprehensive system prompt that includes:
- Role Definition: Fire fighter and emergency responder persona
- Communication Style: Casual, conversational, accessible language
- Response Guidelines:
- Short, digestible responses
- Use of bullet points for complex information
- Natural speech patterns with contractions
- Credible source citation when possible
- Safety Constraints: Emphasis on reliable, accurate fire safety information
Prompt Template
const systemPrompt = `You are a chat bot named Pyre, you are an experienced fire fighter, emergency responder, and expert on fires. Some people in danger have come to you asking for help, you are pretending to be a fire responder, you are in a room where the other person is asking you for help. Your goal is answer their question while sounding natural, experienced, and while providing the best answer. Make sure all of your information is from credible sources, and when possible cite the source. Keep responses conversational and make sure your responses can be understood by a panicked person, using casual language, avoiding filler words, and slight grammatical quirks, just like real people do in digital conversation...`;
User Interface Components
1. Chat Toggle Button
- Position: Fixed bottom-right corner
- Styling: Red gradient, circular, with hover animations
- States: Default (💬) and Active (×)
2. Chat Modal
- Dimensions: 400px × 550px
- Animation: Slide-up entrance with scale effect
- Sections: Header, Messages, Input
3. Message Bubbles
- User Messages: Right-aligned, red gradient background
- AI Messages: Left-aligned, white background with subtle shadow
- Timestamps: Small, semi-transparent time display
4. Input Interface
- Text Input: Rounded, focus states with red accent
- File Upload: Plus button with hover effects
- Character Limit: 500 characters maximum
Security Considerations
Current Implementation
- API Key Exposure: ⚠️ API key is hardcoded (development only)
- Input Validation: Basic length limiting (500 chars)
- File Upload: Client-side preview only, no server processing
Production Recommendations
- Environment Variables: Move API key to secure environment variables
- Proxy Server: Implement backend proxy to hide API credentials
- Rate Limiting: Add request throttling to prevent abuse
- Input Sanitization: Enhanced validation and sanitization
- File Security: Implement server-side file validation and scanning
Performance Optimizations
Current Features
- Lazy Loading: Initial message delayed by 500ms
- Typing Indicators: Visual feedback during API calls
- Scroll Management: Auto-scroll to latest messages
- Animation Optimization: CSS transform-based animations
Potential Improvements
- Message Caching: Store recent conversations
- Debounced Input: Reduce API calls during typing
- Progressive Loading: Load chat history incrementally
- Service Worker: Offline support and caching
Error Handling
API Failures
try {
const response = await fetch(apiUrl, requestConfig);
if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}
// Process response
} catch (error) {
console.error('Error communicating with Gemini API:', error);
return "Sorry, I'm having trouble connecting right now. Please try again in a moment.";
}
User Experience
- Graceful Degradation: Fallback messages for API failures
- Visual Feedback: Typing indicators and loading states
- Input Validation: Character limits and file type restrictions
Deployment Considerations
Development Setup
- Include the HTML/CSS/JS code in your web page
- Ensure internet connectivity for API calls
- Test across different browsers and devices
Production Setup
- Security: Implement backend API proxy
- Monitoring: Add error tracking and analytics
- Testing: Cross-browser compatibility testing
- Performance: Optimize for mobile devices
Browser Compatibility
Supported Features
- Modern ES6+: Async/await, arrow functions, template literals
- CSS3: Grid, flexbox, custom properties, animations
- File API: FileReader for file upload previews
- Fetch API: Modern HTTP requests
Minimum Requirements
- Chrome 60+, Firefox 55+, Safari 12+, Edge 79+
- JavaScript enabled
- Local storage support (future enhancement)
Accessibility Features
Current Implementation
- Keyboard Navigation: Enter key for message sending
- Focus Management: Auto-focus on modal open
- Visual Indicators: Clear button states and hover effects
- Semantic HTML: Proper button and input elements
Enhancement Opportunities
- ARIA Labels: Screen reader support
- High Contrast: Alternative color schemes
- Keyboard Shortcuts: Full keyboard navigation
- Font Scaling: Responsive text sizing
API Rate Limits & Quotas
Gemini API Limits
- Requests per minute: Varies by API key tier
- Token limits: Context length restrictions
- Usage monitoring: Track through Google Cloud Console
Best Practices
- Implement client-side rate limiting
- Use connection pooling for high-traffic scenarios
- Monitor API usage and costs
- Implement exponential backoff for retries
Future Enhancements
Technical Roadmap
- Multi-language Support: Internationalization framework
- Voice Input: Speech-to-text integration
- Rich Media: Image analysis capabilities
- Offline Mode: Service worker implementation
- Analytics: User interaction tracking
- Theming: Customizable color schemes and branding
Integration Possibilities
- Emergency Services API: Direct connection to 911 services
- Weather API: Fire risk based on weather conditions
- Geolocation: Location-specific fire safety advice
- IoT Integration: Smart home fire detection systems