keymorph
v1.1.0
Published
Official SDK for KeyMorph - Unified API gateway for Gemini keys with automatic rotation and failover
Maintainers
Readme
KeyMorph SDK
Official JavaScript/TypeScript SDK for KeyMorph - Unified API gateway for Gemini keys with automatic rotation, failover, and analytics.
Features
- 🚀 Simple and intuitive API
- 📦 Works in Node.js and browsers
- 🔄 Automatic key rotation and failover
- 📊 Built-in error handling
- 🌊 Streaming support with clean text chunks
- 💪 Full TypeScript support
- ⚡ Zero dependencies
Installation
npm install keymorphQuick Start
import KeyMorph from 'keymorph';
// Create a client with your KeyMorph endpoint
const client = new KeyMorph('https://keymorph.zeabur.app/v1/your-endpoint-id');
// Send a message
const response = await client.chat('Hello, how are you?');
console.log(response.text);Usage
Basic Chat
const response = await client.chat('Explain quantum computing in simple terms');
console.log(response.text);With Options
const response = await client.chat('Write a creative poem about coding', {
model: 'gemini-2.5-flash',
temperature: 0.9,
maxTokens: 500
});
console.log(response.text);Streaming Responses
// Raw streaming (default - chunks as they arrive)
await client.stream('Write a long story about space exploration', {
onChunk: (chunk) => {
process.stdout.write(chunk);
},
onComplete: () => {
console.log('\n✓ Streaming complete!');
},
onError: (error) => {
console.error('Error:', error.message);
}
});
// Letter-by-letter display
await client.stream('Write a poem', {
displayMode: 'letter',
letterDelay: 50, // 50ms between each letter
onChunk: (chunk) => process.stdout.write(chunk)
});
// Word-by-word display
await client.stream('Explain quantum computing', {
displayMode: 'word',
wordDelay: 100, // 100ms between each word
onChunk: (chunk) => process.stdout.write(chunk)
});
// Sentence-by-sentence display
await client.stream('Write 3 facts about AI', {
displayMode: 'sentence',
sentenceDelay: 500, // 500ms between each sentence
onChunk: (chunk) => console.log(chunk)
});Advanced Configuration
const client = new KeyMorph({
endpoint: 'https://keymorph.zeabur.app/v1/your-endpoint-id',
timeout: 60000, // 60 seconds
headers: {
'X-Custom-Header': 'value'
}
});Error Handling
import KeyMorph, { KeyMorphError } from 'keymorph';
try {
const response = await client.chat('Hello!');
console.log(response.text);
} catch (error) {
if (error instanceof KeyMorphError) {
console.error('Status:', error.statusCode);
console.error('Message:', error.message);
console.error('Response:', error.response);
}
}API Reference
Constructor
new KeyMorph(config: string | KeyMorphConfig)Parameters:
config- Endpoint URL string or configuration objectendpoint(string, required) - Your KeyMorph endpoint URLtimeout(number, optional) - Request timeout in ms (default: 30000)headers(object, optional) - Custom headers to include
Methods
chat(prompt, options?)
Send a chat message and get a response.
Parameters:
prompt(string, required) - The message to sendoptions(object, optional)model(string) - Gemini model to usetemperature(number) - Response randomness (0-1)maxTokens(number) - Maximum tokens to generateheaders(object) - Custom headers for this request
Returns: Promise<ChatResponse>
text(string) - Generated responsemodel(string) - Model usedlatencyMs(number) - Response timesuccess(boolean) - Request status
stream(prompt, options?)
Stream a chat response with clean text chunks and customizable display modes.
Parameters:
prompt(string, required) - The message to sendoptions(object, optional)model(string) - Gemini model to usetemperature(number) - Response randomness (0-1)maxTokens(number) - Maximum tokens to generatedisplayMode(string) - Display mode: 'raw' (default), 'letter', 'word', or 'sentence'letterDelay(number) - Delay in ms between letters (default: 50, for 'letter' mode)wordDelay(number) - Delay in ms between words (default: 100, for 'word' mode)sentenceDelay(number) - Delay in ms between sentences (default: 500, for 'sentence' mode)onChunk(function) - Callback for each text chunkonComplete(function) - Callback when streaming completesonError(function) - Callback for errors
Returns: Promise<void>
Display Modes:
raw- Stream chunks as they arrive from the API (fastest)letter- Display text letter-by-letter with configurable delayword- Display text word-by-word with configurable delaysentence- Display text sentence-by-sentence with configurable delay
getEndpoint()
Get the current endpoint URL.
Returns: string
setEndpoint(endpoint)
Update the endpoint URL.
Parameters:
endpoint(string) - New endpoint URL
setTimeout(timeout)
Update request timeout.
Parameters:
timeout(number) - Timeout in milliseconds
setHeaders(headers)
Update default headers.
Parameters:
headers(object) - Headers object
Supported Models
KeyMorph supports all Gemini models:
gemini-2.5-flash(Recommended - Fast and efficient)gemini-2.5-flash-lite(Fastest, lower cost)gemini-3-flash-preview(Latest preview)smart-rotate(Automatic rotation across 3 models)
Examples
Node.js CLI Tool
import KeyMorph from 'keymorph';
import readline from 'readline';
const client = new KeyMorph(process.env.KEYMORPH_ENDPOINT!);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('line', async (input) => {
try {
const response = await client.chat(input);
console.log('AI:', response.text);
} catch (error) {
console.error('Error:', error.message);
}
});React Component
import { useState } from 'react';
import KeyMorph from 'keymorph';
const client = new KeyMorph('https://keymorph.zeabur.app/v1/your-endpoint-id');
function ChatApp() {
const [input, setInput] = useState('');
const [response, setResponse] = useState('');
const [loading, setLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
try {
const result = await client.chat(input);
setResponse(result.text);
} catch (error) {
setResponse('Error: ' + error.message);
} finally {
setLoading(false);
}
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Ask anything..."
/>
<button disabled={loading}>
{loading ? 'Thinking...' : 'Send'}
</button>
</form>
{response && <p>{response}</p>}
</div>
);
}Express.js API
import express from 'express';
import KeyMorph from 'keymorph';
const app = express();
const client = new KeyMorph(process.env.KEYMORPH_ENDPOINT!);
app.use(express.json());
app.post('/api/chat', async (req, res) => {
try {
const { message } = req.body;
const response = await client.chat(message);
res.json({ reply: response.text });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000);Getting Your Endpoint
- Sign up at keymorph.zeabur.app
- Add your Gemini API keys
- Create a custom endpoint
- Copy the endpoint URL (e.g.,
https://keymorph.zeabur.app/v1/abc123xyz)
Why KeyMorph?
- Automatic Failover - If one key fails, automatically switches to another
- Smart Rotation - Distribute requests across multiple keys
- Rate Limit Protection - Never hit quota limits with intelligent rotation
- Analytics - Track usage, success rates, and latency
- Zero Downtime - 100% uptime with multi-key redundancy
Links
License
MIT © KeyMorph
Support
- 📧 Email: [email protected]
- 🐛 Issues: GitHub Issues
- 💬 Discussions: GitHub Discussions
