Overview
PolyChat-AI integrates with the OpenRouter API to provide access to multiple AI models through a unified interface. This guide covers the integration architecture, customization options, and extension patterns.All API integration code is located in
src/services/openRouter.tsOpenRouter API Basics
API Endpoint
PolyChat-AI uses the OpenRouter chat completions endpoint:Required Headers
Every API request includes these headers (seesrc/services/openRouter.ts:44-49):
Why these headers?
Why these headers?
- Authorization: Authenticates your OpenRouter API key
- Content-Type: Specifies JSON request body format
- HTTP-Referer: Required by OpenRouter for attribution and analytics
- X-Title: Identifies your application in OpenRouter’s dashboard
Core API Functions
Non-Streaming Requests
ThefetchAIResponse() function handles standard API requests:
- Converts app message format to OpenRouter API format
- Injects system prompt as first message if provided
- Handles both text and multimodal responses (text + images)
- Returns either a string or array of
MessageContentobjects
src/services/openRouter.ts:5-97
Streaming Requests
ThestreamAIResponse() function enables real-time response streaming:
- Real-time chunk delivery via
onChunkcallback - Automatic fallback to non-streaming on error
- Cancellable via
AbortController - Server-Sent Events (SSE) parsing
- Returns complete text when done
src/services/openRouter.ts:102-191
Message Format Conversion
PolyChat-AI uses an internal message format that differs from OpenRouter’s API format. The conversion logic handles this transformation:Internal Format → API Format
- OpenRouter expects simple
{role, content}objects - PolyChat-AI’s internal format supports multimodal content (text + images)
- Text content is extracted and concatenated for API requests
System Prompt Injection
System prompts are automatically prepended to the message list:System prompts are set in Settings (
Ctrl+K) and can be customized per user preference. See the Configuration documentation.Advanced Features
Image Generation
PolyChat-AI includes specialized image generation functions:- Basic Generation
- Reliable Generation
src/services/openRouter.ts:682-731isImageGenerationModel(modelId): Check if model supports image generationgetImageModels(): Fetch list of image-capable models from OpenRouteroptimizeImagePrompt(prompt): Enhance prompts for better qualitycreateAdvancedImagePrompt(): Build detailed prompts with style/mood/lighting options
Model Discovery
Fetch available models from OpenRouter:https://openrouter.ai/api/v1/models and filter based on model capabilities.
See implementations at:
src/services/openRouter.ts:316-466(trending models)src/services/openRouter.ts:218-314(image models)
API Key Validation
Validate an OpenRouter API key before use:src/services/openRouter.ts:827-840
Customization Patterns
Adding Custom Headers
To add custom headers to all API requests:Locate the fetch calls
Open
src/services/openRouter.ts and find the fetch() calls at lines 42 and 126Modifying Request Payload
Customize the request body sent to OpenRouter:Supported OpenRouter parameters
Supported OpenRouter parameters
temperature: Randomness (0-2, default 1)top_p: Nucleus sampling (0-1, default 1)top_k: Token limitingfrequency_penalty: Reduce repetition (-2 to 2)presence_penalty: Encourage new topics (-2 to 2)max_tokens: Response length limitstop: Stop sequences
Creating a Custom API Service
To integrate a different API provider:-
Create a new service file:
src/services/customProvider.ts -
Implement the same interface:
- Update imports: Replace OpenRouter imports with your custom service
-
Maintain type compatibility: Use the same
MessageandMessageContenttypes fromsrc/types/index.ts
Error Handling
The API integration includes comprehensive error handling:Error Types
Automatic Retry Pattern
ThegenerateImageReliable() function demonstrates exponential backoff:
Performance Optimization
Request Cancellation
UseAbortController to cancel in-flight requests:
Caching Responses
Consider implementing a response cache for repeated queries:Testing & Development
Mock API Responses
For testing without API calls:Environment-Based API URLs
Switch between production and development endpoints:Related Resources
OpenRouter Documentation
Official API reference and guides
Model Pricing
Browse available models and pricing
Settings Guide
Configure API keys and preferences
Troubleshooting
Common API issues and solutions