ApiHandler interface. This guide shows you how to add support for any LLM API.
Provider Interface
All providers must implement theApiHandler interface:
Basic Template
Here’s a minimal custom provider:Stream Chunk Types
Your provider should yield these chunk types:Text Chunks
Tool Call Chunks
Reasoning Chunks
Usage Chunks
Message Conversion
Convert HAI Build messages to your API format:Tool Calling Support
If your API supports tools:Error Handling
Use the@withRetry() decorator for automatic retries:
Prompt Caching
If your API supports prompt caching:Reasoning Models
For models with reasoning capabilities:Register Your Provider
Add your provider to the system:Real-World Example: Ollama Provider
Here’s the actual Ollama provider implementation:Testing Your Provider
Create tests for your provider:Best Practices
Client Initialization
Client Initialization
- Lazy-initialize clients in
ensureClient() - Validate required options (API key, model ID)
- Add proxy support if needed
- Include proper headers (User-Agent, etc.)
Error Handling
Error Handling
- Use
@withRetry()for network/rate limit errors - Throw immediately on auth errors (401, 403)
- Include error context (status code, message)
- Log errors for debugging
Streaming
Streaming
- Yield chunks as soon as available
- Don’t buffer entire response
- Handle partial JSON in tool calls
- Report usage at end of stream
Message Conversion
Message Conversion
- Preserve message order
- Handle all message types
- Convert tool results correctly
- Sanitize invalid content
Performance
Performance
- Reuse HTTP clients
- Enable keep-alive
- Support request cancellation
- Add timeouts for long requests
Reference Implementations
Study these providers for examples:- Simple:
ollama.ts- Basic streaming with tools - Advanced:
anthropic.ts- Caching, thinking, retries - Complex:
openai.ts- Azure, reasoning models, multiple formats - Gateway:
openrouter.ts- Cost tracking, error handling
Next Steps
Provider Overview
Understand the provider system
Anthropic Provider
Reference implementation
OpenAI Provider
Complex provider example
OpenRouter Provider
Gateway pattern