Overview
TheChatService handles AI-powered chat message processing for the Gima chatbot. It integrates with GROQ AI models, provides rate limiting, request validation, and streaming text generation with tool support.
Key Features
- AI Integration: Uses GROQ models (llama-3.1-8b-instant) for chat generation
- Rate Limiting: IP-based rate limiting to prevent abuse
- Request Validation: Zod schema validation for incoming messages
- Message Sanitization: Context injection and tool result summarization
- Streaming Support: Real-time streaming responses with AI SDK
- Tool Execution: Supports chat tools for querying backend data
- History Management: Maintains conversation context (last 8 messages)
Class Definition
Constructor
Parameters
Dependency injection for testing and customization
Example
Methods
processMessage()
Processes a chat message request through the AI pipeline with rate limiting, validation, and streaming.Parameters
Raw JSON body from the chat request. Must conform to
chatRequestSchema:Client’s IP address for rate limiting. Pass
null to skip rate limiting.Returns
AI SDK streaming result object with:
textStream: Readable stream of generated textusage: Token usage informationfinishReason: Completion status
Throws
Thrown when client exceeds rate limit. Contains
retryAfter seconds.Thrown when request body fails validation. Contains Zod error
details.Processing Pipeline
- Rate Limiting: Checks IP-based limits (if clientIP provided)
- Validation: Validates request against Zod schema
- Sanitization: Cleans messages and injects tool context
- History Truncation: Keeps last 8 messages to stay within token limits
- AI Generation: Streams response with tool support (max 5 steps)
Example
Error Handling
RateLimitError
Thrown when client exceeds the configured rate limit.ValidationError
Thrown when request body fails Zod validation.Configuration
System Prompt
Defined in@/app/config as SYSTEM_PROMPT. Configures the AI assistant’s behavior and role.
Message History Limit
Tool Integration
Chat tools are defined in@/app/lib/ai/tools/chat-tools and include:
- Asset queries
- Maintenance schedule lookups
- Spare parts inventory
- Report generation
Step Limit
Usage in API Routes
Testing
The service supports dependency injection for easy testing:Related
Backend API Service
HTTP client for Laravel backend data
Chat Tools
Available tools for chat interactions
Rate Limiter
Rate limiting implementation
Schemas
Request validation schemas