# Text-to-Speech
Source: https://docs.electronhub.ai/api-reference/audio/speech
POST /audio/speech
Generate natural-sounding speech from text using AI voice models
Generate high-quality speech audio from text using our collection of state-of-the-art text-to-speech models from leading AI providers.
## Create Speech
`POST /audio/speech`
Convert text to natural-sounding speech audio.
### Request Body
**model** `string` *required*
The TTS model to use for speech generation (e.g., "tts-1", "tts-1-hd", "elevenlabs")
#### Text Input Parameters
**input** `string`
The text to convert to speech (1-4096 characters)
#### Voice Parameters
**voice** `string`
Voice name or ID for speech generation
#### Common Parameters
**response\_format** `string`
The audio format for the generated speech ("mp3", "opus", "aac", "flac", "wav", "pcm")
**speed** `number`
The speed of the generated audio (0.25 to 4.0 for most models, default: 1.0)
**temperature** `number`
Temperature for randomness in speech generation (0.0 to 2.0)
#### Advanced Parameters
**instructions** `string`
**GPT-4o Mini TTS**: Additional instructions to control voice characteristics
**speaker\_transcript** `string`
**Dia model**: Speaker transcript for enhanced voice control (max 1000 chars)
**cfg\_filter\_top\_k** `integer`
**Dia model**: CFG filter top k value (15-50)
**cfg\_scale** `integer`
**Dia model**: CFG scale value for generation control (1-5)
**speech\_rate** `integer`
**Microsoft TTS**: Speech rate adjustment (-100 to 100, default: 0)
**pitch\_adjustment** `integer`
**Microsoft TTS**: Pitch adjustment (-100 to 100, default: 0)
**emotional\_style** `string`
**Microsoft TTS**: Emotional style (e.g., "cheerful", "sad", "angry")
### Response
Returns an audio file in the specified format.
### Basic Example
```javascript Node.js theme={null}
const response = await fetch('https://api.electronhub.ai/v1/audio/speech', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'tts-1',
input: 'Hello! Welcome to Electron Hub text-to-speech.',
voice: 'alloy',
response_format: 'mp3'
})
});
const audioBuffer = await response.arrayBuffer();
const fs = require('fs');
fs.writeFileSync('speech.mp3', Buffer.from(audioBuffer));
```
```python Python theme={null}
import requests
response = requests.post(
'https://api.electronhub.ai/v1/audio/speech',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'model': 'tts-1',
'input': 'Hello! Welcome to Electron Hub text-to-speech.',
'voice': 'alloy',
'response_format': 'mp3'
}
)
with open('speech.mp3', 'wb') as f:
f.write(response.content)
```
```bash cURL theme={null}
curl https://api.electronhub.ai/v1/audio/speech \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "tts-1",
"input": "Hello! Welcome to Electron Hub text-to-speech.",
"voice": "alloy",
"response_format": "mp3"
}' \
--output speech.mp3
```
## Provider-Specific Examples
### OpenAI Models (TTS-1, TTS-1 HD, GPT-4o Mini TTS)
```javascript OpenAI Standard theme={null}
{
"model": "tts-1",
"input": "Hello, world!",
"voice": "alloy",
"speed": 1.0
}
```
```javascript GPT-4o Mini TTS with Instructions theme={null}
{
"model": "gpt-4o-mini-tts",
"input": "Welcome to our store!",
"voice": "nova",
"instructions": "Speak with enthusiasm and excitement, like a friendly shopkeeper"
}
```
### ElevenLabs Models
```javascript ElevenLabs theme={null}
{
"model": "elevenlabs",
"input": "Hello, this is ElevenLabs TTS.",
"voice": "Will (US male)"
}
```
```python Python - ElevenLabs theme={null}
requests.post(
'https://api.electronhub.ai/v1/audio/speech',
json={
'model': 'elevenlabs',
'input': 'Bonjour, je parle français!',
'voice': 'Guillaume (French male)'
}
)
```
### Kokoro 82M Model
```javascript Kokoro theme={null}
{
"model": "kokoro-82m",
"input": "Hello from Kokoro TTS!",
"voice": "af_alloy",
"speed": 1.2
}
```
```python Python - Kokoro theme={null}
requests.post(
'https://api.electronhub.ai/v1/audio/speech',
json={
'model': 'kokoro-82m',
'input': 'こんにちは、世界!',
'voice': 'jf_alpha'
}
)
```
### NariLabs Dia Model (Advanced)
```javascript Dia Advanced theme={null}
{
"model": "dia-1.6b",
"input": "Hello, this is a conversational speech example.",
"speaker_transcript": "Speaking in a calm, professional tone",
"cfg_scale": 3,
"cfg_filter_top_k": 25,
"temperature": 1.2,
"speed": 0.9
}
```
```python Python - Dia theme={null}
requests.post(
'https://api.electronhub.ai/v1/audio/speech',
json={
'model': 'dia-1.6b',
'input': 'Let me tell you a story...',
'speaker_transcript': 'Narrator voice with dramatic pauses',
'cfg_scale': 4,
'temperature': 1.3
}
)
```
### MeloTTS Multilingual
```javascript MeloTTS theme={null}
{
"model": "melotts",
"input": "Bonjour, comment allez-vous?",
"voice": "fr"
}
```
```python Python - MeloTTS Languages theme={null}
# English
requests.post('/v1/audio/speech', json={'model': 'melotts', 'input': 'Hello world', 'voice': 'en'})
# Spanish
requests.post('/v1/audio/speech', json={'model': 'melotts', 'input': 'Hola mundo', 'voice': 'es'})
# Chinese
requests.post('/v1/audio/speech', json={'model': 'melotts', 'input': '你好世界', 'voice': 'zh'})
```
### PlayAI Dialog Models
```javascript PlayAI theme={null}
{
"model": "playai-tts",
"input": "This is a conversational AI speaking.",
"voice": "Celeste-PlayAI",
"temperature": 0.8
}
```
```python Python - PlayAI Arabic theme={null}
requests.post(
'https://api.electronhub.ai/v1/audio/speech',
json={
'model': 'playai-tts-arabic',
'input': 'مرحبا بكم في الذكاء الاصطناعي',
'voice': 'Nasser-PlayAI'
}
)
```
### Microsoft TTS
```javascript Microsoft Basic theme={null}
{
"model": "microsoft-tts",
"input": "Hello, this is Microsoft Azure Text-to-Speech.",
"voice": "en-US-JennyNeural"
}
```
```javascript Microsoft Advanced theme={null}
{
"model": "microsoft-tts",
"input": "Welcome to our exciting new product launch!",
"voice": "en-US-AriaNeural",
"speech_rate": 10,
"pitch_adjustment": 5,
"emotional_style": "cheerful"
}
```
```python Python - Microsoft Multilingual theme={null}
requests.post(
'https://api.electronhub.ai/v1/audio/speech',
json={
'model': 'microsoft-tts',
'input': '你好,欢迎使用微软语音合成服务!',
'voice': 'zh-CN-XiaoxiaoNeural',
'speech_rate': -10,
'emotional_style': 'gentle'
}
)
```
```python Python - Microsoft Emotional theme={null}
requests.post(
'https://api.electronhub.ai/v1/audio/speech',
json={
'model': 'microsoft-tts',
'input': 'I am so sorry to hear about that.',
'voice': 'en-US-SaraNeural',
'emotional_style': 'sad',
'speech_rate': -20
}
)
```
## Available Models
### OpenAI Models
**TTS-1** (`tts-1`)
* Optimized for real-time text-to-speech
* Cost-effective for most applications
* 11 available voices: alloy, ash, ballad, coral, echo, fable, onyx, nova, sage, shimmer, verse
**TTS-1 HD** (`tts-1-hd`)
* High-quality text-to-speech
* Best audio quality with slower generation
* Same 11 voices as TTS-1
**GPT-4o Mini TTS** (`gpt-4o-mini-tts`)
* Advanced TTS with instruction following
* Supports voice control via instructions
* Same 11 voices as TTS-1
### Premium Models
**ElevenLabs** (`elevenlabs`)
* Ultra-realistic human-like voices
* 40+ multilingual voices
* Supports English, Spanish, French, German, Arabic, Chinese, Hindi, Polish
**PlayAI Dialog** (`playai-tts`)
* Specialized for conversational content
* 27 expressive voices
* Optimized for dialogue and storytelling
### Specialized Models
**Kokoro 82M** (`kokoro-82m`)
* Lightweight but high-quality
* 80+ voices in multiple languages
* Open-source Apache-licensed model
**Microsoft TTS** (`microsoft-tts`)
* Enterprise-grade quality
* 100+ neural voices
* Extensive language support
## Voice Examples
### OpenAI Voices
```javascript theme={null}
// Available voices for OpenAI models
const openaiVoices = [
'alloy', // Neutral, balanced
'echo', // Clear, professional
'fable', // Warm, storytelling
'onyx', // Deep, authoritative
'nova', // Bright, energetic
'shimmer' // Gentle, soothing
];
```
### ElevenLabs Voices
```javascript theme={null}
// Sample of ElevenLabs voices by language
const elevenlabsVoices = {
english: ['Will (US male)', 'Jessica (US female)', 'George (UK male)', 'Lily (UK female)'],
spanish: ['Juan (Spanish male)', 'Gabriela (Spanish female)'],
french: ['Guillaume (French male)', 'Darine (French female)'],
german: ['Kurt (German male)', 'Leonie (German female)']
};
// Use with voice parameter and text input
{
"model": "elevenlabs",
"input": "Hello world",
"voice": "Will (US male)"
}
```
### Microsoft TTS Voices
```javascript theme={null}
// Sample of Microsoft Azure Neural voices
const microsoftVoices = {
english: [
'en-US-JennyNeural', // Friendly female
'en-US-GuyNeural', // Casual male
'en-US-AriaNeural', // News anchor style
'en-US-DavisNeural', // Professional male
'en-GB-SoniaNeural', // British female
'en-AU-NatashaNeural' // Australian female
],
chinese: [
'zh-CN-XiaoxiaoNeural', // Standard female
'zh-CN-YunyangNeural', // Professional male
'zh-HK-HiuMaanNeural', // Hong Kong Cantonese
'zh-TW-HsiaoChenNeural' // Taiwan Mandarin
],
multilingual: [
'es-ES-ElviraNeural', // Spanish
'fr-FR-DeniseNeural', // French
'de-DE-KatjaNeural', // German
'ja-JP-NanamiNeural', // Japanese
'ko-KR-SunHiNeural' // Korean
]
};
// Use with text input and advanced controls
{
"model": "microsoft-tts",
"input": "Hello world",
"voice": "en-US-AriaNeural",
"emotional_style": "cheerful",
"speech_rate": 10
}
```
## Model-Specific Parameters
| Provider | Special Parameters | Usage |
| - | - | - |
| **GPT-4o Mini TTS** | `instructions` | Natural language voice control |
| **Dia 1.6B** | `speaker_transcript`, `cfg_scale`, `cfg_filter_top_k` | Advanced voice conditioning |
| **Microsoft TTS** | `speech_rate`, `pitch_adjustment`, `emotional_style` | Voice modulation and emotions |
| **MeloTTS** | `lang` | Language selection (en, fr, es, etc.) |
| **All Models** | `speed`, `temperature`, `top_p` | Common generation controls |
## Advanced Features
### Speed Control
Adjust playback speed for different use cases:
```json theme={null}
{
"model": "tts-1",
"input": "This text will be spoken faster.",
"voice": "alloy",
"speed": 1.5
}
```
### Audio Formats
Choose the optimal format for your application:
* **MP3**: Standard, widely compatible
* **WAV**: Uncompressed, highest quality
* **OGG/Opus**: Efficient compression
* **FLAC**: Lossless compression
* **AAC**: Good balance of quality and size
### Instruction-Based Control (GPT-4o Mini TTS)
Control voice characteristics with natural language:
```json theme={null}
{
"model": "gpt-4o-mini-tts",
"input": "Welcome to our store!",
"voice": "alloy",
"instructions": "Speak with enthusiasm and excitement, like a friendly shopkeeper"
}
```
### Microsoft TTS Advanced Controls
Microsoft TTS offers fine-grained control over speech characteristics:
#### Speech Rate Control
```json theme={null}
{
"model": "microsoft-tts",
"input": "This text will be spoken faster.",
"voice": "en-US-JennyNeural",
"speech_rate": 50
}
```
#### Pitch Adjustment
```json theme={null}
{
"model": "microsoft-tts",
"input": "This text has a higher pitch.",
"voice": "en-US-AriaNeural",
"pitch_adjustment": 25
}
```
#### Emotional Styles
Different voices support different emotional styles:
```json theme={null}
{
"model": "microsoft-tts",
"input": "I'm so excited about this news!",
"voice": "en-US-AriaNeural",
"emotional_style": "cheerful",
"speech_rate": 10
}
```
**Available Emotional Styles** (voice-dependent):
* `cheerful` - Happy and upbeat
* `sad` - Melancholic tone
* `angry` - Frustrated or upset
* `fearful` - Nervous or scared
* `calm` - Relaxed and peaceful
* `gentle` - Soft and caring
* `newscast` - Professional news anchor
* `customerservice` - Helpful and polite
## Best Practices
### Text Optimization
* Use clear punctuation for natural pauses
* Spell out numbers and abbreviations
* Use SSML tags for fine-grained control (model-dependent)
### Voice Selection
* **Customer Service**: Professional voices (echo, George)
* **Storytelling**: Warm voices (fable, nova)
* **Educational**: Clear voices (alloy, shimmer)
* **Gaming**: Character voices (onyx, sage)
### Performance Tips
* Cache generated audio when possible
* Use appropriate audio formats for your platform
* Consider real-time vs. high-quality models based on use case
## Error Handling
Common error scenarios:
```javascript theme={null}
try {
const response = await fetch('/v1/audio/speech', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'tts-1',
input: text,
voice: 'alloy'
})
});
if (!response.ok) {
const error = await response.json();
console.error('TTS Error:', error);
}
} catch (error) {
console.error('Network Error:', error);
}
```
## Use Cases
* **Voice Assistants**: Natural conversation interfaces
* **Audiobooks**: Long-form content narration
* **E-learning**: Educational content delivery
* **Accessibility**: Screen reader alternatives
* **Gaming**: Character voice generation
* **Customer Service**: Automated phone systems
* **Content Creation**: Podcast and video narration
# Speech-to-Text
Source: https://docs.electronhub.ai/api-reference/audio/transcriptions
POST /audio/transcriptions
Transcribe audio to text
`POST /v1/audio/transcriptions`
Upload an audio file and receive a text transcript.
## Limits
| Cap | Value |
| - | - |
| File size | **25 MB** |
| Duration | **25 minutes** |
| Formats | `flac`, `mp3`, `mp4`, `mpeg`, `mpga`, `m4a`, `ogg`, `wav`, `webm` |
Billing is **per minute** of audio (minimum 1 second). Rates are listed on each model in `/v1/models`.
## Request (multipart)
**file** `file` *required*
Audio file to transcribe
**model** `string` *required*
STT model ID (e.g. `deepgram-nova-3`, `whisper-large-v3-turbo`)
**language** `string`
ISO-639-1 code, or `auto` / `multi` where supported
**response\_format** `string`
`json` (default), `text`, `srt`, `verbose_json`, or `vtt`
**prompt** `string`
Optional hint text (Whisper-family models)
**temperature** `number`
`0`–`1` (ignored by some engines)
**model\_config** `string`
JSON string of engine options (Deepgram: `smart_format`, `punctuate`, `diarize`, …)
You can also pass Deepgram flags as flat form fields: `smart_format`, `punctuate`, `diarize`, `utterance`, `numerals`.
## Response
Default (`json`):
```json theme={null}
{ "text": "Hello, how are you?" }
```
`text` / `srt` / `vtt` return a plain-text body. `verbose_json` may include extra fields such as `duration`.
## Models
Usable models (see `/v1/models` for live pricing):
| Model | Notes |
| - | - |
| `deepgram-nova-3` | Multilingual; upload + streaming engines |
| `deepgram-nova-2` | Prefer `language=en` (not `auto`) |
| `deepgram-flux` | Streaming engine; file upload converted server-side |
| `whisper-large-v3-turbo` | Whisper turbo |
| `distil-whisper-large-v2` | Distil-Whisper |
| `grok-stt` | xAI |
| `assemblyai-universal-streaming` | Use `language=en` (or `es`/`de`/…) |
| `speechmatics-standard` | Speechmatics |
| `soniox-stt-rt-v4` | Prefer omitting `language` or use a concrete code |
## Examples
```bash cURL theme={null}
curl https://api.electronhub.ai/v1/audio/transcriptions \
-H "Authorization: Bearer YOUR_API_KEY" \
-F model=deepgram-nova-3 \
-F language=auto \
-F file=@audio.mp3
```
```python Python (OpenAI SDK) theme={null}
from openai import OpenAI
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.electronhub.ai/v1",
)
with open("audio.mp3", "rb") as f:
result = client.audio.transcriptions.create(
model="deepgram-nova-3",
file=f,
language="auto",
)
print(result.text)
```
```javascript Node.js (OpenAI SDK) theme={null}
import OpenAI from "openai";
import fs from "fs";
const openai = new OpenAI({
apiKey: "YOUR_API_KEY",
baseURL: "https://api.electronhub.ai/v1",
});
const result = await openai.audio.transcriptions.create({
model: "deepgram-nova-3",
file: fs.createReadStream("audio.mp3"),
language: "auto",
});
console.log(result.text);
```
# Chat Completions
Source: https://docs.electronhub.ai/api-reference/chat/completions
POST /chat/completions
Create a chat completion
## Create Chat Completion
`POST /v1/chat/completions`
### Request Body
**model** `string` *required*
Model to use for completion (e.g., `gpt-4o`, `gpt-5.1`, `claude-sonnet-4-6`, `deepseek-r1`). Append `:reasoning-exclude` to disable reasoning output for a single request.
**messages** `array` *required*
Array of message objects forming the conversation.
**max\_tokens** `integer`
Maximum number of tokens to generate. Reasoning tokens are billed as output tokens and counted against this limit.
**temperature** `number`
Sampling temperature between 0 and 2.
**stream** `boolean`
Enable streaming responses (SSE).
**reasoning\_effort** `string`
Controls reasoning depth on supported models. One of `none`, `minimal`, `low`, `medium`, `high`, `xhigh`. Silently ignored for models that don't support reasoning\_effort.
**reasoning** `object`
Reasoning configuration object. Supports:
* `reasoning.effort` — same enum as `reasoning_effort`.
* `reasoning.exclude` (boolean) — strip reasoning from the response entirely.
* `reasoning.delta_field` — `"reasoning"` or `"reasoning_content"`; overrides the streaming/non-streaming field name regardless of which endpoint variant was hit.
**reasoning\_delta\_field** `string`
Shorthand for `reasoning.delta_field`. Accepts `"reasoning"` or `"reasoning_content"`.
**reasoning\_content\_compat** `boolean`
Shorthand: set to `true` to force the legacy `reasoning_content` field, equivalent to `reasoning.delta_field = "reasoning_content"`.
## Endpoint Variants (Reasoning Output)
Some models emit a separate reasoning / thinking stream in addition to the final answer. Three base paths control how that stream is surfaced — **all of them accept the same request shape and model names**.
| Base path | Behavior | Use when |
| - | - | - |
| `POST /v1/chat/completions` | Reasoning and answer are returned as **separate fields** (`reasoning` + `content`). Default. | Most OpenAI-compatible clients. |
| `POST /v1legacy/chat/completions` | Same as `/v1/`, but reasoning uses the legacy field name **`reasoning_content`**. | Clients that only parse `reasoning_content` (e.g. older DeepSeek SDKs). |
| `POST /v1thinking/chat/completions` | Reasoning and answer are **merged into the normal `content` stream**, wrapped in `...` tags. | Clients that ignore reasoning fields but should still display thoughts inline. |
Per-request overrides (`reasoning.delta_field`, `reasoning_delta_field`, `reasoning_content_compat`) take precedence over the endpoint default. If a model does not emit reasoning, these fields are simply absent from the response.
### Streaming output shape
When reasoning is delivered as a separate field, deltas are interleaved — reasoning chunks come first, followed by content chunks:
```text theme={null}
data: {"id":"chatcmpl-...","choices":[{"index":0,"delta":{"reasoning":"Let me think..."},"finish_reason":null}], ...}
data: {"id":"chatcmpl-...","choices":[{"index":0,"delta":{"content":"The answer is 4."},"finish_reason":null}], ...}
data: [DONE]
```
Against `/v1legacy/chat/completions` the same deltas use `delta.reasoning_content` instead of `delta.reasoning`.
Against `/v1thinking/chat/completions` everything appears in `delta.content`:
```text theme={null}
data: {"choices":[{"delta":{"content":"Let me think...The answer is 4."}}]}
```
### Non-streaming output shape
```json theme={null}
{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "The answer is 4.",
"reasoning": "Let me think..."
},
"finish_reason": "stop"
}],
"usage": { "...": "..." }
}
```
`reasoning` becomes `reasoning_content` on `/v1legacy/`. On `/v1thinking/`, the reasoning stays embedded inside `content` (`"...The answer..."`) and no separate field is emitted.
## Disabling Reasoning Output
Reasoning can be hidden in three equivalent ways — the model still pays the cost for reasoning compute, but the tokens are stripped from the response:
1. Request body: `{ "reasoning": { "exclude": true } }`
2. Model suffix: `"model": "deepseek-r1:reasoning-exclude"`
3. Request body: `{ "reasoning_effort": "none" }` *(only honored on OpenAI-shaped models — safely ignored elsewhere for API parity).*
When excluded, neither the `reasoning` field nor `` tags appear in the response, regardless of which endpoint variant was hit.
### Example
```python Python theme={null}
import requests
# Default: reasoning + content in separate fields
response = requests.post(
'https://api.electronhub.ai/v1/chat/completions',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'model': 'deepseek-r1',
'messages': [{'role': 'user', 'content': "What's 2 + 2?"}],
'reasoning_effort': 'medium'
}
)
data = response.json()
print(data['choices'][0]['message']['reasoning']) # thinking text
print(data['choices'][0]['message']['content']) # answer
```
```javascript Node.js theme={null}
const res = await fetch('https://api.electronhub.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.ELECTRONHUB_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'deepseek-r1',
messages: [{ role: 'user', content: "What's 2 + 2?" }],
reasoning_effort: 'medium'
})
});
const data = await res.json();
console.log(data.choices[0].message.reasoning);
console.log(data.choices[0].message.content);
```
```bash cURL theme={null}
# Legacy field name (reasoning_content)
curl https://api.electronhub.ai/v1legacy/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "deepseek-r1",
"messages": [{"role": "user", "content": "What is 2+2?"}]
}'
# Merged ( inline)
curl https://api.electronhub.ai/v1thinking/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "deepseek-r1",
"messages": [{"role": "user", "content": "What is 2+2?"}]
}'
# Hide reasoning entirely
curl https://api.electronhub.ai/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "deepseek-r1:reasoning-exclude",
"messages": [{"role": "user", "content": "What is 2+2?"}]
}'
```
## Streaming
Enable real-time responses with streaming:
```bash theme={null}
curl https://api.electronhub.ai/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [
{"role": "user", "content": "Tell me a story"}
],
"stream": true
}'
```
## Function Calling
Use function calling for tool integration:
```bash theme={null}
curl https://api.electronhub.ai/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4",
"messages": [
{"role": "user", "content": "What is the weather like in Boston?"}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location"]
}
}
}
],
"tool_choice": "auto"
}'
```
# Embeddings
Source: https://docs.electronhub.ai/api-reference/embeddings
POST /embeddings
Generate vector embeddings for text
`input` accepts a string or an array of strings (batch in one request).
# Image Edits
Source: https://docs.electronhub.ai/api-reference/images/edits
POST /images/edits
Edit existing images using AI
Create variations or edits of existing images using AI models.
## Edit Images
`POST /images/edits`
Create edited or extended versions of an existing image.
### Request Body
**image** `file` *required*
The image to edit. Must be a valid PNG file, less than 4MB, and square.
**mask** `file`
Additional image whose fully transparent areas indicate where image should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as image.
**prompt** `string` *required*
A text description of the desired image(s)
**model** `string`
The model to use for image editing ("flux-1-kontext-pro", "flux-1-kontext-max", etc)
**n** `integer`
Number of images to generate (1-10)
**size** `string`
Size of the generated images ("256x256", "512x512", "1024x1024")
**response\_format** `string`
Format of the generated images ("url" or "b64\_json")
### Response
Returns an array of image objects with URLs or base64-encoded images.
### Example
```javascript Node.js theme={null}
const formData = new FormData();
formData.append('image', imageFile);
formData.append('prompt', 'Add a blue sky to this image');
formData.append('n', '1');
formData.append('size', '1024x1024');
const response = await fetch('https://api.electronhub.ai/v1/images/edits', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
},
body: formData
});
const data = await response.json();
console.log(data);
```
```python Python theme={null}
import requests
with open('image.png', 'rb') as image_file:
response = requests.post(
'https://api.electronhub.ai/v1/images/edits',
headers={
'Authorization': 'Bearer YOUR_API_KEY'
},
files={
'image': image_file
},
data={
'prompt': 'Add a blue sky to this image',
'n': 1,
'size': '1024x1024'
}
)
print(response.json())
```
```bash cURL theme={null}
curl -X POST "https://api.electronhub.ai/v1/images/edits" \
-H "Authorization: Bearer YOUR_API_KEY" \
-F image="@image.png" \
-F prompt="Add a blue sky to this image" \
-F n=1 \
-F size="1024x1024"
```
## Image Variations
`POST /images/variations`
Create variations of an existing image.
### Request Body
**image** `file` *required*
The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square.
**model** `string`
The model to use for generating variations ("flux-1-kontext-pro", "flux-1-kontext-max", etc)
**n** `integer`
Number of images to generate (1-10)
**size** `string`
Size of the generated images ("256x256", "512x512", "1024x1024")
**response\_format** `string`
Format of the generated images ("url" or "b64\_json")
# Image Generations
Source: https://docs.electronhub.ai/api-reference/images/generations
POST /images/generations
Generate images using AI models
Create original images using AI models like DALL-E.
## Generate Images
`POST /images/generations`
Generate images from text descriptions.
### Request Body
**prompt** `string` *required*
A text description of the desired image(s)
**model** `string`
The model to use for image generation (e.g., "dall-e-3", "dall-e-2")
**n** `integer`
Number of images to generate (1-10 for dall-e-2, 1 for dall-e-3)
**size** `string`
Size of the generated images ("256x256", "512x512", "1024x1024", "1792x1024", "1024x1792")
**quality** `string`
Quality of the image ("standard" or "hd")
**style** `string`
Style of the generated images ("vivid" or "natural")
**response\_format** `string`
Format of the generated images ("url" or "b64\_json")
### Response
Returns an array of image objects with URLs or base64-encoded images.
### Example
```javascript Node.js theme={null}
const response = await fetch('https://api.electronhub.ai/v1/images/generations', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: 'A futuristic cityscape at sunset',
model: 'dall-e-3',
n: 1,
size: '1024x1024',
quality: 'hd'
})
});
const data = await response.json();
console.log(data);
```
```python Python theme={null}
import requests
response = requests.post(
'https://api.electronhub.ai/v1/images/generations',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'prompt': 'A futuristic cityscape at sunset',
'model': 'dall-e-3',
'n': 1,
'size': '1024x1024',
'quality': 'hd'
}
)
print(response.json())
```
```bash cURL theme={null}
curl -X POST "https://api.electronhub.ai/v1/images/generations" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A futuristic cityscape at sunset",
"model": "dall-e-3",
"n": 1,
"size": "1024x1024",
"quality": "hd"
}'
```
# Messages API
Source: https://docs.electronhub.ai/api-reference/messages
POST /messages
Create a message with the Anthropic Messages format
Send a structured conversation to a model and receive an assistant message. Models trained for alternating turns expect `user` and `assistant` messages; a top-level `system` field sets standing instructions.
## Create a message
`POST /v1/messages`
### Headers
| Header | Required | Description |
| - | - | - |
| `Authorization` | Yes\* | `Bearer ` |
| `x-api-key` | Yes\* | Alternative to `Authorization` |
| `Content-Type` | Yes | `application/json` |
| `anthropic-version` | No | Accepted when present (for example `2023-06-01`) |
\*Provide one of `Authorization` or `x-api-key`.
### Body parameters
**model** `string` *required*
Model ID. Examples: `claude-sonnet-4-5-20250929`, `glm-5.3:dev`.
**messages** `array` *required*
Input turns. Each item has `role` and `content`.
* `role`: `user`, `assistant`, or `system` (mid-conversation system instruction; cannot be the first entry)
* `content`: string, or an array of content blocks (see below)
Consecutive same-role turns may be merged by the model. If the last message is `assistant`, generation continues from that partial reply.
**max\_tokens** `integer`
Maximum number of tokens to generate before stopping. Required by many Anthropic clients; omit only when the client supplies a default.
**system** `string | array`
Standing system prompt for the whole conversation.
* string: plain text
* array: list of `{ "type": "text", "text": "...", "cache_control"?: { "type": "ephemeral", "ttl"?: "5m" \| "1h" } }` blocks
Keep the array shape when using prompt caching breakpoints. Do not put the initial system prompt as `messages[0].role = "system"`; use this field instead.
**thinking** `object`
Extended thinking configuration.
| `type` | Fields |
| - | - |
| `enabled` | `budget_tokens` (required), optional `display` |
| `adaptive` | optional `budget_tokens`, optional `display` |
| `disabled` | none |
`display` is `"summarized"` or `"omitted"`. When thinking is enabled, assistant `content` may include `thinking` blocks (with `signature`) before `text` / `tool_use`.
**tools** `array`
Tools the model may call. Each custom tool:
* `name` (string, required)
* `description` (string)
* `input_schema` (JSON Schema object)
* optional: `cache_control`, `strict`, `defer_loading`, `eager_input_streaming`, `allowed_callers`, `input_examples`
Anthropic built-in tools may set `type` (for example `bash_20250124`) and omit `input_schema`.
**tool\_choice** `object`
How the model should use tools:
* `{ "type": "auto" }`
* `{ "type": "any" }`
* `{ "type": "tool", "name": "" }`
* `{ "type": "none" }`
**temperature** `number`
Sampling temperature. Range depends on the upstream model (commonly 0 to 1).
**top\_p** `number`
Nucleus sampling. `0` is ignored.
**top\_k** `integer`
Top-k sampling. `0` is ignored.
**stop\_sequences** `array`
Custom strings that stop generation when emitted.
**stream** `boolean`
If `true`, respond with server-sent events. Default `false`.
**metadata** `object`
Optional `{ "user_id": string }` for abuse tracking. Opaque ID only; do not put PII.
**betas** `array`
Anthropic beta feature flags. Accepted and forwarded when relevant.
**context\_management** `object`
Server-side context edits, for example:
```json theme={null}
{
"edits": [
{ "type": "clear_thinking_20251015", "keep": "all" }
]
}
```
**output\_config** `object`
Output controls such as `{ "effort": "low" | "medium" | "high" }`.
### Content blocks
`content` may be a string (shorthand for one `text` block) or an array of blocks.
#### User / mid-conversation system
| `type` | Fields | Notes |
| - | - | - |
| `text` | `text`, optional `cache_control` | Primary text |
| `image` | `source` | `source.type`: `base64` (`media_type`, `data`) or `url` (`url`) |
| `document` | `source`, optional `title`, `context` | PDF / text document input |
| `tool_result` | `tool_use_id`, `content`, optional `is_error`, `cache_control` | Reply to a prior `tool_use` |
| `mid_conv_system` | `content` (text blocks) | Structured mid-conversation system payload |
| `tool_addition` / `tool_removal` | `tool` | Mid-conversation tool availability changes |
Server tool result types (for example `web_search_tool_result`) are accepted as passthrough blocks.
#### Assistant
| `type` | Fields | Notes |
| - | - | - |
| `text` | `text`, optional `cache_control` | Visible reply |
| `tool_use` | `id`, `name`, `input`, optional `cache_control` | Client tool call |
| `server_tool_use` | `id`, `name`, `input` | Server-executed tool call |
| `thinking` | `thinking`, `signature` | Prior-turn reasoning; echo unchanged on the next request |
| `redacted_thinking` | `data` | Encrypted thinking; echo unchanged |
On multi-turn requests, include the full previous assistant `content` array (including thinking blocks) so reasoning continuity is preserved.
### Response
Non-streaming responses are Anthropic message objects:
```json theme={null}
{
"id": "msg_...",
"type": "message",
"role": "assistant",
"model": "claude-sonnet-4-5-20250929",
"content": [
{ "type": "text", "text": "..." }
],
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 10,
"output_tokens": 20
}
}
```
`stop_reason` is typically `end_turn`, `max_tokens`, `stop_sequence`, or `tool_use`.
Errors use Anthropic's envelope:
```json theme={null}
{
"type": "error",
"error": {
"type": "invalid_request_error",
"message": "..."
}
}
```
### Example
```bash cURL theme={null}
curl https://api.electronhub.ai/v1/messages \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4-5-20250929",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Hello"}
]
}'
```
```python Python theme={null}
import anthropic
client = anthropic.Anthropic(
api_key="YOUR_API_KEY",
base_url="https://api.electronhub.ai/v1",
)
message = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
)
print(message.content)
```
```javascript Node.js theme={null}
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
apiKey: "YOUR_API_KEY",
baseURL: "https://api.electronhub.ai/v1",
});
const message = await client.messages.create({
model: "claude-sonnet-4-5-20250929",
max_tokens: 1024,
messages: [{ role: "user", content: "Hello" }],
});
console.log(message.content);
```
## Count tokens
`POST /v1/messages/count_tokens`
Estimate input tokens for a Messages request without running inference.
### Body
Same shape as [Create a message](#create-a-message): at least `model` and `messages`. `system`, `tools`, and related fields are included in the estimate when present.
### Response
```json theme={null}
{
"input_tokens": 1234
}
```
# List Models
Source: https://docs.electronhub.ai/api-reference/models
GET /models
List all available models
Retrieve a list of available models that can be used with the API.
## Response
Returns a list of model objects containing information about each available model including their capabilities and pricing tier.
## Example Response
```json theme={null}
{
"object": "list",
"data": [
{
"id": "gpt-4o",
"object": "model",
"owned_by": "openai"
},
{
"id": "claude-3-5-sonnet-20241022",
"object": "model",
"owned_by": "anthropic"
},
{
"id": "gemini-pro",
"object": "model",
"owned_by": "google"
}
]
}
```
# Moderations
Source: https://docs.electronhub.ai/api-reference/moderations
POST /moderations
Classify text content for safety violations
The Moderations API helps detect potentially harmful content in text.
## Create Moderation
`POST /moderations`
Classify a text to see if it violates OpenAI's usage policies.
### Request Body
**input** `string | array` *required*
The input text to classify
**model** `string`
The moderation model to use (e.g., "text-moderation-latest", "text-moderation-stable")
### Response
Returns a moderation object with classification results.
### Example
```javascript Node.js theme={null}
const response = await fetch('https://api.electronhub.ai/v1/moderations', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
input: 'I want to hurt someone.',
model: 'text-moderation-latest'
})
});
const data = await response.json();
console.log(data);
```
```python Python theme={null}
import requests
response = requests.post(
'https://api.electronhub.ai/v1/moderations',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'input': 'I want to hurt someone.',
'model': 'text-moderation-latest'
}
)
print(response.json())
```
```bash cURL theme={null}
curl -X POST "https://api.electronhub.ai/v1/moderations" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"input": "I want to hurt someone.",
"model": "text-moderation-latest"
}'
```
### Response Format
The response contains the following fields:
* `id`: Unique identifier for the moderation request
* `model`: The model used for moderation
* `results`: Array of result objects with the following properties:
* `flagged`: Whether the content was flagged
* `categories`: Object with boolean values for each category
* `category_scores`: Object with confidence scores for each category
### Categories
The moderation model checks for the following categories:
* **hate**: Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste
* **hate/threatening**: Hateful content that also includes violence or serious harm towards the targeted group
* **harassment**: Content that expresses, incites, or promotes harassing language towards any target
* **harassment/threatening**: Harassment content that also includes violence or serious harm towards any target
* **self-harm**: Content that promotes, encourages, or depicts acts of self-harm
* **self-harm/intent**: Content where the speaker expresses that they are engaging or intend to engage in acts of self-harm
* **self-harm/instructions**: Content that encourages performing acts of self-harm
* **sexual**: Content meant to arouse sexual excitement
* **sexual/minors**: Sexual content that includes an individual who is under 18 years old
* **violence**: Content that depicts death, violence, or physical injury
* **violence/graphic**: Content that depicts death, violence, or physical injury in graphic detail
# Create Proxy Key
Source: https://docs.electronhub.ai/api-reference/proxy-create
POST /auth/proxy/create
Create a new proxy key with specified permissions and limits
Tier key caps: Free 10, Basic 15, Standard 30, Pro 50, Enterprise 100.
llocated\_ammount max is ,000. expires\_at is a Unix timestamp, or -1 for no expiry. Empty model\_whitelist / ip\_whitelist means unrestricted.
```bash cURL theme={null}
curl https://api.electronhub.ai/v1/auth/proxy/create \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ELECTRONHUB_API_KEY" \
-d '{
"name": "Production API Key",
"expires_at": 1735689600,
"allocated_ammount": 100.0,
"model_whitelist": ["gpt-4o", "claude-3-5-sonnet-20241022"],
"ip_whitelist": ["192.168.1.0/24", "203.0.113.42"]
}'
```
```python Python theme={null}
import httpx
import time
# Calculate expiration date (30 days from now)
expires_at = int(time.time()) + (30 * 24 * 60 * 60)
client = httpx.Client()
response = client.post(
"https://api.electronhub.ai/v1/auth/proxy/create",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
},
json={
"name": "Production API Key",
"expires_at": expires_at,
"allocated_ammount": 100.0,
"model_whitelist": ["gpt-4o", "claude-3-5-sonnet-20241022"],
"ip_whitelist": ["192.168.1.0/24", "203.0.113.42"]
}
)
proxy_key = response.json()
print(f"Created proxy key: {proxy_key['key']}")
```
```javascript Node.js theme={null}
// Calculate expiration date (30 days from now)
const expiresAt = Math.floor(Date.now() / 1000) + (30 * 24 * 60 * 60);
const response = await fetch('https://api.electronhub.ai/v1/auth/proxy/create', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.ELECTRONHUB_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'Production API Key',
expires_at: expiresAt,
allocated_ammount: 100.0,
model_whitelist: ['gpt-4o', 'claude-3-5-sonnet-20241022'],
ip_whitelist: ['192.168.1.0/24', '203.0.113.42']
}),
});
const proxyKey = await response.json();
console.log(`Created proxy key: ${proxyKey.key}`);
```
```json Response theme={null}
{
"name": "Production API Key",
"key": "ek-proxy-1234567890abcdef",
"expires_at": 1735689600,
"allocated_ammount": 100.0,
"used_ammount": 0.0,
"is_active": true,
"model_whitelist": ["gpt-4o", "claude-3-5-sonnet-20241022"],
"ip_whitelist": ["192.168.1.0/24", "203.0.113.42"],
"created_at": 1704067200,
"last_used": null
}
```
# Delete Proxy Key
Source: https://docs.electronhub.ai/api-reference/proxy-delete
POST /auth/proxy/remove
Delete a specific proxy key you own
Permanent delete. Identify the key with body field proxy\_key. Legacy DELETE /v1/auth/proxy/delete/ still works but is discouraged.
```bash cURL theme={null}
curl -X POST https://api.electronhub.ai/v1/auth/proxy/remove \
-H "Authorization: Bearer $ELECTRONHUB_API_KEY" \
-H "Content-Type: application/json" \
-d '{"proxy_key": "ek-proxy-1234567890abcdef"}'
```
```python Python theme={null}
import httpx
response = httpx.post(
"https://api.electronhub.ai/v1/auth/proxy/remove",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={"proxy_key": "ek-proxy-1234567890abcdef"},
)
result = response.json()
print(f"Delete result: {result['message']}")
```
```javascript Node.js theme={null}
const response = await fetch('https://api.electronhub.ai/v1/auth/proxy/remove', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.ELECTRONHUB_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ proxy_key: 'ek-proxy-1234567890abcdef' }),
});
const result = await response.json();
console.log(`Delete result: ${result.message}`);
```
```json Success Response theme={null}
{
"message": "Proxy key deleted"
}
```
```json Error Response theme={null}
{
"detail": "Proxy key not found"
}
```
# Delete All Proxy Keys
Source: https://docs.electronhub.ai/api-reference/proxy-delete-all
DELETE /auth/proxy/delete
Delete all proxy keys for the authenticated user
Deletes every proxy key on the account. Irreversible.
```bash cURL theme={null}
curl -X DELETE https://api.electronhub.ai/v1/auth/proxy/delete \
-H "Authorization: Bearer $ELECTRONHUB_API_KEY"
```
```python Python theme={null}
import httpx
response = httpx.delete(
"https://api.electronhub.ai/v1/auth/proxy/delete",
headers={"Authorization": f"Bearer {api_key}"},
)
result = response.json()
print(f"Bulk delete result: {result['message']}")
```
```javascript Node.js theme={null}
const response = await fetch('https://api.electronhub.ai/v1/auth/proxy/delete', {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${process.env.ELECTRONHUB_API_KEY}`,
},
});
const result = await response.json();
console.log(`Bulk delete result: ${result.message}`);
```
```json Success Response theme={null}
{
"message": "Proxy keys deleted"
}
```
```json No Keys Response theme={null}
{
"message": "Proxy keys deleted"
}
```
# List Proxy Keys
Source: https://docs.electronhub.ai/api-reference/proxy-keys
GET /auth/proxy
Retrieve all proxy keys for the authenticated user
```bash cURL theme={null}
curl https://api.electronhub.ai/v1/auth/proxy \
-H "Authorization: Bearer $ELECTRONHUB_API_KEY"
```
```python Python theme={null}
import httpx
client = httpx.Client()
response = client.get(
"https://api.electronhub.ai/v1/auth/proxy",
headers={
"Authorization": f"Bearer {api_key}"
}
)
proxy_keys = response.json()
print(f"Found {len(proxy_keys)} proxy keys")
```
```javascript Node.js theme={null}
const response = await fetch('https://api.electronhub.ai/v1/auth/proxy', {
method: 'GET',
headers: {
'Authorization': `Bearer ${process.env.ELECTRONHUB_API_KEY}`,
},
});
const proxyKeys = await response.json();
console.log(`Found ${proxyKeys.length} proxy keys`);
```
```json Response theme={null}
[
{
"name": "Production API Key",
"key": "ek-proxy-1234567890abcdef",
"expires_at": 1735689600,
"allocated_ammount": 100.0,
"used_ammount": 25.5,
"is_active": true,
"model_whitelist": ["gpt-4o", "claude-3-5-sonnet-20241022"],
"ip_whitelist": ["192.168.1.0/24"],
"created_at": 1704067200,
"last_used": 1704153600
},
{
"name": "Development Key",
"key": "ek-proxy-abcdef1234567890",
"expires_at": -1,
"allocated_ammount": 10.0,
"used_ammount": 2.1,
"is_active": true,
"model_whitelist": [],
"ip_whitelist": [],
"created_at": 1704067200,
"last_used": 1704139200
}
]
```
# Lookup Proxy Key
Source: https://docs.electronhub.ai/api-reference/proxy-lookup
POST /auth/proxy/lookup
Retrieve metadata about a single proxy key you own
Identify the key with body field proxy\_key. Legacy GET /v1/auth/proxy/ still works but is discouraged.
```bash cURL theme={null}
curl https://api.electronhub.ai/v1/auth/proxy/lookup \
-H "Authorization: Bearer $ELECTRONHUB_API_KEY" \
-H "Content-Type: application/json" \
-d '{"proxy_key": "ek-proxy-1234567890abcdef"}'
```
```python Python theme={null}
import httpx
response = httpx.post(
"https://api.electronhub.ai/v1/auth/proxy/lookup",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={"proxy_key": "ek-proxy-1234567890abcdef"},
)
proxy = response.json()
print(proxy["name"], proxy["allocated_ammount"] - proxy["used_ammount"])
```
```javascript Node.js theme={null}
const response = await fetch('https://api.electronhub.ai/v1/auth/proxy/lookup', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.ELECTRONHUB_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ proxy_key: 'ek-proxy-1234567890abcdef' }),
});
const proxy = await response.json();
console.log(proxy.name, proxy.allocated_ammount - proxy.used_ammount);
```
```json Response theme={null}
{
"name": "Production API Key",
"key": "ek-proxy-1234567890abcdef",
"user_id": "user_abc123",
"expires_at": 1735689600,
"allocated_ammount": 100.0,
"used_ammount": 25.5,
"is_active": true,
"model_whitelist": ["gpt-4o", "claude-3-5-sonnet-20241022"],
"ip_whitelist": ["192.168.1.0/24"],
"enabled_thinking": true,
"created_at": 1704067200,
"last_used": 1704153600
}
```
# Toggle Proxy Key Status
Source: https://docs.electronhub.ai/api-reference/proxy-toggle
POST /auth/proxy/toggle
Enable or disable a proxy key without deleting it
Identify the key with body field proxy\_key. Legacy POST /v1/auth/proxy/toggle/ still works but is discouraged.
```bash cURL theme={null}
curl -X POST https://api.electronhub.ai/v1/auth/proxy/toggle \
-H "Authorization: Bearer $ELECTRONHUB_API_KEY" \
-H "Content-Type: application/json" \
-d '{"proxy_key": "ek-proxy-1234567890abcdef"}'
```
```python Python theme={null}
import httpx
response = httpx.post(
"https://api.electronhub.ai/v1/auth/proxy/toggle",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={"proxy_key": "ek-proxy-1234567890abcdef"},
)
result = response.json()
print(f"Status updated: {result['message']}")
print(f"New status: {'Active' if result['status'] else 'Inactive'}")
```
```javascript Node.js theme={null}
const response = await fetch('https://api.electronhub.ai/v1/auth/proxy/toggle', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.ELECTRONHUB_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ proxy_key: 'ek-proxy-1234567890abcdef' }),
});
const result = await response.json();
console.log(`Status updated: ${result.message}`);
console.log(`New status: ${result.status ? 'Active' : 'Inactive'}`);
```
```json Enable Response theme={null}
{
"message": "Proxy key status updated",
"status": true
}
```
```json Disable Response theme={null}
{
"message": "Proxy key status updated",
"status": false
}
```
# Update Proxy Key
Source: https://docs.electronhub.ai/api-reference/proxy-update
POST /auth/proxy/update
Update an existing proxy key's configuration
Identify the key with body field proxy\_key. Legacy POST /v1/auth/proxy/update/ still works but is discouraged.
```bash cURL theme={null}
curl https://api.electronhub.ai/v1/auth/proxy/update \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ELECTRONHUB_API_KEY" \
-d '{
"proxy_key": "ek-proxy-1234567890abcdef",
"name": "Updated Production Key",
"expires_at": 1767225600,
"allocated_ammount": 150.0,
"model_whitelist": ["gpt-4o", "claude-3-5-sonnet-20241022", "dall-e-3"],
"ip_whitelist": ["192.168.1.0/24"]
}'
```
```python Python theme={null}
import httpx
import time
expires_at = int(time.time()) + (60 * 24 * 60 * 60)
response = httpx.post(
"https://api.electronhub.ai/v1/auth/proxy/update",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={
"proxy_key": "ek-proxy-1234567890abcdef",
"name": "Updated Production Key",
"expires_at": expires_at,
"allocated_ammount": 150.0,
"model_whitelist": ["gpt-4o", "claude-3-5-sonnet-20241022", "dall-e-3"],
"ip_whitelist": ["192.168.1.0/24"],
},
)
result = response.json()
print(f"Update result: {result['message']}")
```
```javascript Node.js theme={null}
const expiresAt = Math.floor(Date.now() / 1000) + (60 * 24 * 60 * 60);
const response = await fetch('https://api.electronhub.ai/v1/auth/proxy/update', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.ELECTRONHUB_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
proxy_key: 'ek-proxy-1234567890abcdef',
name: 'Updated Production Key',
expires_at: expiresAt,
allocated_ammount: 150.0,
model_whitelist: ['gpt-4o', 'claude-3-5-sonnet-20241022', 'dall-e-3'],
ip_whitelist: ['192.168.1.0/24'],
}),
});
const result = await response.json();
console.log(`Update result: ${result.message}`);
```
```json Success Response theme={null}
{
"message": "Proxy key updated"
}
```
```json Error Response theme={null}
{
"detail": "Allocated ammount cannot exceed your daily limit of 100"
}
```
# Validate Proxy Key Access
Source: https://docs.electronhub.ai/api-reference/proxy-validate
POST /auth/proxy/validate
Validate if a proxy key can access a specific model from the current IP
Authorize with the proxy key itself (Bearer ek-proxy-...). Optional model checks model whitelist against the caller IP.
```bash cURL theme={null}
curl https://api.electronhub.ai/v1/auth/proxy/validate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ek-proxy-1234567890abcdef" \
-d '{
"model": "gpt-4o"
}'
```
```python Python theme={null}
import httpx
# Use proxy key for validation
proxy_key = "ek-proxy-1234567890abcdef"
client = httpx.Client()
response = client.post(
"https://api.electronhub.ai/v1/auth/proxy/validate",
headers={
"Authorization": f"Bearer {proxy_key}",
"Content-Type": "application/json"
},
json={
"model": "gpt-4o"
}
)
result = response.json()
if result["valid"]:
print(f"Access granted: {result['message']}")
else:
print(f"Access denied: {result['message']}")
```
```javascript Node.js theme={null}
const proxyKey = 'ek-proxy-1234567890abcdef';
const response = await fetch('https://api.electronhub.ai/v1/auth/proxy/validate', {
method: 'POST',
headers: {
'Authorization': `Bearer ${proxyKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'gpt-4o'
}),
});
const result = await response.json();
if (result.valid) {
console.log(`Access granted: ${result.message}`);
} else {
console.log(`Access denied: ${result.message}`);
}
```
```json Valid Access theme={null}
{
"valid": true,
"message": "Access granted"
}
```
```json Invalid Model theme={null}
{
"valid": false,
"message": "Model 'gpt-4o' not in whitelist"
}
```
```json IP Restricted theme={null}
{
"valid": false,
"message": "IP address not in whitelist"
}
```
```json Expired Key theme={null}
{
"valid": false,
"message": "Proxy key has expired"
}
```
# Regenerate API Key
Source: https://docs.electronhub.ai/api-reference/regenerate-key
GET /auth/key/regen
Generate a new API key for the authenticated user
> [!WARNING]
>
> Immediately invalidates the current primary API key. Proxy keys are unaffected. The old key cannot be recovered.
```bash cURL theme={null}
curl https://api.electronhub.ai/v1/auth/key/regen \
-H "Authorization: Bearer $ELECTRONHUB_API_KEY"
```
```python Python theme={null}
import httpx
client = httpx.Client()
response = client.get(
"https://api.electronhub.ai/v1/auth/key/regen",
headers={
"Authorization": f"Bearer {api_key}"
}
)
result = response.json()
new_api_key = result["key"]
print(f"New API key: {new_api_key}")
# Important: Update your applications with the new key
print("Remember to update all applications with the new API key!")
```
```javascript Node.js theme={null}
const response = await fetch('https://api.electronhub.ai/v1/auth/key/regen', {
method: 'GET',
headers: {
'Authorization': `Bearer ${process.env.ELECTRONHUB_API_KEY}`,
},
});
const result = await response.json();
const newApiKey = result.key;
console.log(`New API key: ${newApiKey}`);
// Important: Update your applications with the new key
console.log('Remember to update all applications with the new API key!');
```
```json Response theme={null}
{
"key": "ek-1234567890abcdef1234567890abcdef"
}
```
# Responses API
Source: https://docs.electronhub.ai/api-reference/responses
POST /responses
Create a model response with the OpenAI Responses format
Create a model response from text or message input.
## Create Response
`POST /responses`
Create a text response using OpenAI's response format.
### Request Body
**model** `string` *required*
The model to use for response (e.g., "gpt-4o")
**input** `string | array` *required*
The input text or array of messages to generate responses for
**instructions** `string`
System instructions for the model
**max\_output\_tokens** `integer`
Maximum number of output tokens to generate
**temperature** `number`
Temperature for randomness (default: 1.0)
**top\_p** `number`
Nucleus sampling parameter (default: 1.0)
**stream** `boolean`
Whether to stream back partial progress (default: false)
**tools** `array`
Array of tools available to the model
**tool\_choice** `string | object`
Tool choice preference ("auto", "none", or specific tool object)
**web\_search** `boolean`
Enable web search capabilities (default: false)
**reasoning** `object`
Reasoning configuration with effort level and summary options
**metadata** `object`
Additional metadata as key-value pairs
### Response
Returns a response object with the generated text.
### Example
```javascript Node.js theme={null}
const response = await fetch('https://api.electronhub.ai/v1/responses', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-4o',
input: 'Write a short story about a robot:',
instructions: 'Write in a creative and engaging style',
max_output_tokens: 500,
temperature: 0.7
})
});
const data = await response.json();
console.log(data);
```
```python Python theme={null}
import requests
response = requests.post(
'https://api.electronhub.ai/v1/responses',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'model': 'gpt-4o',
'input': 'Write a short story about a robot:',
'instructions': 'Write in a creative and engaging style',
'max_output_tokens': 500,
'temperature': 0.7
}
)
print(response.json())
```
```bash cURL theme={null}
curl -X POST "https://api.electronhub.ai/v1/responses" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o",
"input": "Write a short story about a robot:",
"instructions": "Write in a creative and engaging style",
"max_output_tokens": 500,
"temperature": 0.7
}'
```
# Decisions
Source: https://docs.electronhub.ai/api-reference/systemone
POST /systemone
Get structured judgments your code can act on
Send the facts in `state` and the judgments you need in `questions`. The answer is a pick from a set, a score on a scale, or a yes/no measure. `state` is text or JSON. The model does not read images, and it does not write chat text.
`jev` is TypeSafe's decision model at \$0.042 per million input tokens. Output tokens are free. Requests count toward your normal rate limits.
## Create Decision
`POST /systemone`
`POST /decisions` is the same endpoint.
### Request Body
**model** `string` (default: jev)
`jev`. `jev-latest`, `typesafe/jev`, and `typesafe/jev-latest` are aliases. Version pins such as `typesafe/jev-1.13` are rejected because only the current Jev is served. Proxy keys must send `model`.
**state** `string | object | array` *required*
The facts needed to answer: the ticket, records, conversation, or policy. A string, object, or array, including an empty one. Numbers, booleans, and `null` are rejected. Image parts and data-URL images are rejected. See [Images](#images).
**questions** `object` *required*
A non-empty map of question IDs to question definitions. Answers use the same IDs. IDs must be non-empty and cannot be `__proto__`.
Each question has:
**questions.\{id}.type** `string` *required*
`choice`, `score`, or `noul`. Case-sensitive.
**questions.\{id}.instructions** `string | object | array` *required*
The question to answer. The question ID only labels the answer; it is not read as the question.
**questions.\{id}.criteria** `object | array`
What each option or level means. Required for `choice` and `score`, optional for `noul`. See [Question types](#question-types).
Every question sees the same `state`. Send independent questions together in one call and keep each one focused on a single judgment. The combined `state` and `questions` can be up to 32,000 tokens. Other body fields, such as `user`, `session_id`, or `assets`, are ignored.
### Images
Jev does not read image bytes. An image part in `state` (`image_url`, `image`, or `input_image`), or any `data:image/` URL, is rejected with `400` and `param` set to `state`. Describe the image with a vision model such as `gemini-2.5-flash`, then put that description in `state`.
```python theme={null}
auth = {"Authorization": "Bearer YOUR_API_KEY"}
text = requests.post("https://api.electronhub.ai/v1/chat/completions", headers=auth, json={
"model": "gemini-2.5-flash",
"messages": [{"role": "user", "content": [
{"type": "text", "text": "Describe this image."},
{"type": "image_url", "image_url": {"url": data_url}}]}],
}).json()["choices"][0]["message"]["content"]
answer = requests.post("https://api.electronhub.ai/v1/decisions", headers=auth, json={
"model": "jev", "state": text,
"questions": {"colour": {"type": "choice", "instructions": "Dominant colour?",
"criteria": {"red": "red", "green": "green", "blue": "blue"}}}}).json()
```
A written description is ordinary text, including one stored under a field named `image`. There is no `box` question type. Ask a `choice`, `score`, or `noul` about the description.
### Question types
| Type | `criteria` | Answer fields |
| - | - | - |
| `choice` | Object of option ID to description. 1 to 255 options. | `choice`, `probabilities`, `confidence` |
| `score` | Array of level descriptions, lowest first. 1 to 10 levels. An object keyed `"0"`, `"1"`, ... with no gaps is also accepted. | `score`, `legend`, `probabilities`, `confidence` |
| `noul` | Optional. If sent, an object with both `true` and `false` keys and no others. | `noul` |
Descriptions may be strings, objects, or arrays, and may be empty. A `choice` description may also be `null`. Numbers and booleans are rejected.
### Reading answers
* `choice`: the selected option ID. `probabilities` maps every option ID to a probability.
* `score`: the expected level on the 0-based scale, as a decimal (for example `2.82` of 0 to 3). `legend` maps each level index to the description you sent. `probabilities` maps each level index to a probability.
* `noul`: the probability of yes, from 0 to 1. Near 0.5 means uncertain. There is no `confidence` field.
* `confidence`: a separate certainty signal from 0 to 1. It is not the largest probability and may be omitted; treat a missing value as unknown.
Probabilities are rounded to two decimals. Identical requests can differ by about 0.02, so compare against thresholds rather than exact values.
### Example
```bash cURL theme={null}
curl -X POST "https://api.electronhub.ai/v1/systemone" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "jev",
"state": "My card was charged twice. Please help ASAP.",
"questions": {
"team": {
"type": "choice",
"instructions": "Which team should handle this?",
"criteria": {
"billing": "Payments and refunds",
"technical": "Bugs and integrations",
"sales": "Pricing and new accounts"
}
},
"severity": {
"type": "score",
"instructions": "How severe is this request?",
"criteria": [
"No impact",
"Minor inconvenience",
"The customer is blocked",
"Money or data is at risk"
]
},
"urgent": {
"type": "noul",
"instructions": "Does this need a response today?",
"criteria": {
"true": "The customer is blocked or money is at risk",
"false": "It can wait"
}
}
}
}'
```
```javascript Node.js theme={null}
const response = await fetch('https://api.electronhub.ai/v1/systemone', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'jev',
state: 'My card was charged twice. Please help ASAP.',
questions: {
team: {
type: 'choice',
instructions: 'Which team should handle this?',
criteria: {
billing: 'Payments and refunds',
technical: 'Bugs and integrations',
sales: 'Pricing and new accounts'
}
}
}
})
});
const { answers } = await response.json();
console.log(answers.team.choice);
```
```python Python theme={null}
import requests
response = requests.post(
'https://api.electronhub.ai/v1/systemone',
headers={'Authorization': 'Bearer YOUR_API_KEY'},
json={
'model': 'jev',
'state': 'My card was charged twice. Please help ASAP.',
'questions': {
'team': {
'type': 'choice',
'instructions': 'Which team should handle this?',
'criteria': {
'billing': 'Payments and refunds',
'technical': 'Bugs and integrations',
'sales': 'Pricing and new accounts',
},
}
},
},
timeout=60,
)
print(response.json()['answers']['team']['choice'])
```
### Response
```json theme={null}
{
"id": "gen-dec-1791097042-2ZZZZefJjFbJsulpQa5T",
"object": "decision",
"model": "jev",
"answers": {
"team": {
"type": "choice",
"choice": "billing",
"probabilities": { "billing": 1, "sales": 0, "technical": 0 },
"confidence": 1
},
"severity": {
"type": "score",
"score": 2.82,
"legend": {
"0": "No impact",
"1": "Minor inconvenience",
"2": "The customer is blocked",
"3": "Money or data is at risk"
},
"probabilities": { "0": 0, "1": 0.08, "2": 0.01, "3": 0.91 },
"confidence": 0.82
},
"urgent": {
"type": "noul",
"noul": 0.88
}
},
"usage": {
"input_tokens": 434,
"output_tokens": 68,
"total_tokens": 502
}
}
```
Read each answer by its question ID, then apply your own rules. Validate thresholds on your own examples.
```javascript theme={null}
const { team } = data.answers;
if ((team.confidence ?? 0) < 0.8) {
queueForReview(ticket);
} else {
routeTicket(ticket, team.choice);
}
```
## Describe the endpoint
`GET /systemone` (or `GET /decisions`) returns the default model (`jev`), its context length and price, the question types, and a `models` list with every decision model. No API key is needed. `jev` allows 32,000 tokens.
## Errors
| Status | Meaning |
| - | - |
| 400 | Invalid body, such as a missing `instructions`, an unknown `type`, invalid `criteria`, or image content in `state`. `param` names the field. Also returned for a version-pinned or unsupported model, and when the request exceeds that model's context limit. |
| 401 | Missing or invalid API key. |
| 402 | Insufficient balance. |
| 429 | Your rate limit was reached, or the decision model is busy. Wait for `Retry-After` when present, then retry with backoff. |
| 503 | The decision model is temporarily unavailable. Retry with backoff. |
Failed requests are not charged.
# Get Usage
Source: https://docs.electronhub.ai/api-reference/usage
GET /user/me
Get current user usage statistics and account information
Retrieve current user usage statistics, account information, and billing details.
## Response
Returns comprehensive usage information including subscription status, remaining credits, token usage, request history, and endpoint-specific usage statistics.
## Example Response
```json theme={null}
{
"subscription": "pro",
"credits": 1250,
"usage": {
"input_tokens": 45230,
"output_tokens": 12870
},
"history": [
{
"date": "2024-12-26",
"requests": 142
},
{
"date": "2024-12-25",
"requests": 98
}
],
"endpoints": {
"chat.completions": 95,
"images.generations": 23,
"images.edits": 5,
"videos.generations": 2
}
}
```
## Code Examples
```python Python theme={null}
from httpx import Client
api_key = "ek-your-api-key"
headers = {
"Authorization": f"Bearer {api_key}"
}
client = Client()
response = client.get("https://api.electronhub.ai/v1/user/me", headers=headers)
print(response.json())
```
```javascript Node.js theme={null}
const response = await fetch('https://api.electronhub.ai/v1/user/me', {
method: 'GET',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const data = await response.json();
console.log(data);
```
```bash cURL theme={null}
curl -X GET "https://api.electronhub.ai/v1/user/me" \
-H "Authorization: Bearer YOUR_API_KEY"
```
## Response Fields
### subscription
Your current subscription plan (e.g., "free", "starter", "pro", "enterprise")
### credits
Number of credits remaining in your account
### usage
Token usage statistics:
* `input_tokens` - Total input tokens consumed
* `output_tokens` - Total output tokens generated
### history
Array of daily usage records showing request counts by date
### endpoints
Usage breakdown by API endpoint:
* `chat.completions` - Chat completion requests
* `images.generations` - Image generation requests
* `images.edits` - Image editing requests
* `videos.generations` - Video generation requests
## Use Cases
* **Monitor Usage**: Track API consumption to manage costs
* **Billing Information**: Check remaining credits and subscription status
* **Usage Analytics**: Analyze patterns in API usage over time
* **Endpoint Analysis**: Understand which endpoints are used most frequently
## Rate Limits
This endpoint is subject to standard rate limits. You can check usage information up to once per minute without impacting your request quota.
# Get User Logs
Source: https://docs.electronhub.ai/api-reference/user-logs
GET /user/logs
Get recent API request logs for the authenticated user
Retrieve recent API request logs for the authenticated user. This endpoint provides detailed information about your API usage history, including model usage, costs, timestamps, and request status.
## Response
Returns an array of log entries containing information about recent API requests made with your API key.
## Log Entry Fields
* **key** - The API key used for the request
* **model** - The model that was used
* **route** - The API endpoint that was called
* **credits** - The cost in credits for this request
* **timestamp** - Unix timestamp when the request was made
* **status** - Request status (success, cancelled, error)
* **ip** - IP address from which the request was made
* **input\_tokens** - Number of input tokens (for text models)
* **output\_tokens** - Number of output tokens (for text models)
## Example Response
```json theme={null}
[
{
"key": "ek-abc123def456ghi789jkl012mno345pqr678stu901vwx234yz567",
"model": "gpt-4o",
"route": "chat.completions",
"credits": 0.001475,
"timestamp": 1747802046,
"status": "success",
"input_tokens": 23,
"output_tokens": 9,
"ip": "14.161.20.81"
},
{
"key": "ek-abc123def456ghi789jkl012mno345pqr678stu901vwx234yz567",
"model": "dall-e-3",
"route": "images.generations",
"credits": 0.2,
"timestamp": 1747245603,
"status": "success",
"ip": "2001:ee0:d781:2280:e9d8:c4d6:c683:e48"
},
{
"key": "ek-abc123def456ghi789jkl012mno345pqr678stu901vwx234yz567",
"model": "claude-3-5-sonnet-20241022",
"route": "chat.completions",
"credits": 0.000609,
"timestamp": 1747802047,
"status": "success",
"input_tokens": 23,
"output_tokens": 36,
"ip": "14.161.20.81"
}
]
```
## Use Cases
* **Usage Tracking** - Monitor your API usage patterns and costs
* **Debugging** - Identify failed requests and troubleshoot issues
* **Analytics** - Analyze which models you use most frequently
* **Billing** - Track credit consumption over time
* **Security** - Monitor IP addresses accessing your API key
# Get Model Breakdown
Source: https://docs.electronhub.ai/api-reference/user-models
GET /user/models
Retrieve a per-model cost and usage breakdown for the authenticated user, including request counts, token usage, total cost, and provider information for every model used.
Per-model usage: `total_consumption`, `models` map (`requests`, `input_tokens`, `output_tokens`, `total_cost`, `owned_by`), and `last_updated`.
# Video Generations
Source: https://docs.electronhub.ai/api-reference/videos/generations
POST /videos/generations
Generate videos from text prompts via Server-Sent Events (SSE)
Create original short videos from text prompts. This endpoint streams results over SSE. Send `Accept: text/event-stream` to receive incremental updates until completion.
> [!NOTE]
>
> Video generation typically takes 3–6 minutes to complete. Set your HTTP client timeout to at least 600–900 seconds to avoid premature disconnects.
### Examples
```python Python theme={null}
import httpx, orjson
url = "https://api.electronhub.ai/v1/videos/generations"
payload = {
"model": "midjourney-video",
"prompt": "a playful cat",
# "size": "16:9", # optional
}
headers = {
"Accept": "text/event-stream",
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json",
}
with httpx.stream("POST", url, json=payload, headers=headers, timeout=900) as response:
for line in response.iter_lines():
if line:
data = orjson.loads(line)
if data:
if data.get("heartbeat"):
print("Pending...")
else:
print(line)
```
```bash cURL theme={null}
curl -N -X POST "https://api.electronhub.ai/v1/videos/generations" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Accept: text/event-stream" \
-H "Content-Type: application/json" \
--max-time 900 \
-d '{
"model": "midjourney-video",
"prompt": "a playful cat",
"size": "16:9"
}'
```
# Advanced Billing Topics
Source: https://docs.electronhub.ai/billing/advanced
Rate limits, caching, token pricing, and cost optimizations
This section covers advanced billing features and optimizations.
## Prompt Caching & Token Pricing
Some models support **prompt caching**, which can reduce costs when you reuse the same content.
> [!NOTE]
>
> **How it works:**
>
> * You can mark parts of your prompt to be cached
> * Cached content is stored for 5 minutes (or 1 hour with paid option)
> * When you reuse cached content, you pay less (cache reads are cheaper than regular input)
> **Token Pricing Structure**
>
> * **Base input tokens**: Regular price per million tokens
> * **Cache write (5 min)**: 1.25x base input price (25% more expensive)
> * **Cache write (1 hour)**: 2x base input price (100% more expensive)
> * **Cache read**: 0.1x base input price (90% cheaper!)
> * **Output tokens**: Usually more expensive than input tokens
> [!TIP]
>
> **When to use caching:**
>
> * When you have large, repeated context (like a long document)
> * When you're asking multiple questions about the same content
> * When you want to reduce costs for repeated prompts
## Rate Limit Scaling
Your rate limits can scale based on your **total purchased credits** (permanent credits spending). The scaling applies a multiplier to your base tier rate limit:
### Scaling Tiers
| Total Spent | Scale Tier | Multiplier | Example (Pro Tier) |
| - | - | - | - |
| `$0`-`$99` | Base | 1x (no scaling) | 30 requests/min |
| `$100+` | Tier 1 | 2x | 60 requests/min (30 × 2) |
| `$250+` | Tier 2 | 3x | 90 requests/min (30 × 3) |
| `$500+` | Tier 3 | 5x | 150 requests/min (30 × 5) |
| `$1,000+` | Tier 4 | 7x | 210 requests/min (30 × 7) |
| `$2,500+` | Tier 5 | 10x | 300 requests/min (30 × 10) |
> [!NOTE]
>
> **How it works:**
>
> * Your base rate limit depends on your subscription tier (e.g., Pro tier = 30 requests/min)
> * The multiplier is applied to your base limit based on your total permanent credits spending
> * **Example**: If you're on Pro tier (30 req/min) and have spent `$500+` on permanent credits, your rate limit becomes 150 requests/min (30 × 5)
> **Base Rate Limits by Tier**
>
> * Free: 5 requests/min
> * Starter: 10 requests/min
> * Plus: 15 requests/min
> * Core: 20 requests/min
> * Pro: 30 requests/min
> * Business: 60 requests/min
> * Enterprise: 100 requests/min
> [!NOTE]
>
> **Note:** Rate limit scaling applies to all tiers based on your total permanent credits spending. The multiplier is cumulative - you get the highest multiplier you qualify for.
## Calculating Credit Costs
> **Cost Calculation**
>
> Credits are calculated based on:
>
> * **Token-based models**: Price per million tokens × tokens used
> * **Fixed-price models**: Fixed cost per request (like image generation)
> [!TIP]
>
> Check the model pricing in the dashboard or API documentation for specific costs.
> **Example Calculation**
>
> * Model costs `$3` per million input tokens and `$15` per million output tokens
> * You use 1,000 input tokens and 500 output tokens
> * Cost = (1,000 / 1,000,000 × `$3`) + (500 / 1,000,000 × `$15`) = `$0.003` + `$0.0075` = `$0.0105` credits
## Understanding Tokens
> [!NOTE]
>
> **What are Tokens?**
>
> **Tokens** are the units that AI models use to process text. When you send a message to an AI model:
>
> * **Input tokens** = the text you send (your prompt/question)
> * **Output tokens** = the text the AI generates (the response)
> [!NOTE]
>
> For example, if you ask "What is the weather?" and the AI responds "The weather is sunny today", both your question and the response are counted as tokens. The cost of using a model depends on how many tokens you use.
> **Key Points**
>
> * Tokens are priced per million tokens (MTok)
> * Different models have different token prices
> * Input tokens and output tokens are priced separately (output is usually more expensive)
> * Some models support **prompt caching**, which can reduce costs for repeated content
# Coding Plan (DevPass)
Source: https://docs.electronhub.ai/billing/coding-plan
Flat monthly plan for coding agents. Unlimited tokens, no credits.
The **Coding Plan** (DevPass) is a flat monthly plan for coding agents and CLIs — Claude Code, Cursor, Cline, Roo Code, or any OpenAI- or Anthropic-compatible tool.
A dedicated `ek-dev-` key. Unlimited tokens. No credits. Independent of every other Electron Hub plan.
## Tiers
| | **Lite** | **Turbo** |
| - | - | - |
| Price | **\$10**/month | **\$40**/month |
| Token usage | **Unlimited** | **Unlimited** |
| Concurrency slots | 2 | 5 |
| Requests per minute | 8 (burst 4) | 20 (burst 8) |
| Priority when busy | Standard | High |
| Full-speed soft headroom | Generous | 6× Lite |
> [!WARNING]
>
> Launch seats are capped per tier. If a tier is sold out, join the waitlist on the dashboard. You are notified when a seat opens (first come, first served).
## Included models
| Series | Model ID | Input | Context · Quant | Notes |
| - | - | - | - | - |
| Flash · 0.5× | `glm-5.3-flash:dev` | → | 1M · FP8 | 320B-A18B. Native multimodal (text, image, video). Hybrid sparse and linear attention. |
| Flash · 0.5× | `mimo-v2.6-flash:dev` | → | 1M | 309B-A15B MoE (256 experts, 8 active). Hybrid sliding-window and global attention. Native vision. |
| Standard · 1× | `deepseek-v4.1-flash:dev` | → | 1M · FP8 + FP4 (FP4 experts) | 552B backbone. 8B prefill / 16B decode active. Native vision. |
| Standard · 1× | `qwen3.8-27b:dev` | → | 262K · BF16 | Multimodal agentic coding. |
| Standard · 1× | `minimax-m2.7:dev` | → | 180K · FP8 | Agentic productivity and multi-agent work. |
| Heavy · 2× | `glm-5.3:dev` | → | 262K · FP8 | 744B-A40B. Text-only. Same GLM-5.2 base, post-trained. Stronger complex coding and long-horizon agents. Uses 2 concurrency slots per request. |
All models support function calling on `/v1/chat/completions`, `/v1/messages`, and `/v1/responses`.
Series weight (0.5× / 1× / 2×) affects soft full-speed headroom (`ceil(raw × weight)`). It does not stop you from using the plan. Dashboard per-model stats stay raw.
Heavy models also hold **2 concurrency slots** per request; Flash and Standard models hold 1. See [Concurrency slots](#concurrency-slots).
> [!NOTE]
>
> `:dev` models accept only `ek-dev-` keys. DevPass keys can call only `:dev` models. Keep your master key configured if you need the rest of the catalog.
## Quickstart
1. Subscribe on the [Dashboard](https://app.electronhub.ai) → **Console** → **Coding Plan**.
2. Your `ek-dev-...` key is provisioned within seconds. It is always retrievable from the Coding Plan tab. Regenerating it immediately invalidates the old key.
3. Use it as a Bearer token:
```bash theme={null}
curl -X POST "https://api.electronhub.ai/v1/chat/completions" \
-H "Authorization: Bearer ek-dev-YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "glm-5.3:dev",
"messages": [{"role": "user", "content": "Refactor this function..."}],
"stream": true
}'
```
## Fair use
One person, one seat. Lite and Turbo are alternative tiers, not stackable. If two concurrency slots are not enough, upgrade. Do not open another account, email, or payment method to hold a second seat.
The `ek-dev-` key may run on machines you personally use (home, work, laptop, CI, VPN). All of that usage counts against the same seat.
The plan is for interactive coding by that one person. These are violations and lead to suspension:
* a second seat under any identity you control
* sharing the key with anyone else
* pooling keys or seats to raise throughput
* resale, subletting, or access-as-a-service
* a deployed app or backend that serves other people
* unattended or multi-user production traffic
We treat extra seats, shared keys, and resale as the same violation. Chargebacks are account-level violations.
High-duty-cycle or multi-user traffic belongs on a regular Electron Hub API key billed on credits.
> **Concurrency slots**
>
> Each plan has a fixed number of concurrency slots: **2 on Lite, 5 on Turbo**. A request holds its slots until it finishes. Request starts are limited separately (see [Requests per minute](#requests-per-minute)).
>
> | Series | Slots per request | Lite (2 slots) | Turbo (5 slots) |
> | - | - | - | - |
> | Flash · Standard | 1 | 2 requests | 5 requests |
> | Heavy (`glm-5.3:dev`) | 2 | 1 request | 2 requests, plus 1 Flash or Standard request |
>
> Series can be mixed in any combination that fits the slot total. If the slots a request needs are not free, you get a `429` with `Retry-After`. Wait for a request to finish, then retry. Coding agents handle this automatically.
>
> To keep parallel work moving on Lite, route subagents and background tasks to a Flash model and reserve the Heavy model for the main session. While the plan is temporarily reduced to one slot, a Heavy request uses that single slot.
> **Full-speed soft headroom (daily)**
>
> Each plan includes full-speed headroom that resets at **21:00 UTC**. Going past it never blocks you. Requests continue with reduced concurrency and paced admission (consumption-scaled spacing, up to 30 seconds when far into overage) until the reset. The dashboard shows how close you are to full-speed headroom.
> **Full-speed soft headroom (weekly)**
>
> A rolling weekly soft headroom sits above the daily one. Past it, the same slow lane applies (lower concurrency and paced admission). This is not a hard stop. It keeps sustained 24/7 grinders from crowding out interactive work across the week.
> **Requests per minute**
>
> Request starts refill continuously at **8 per minute on Lite** and **20 per minute on Turbo**. Up to **4** (Lite) or **8** (Turbo) can start back-to-back after a quiet moment. Every request counts as one start, Heavy included. In the slow lane (past full-speed headroom, or in low-interactivity mode) it is 3 per minute (burst 2).
>
> Past the limit you get a `429` with an exact `Retry-After` (Lite: about 8 seconds per start). `X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset` report this budget on every response. These `429`s never count toward the temporary pause.
> **Temporary pause after concurrency hammering**
>
> Repeatedly hitting the parallel-slot limit (about 100 concurrency `429`s in a usage day) can pause admission for **5 hours**. While paused, requests return **`403`**. Your key stays valid. Service resumes automatically at the time shown on the dashboard. Regenerating the key clears an automatic concurrency pause.
### Low-interactivity mode
Plans are sized for a person coding, even intensively, all day. When an account shows a usage pattern far beyond typical interactive work, the plan enters **low-interactivity mode** for about **24 hours**:
* Under light load, behavior is unchanged.
* When the platform is busy, requests may be queued behind interactive sessions and may need a retry.
* Nothing is blocked. Your plan, models, and answer quality stay the same.
* Interactive mode resumes automatically at the time shown on the Coding Plan tab. No action is required.
Low-interactivity mode is a temporary fairness control so interactive subscribers keep responsive access during busy periods. It is **not** a suspension.
If this surprises you, check for a runaway automation first, then ask on [Discord](https://discord.com/invite/electronhub).
## Errors
| Status | Meaning | What to do |
| - | - | - |
| `429` | Not enough free concurrency slots (Heavy requests need 2), or the per-minute request limit was reached | Honor `Retry-After`, then retry |
| `404` model error | Model not in the Coding Plan list | Use a `:dev` model from the table above |
| `403` | Temporarily paused after concurrency hammering | Wait for the resume time on the dashboard, or regenerate your key to clear the pause |
| `403` | Subscription suspended or ended | Check payment, or resubscribe. A second seat or shared use can also cause this. |
## Terms
* Monthly billing via **Creem**, auto-renewing, non-refundable. Cancel any time. Your key stays active until the period ends.
* Fair use is binding. Extra seats, shared keys, pooling, and resale are suspended. Chargebacks are account-level violations.
## FAQ
> **Is token usage really unlimited?**
>
> Yes. There is no hard token cap and no per-token charge. Soft full-speed headroom only affects concurrency, request rate, and latency when you are far past typical interactive use. Requests are never blocked for burning tokens.
> **I bought during beta. Do I keep the old price?**
>
> Yes. Founding and beta subscribers who purchased at the launch rate keep that price for as long as the subscription stays active. If you cancel and subscribe again later, the current public price applies.
> **Can I buy a second Coding Plan seat?**
>
> No. See [Fair use](#fair-use). One person, one seat. Upgrade Lite to Turbo if you need more parallel slots.
> **Can I upgrade Lite to Turbo?**
>
> Yes. Change plans in the Creem billing portal. Your existing key picks up Turbo limits automatically.
> **What happens when my subscription ends?**
>
> Your `ek-dev-` key is deactivated. Resubscribe any time to restore it.
> **What does the Low-interactivity mode banner mean?**
>
> See [Low-interactivity mode](#low-interactivity-mode). Requests remain available. Under load they may queue behind interactive sessions until interactive mode resumes automatically.
# Understanding Credits
Source: https://docs.electronhub.ai/billing/credits
Learn about all credit types and how they work
Credits are the currency used in Electron Hub to pay for AI model usage. This guide explains all the different types of credits and how they work.
## Types of Credits
> **Weekly Credits**
>
> **Weekly Credits** are credits that are automatically added to your account every **Sunday at 21:00 UTC** (9:00 PM UTC). The amount you receive depends on your subscription tier:
>
> | Tier | Weekly Credits |
> | - | - |
> | Free | \$0.25 |
> | Starter | \$8 |
> | Plus | \$15 |
> | Core | \$30 |
> | Pro | \$50 |
> | Business | \$100 |
> | Enterprise | \$200 |
>
> > [!WARNING]
> >
> > **Important Notes:**
> >
> > * Weekly credits refill every **Sunday at 21:00 UTC**
> > * Unused weekly credits do **not** carry over to the next week
> > * Your balance is automatically set to your weekly credits amount at refill time
> > * Weekly credits are separate from permanent credits
> **Permanent Credits**
>
> **Permanent Credits** are credits you purchase with real money.
>
> > **Key Features**
> >
> > * Never expire
> > * Volume discounts available
> > * Can be used alongside weekly credits
>
> See [Pay-as-You-Go](/billing/pay-as-you-go) for details.
> **Flex Credits**
>
> **Flex Credits** (also called "Flex Wallet") are a savings feature that lets you save unused weekly credits for later use.
>
> > [!NOTE]
> >
> > **How it works:**
> >
> > * You can save up to **20% of your weekly credits** per week to your flex wallet
> > * The total cap is **50% of your weekly credits** (e.g., if you get \$50/week, your flex wallet can hold up to \$25)
> > * You can save at any time (no cooldown) — but the weekly save limit resets every Sunday at 21:00 UTC
> > * Flex credits are used automatically when your regular balance runs out (if flex credits are enabled)
> > * Flex balance rolls over until you use it
>
> > **Example**
> >
> > * You have a Pro subscription (\$50/week)
> > * Weekly save limit: \$10 (20% of \$50)
> > * Maximum flex wallet: \$25 (50% of \$50)
> > * If you save \$10 every week for 2.5 weeks, you'll have \$25 saved (the maximum)
>
> > [!TIP]
> >
> > **When to use Flex Credits:**
> >
> > * Enable flex credits if you want to build up a buffer for heavy usage weeks
> > * Useful if you don't use all your weekly credits every week
> > * Flex balance rolls over — save up over a few weeks and use it when you need extra credits
> **Neutrinos**
>
> **Neutrinos** are special free usage requests for **free models** (models that end with `:free` suffix).
>
> > [!NOTE]
> >
> > **Key Points:**
> >
> > * All users get **10 Neutrinos per day** (resets at 21:00 UTC)
> > * Neutrinos are used instead of credits for free models
> > * You can earn more Neutrinos by watching ads (up to **200 daily**)
>
> > **Ad Rewards (up to 3 ads per day)**
> >
> > * Base: **10** Neutrinos
> > * 1st ad: **+30** Neutrinos (total: 40)
> > * 2nd ad: **+60** Neutrinos (total: 100)
> > * 3rd ad: **+100** Neutrinos (total: 200)
>
> > [!WARNING]
> >
> > **Important:** Neutrinos are charged for **all requests** (failed, cancelled, and successful) - unlike regular credits which are only charged for successful/cancelled requests.
## How Credits are Deducted
> **Deduction Priority**
>
> Credits are deducted in this priority order:
>
> 1. **Permanent credits** (if enabled and within monthly limit)
> 2. **Regular balance** (weekly credits)
> 3. **Flex credits** (if enabled)
> [!WARNING]
>
> **Charging Rules:**
>
> **Regular Credits:** Only charged for **successful** and **cancelled** requests. **Failed requests are NOT charged.**
>
> **Neutrinos:** Charged for **all requests** (failed, cancelled, and successful) - this is different from regular credits.
> **Example: Successful Request**
>
> * You have 5 permanent credits, 10 regular credits, and 3 flex credits
> * You make a request costing 15 credits
> * System uses: 5 permanent + 10 regular + 3 flex = 18 credits total (you have enough!)
> **Example: Failed Request**
>
> * You make a request that fails (e.g., model unavailable, timeout)
> * **Regular credits**: NOT charged (you keep your credits)
> * **Neutrinos**: Still charged (if using a `:free` model)
## Credit Reset Times
> **Weekly Refill**
>
> * **Weekly credits**: Refill every **Sunday at 21:00 UTC**
> * **Neutrinos**: Reset every day at **21:00 UTC**
> * **Flex weekly save limit**: Resets every **Sunday at 21:00 UTC**
> **Never Reset**
>
> * **Permanent credits**: Never reset (they're permanent!)
> * **Flex credits balance**: Rolls over until used
> [!NOTE]
>
> **Monthly spending limits:** Reset on the 1st of each month (for permanent credits monthly limits)
## Checking Your Balance
> **Where to Check**
>
> You can check your balance:
>
> * In the [Electron Hub Dashboard](https://app.electronhub.ai)
> * Through the API by checking your user information
> * Balance includes: regular credits, flex credits (if enabled), and permanent credits (if enabled)
## Managing Credit Settings
**1. Access Dashboard**
Go to the [Electron Hub Dashboard](https://app.electronhub.ai)
**2. Navigate to Settings**
Navigate to account settings
**3. Configure Credits**
* Toggle flex credits on/off
* Toggle permanent credits on/off
* Set permanent credits monthly limits
## Credit Transfers
> [!WARNING]
>
> **No transfers:** Credits cannot be transferred between accounts. Each account's credits are tied to that specific account.
# Model Types & Access
Source: https://docs.electronhub.ai/billing/model-access
Understanding which models you can access and how they are billed
Understanding which models you can access and how they're billed.
## Model Categories
Electron Hub has three main model categories:
> **Free Models (:free suffix)**
>
> > **Free Models**
> >
> > * Models that end with `:free` (e.g., `gpt-3.5-turbo:free`)
> > * Use **Neutrinos** instead of credits
> > * No subscription required
> > * Best for: Testing, light usage, learning
>
> > [!WARNING]
> >
> > **Uptime:** We don't guarantee 100% uptime at peak times (we host these ourselves and need to ensure fair usage)
> **Freemium Models**
>
> > **Freemium Models**
> >
> > * Models that don't require a subscription
> > * **Do deduct credits** from your balance
> > * Available to all users (Free tier and above)
> > * Better uptime than free models
> > * Best for: Regular usage without subscription commitment
> **Premium/Ultimate Models**
>
> > **Premium Models**
> >
> > * Models that **require a subscription** (Starter plan or higher) **OR permanent credits**
> > * Free tier users with permanent credits can access premium models
> > * Also deduct credits from your balance
> > * Better uptime than free/freemium models
>
> > **Ultimate Models**
> >
> > * Models that **require a Pro tier or higher** subscription
> > * Also deduct credits from your balance
> > * Best for: Production applications, critical workloads
## Premium Model Examples
> **Popular Premium Models**
>
> * `gpt-4`
> * `o1`, `o1-low`, `o1-high`
> * `o3-pro`, `o3-pro-low`, `o3-pro-high`
> * `o3-deep-research`
> * `claude-sonnet-4-5-20250929`
> * `gemini-3-pro-preview`
## Model Access by Tier
> **Free Tier**
>
> * Free models (with Neutrinos)
> * Freemium models (with credits)
> **Free + Permanent Credits**
>
> * Free models
> * Freemium models
> * **Premium models** (credits required)
> **Starter/Plus/Core**
>
> * All freemium models
> * Premium models
> **Pro/Business/Enterprise**
>
> * All models including
> * Premium models
> * Ultimate models
> [!NOTE]
>
> **Note:** Free tier users who have purchased permanent credits can access premium models (but not ultimate models). Ultimate models still require a Pro tier or higher subscription. Check the model list in the dashboard or API documentation to see which models require which tier.
## Why don't free models guarantee 100% uptime?
> [!NOTE]
>
> Free models are hosted by Electron Hub directly, and during peak usage times, we need to ensure fair distribution of resources among all users.
> [!TIP]
>
> For guaranteed uptime and better performance, we recommend:
>
> * Using freemium models (deduct credits but better uptime)
> * Subscribing to a premium tier to access premium models (routed to multiple providers)
## Model Status
> **[Check Status](https://status.electronhub.ai)**
>
> Check the [Status Page](https://status.electronhub.ai) for real-time uptime status of popular models.
# Billing & Credits Overview
Source: https://docs.electronhub.ai/billing/overview
Everything you need to know about billing, credits, subscriptions, and payments
Welcome to the Electron Hub Billing documentation! This section covers everything you need to know about billing, credits, subscriptions, and payments.
## Quick Navigation
> **[Subscriptions](/billing/subscriptions)**
>
> Subscription tiers and benefits
> **[Coding Plan (DevPass)](/billing/coding-plan)**
>
> Unlimited tokens for coding agents — flat monthly price, no credits
> **[Pay-as-You-Go](/billing/pay-as-you-go)**
>
> Permanent credits and purchasing
> **[Credits](/billing/credits)**
>
> Understanding all credit types
> **[Model Access](/billing/model-access)**
>
> Which models you can access
> **[Advanced Topics](/billing/advanced)**
>
> Rate limits, caching, and optimizations
> **[Troubleshooting](/billing/troubleshooting)**
>
> Common issues and solutions
> **[Privacy & Security](/billing/privacy-security)**
>
> Data protection and moderation
***
Electron Hub offers two flexible billing models to suit different usage patterns and needs:
## Billing Models
> **Subscriptions**
>
> **Weekly credits** that refill every **Sunday at 21:00 UTC**
>
> **Ideal for:**
>
> * Regular, consistent usage
>
> * Predictable monthly costs
>
> * Access to premium/ultimate models
>
> * Higher rate limits and more features
>
> > [!NOTE]
> >
> > **Annual Savings:** Annual subscriptions save you **20%** compared to monthly billing!
> **Pay-as-You-Go**
>
> **Permanent credits** that never expire
>
> **Ideal for:**
>
> * Irregular or unpredictable usage
>
> * One-time projects
>
> * Testing and experimentation
>
> * Supplementing subscription credits
>
> > [!NOTE]
> >
> > **Volume Discounts:** Get up to **20% bonus** credits on larger purchases!
> [!NOTE]
>
> Building with coding agents or CLI tools? There's a third option: the **[Coding Plan (DevPass)](/billing/coding-plan)** — **unlimited token usage** for **$10** (Lite) or **$40** (Turbo) per month, a dedicated `ek-dev-` key, and a curated set of `:dev` coding models. It never consumes credits and stacks with any other plan. Founding / beta subscribers keep their launch price while the subscription stays active.
## Which Model Should I Choose?
> **Choose Subscriptions if...**
>
> * You use the service regularly
> * You want predictable monthly costs
> * You need access to premium models
> * You prefer automatic weekly credits
> **Choose Pay-as-You-Go if...**
>
> * Your usage is irregular or unpredictable
> * You're testing the service
> * You want to supplement your subscription credits
> * You prefer one-time purchases
> [!TIP]
>
> **Pro Tip:** You can use both! Many users combine subscriptions with permanent credits for maximum flexibility.
## Getting Started
> **[Subscriptions](/billing/subscriptions)**
>
> Learn about subscription tiers and benefits
> **[Permanent Credits](/billing/pay-as-you-go)**
>
> Purchase credits that never expire
## Helpful Links
> **[Dashboard](https://app.electronhub.ai)**
>
> Manage your account and billing
> **[Status Page](https://status.electronhub.ai)**
>
> Check service uptime and status
> **[Terms of Service](https://tos.electronhub.ai)**
>
> Review our terms and conditions
> **[Privacy Policy](https://privacy.electronhub.ai)**
>
> Learn about our privacy practices
# Pay-as-You-Go
Source: https://docs.electronhub.ai/billing/pay-as-you-go
Purchase permanent credits that never expire
Pay-as-You-Go allows you to purchase permanent credits that never expire. This gives you maximum flexibility without any recurring commitment.
## What are Permanent Credits?
> **Permanent Credits** are credits you purchase with real money. Unlike weekly credits, these credits:
>
> * **Never expire** - they stay in your account forever
> * Can be purchased through **PayPal** or **Cryptocurrency**
> * Can be used alongside weekly credits
> * Have volume discounts (the more you spend, the more bonus credits you get)
## Pricing
> **Base Rate**
>
> **`$1` USD = 2 credits**
> **Volume Discounts**
>
> * Every `$500` spent: **5% bonus**
> * Maximum discount: **20% bonus** (at `$2,000+` total spending)
> **Pricing Examples**
>
> * First purchase: `$100` = 200 credits (no bonus yet)
> * After `$500` total: `$100` purchase = 210 credits (5% bonus)
> * After `$2,000` total: `$100` purchase = 240 credits (20% bonus, maximum)
## Payment Methods
> **PayPal**
>
> * **Range:** `$5` - `$5,000` USD
>
> * **Fees:** No fees
>
> * **Processing:** Instant
>
> * **Credits:** Added immediately
>
> > [!NOTE]
> >
> > **Best for:** Quick purchases, users who prefer traditional payment methods
> **Cryptocurrency**
>
> * **Range:** `$25` - `$1,000` USD
>
> * **Fees:** 5% processing fee
>
> * **Processing:** 10 minutes to 24 hours
>
> * **Credits:** Added after confirmation
>
> * **Supported:** 300+ cryptocurrencies (BTC, ETH, USDT, LTC, DOGE, SOL, and more)
>
> > [!WARNING]
> >
> > Orders expire after 24 hours if payment is not confirmed.
## How to Purchase
**1. Access Dashboard**
Go to the [Electron Hub Dashboard](https://app.electronhub.ai)
**2. Navigate to Payment**
Navigate to the credits/payment section
**3. Select Payment Method**
Choose between **PayPal** or **Cryptocurrency**
**4. Select Amount**
Select the amount you want to purchase (see Payment Methods above for limits)
**5. Complete Payment**
Complete payment through your chosen method
**6. Credits Added**
Credits are added to your account (PayPal: instant, Crypto: after confirmation)
## Payment Limits
> **Purchase Limits**
>
> * **Daily limit**: 20 orders per day
> * **Monthly limit**: `$5,000` USD per month
> * **Transaction limits**: See Payment Methods section above
> * Limits reset automatically
## Monthly Spending Limits
> **Spending Controls**
>
> You can set a **monthly spending limit** for permanent credits to control costs:
>
> * **0 = Unlimited** (no limit)
> * **Any positive number** = Maximum amount you can spend per month
> * **Maximum limit**: `$100,000` USD per month
> * Limits reset on the 1st of each month
> [!TIP]
>
> **Use cases:**
>
> * Budget control for teams
> * Preventing accidental overspending
> * Managing costs for production applications
## Rate Limit Scaling
> [!NOTE]
>
> Your rate limits scale based on your **total purchased credits** (permanent credits spending). See [Rate Limit Scaling](/billing/advanced#rate-limit-scaling) for complete details.
## Low Balance Alerts
> **Stay Informed**
>
> You can enable **low balance alerts** for permanent credits:
>
> * Set a threshold (e.g., 10 credits)
> * Receive email alerts when your permanent credits balance drops below the threshold
> * Alerts are sent at most once every 24 hours (to prevent spam)
## Refund Policy
> [!NOTE]
>
> **Permanent Credits Purchases:** Refunds are available within 30 days of purchase if you haven't used the credits. Once credits have been used, refunds are not available except in cases of technical errors or service issues. For complete refund terms and troubleshooting, see [Refund Requests](/billing/troubleshooting#refund-requests) or review our [Terms of Service](https://tos.electronhub.ai).
# Privacy & Security
Source: https://docs.electronhub.ai/billing/privacy-security
Data protection, moderation, and privacy policies
## No-Log Policy for Prompts
> [!NOTE]
>
> **We do not log your prompt content.** Your prompts and AI responses are not stored in our logs. We only log:
>
> * Request metadata (model used, tokens, credits, timestamp, status)
> * Technical information (IP address, API key used, route accessed)
> * Usage statistics (for billing and analytics)
> [!NOTE]
>
> **What this means:**
>
> * Your conversations and prompts remain private
> * We cannot see what you're asking the AI
> * We cannot reconstruct your conversations from our logs
> * Your data privacy is protected
## Content Moderation
To comply with our AI provider content policies and legal requirements, we apply moderation to detect and flag requests involving:
> **CSAM Detection**
>
> **CSAM (Child Sexual Abuse Material)**: Any content related to child exploitation
> **Illegal Activities**
>
> Content about making drugs, bombs, weapons, or other illegal activities
> **Harmful Content**
>
> Content that could cause real-world harm
> [!NOTE]
>
> **How it works:**
>
> * Requests are automatically scanned before being sent to AI providers
> * Flagged requests are blocked and not processed
> * No credits are charged for blocked requests
> * This helps us maintain compliance with provider policies and legal requirements
> [!NOTE]
>
> **Your privacy is still protected:**
>
> * Moderation checks are automated and do not involve human review of your content
> * We do not store the content of blocked requests
> * This is a necessary measure to ensure service availability and legal compliance
# Subscriptions
Source: https://docs.electronhub.ai/billing/subscriptions
Subscription tiers, benefits, and how to subscribe
Subscriptions provide weekly credits that automatically refill every Sunday, along with access to premium features and models.
## Subscription Tiers
Electron Hub offers several monthly subscription tiers, available through **Creem** (recommended), **lava.top**, or **Ko-fi**:
| Tier | Weekly Credits | Max Bots | Studio Credits |
| - | - | - | - |
| Free | \$0.25 | 5 | 5 |
| Starter | \$8 | 20 | 20 |
| Plus | \$15 | 30 | 50 |
| Core | \$30 | 50 | 75 |
| Pro | \$50 | 100 | 150 |
| Business | \$100 | 150 | 300 |
| Enterprise | \$200 | 200 | 500 |
> **Benefits of Higher Tiers**
>
> * More weekly credits
> * Access to premium/ultimate models
> * Higher rate limits
> * More bot creation slots
> * More studio credits (for AI bot creation)
## Annual vs Monthly Billing
> **Save 20% with Annual Billing**
>
> **Annual subscriptions save you 20%** compared to monthly billing!
>
> **Example (Creem Pro):**
>
> * Monthly Pro tier: `$69`/month
> * Annual Pro tier: `$69` × 12 × 0.8 = `$662.40`/year (Save 20%)
> [!TIP]
>
> Annual subscriptions are perfect for users who:
>
> * Plan to use the service long-term
> * Want to maximize value
> * Prefer fewer payment transactions
## Enterprise Tier
Enterprise is the highest subscription tier:
> **Benefits**
>
> * **\$200/week** credits
> * 200 max bots
> * 500 studio credits
> [!NOTE]
>
> Enterprise plans start at **\$249+/month** (**\$2,390/year** on Creem). Weekly credits are the same regardless of provider.
## How to Subscribe
You can subscribe with **Creem** (recommended), **lava.top**, or **Ko-fi**. All three grant the same tier benefits. You can only have one active subscription at a time.
**Creem (Recommended)**
**1. Open Billing**
Go to the [Electron Hub Dashboard](https://app.electronhub.ai) → **Console** → **Billing** → **Subscription**.
**2. Choose your plan**
Pick a tier and billing period (monthly or annual), then click **Subscribe**.
**3. Complete checkout**
You'll be redirected to Creem's hosted checkout to enter your payment details.
**4. Activate Benefits**
Once Creem confirms the payment (usually within a few seconds), your subscription benefits are applied automatically.
> [!NOTE]
>
> Creem subscribers get a **Manage billing** button (update card, invoices, change plan) and a **Cancel** option on the Billing → Subscription page.
> [!TIP]
>
> Creem pricing is slightly higher than Ko-fi's for the same tier, to cover payment processing fees. In-app benefits are identical either way.
**lava.top**
**1. Open Billing**
Go to the [Electron Hub Dashboard](https://app.electronhub.ai) → **Console** → **Billing** → **Subscription**.
**2. Choose plan and currency**
Pick a tier, billing period (monthly or annual), and currency (**USD**, **EUR**, or **RUB**), then start checkout.
**3. Complete checkout**
You'll be redirected to lava.top to finish payment.
**4. Activate Benefits**
Once lava.top confirms the payment (usually within a minute or two), your subscription benefits are applied automatically.
> [!NOTE]
>
> lava.top has no billing portal and no in-place plan change. Cancel from Billing → Subscription (access continues until the paid period ends). To change plan, cancel first, then subscribe again.
**Ko-fi**
**1. Verify your email**
Go to the [Electron Hub Dashboard](https://app.electronhub.ai) → **Console** → **Billing** → **Subscription** and verify your account email.
**2. Subscribe on Ko-fi**
Join the monthly membership for your desired tier on the Electron Hub Ko-fi page, using the same email as your verified Electron Hub account.
**3. Activate Benefits**
Once Ko-fi confirms the payment (usually within \~1 minute), it's matched to your account by email and your subscription benefits are applied.
> [!WARNING]
>
> **Important:** The email you pay with on Ko-fi must match your verified Electron Hub email exactly. If your email isn't verified yet when the payment arrives, it's held as pending and applied once you verify.
> [!NOTE]
>
> Ko-fi monthly memberships renew automatically. Ko-fi annual plans are one-time shop purchases (12 months, no auto-renew).
> [!WARNING]
>
> You can only have one active subscription provider at a time (Creem, lava.top, or Ko-fi). Cancel the existing one before switching. On Creem you can also change plans in the billing portal.
## Subscription Renewal
> **Automatic Renewal**
>
> **Creem**, **lava.top**, and **Ko-fi monthly** memberships renew automatically. **Ko-fi annual** plans are one-time purchases for 12 months and do not auto-renew. Your expiry date is shown on the Billing → Subscription page.
## What Happens When Subscription Expires?
> [!WARNING]
>
> If your subscription expires:
>
> * You'll be downgraded to the Free tier
> * You'll receive \$0.25 weekly credits
> * You'll lose access to premium/ultimate models
> * Your permanent credits remain (they never expire)
> * Your flex credits remain (if you have any)
## Weekly Credits Refill
> [!NOTE]
>
> Weekly credits refill every **Sunday at 21:00 UTC** (9:00 PM UTC). Unused weekly credits do **not** carry over to the next week - this is why [Flex Credits](/billing/credits#flex-credits) are useful for saving unused credits.
# Billing Troubleshooting
Source: https://docs.electronhub.ai/billing/troubleshooting
Common billing issues and how to resolve them
Common billing issues and how to resolve them.
## I ran out of credits. What can I do?
**1. Wait for Weekly Refill**
Wait for the weekly refill (every Sunday at 21:00 UTC) to get your weekly credits
**2. Enable Flex Credits**
Enable flex credits if you have any saved
**3. Enable Permanent Credits**
Enable permanent credits if you have purchased credits
**4. Purchase More Credits**
Purchase more permanent credits through PayPal or cryptocurrency
**5. Upgrade Subscription**
Upgrade your subscription for more weekly credits
> **My credits didn't refill on Sunday at 21:00 UTC**
>
> > **Troubleshooting Steps**
> >
> > Credits refill automatically every Sunday at 21:00 UTC. If you don't see your credits:
> >
> > 1. Refresh your dashboard
> > 2. Check that it's actually past Sunday 21:00 UTC
> > 3. Contact support if the issue persists
> **I purchased credits but they're not showing up**
>
> **1. Check Payment**
>
> Check your PayPal or cryptocurrency payment status
>
> **2. Refresh Dashboard**
>
> Refresh your dashboard
>
> **3. Check Permanent Credits**
>
> Check your permanent credits balance (separate from regular balance)
>
> **4. Enable Permanent Credits**
>
> Make sure permanent credits are enabled in your settings
>
> **5. Contact Support**
>
> Contact support with your order ID if still not showing
> **Why can't I use a premium or ultimate model?**
>
> > **Premium Models**
> >
> > **Premium models** can be accessed if you have:
> >
> > * A **Starter plan or higher** subscription, OR
> > * **Permanent credits** (free tier users with permanent credits can access premium models)
>
> > **Ultimate Models**
> >
> > **Ultimate models** require a **Pro tier or higher** subscription.
>
> > [!TIP]
> >
> > Check your subscription tier in the dashboard. If you're on free tier without permanent credits, you can either:
> >
> > * Purchase permanent credits to access premium models, or
> > * Upgrade through **Console → Billing → Subscription** (Creem, lava.top, or Ko-fi) to access premium/ultimate models
> **How do I enable/disable flex credits or permanent credits?**
>
> **1. Access Dashboard**
>
> Go to the [Electron Hub Dashboard](https://app.electronhub.ai)
>
> **2. Navigate to Settings**
>
> Navigate to account settings
>
> **3. Configure Credits**
>
> * Toggle flex credits on/off
> * Toggle permanent credits on/off
> * Set permanent credits monthly limits
> **Why are free models sometimes unavailable?**
>
> > [!NOTE]
> >
> > Free models are hosted by Electron Hub and may experience downtime during peak usage to ensure fair resource distribution.
>
> > [!TIP]
> >
> > For better reliability:
> >
> > * Use freemium models (they deduct credits but have better uptime)
> > * Subscribe to access premium models (routed to multiple providers for maximum uptime)
## Refund Requests
> **Permanent Credits Purchases**
>
> > [!NOTE]
> >
> > Refunds are available within 30 days of purchase if you haven't used the credits. Once credits have been used, refunds are not available except in cases of technical errors or service issues.
> **Subscription Refunds**
>
> > [!NOTE]
> >
> > Subscriptions are managed through **Creem**, **lava.top**, or **Ko-fi**, depending on which you subscribed with (check Billing → Subscription to see your provider). Creem subscribers can cancel anytime from the **Manage billing** portal. lava.top subscribers cancel from Billing → Subscription (period-end only). Refund requests for Creem, lava.top, or Ko-fi should go through that provider's support.
> **Failed Requests**
>
> > [!NOTE]
> >
> > Credits are **not charged** for failed requests (only successful and cancelled requests are charged). If you believe you were incorrectly charged for a failed request, contact support with your request ID.
> **Technical Issues**
>
> > [!NOTE]
> >
> > If you experience technical issues that prevent you from using the service, contact support for assistance. Refunds may be provided on a case-by-case basis.
> **How to Request a Refund**
>
> To request a refund, contact support through the dashboard or email with:
>
> * Your order ID or transaction ID
> * Reason for refund request
> * Date of purchase
> [!TIP]
>
> For complete refund terms, please review our [Terms of Service](https://tos.electronhub.ai).
# Chat Examples
Source: https://docs.electronhub.ai/examples/chat-examples
Real-world examples using chat completion models
Explore practical examples for implementing chat functionality with the Electron Hub API.
## Basic Chat Completion
### Simple Question and Answer
```javascript Node.js theme={null}
const response = await fetch('https://api.electronhub.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: [
{ role: 'user', content: 'What is the capital of France?' }
],
max_tokens: 100
})
});
const data = await response.json();
console.log(data.choices[0].message.content);
```
```python Python theme={null}
import requests
response = requests.post(
'https://api.electronhub.ai/v1/chat/completions',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'model': 'gpt-3.5-turbo',
'messages': [
{'role': 'user', 'content': 'What is the capital of France?'}
],
'max_tokens': 100
}
)
print(response.json()['choices'][0]['message']['content'])
```
```bash cURL theme={null}
curl -X POST "https://api.electronhub.ai/v1/chat/completions" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [
{"role": "user", "content": "What is the capital of France?"}
],
"max_tokens": 100
}'
```
## Conversation with Context
### Multi-turn Conversation
```javascript theme={null}
const conversationHistory = [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Hello! Can you help me with math?' },
{ role: 'assistant', content: 'Of course! I\'d be happy to help you with math. What would you like to work on?' },
{ role: 'user', content: 'What is 25 * 4?' }
];
const response = await fetch('https://api.electronhub.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: conversationHistory,
max_tokens: 150,
temperature: 0.7
})
});
const data = await response.json();
console.log(data.choices[0].message.content);
```
## Specialized Chat Applications
### Customer Support Bot
```javascript theme={null}
async function customerSupportChat(userMessage, customerData) {
const systemPrompt = `You are a helpful customer support agent for TechCorp.
Customer Info:
- Name: ${customerData.name}
- Account Type: ${customerData.accountType}
- Recent Orders: ${customerData.recentOrders}
Provide helpful, professional responses. If you need to escalate, say "Let me connect you with a specialist."`;
const response = await fetch('https://api.electronhub.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-4',
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userMessage }
],
max_tokens: 300,
temperature: 0.3
})
});
const data = await response.json();
return data.choices[0].message.content;
}
// Usage
const response = await customerSupportChat(
"I can't access my account",
{
name: "John Doe",
accountType: "Premium",
recentOrders: ["Order #12345", "Order #12346"]
}
);
```
### Code Assistant
```javascript theme={null}
async function codeAssistant(codeQuestion, programmingLanguage = 'JavaScript') {
const systemPrompt = `You are an expert ${programmingLanguage} developer.
Provide clear, well-commented code examples.
Explain complex concepts in simple terms.
Always include error handling when appropriate.`;
const response = await fetch('https://api.electronhub.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-4',
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: codeQuestion }
],
max_tokens: 1000,
temperature: 0.2
})
});
const data = await response.json();
return data.choices[0].message.content;
}
// Usage
const codeHelp = await codeAssistant(
"How do I implement a binary search algorithm?",
"Python"
);
```
## Streaming Responses
### Real-time Chat with Streaming
```javascript theme={null}
async function streamingChat(messages) {
const response = await fetch('https://api.electronhub.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: messages,
stream: true,
max_tokens: 500
})
});
const reader = response.body.getReader();
let assistantMessage = '';
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = new TextDecoder().decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') {
return assistantMessage;
}
try {
const parsed = JSON.parse(data);
const content = parsed.choices?.[0]?.delta?.content;
if (content) {
assistantMessage += content;
// Update UI in real-time
updateChatUI(content);
}
} catch (e) {
// Ignore parsing errors for malformed chunks
}
}
}
}
} finally {
reader.releaseLock();
}
return assistantMessage;
}
function updateChatUI(newContent) {
// Update your chat interface with the new content
const chatContainer = document.getElementById('chat-messages');
const lastMessage = chatContainer.lastElementChild;
lastMessage.textContent += newContent;
}
```
## Advanced Examples
### Function Calling
```javascript theme={null}
const tools = [
{
type: "function",
function: {
name: "get_weather",
description: "Get the current weather for a location",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The city and state or country"
},
unit: {
type: "string",
enum: ["celsius", "fahrenheit"],
description: "Temperature unit"
}
},
required: ["location"]
}
}
}
];
async function chatWithFunctions(userMessage) {
const response = await fetch('https://api.electronhub.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-4',
messages: [
{ role: 'user', content: userMessage }
],
tools: tools,
tool_choice: 'auto'
})
});
const data = await response.json();
const message = data.choices[0].message;
if (message.tool_calls) {
// Handle function calls
for (const toolCall of message.tool_calls) {
if (toolCall.function.name === 'get_weather') {
const args = JSON.parse(toolCall.function.arguments);
const weather = await getWeather(args.location, args.unit);
// Send function result back to the model
const followUpResponse = await fetch('https://api.electronhub.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-4',
messages: [
{ role: 'user', content: userMessage },
message,
{
role: 'tool',
tool_call_id: toolCall.id,
content: JSON.stringify(weather)
}
]
})
});
const followUpData = await followUpResponse.json();
return followUpData.choices[0].message.content;
}
}
}
return message.content;
}
async function getWeather(location, unit = 'celsius') {
// Mock weather API call
return {
location: location,
temperature: unit === 'celsius' ? '22' : '72',
unit: unit,
description: 'Sunny'
};
}
```
### Content Moderation Integration
```javascript theme={null}
async function moderatedChat(userMessage, conversationHistory = []) {
// First, check if the user message is appropriate
const moderationResponse = await fetch('https://api.electronhub.ai/v1/moderations', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
input: userMessage,
model: 'text-moderation-latest'
})
});
const moderationData = await moderationResponse.json();
if (moderationData.results[0].flagged) {
return {
response: "I'm sorry, but I can't respond to that type of content. Please keep our conversation respectful.",
flagged: true
};
}
// If content is safe, proceed with chat
const messages = [
...conversationHistory,
{ role: 'user', content: userMessage }
];
const chatResponse = await fetch('https://api.electronhub.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: messages,
max_tokens: 300
})
});
const chatData = await chatResponse.json();
return {
response: chatData.choices[0].message.content,
flagged: false
};
}
```
## Error Handling Examples
### Robust Chat Implementation
```javascript theme={null}
class ChatService {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseURL = 'https://api.electronhub.ai/v1';
}
async sendMessage(messages, options = {}) {
const {
model = 'gpt-3.5-turbo',
maxTokens = 500,
temperature = 0.7,
retries = 3
} = options;
for (let attempt = 1; attempt <= retries; attempt++) {
try {
const response = await fetch(`${this.baseURL}/chat/completions`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model,
messages,
max_tokens: maxTokens,
temperature
})
});
if (!response.ok) {
if (response.status === 429) {
// Rate limited - wait and retry
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
if (response.status >= 500) {
// Server error - retry
if (attempt < retries) continue;
}
throw new Error(`API request failed: ${response.status}`);
}
const data = await response.json();
return data.choices[0].message.content;
} catch (error) {
if (attempt === retries) {
throw new Error(`Failed to get response after ${retries} attempts: ${error.message}`);
}
console.warn(`Attempt ${attempt} failed:`, error.message);
}
}
}
}
// Usage
const chatService = new ChatService('YOUR_API_KEY');
try {
const response = await chatService.sendMessage([
{ role: 'user', content: 'Hello, how are you?' }
]);
console.log(response);
} catch (error) {
console.error('Chat failed:', error.message);
// Handle error appropriately
}
```
# Embedding Examples
Source: https://docs.electronhub.ai/examples/embedding-examples
Text embeddings for semantic search and recommendations
Learn how to use text embeddings for semantic search, similarity matching, and other ML applications.
## Basic Embeddings
### Simple Text Embedding
```javascript Node.js theme={null}
const response = await fetch('https://api.electronhub.ai/v1/embeddings', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
input: 'The quick brown fox jumps over the lazy dog',
model: 'text-embedding-3-small'
})
});
const data = await response.json();
console.log('Embedding vector:', data.data[0].embedding);
console.log('Vector dimensions:', data.data[0].embedding.length);
```
```python Python theme={null}
import requests
import numpy as np
response = requests.post(
'https://api.electronhub.ai/v1/embeddings',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'input': 'The quick brown fox jumps over the lazy dog',
'model': 'text-embedding-3-small'
}
)
data = response.json()
embedding = data['data'][0]['embedding']
print(f'Embedding vector: {embedding[:5]}...') # First 5 dimensions
print(f'Vector dimensions: {len(embedding)}')
```
```bash cURL theme={null}
curl -X POST "https://api.electronhub.ai/v1/embeddings" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"input": "The quick brown fox jumps over the lazy dog",
"model": "text-embedding-3-small"
}'
```
## Batch Embeddings
### Processing Multiple Texts
```javascript theme={null}
async function getBatchEmbeddings(texts, model = 'text-embedding-3-small') {
const response = await fetch('https://api.electronhub.ai/v1/embeddings', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
input: texts,
model: model
})
});
const data = await response.json();
return texts.map((text, index) => ({
text: text,
embedding: data.data[index].embedding,
index: index
}));
}
// Usage
const documents = [
'Machine learning is a subset of artificial intelligence',
'Deep learning uses neural networks with many layers',
'Natural language processing helps computers understand text',
'Computer vision enables machines to interpret images',
'Robotics combines AI with mechanical engineering'
];
const embeddings = await getBatchEmbeddings(documents);
console.log(`Generated ${embeddings.length} embeddings`);
```
## Semantic Search
### Document Search System
```javascript theme={null}
class SemanticSearchEngine {
constructor(apiKey) {
this.apiKey = apiKey;
this.documents = [];
this.embeddings = [];
}
async addDocuments(documents) {
const response = await fetch('https://api.electronhub.ai/v1/embeddings', {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
input: documents,
model: 'text-embedding-3-small'
})
});
const data = await response.json();
documents.forEach((doc, index) => {
this.documents.push({
id: this.documents.length,
text: doc,
embedding: data.data[index].embedding
});
});
console.log(`Added ${documents.length} documents to search index`);
}
async search(query, topK = 5) {
// Get query embedding
const response = await fetch('https://api.electronhub.ai/v1/embeddings', {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
input: query,
model: 'text-embedding-3-small'
})
});
const data = await response.json();
const queryEmbedding = data.data[0].embedding;
// Calculate similarities
const similarities = this.documents.map(doc => ({
...doc,
similarity: this.cosineSimilarity(queryEmbedding, doc.embedding)
}));
// Sort by similarity and return top results
return similarities
.sort((a, b) => b.similarity - a.similarity)
.slice(0, topK);
}
cosineSimilarity(a, b) {
const dotProduct = a.reduce((sum, ai, i) => sum + ai * b[i], 0);
const magnitudeA = Math.sqrt(a.reduce((sum, ai) => sum + ai * ai, 0));
const magnitudeB = Math.sqrt(b.reduce((sum, bi) => sum + bi * bi, 0));
return dotProduct / (magnitudeA * magnitudeB);
}
}
// Usage
const searchEngine = new SemanticSearchEngine('YOUR_API_KEY');
// Add knowledge base
const knowledgeBase = [
'Python is a high-level programming language known for its simplicity',
'JavaScript is the language of the web, used for both frontend and backend',
'Machine learning algorithms can learn patterns from data',
'APIs enable different software applications to communicate',
'Databases store and organize large amounts of structured data',
'Cloud computing provides on-demand computing resources',
'Cybersecurity protects systems from digital attacks and threats'
];
await searchEngine.addDocuments(knowledgeBase);
// Search for relevant documents
const results = await searchEngine.search('web development programming', 3);
console.log('Search Results:');
results.forEach((result, index) => {
console.log(`${index + 1}. [${result.similarity.toFixed(3)}] ${result.text}`);
});
```
## Similarity Matching
### Content Recommendation System
```javascript theme={null}
class ContentRecommendationEngine {
constructor(apiKey) {
this.apiKey = apiKey;
this.contentItems = [];
}
async addContent(items) {
// Items should be objects with id, title, description, category
const descriptions = items.map(item =>
`${item.title}. ${item.description}. Category: ${item.category}`
);
const response = await fetch('https://api.electronhub.ai/v1/embeddings', {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
input: descriptions,
model: 'text-embedding-3-small'
})
});
const data = await response.json();
items.forEach((item, index) => {
this.contentItems.push({
...item,
embedding: data.data[index].embedding
});
});
}
async getRecommendations(userPreferences, count = 5) {
// Get embedding for user preferences
const response = await fetch('https://api.electronhub.ai/v1/embeddings', {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
input: userPreferences,
model: 'text-embedding-3-small'
})
});
const data = await response.json();
const userEmbedding = data.data[0].embedding;
// Calculate similarities and rank content
const recommendations = this.contentItems.map(item => ({
...item,
similarity: this.cosineSimilarity(userEmbedding, item.embedding)
}));
return recommendations
.sort((a, b) => b.similarity - a.similarity)
.slice(0, count);
}
async findSimilarContent(contentId, count = 5) {
const targetContent = this.contentItems.find(item => item.id === contentId);
if (!targetContent) return [];
const similarities = this.contentItems
.filter(item => item.id !== contentId)
.map(item => ({
...item,
similarity: this.cosineSimilarity(targetContent.embedding, item.embedding)
}));
return similarities
.sort((a, b) => b.similarity - a.similarity)
.slice(0, count);
}
cosineSimilarity(a, b) {
const dotProduct = a.reduce((sum, ai, i) => sum + ai * b[i], 0);
const magnitudeA = Math.sqrt(a.reduce((sum, ai) => sum + ai * ai, 0));
const magnitudeB = Math.sqrt(b.reduce((sum, bi) => sum + bi * bi, 0));
return dotProduct / (magnitudeA * magnitudeB);
}
}
// Usage
const recommender = new ContentRecommendationEngine('YOUR_API_KEY');
const contentCatalog = [
{
id: 1,
title: 'Introduction to Machine Learning',
description: 'Learn the basics of ML algorithms and applications',
category: 'Technology'
},
{
id: 2,
title: 'Cooking Italian Pasta',
description: 'Traditional recipes for authentic Italian pasta dishes',
category: 'Food'
},
{
id: 3,
title: 'JavaScript for Beginners',
description: 'Complete guide to learning JavaScript programming',
category: 'Technology'
},
{
id: 4,
title: 'Yoga and Meditation',
description: 'Mindfulness practices for physical and mental wellness',
category: 'Health'
},
{
id: 5,
title: 'Data Science with Python',
description: 'Analyze data and build predictive models using Python',
category: 'Technology'
}
];
await recommender.addContent(contentCatalog);
// Get recommendations based on user preferences
const userPrefs = 'I am interested in programming and software development';
const recommendations = await recommender.getRecommendations(userPrefs, 3);
console.log('Recommended content:');
recommendations.forEach((rec, index) => {
console.log(`${index + 1}. ${rec.title} (${rec.similarity.toFixed(3)})`);
});
// Find similar content to a specific item
const similar = await recommender.findSimilarContent(3, 2); // Similar to JavaScript course
console.log('\nSimilar to JavaScript course:');
similar.forEach((item, index) => {
console.log(`${index + 1}. ${item.title} (${item.similarity.toFixed(3)})`);
});
```
## Advanced Use Cases
### Multilingual Document Clustering
```javascript theme={null}
class DocumentClusterer {
constructor(apiKey) {
this.apiKey = apiKey;
}
async clusterDocuments(documents, numClusters = 3) {
// Get embeddings for all documents
const response = await fetch('https://api.electronhub.ai/v1/embeddings', {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
input: documents,
model: 'text-embedding-3-small'
})
});
const data = await response.json();
const embeddings = data.data.map(item => item.embedding);
// Simple k-means clustering
const clusters = await this.kMeansClustering(embeddings, numClusters);
// Group documents by cluster
const clusteredDocs = {};
clusters.forEach((clusterIndex, docIndex) => {
if (!clusteredDocs[clusterIndex]) {
clusteredDocs[clusterIndex] = [];
}
clusteredDocs[clusterIndex].push({
index: docIndex,
text: documents[docIndex],
embedding: embeddings[docIndex]
});
});
return clusteredDocs;
}
async kMeansClustering(embeddings, k, maxIterations = 100) {
const dimensions = embeddings[0].length;
// Initialize centroids randomly
let centroids = Array.from({ length: k }, () =>
Array.from({ length: dimensions }, () => Math.random() * 2 - 1)
);
let assignments = new Array(embeddings.length);
for (let iteration = 0; iteration < maxIterations; iteration++) {
// Assign points to closest centroids
const newAssignments = embeddings.map(embedding => {
let closestCentroid = 0;
let closestDistance = this.euclideanDistance(embedding, centroids[0]);
for (let i = 1; i < k; i++) {
const distance = this.euclideanDistance(embedding, centroids[i]);
if (distance < closestDistance) {
closestDistance = distance;
closestCentroid = i;
}
}
return closestCentroid;
});
// Check for convergence
if (JSON.stringify(assignments) === JSON.stringify(newAssignments)) {
break;
}
assignments = newAssignments;
// Update centroids
for (let i = 0; i < k; i++) {
const clusterPoints = embeddings.filter((_, index) => assignments[index] === i);
if (clusterPoints.length > 0) {
centroids[i] = this.calculateCentroid(clusterPoints);
}
}
}
return assignments;
}
euclideanDistance(a, b) {
return Math.sqrt(a.reduce((sum, ai, i) => sum + Math.pow(ai - b[i], 2), 0));
}
calculateCentroid(points) {
const dimensions = points[0].length;
const centroid = new Array(dimensions).fill(0);
points.forEach(point => {
point.forEach((value, i) => {
centroid[i] += value;
});
});
return centroid.map(sum => sum / points.length);
}
}
// Usage
const clusterer = new DocumentClusterer('YOUR_API_KEY');
const documents = [
'Machine learning algorithms learn from data to make predictions',
'Deep neural networks have multiple hidden layers for complex patterns',
'Pizza is a traditional Italian dish with tomato sauce and cheese',
'Pasta comes in many shapes and is often served with various sauces',
'Basketball is played by two teams of five players each',
'Soccer is the most popular sport worldwide with billions of fans',
'Artificial intelligence aims to create machines that can think',
'Lasagna is a layered pasta dish baked in the oven',
'Tennis is played on a rectangular court with a net in the middle'
];
const clusters = await clusterer.clusterDocuments(documents, 3);
console.log('Document Clusters:');
Object.entries(clusters).forEach(([clusterIndex, docs]) => {
console.log(`\nCluster ${parseInt(clusterIndex) + 1}:`);
docs.forEach(doc => {
console.log(` - ${doc.text}`);
});
});
```
### Question Answering with Embeddings
```javascript theme={null}
class EmbeddingQASystem {
constructor(apiKey) {
this.apiKey = apiKey;
this.knowledgeBase = [];
}
async addKnowledge(qaPairs) {
// qaPairs: [{question: string, answer: string}]
const questions = qaPairs.map(pair => pair.question);
const response = await fetch('https://api.electronhub.ai/v1/embeddings', {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
input: questions,
model: 'text-embedding-3-small'
})
});
const data = await response.json();
qaPairs.forEach((pair, index) => {
this.knowledgeBase.push({
question: pair.question,
answer: pair.answer,
embedding: data.data[index].embedding
});
});
}
async answerQuestion(userQuestion, threshold = 0.7) {
// Get embedding for user question
const response = await fetch('https://api.electronhub.ai/v1/embeddings', {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
input: userQuestion,
model: 'text-embedding-3-small'
})
});
const data = await response.json();
const questionEmbedding = data.data[0].embedding;
// Find most similar question
const similarities = this.knowledgeBase.map(item => ({
...item,
similarity: this.cosineSimilarity(questionEmbedding, item.embedding)
}));
const bestMatch = similarities.reduce((best, current) =>
current.similarity > best.similarity ? current : best
);
if (bestMatch.similarity >= threshold) {
return {
answer: bestMatch.answer,
confidence: bestMatch.similarity,
matchedQuestion: bestMatch.question
};
} else {
return {
answer: "I don't have enough information to answer that question.",
confidence: bestMatch.similarity,
matchedQuestion: bestMatch.question
};
}
}
cosineSimilarity(a, b) {
const dotProduct = a.reduce((sum, ai, i) => sum + ai * b[i], 0);
const magnitudeA = Math.sqrt(a.reduce((sum, ai) => sum + ai * ai, 0));
const magnitudeB = Math.sqrt(b.reduce((sum, bi) => sum + bi * bi, 0));
return dotProduct / (magnitudeA * magnitudeB);
}
}
// Usage
const qaSystem = new EmbeddingQASystem('YOUR_API_KEY');
const knowledgeBase = [
{
question: "What is machine learning?",
answer: "Machine learning is a subset of AI that enables computers to learn and improve from experience without being explicitly programmed."
},
{
question: "How do neural networks work?",
answer: "Neural networks are computing systems inspired by biological neural networks, consisting of interconnected nodes that process information."
},
{
question: "What is the difference between AI and ML?",
answer: "AI is the broader concept of machines being able to carry out tasks in a smart way, while ML is a subset of AI that focuses on learning from data."
},
{
question: "What programming languages are used for data science?",
answer: "Python and R are the most popular languages for data science, along with SQL for database operations."
}
];
await qaSystem.addKnowledge(knowledgeBase);
// Test questions
const testQuestions = [
"What exactly is machine learning?",
"Can you explain neural networks?",
"What's the relationship between AI and machine learning?",
"What should I learn to become a data scientist?"
];
for (const question of testQuestions) {
const result = await qaSystem.answerQuestion(question);
console.log(`\nQ: ${question}`);
console.log(`A: ${result.answer}`);
console.log(`Confidence: ${result.confidence.toFixed(3)}`);
console.log(`Matched: ${result.matchedQuestion}`);
}
```
# Image Examples
Source: https://docs.electronhub.ai/examples/image-examples
Image generation and editing examples
Learn how to generate, edit, and manipulate images using the Electron Hub API.
## Basic Image Generation
### Simple Image Generation
```javascript Node.js theme={null}
const response = await fetch('https://api.electronhub.ai/v1/images/generations', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: 'A beautiful sunset over a calm lake with mountains in the background',
model: 'dall-e-3',
size: '1024x1024',
quality: 'hd',
n: 1
})
});
const data = await response.json();
console.log('Generated image URL:', data.data[0].url);
```
```python Python theme={null}
import requests
response = requests.post(
'https://api.electronhub.ai/v1/images/generations',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'prompt': 'A beautiful sunset over a calm lake with mountains in the background',
'model': 'dall-e-3',
'size': '1024x1024',
'quality': 'hd',
'n': 1
}
)
data = response.json()
print('Generated image URL:', data['data'][0]['url'])
```
```bash cURL theme={null}
curl -X POST "https://api.electronhub.ai/v1/images/generations" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A beautiful sunset over a calm lake with mountains in the background",
"model": "dall-e-3",
"size": "1024x1024",
"quality": "hd",
"n": 1
}'
```
## Advanced Image Generation
### Marketing Materials Generator
```javascript theme={null}
async function generateMarketingImage(productName, style = 'modern') {
const stylePrompts = {
modern: 'clean, minimalist, modern design with white background',
vintage: 'vintage, retro, nostalgic style with warm colors',
luxury: 'premium, elegant, sophisticated with gold accents',
playful: 'colorful, fun, energetic with bold graphics'
};
const prompt = `Professional marketing image for ${productName}, ${stylePrompts[style]}, high quality, commercial photography style, well-lit, product showcase`;
const response = await fetch('https://api.electronhub.ai/v1/images/generations', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: prompt,
model: 'dall-e-3',
size: '1792x1024', // Landscape for marketing
quality: 'hd',
style: 'vivid'
})
});
const data = await response.json();
return {
imageUrl: data.data[0].url,
revisedPrompt: data.data[0].revised_prompt
};
}
// Usage
const marketingImage = await generateMarketingImage('wireless headphones', 'modern');
console.log('Marketing image:', marketingImage.imageUrl);
```
### Batch Image Generation
```javascript theme={null}
async function generateImageVariations(basePrompt, count = 4) {
const variations = [
`${basePrompt}, daylight, bright and cheerful`,
`${basePrompt}, golden hour, warm lighting`,
`${basePrompt}, minimalist style, clean composition`,
`${basePrompt}, detailed and realistic, high resolution`
];
const promises = variations.slice(0, count).map(async (prompt, index) => {
const response = await fetch('https://api.electronhub.ai/v1/images/generations', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: prompt,
model: 'dall-e-2', // Using DALL-E 2 for batch generation
size: '512x512',
n: 1
})
});
const data = await response.json();
return {
index: index + 1,
prompt: prompt,
imageUrl: data.data[0].url
};
});
try {
const results = await Promise.all(promises);
return results;
} catch (error) {
console.error('Batch generation failed:', error);
throw error;
}
}
// Usage
const variations = await generateImageVariations('a cozy coffee shop interior');
variations.forEach(variation => {
console.log(`Variation ${variation.index}: ${variation.imageUrl}`);
});
```
## Image Editing
### Basic Image Editing
```javascript theme={null}
async function editImage(imageFile, editPrompt, maskFile = null) {
const formData = new FormData();
formData.append('image', imageFile);
formData.append('prompt', editPrompt);
formData.append('model', 'dall-e-2');
formData.append('size', '1024x1024');
formData.append('n', 1);
if (maskFile) {
formData.append('mask', maskFile);
}
const response = await fetch('https://api.electronhub.ai/v1/images/edits', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
},
body: formData
});
const data = await response.json();
return data.data[0].url;
}
// Usage with file input
const fileInput = document.getElementById('image-upload');
const file = fileInput.files[0];
if (file) {
const editedImageUrl = await editImage(
file,
'Add a beautiful blue sky with fluffy white clouds'
);
console.log('Edited image:', editedImageUrl);
}
```
### Advanced Image Editing with Masks
```javascript theme={null}
async function advancedImageEdit(originalImage, maskImage, editDescription) {
const formData = new FormData();
// Convert base64 or URL to File object if needed
if (typeof originalImage === 'string') {
const response = await fetch(originalImage);
const blob = await response.blob();
originalImage = new File([blob], 'original.png', { type: 'image/png' });
}
formData.append('image', originalImage);
formData.append('mask', maskImage);
formData.append('prompt', editDescription);
formData.append('model', 'dall-e-2');
formData.append('size', '1024x1024');
formData.append('n', 2); // Generate 2 variations
try {
const response = await fetch('https://api.electronhub.ai/v1/images/edits', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
},
body: formData
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.data.map(item => item.url);
} catch (error) {
console.error('Image editing failed:', error);
throw error;
}
}
// Usage
const editedImages = await advancedImageEdit(
originalImageFile,
maskImageFile,
'Replace the background with a tropical beach scene'
);
editedImages.forEach((url, index) => {
console.log(`Edited variation ${index + 1}: ${url}`);
});
```
## Image Variations
### Creating Image Variations
```javascript theme={null}
async function createImageVariations(sourceImage, count = 3) {
const formData = new FormData();
formData.append('image', sourceImage);
formData.append('model', 'dall-e-2');
formData.append('n', count);
formData.append('size', '1024x1024');
const response = await fetch('https://api.electronhub.ai/v1/images/variations', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
},
body: formData
});
const data = await response.json();
return data.data.map(item => item.url);
}
// Usage
const fileInput = document.getElementById('source-image');
const sourceFile = fileInput.files[0];
if (sourceFile) {
const variations = await createImageVariations(sourceFile, 4);
variations.forEach((url, index) => {
console.log(`Variation ${index + 1}: ${url}`);
// Display in UI
const img = document.createElement('img');
img.src = url;
img.style.width = '200px';
img.style.height = '200px';
img.style.objectFit = 'cover';
img.style.margin = '10px';
document.getElementById('variations-container').appendChild(img);
});
}
```
## Specialized Use Cases
### Logo Generator
```javascript theme={null}
async function generateLogo(companyName, industry, style = 'modern') {
const industryPrompts = {
tech: 'technology, digital, innovation, circuits, geometric',
food: 'culinary, fresh, appetite, organic, kitchen',
fitness: 'strength, energy, movement, health, athletic',
finance: 'trust, stability, growth, professional, corporate',
creative: 'artistic, imaginative, colorful, expressive, design'
};
const stylePrompts = {
modern: 'clean, minimalist, simple, contemporary',
vintage: 'retro, classic, traditional, timeless',
playful: 'fun, colorful, energetic, dynamic',
elegant: 'sophisticated, premium, luxurious, refined'
};
const prompt = `Professional logo design for "${companyName}", ${industryPrompts[industry] || 'business'}, ${stylePrompts[style]}, vector style, simple, memorable, scalable, white background, high contrast`;
const response = await fetch('https://api.electronhub.ai/v1/images/generations', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: prompt,
model: 'dall-e-3',
size: '1024x1024',
quality: 'hd',
style: 'natural' // More appropriate for logos
})
});
const data = await response.json();
return {
logoUrl: data.data[0].url,
originalPrompt: prompt,
revisedPrompt: data.data[0].revised_prompt
};
}
// Usage
const logo = await generateLogo('TechFlow Solutions', 'tech', 'modern');
console.log('Generated logo:', logo.logoUrl);
```
### Art Style Transfer
```javascript theme={null}
async function generateArtInStyle(subject, artStyle) {
const artStyles = {
impressionist: 'impressionist painting style, like Monet, soft brushstrokes, light and color',
cubist: 'cubist art style, like Picasso, geometric shapes, abstract forms',
surreal: 'surrealist art, dreamlike, fantasy, impossible scenes',
photorealistic: 'photorealistic, highly detailed, professional photography',
watercolor: 'watercolor painting, soft colors, flowing, artistic',
oilpainting: 'oil painting, rich textures, classical art style',
cartoon: 'cartoon style, animated, colorful, fun illustration',
sketch: 'pencil sketch, black and white, artistic drawing'
};
const prompt = `${subject}, ${artStyles[artStyle] || artStyle}, masterpiece, high quality art, detailed, artistic composition`;
const response = await fetch('https://api.electronhub.ai/v1/images/generations', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: prompt,
model: 'dall-e-3',
size: '1024x1024',
quality: 'hd',
style: 'vivid'
})
});
const data = await response.json();
return data.data[0].url;
}
// Usage
const artPiece = await generateArtInStyle(
'a majestic mountain landscape with a lake',
'impressionist'
);
console.log('Art piece:', artPiece);
```
## Error Handling and Utilities
### Robust Image Generation Service
```javascript theme={null}
class ImageGenerationService {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseURL = 'https://api.electronhub.ai/v1';
}
async generateImage(prompt, options = {}) {
const {
model = 'dall-e-3',
size = '1024x1024',
quality = 'standard',
style = 'vivid',
retries = 3
} = options;
for (let attempt = 1; attempt <= retries; attempt++) {
try {
const response = await fetch(`${this.baseURL}/images/generations`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt,
model,
size,
quality,
style,
n: 1
})
});
if (!response.ok) {
if (response.status === 400) {
const error = await response.json();
throw new Error(`Content policy violation: ${error.error.message}`);
}
if (response.status === 429) {
// Rate limited
const delay = Math.pow(2, attempt) * 1000;
console.log(`Rate limited, waiting ${delay}ms before retry ${attempt}`);
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return {
success: true,
imageUrl: data.data[0].url,
revisedPrompt: data.data[0].revised_prompt
};
} catch (error) {
if (attempt === retries) {
return {
success: false,
error: error.message
};
}
console.warn(`Attempt ${attempt} failed:`, error.message);
}
}
}
async downloadImage(imageUrl, filename) {
try {
const response = await fetch(imageUrl);
const blob = await response.blob();
// Create download link
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename || 'generated-image.png';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
return true;
} catch (error) {
console.error('Download failed:', error);
return false;
}
}
validatePrompt(prompt) {
if (!prompt || prompt.trim().length === 0) {
throw new Error('Prompt cannot be empty');
}
if (prompt.length > 1000) {
throw new Error('Prompt too long (max 1000 characters)');
}
// Check for potentially problematic content
const restrictedTerms = ['violence', 'harmful', 'illegal'];
const lowerPrompt = prompt.toLowerCase();
for (const term of restrictedTerms) {
if (lowerPrompt.includes(term)) {
throw new Error(`Prompt contains restricted content: ${term}`);
}
}
return true;
}
}
// Usage
const imageService = new ImageGenerationService('YOUR_API_KEY');
try {
imageService.validatePrompt('A beautiful landscape painting');
const result = await imageService.generateImage(
'A serene Japanese garden with cherry blossoms',
{
model: 'dall-e-3',
size: '1024x1024',
quality: 'hd'
}
);
if (result.success) {
console.log('Generated image:', result.imageUrl);
console.log('Revised prompt:', result.revisedPrompt);
// Download the image
await imageService.downloadImage(result.imageUrl, 'japanese-garden.png');
} else {
console.error('Generation failed:', result.error);
}
} catch (error) {
console.error('Validation failed:', error.message);
}
```
# Authentication
Source: https://docs.electronhub.ai/getting-started/authentication
Learn how to authenticate with the Electron Hub API
The Electron Hub API uses API keys for authentication. You'll need to include your API key in the `Authorization` header of every request.
## Key Types
Electron Hub issues three kinds of API keys, all used the same way (Bearer token):
| Prefix | Type | What it's for |
| - | - | - |
| `ek-` | **Master key** | Your main account key — full model catalog, billed against your credits |
| `ek-proxy-` | **Proxy key** | Scoped sub-keys you create under your master key, with per-key budgets and model allowlists |
| `ek-dev-` | **DevPass key** | [Coding Plan](/billing/coding-plan) key — flat-rate access to the dedicated `:dev` coding models, never touches credits |
> [!NOTE]
>
> `:dev` models accept only `ek-dev-` keys, and DevPass keys work only on the Coding Plan model list — the key types don't overlap.
## Getting Your API Key
1. Visit the [Electron Hub Console](https://app.electronhub.ai)
2. Sign up or log in to your account
3. Navigate to the API Keys section
4. Generate a new API key
5. Copy and securely store your API key
> [!WARNING]
>
> Keep your API key secure and never share it publicly. Treat it like a password.
## Using Your API Key
Include your API key in the `Authorization` header with the `Bearer` prefix:
```bash theme={null}
curl -X POST "https://api.electronhub.ai/v1/chat/completions" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [
{"role": "user", "content": "Hello!"}
]
}'
```
## Environment Variables
For security, store your API key as an environment variable:
```bash theme={null}
export ELECTRONHUB_API_KEY="your_api_key_here"
```
Then use it in your code:
```python theme={null}
import os
api_key = os.getenv("ELECTRONHUB_API_KEY")
```
## API Key Management
* **Regenerate Keys**: You can regenerate your API key at any time in the console
* **Multiple Keys**: Create separate keys for different environments (development, production)
* **Monitor Usage**: Track your API usage in the console dashboard
## Rate Limiting
API keys are subject to rate limits based on your plan. See our [rate limits guide](/getting-started/rate-limits) for more information.
# Error Handling
Source: https://docs.electronhub.ai/getting-started/errors
Common errors and how to handle them gracefully
This guide covers the error codes you might encounter when using the Electron Hub API, along with solutions and best practices for handling them.
## HTTP Status Codes
The Electron Hub API uses standard HTTP status codes to indicate the success or failure of requests.
| Code | Status | Description |
| - | - | - |
| **200** | OK | Request successful |
| **400** | Bad Request | Invalid request format or parameters |
| **401** | Unauthorized | Invalid or missing API key |
| **403** | Forbidden | API key lacks required permissions |
| **404** | Not Found | Endpoint or resource not found |
| **429** | Too Many Requests | Rate limit exceeded |
| **500** | Internal Server Error | Server-side error |
| **503** | Service Unavailable | Service temporarily unavailable |
## Common Error Codes
### 401 - Authentication Errors
**Invalid API Key**
* **Cause:** The API key is incorrect, missing, or malformed
* **Solution:** Verify your API key from the [Electron Hub Console](https://app.electronhub.ai)
**Expired API Key**
* **Cause:** Your API key has been revoked or expired
* **Solution:** Generate a new API key from your dashboard
### 429 - Rate Limit Errors
**Request Rate Limit**
* **Cause:** Too many requests sent in a short time period
* **Solution:** Implement exponential backoff and respect rate limits
**Token Rate Limit**
* **Cause:** Token usage has exceeded your plan limits
* **Solution:** Upgrade your plan or wait for the limit to reset
### 400 - Bad Request Errors
**Invalid Model**
* **Cause:** The specified model is not available or misspelled
* **Solution:** Check the [models documentation](/models/overview) for available models
**Invalid Parameters**
* **Cause:** Request parameters are missing or invalid
* **Solution:** Verify all required parameters are provided with correct types
**Content Policy Violation**
* **Cause:** Input content violates usage policies
* **Solution:** Review and modify your content to comply with policies
### 402 - Payment Required
**Insufficient Credits**
* **Cause:** Your account has insufficient credits or balance
* **Solution:** Purchase additional credits or upgrade your plan
**Premium Model Access**
* **Cause:** Attempting to use a premium model without subscription
* **Solution:** Upgrade to a plan that includes premium model access
### 500 - Server Errors
**Internal Server Error**
* **Cause:** Unexpected error on our servers
* **Solution:** Retry with exponential backoff; contact support if persistent
### 503 - Service Unavailable
**Model Temporarily Unavailable**
* **Cause:** The requested model is temporarily offline
* **Solution:** Try again later or use an alternative model
## Error Response Format
All errors return a consistent JSON envelope with a top-level `error` object:
```json theme={null}
{
"error": {
"message": "Description of the error",
"type": "invalid_request_error",
"param": "parameter_name",
"code": 400
}
}
```
* `message` — human-readable description (always present).
* `type` — error category (e.g. `invalid_request_error`).
* `param` — the offending parameter, or `null`.
* `code` — the HTTP status code, or `null`.
The Anthropic-compatible `/v1/messages` endpoint instead returns Anthropic's native error shape: `{"type": "error", "error": {"type": "...", "message": "..."}}`.
## Best Practices
### Implement Retry Logic
```javascript theme={null}
async function makeAPICall(requestFn, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await requestFn();
} catch (error) {
if (error.status >= 400 && error.status < 500 && error.status !== 429) {
throw error; // Don't retry client errors (except rate limits)
}
if (attempt === maxRetries) {
throw error;
}
// Exponential backoff
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
```
### Handle Specific Error Types
```javascript theme={null}
try {
const response = await electronhubAPI.chat.completions.create({
model: 'gpt-4',
messages: messages
});
} catch (error) {
switch (error.status) {
case 401:
console.error('Invalid API key');
break;
case 429:
console.error('Rate limit exceeded');
break;
case 400:
console.error('Invalid request:', error.message);
break;
default:
console.error('API error:', error.message);
}
}
```
### Monitor Rate Limits
Check response headers for rate limit information:
```javascript theme={null}
const response = await fetch('https://api.electronhub.ai/v1/chat/completions', {
method: 'POST',
headers: { 'Authorization': 'Bearer YOUR_API_KEY' },
body: JSON.stringify(requestData)
});
console.log('Rate limit remaining:', response.headers.get('x-ratelimit-remaining'));
console.log('Rate limit reset:', response.headers.get('x-ratelimit-reset'));
```
## Getting Help
If you encounter persistent errors or need assistance:
* Check our [status page](https://status.electronhub.ai) for service updates
* Join our [Discord community](https://discord.com/invite/electronhub) for help
* Contact support at [support@electronhub.ai](mailto:support@electronhub.ai)
* Review our [best practices guide](/guides/best-practices) for optimization tips
# Introduction
Source: https://docs.electronhub.ai/getting-started/introduction
Welcome to Electron Hub API - Your unified gateway to 450+ AI models

Welcome to the Electron Hub API documentation! This comprehensive guide will help you integrate our powerful AI capabilities into your applications.
## What is Electron Hub?
Electron Hub provides unified access to multiple AI models through a single, easy-to-use API. Whether you need chat completions, image generation, speech-to-text, embeddings, or content moderation, we've got you covered.
## Key Features
* **Multiple Model Support**: Access models from OpenAI, Anthropic, and other providers
* **Unified Interface**: Consistent API across all model types
* **High Performance**: Optimized for speed and reliability
* **Competitive Pricing**: Cost-effective access to premium AI models
* **Developer-Friendly**: Comprehensive documentation and examples
## Getting Started
1. **Get an API Key**: Sign up at [our playground](https://app.electronhub.ai)
2. **Read the Quickstart**: Follow our [quickstart guide](/getting-started/quickstart)
3. **Explore the API**: Check out our [API reference](/api-reference/chat/completions)
4. **Try Examples**: See our [examples](/examples/chat-examples) in action
## Need Help?
* Join our [Discord community](https://discord.com/invite/electronhub)
* Check out the [playground](https://app.electronhub.ai)
* Read our [best practices guide](/guides/best-practices)
## Quick Links
> **[Electron Hub Dashboard](https://app.electronhub.ai)**
>
> Build AI applications using Electron Hub API for any purpose using our models.
> **[Electron Hub Models](https://app.electronhub.ai#models)**
>
> Explore all of the models available in the Electron Hub API.
# Quickstart
Source: https://docs.electronhub.ai/getting-started/quickstart
Get started with Electron Hub API in minutes
**1. Get Your API Key**
Create your free account at [app.electronhub.ai](https://app.electronhub.ai)
### Generate API Key
Visit the [API Keys section](https://app.electronhub.ai) to generate your first API key.
> [!WARNING]
>
> Keep your API key secure! Never share it or include it in client-side code.
**2. Make Your First Request**
```python Python theme={null}
import requests
response = requests.post(
'https://api.electronhub.ai/v1/chat/completions',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'model': 'gpt-3.5-turbo',
'messages': [
{'role': 'user', 'content': 'Hello! How are you?'}
]
}
)
print(response.json()['choices'][0]['message']['content'])
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.electronhub.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: [
{ role: 'user', content: 'Hello! How are you?' }
]
})
});
const data = await response.json();
console.log(data.choices[0].message.content);
```
```bash cURL theme={null}
curl https://api.electronhub.ai/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [
{"role": "user", "content": "Hello! How are you?"}
]
}'
```
**3. Explore Different Models**
### Chat Models
Perfect for conversations and text generation:
* **GPT-4**: Most capable, best for complex tasks
* **GPT-3.5-turbo**: Fast and cost-effective
* **Claude 3**: Great for analysis and reasoning
### Example: Using GPT-4
```python theme={null}
response = requests.post(
'https://api.electronhub.ai/v1/chat/completions',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'model': 'gpt-4',
'messages': [
{'role': 'user', 'content': 'Explain quantum computing in simple terms'}
]
}
)
```
**4. Try Image Generation**
Generate images from text descriptions:
```python theme={null}
response = requests.post(
'https://api.electronhub.ai/v1/images/generations',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'prompt': 'A futuristic cityscape at sunset',
'model': 'dall-e-3',
'size': '1024x1024'
}
)
image_url = response.json()['data'][0]['url']
print(f"Generated image: {image_url}")
```
**5. Text Embeddings**
Convert text to vectors for semantic search:
```python theme={null}
response = requests.post(
'https://api.electronhub.ai/v1/embeddings',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'input': 'Your text to embed',
'model': 'text-embedding-3-small'
}
)
embedding = response.json()['data'][0]['embedding']
```
## Next Steps
> **[Authentication Guide](/getting-started/authentication)**
>
> Learn about API keys and security best practices
> **[Rate Limits](/getting-started/rate-limits)**
>
> Understand rate limits and optimization strategies
> **[API Reference](/api-reference/chat/completions)**
>
> Explore all available endpoints and parameters
> **[Examples](/examples/chat-examples)**
>
> See practical examples and use cases
> **[Best Practices](/guides/best-practices)**
>
> Learn optimization and production tips
> **[Contact Support](mailto:support@electronhub.ai)**
>
> Get help from our support team
## Troubleshooting
### Common Issues
**401 Unauthorized**
* Check that your API key is correct
* Ensure you're using the `Bearer` prefix
* Verify your key hasn't expired
**429 Rate Limited**
* Slow down your request rate
* Check your usage limits in the dashboard
* Consider upgrading your plan
**400 Bad Request**
* Verify all required parameters are included
* Check parameter types and formats
* Review the API reference for correct syntax
Need more help? Join our [Discord community](https://discord.com/invite/electronhub) or check the [troubleshooting guide](/getting-started/errors).
# Rate Limits
Source: https://docs.electronhub.ai/getting-started/rate-limits
Understanding rate limits and how to handle them effectively
## Overview
Electron Hub implements rate limiting to ensure fair usage and maintain service quality for all users. Rate limits are measured in **Requests Per Minute (RPM)** and vary by subscription plan.
> [!TIP]
>
> You can check your current rate limits and usage anytime in the [API Keys section](https://app.electronhub.ai) of your dashboard.
## Rate Limit Tiers
| Subscription Plan | Requests per minute (RPM) | Best For |
| - | - | - |
| **Free** | 5 RPM | Testing and prototypes |
| **Starter** | 10 RPM | Small applications |
| **Plus** | 15 RPM | Growing projects |
| **Core** | 20 RPM | Professional use |
| **Pro** | 30 RPM | Production applications |
| **Business** | 60 RPM | High-volume usage |
| **Enterprise** | 100+ RPM | Custom enterprise needs |
## How Rate Limiting Works
### Request Counting
* Each API call counts as **one request** regardless of model or complexity
* Both successful and failed requests count toward your limit
* Streaming requests count as a single request when initiated
### Time Windows
* Rate limits are calculated using a **sliding window** of 60 seconds
* If you exceed your limit, you'll receive a `429` error
* The limit resets continuously, not at fixed intervals
* **Important**: When you exceed your rate limit, there's a **3-minute cooldown period** before you can make requests again
> [!WARNING]
>
> **Cooldown Period**: If you exceed your rate limit, you must wait 3 minutes (180 seconds) before making any new requests. This cooldown is enforced even if your normal rate limit window would have reset.
### Rate Limit Headers
Every API response includes headers showing your current status:
```http theme={null}
X-RateLimit-Limit: 20
X-RateLimit-Remaining: 15
X-RateLimit-Reset: 1640995200
```
## Handling Rate Limits
### Error Responses
When you encounter rate limits, you'll receive different error codes depending on the type of limit:
**Rate Limit Exceeded (429)**
```json theme={null}
{
"error": {
"message": "Rate limit exceeded. Try again in 180 seconds.",
"type": "error",
"param": null,
"code": 429
}
}
```
**IP Address Limit (403)**
```json theme={null}
{
"error": {
"message": "IP address limit reached. Maximum 3 API keys for IP 192.168.1.1. Please upgrade to a premium plan to bypass this limit.",
"type": "error",
"param": null,
"code": 403
}
}
```
**Insufficient Balance (402)**
```json theme={null}
{
"error": {
"message": "Insufficient balance.\n\nPlease wait for the next weekly refill or purchase more tokens in Electron Hub.",
"type": "error",
"param": null,
"code": 402
}
}
```
**Proxy Key Limit Exceeded (402)**
```json theme={null}
{
"error": {
"message": "Exceeded allocated amount for this key.",
"type": "error",
"param": null,
"code": 402
}
}
```
### Coding Plan (DevPass) Keys
`ek-dev-` keys have their own RPM limit: **8 on Lite (burst 4), 20 on Turbo (burst 8)**. Every request counts once, and `X-RateLimit-*` headers report this budget. They also have concurrency slots (2 on Lite, 5 on Turbo; a Heavy-series request such as `glm-5.3:dev` holds 2), plus daily/weekly fair-use headroom and optional low-interactivity / pause controls — see [Coding Plan → Fair Use](/billing/coding-plan#fair-use) and [Low-interactivity mode](/billing/coding-plan#low-interactivity-mode).
## Special Model Limits
Some models have additional daily limits beyond the standard rate limits:
### Google Models (Daily Limits)
Google experimental/preview/image models have daily usage limits that reset at 21:00 UTC:
| Subscription Plan | Daily Requests | Models Affected |
| - | - | - |
| **Free** | 10 | Experimental/Preview/Image models only |
| **Starter** | 50 | Experimental/Preview/Image models only |
| **Plus** | 100 | Experimental/Preview/Image models only |
| **Core** | 150 | Experimental/Preview/Image models only |
| **Pro** | 300 | Experimental/Preview/Image models only |
| **Business** | 500 | Experimental/Preview/Image models only |
| **Enterprise** | 1000 | Experimental/Preview/Image models only |
> [!NOTE]
>
> **Experimental/Preview/Image models** include models with `-exp`, `-preview`, or `-image` in their names, such as:
>
> * `gemini-1.5-flash-exp`
> * `gemini-2.0-flash-exp`
> * `gemini-2.0-flash-thinking-exp-1219`
> * `gemini-2.5-flash-preview-05-20`
> * `gemini-2.5-pro-preview-05-06`
> * `gemini-2.5-flash-image`
> * `gemini-3-pro-image-preview`
>
> Regular Google models (like `gemini-1.5-flash`, `gemini-1.5-pro`, `gemma-3-27b-it`) are **not** subject to these daily limits.
### Anthropic Models (Daily + Monthly Limits)
Anthropic (Claude) models have **two layers** of rate limiting:
#### Daily Request Limits
| Subscription Plan | Daily Requests |
| - | - |
| **Free** | 50 |
| **Starter** | 100 |
| **Plus** | 150 |
| **Core** | 300 |
| **Pro** | 500 |
| **Business** | 1,000 |
| **Enterprise** | 2,000 |
* **Reset Time**: 21:00 UTC daily
* **Applies to**: All Claude model requests (via `/chat/completions`, `/messages`, or `/responses`)
#### Monthly Token Limits
In addition to daily request limits, Anthropic models have a **monthly token budget** that caps total input + output tokens:
| Subscription Plan | Monthly Token Limit |
| - | - |
| **Free** | 100K tokens |
| **Starter** | 5M tokens |
| **Plus** | 10M tokens |
| **Core** | 20M tokens |
| **Pro** | 40M tokens |
| **Business** | 80M tokens |
| **Enterprise** | 150M tokens |
* **Reset Time**: 21:00 UTC on the 1st of each month
* **Applies to**: Combined input + output tokens across all Claude models
> [!WARNING]
>
> Even if you haven't hit your daily request limit, you can still be blocked if your monthly token budget is exhausted. Monitor both limits in your [dashboard](https://app.electronhub.ai).
### OpenAI Models (Monthly Token Limits)
OpenAI models have a **monthly token budget** that caps total input + output tokens. No separate daily request limit applies.
| Subscription Plan | Monthly Token Limit |
| - | - |
| **Free** | 100K tokens |
| **Starter** | 10M tokens |
| **Plus** | 25M tokens |
| **Core** | 50M tokens |
| **Pro** | 100M tokens |
| **Business** | 200M tokens |
| **Enterprise** | 300M tokens |
* **Reset Time**: 21:00 UTC on the 1st of each month
* **Applies to**: Combined input + output tokens across all OpenAI models
### Midjourney Models (Daily Limits)
Midjourney image generation has a separate daily limit:
* **Daily Limit**: 50 requests per day
* **Reset Time**: 21:00 UTC
* **Applies to**: All Midjourney image generation endpoints
### Implementing Retry Logic
```python Python Retry Logic theme={null}
import time
import random
from openai import OpenAI, RateLimitError
client = OpenAI(
base_url="https://api.electronhub.ai/v1",
api_key="ek-your-api-key"
)
def make_request_with_retry(max_retries=3):
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello!"}]
)
return response
except RateLimitError:
if attempt < max_retries - 1:
# Exponential backoff with jitter
wait_time = (2 ** attempt) + random.uniform(0, 1)
print(f"Rate limited. Waiting {wait_time:.2f} seconds...")
time.sleep(wait_time)
else:
raise
return None
# Usage
response = make_request_with_retry()
```
```javascript Node.js Retry Logic theme={null}
import { OpenAI } from 'openai';
const client = new OpenAI({
baseURL: 'https://api.electronhub.ai/v1',
apiKey: 'ek-your-api-key'
});
async function makeRequestWithRetry(maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello!' }]
});
return response;
} catch (error) {
if (error.status === 429 && attempt < maxRetries - 1) {
// Exponential backoff with jitter
const waitTime = (2 ** attempt + Math.random()) * 1000;
console.log(`Rate limited. Waiting ${waitTime/1000:.2f} seconds...`);
await new Promise(resolve => setTimeout(resolve, waitTime));
} else {
throw error;
}
}
}
}
// Usage
const response = await makeRequestWithRetry();
```
### Request Queuing
For applications with variable load, implement a request queue:
```python Python Queue theme={null}
import asyncio
import time
from typing import List, Callable
class RateLimitedClient:
def __init__(self, client, rpm_limit: int):
self.client = client
self.rpm_limit = rpm_limit
self.request_times: List[float] = []
self.lock = asyncio.Lock()
async def make_request(self, request_func: Callable):
async with self.lock:
now = time.time()
# Remove requests older than 60 seconds
cutoff = now - 60
self.request_times = [t for t in self.request_times if t > cutoff]
# Check if we need to wait
if len(self.request_times) >= self.rpm_limit:
wait_time = 60 - (now - self.request_times[0])
if wait_time > 0:
await asyncio.sleep(wait_time)
now = time.time()
# Make the request
self.request_times.append(now)
return await request_func()
# Usage
rate_limited_client = RateLimitedClient(client, rpm_limit=20)
async def my_request():
return client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello!"}]
)
response = await rate_limited_client.make_request(my_request)
```
```javascript Node.js Queue theme={null}
class RateLimitedClient {
constructor(client, rpmLimit) {
this.client = client;
this.rpmLimit = rpmLimit;
this.requestTimes = [];
}
async makeRequest(requestFunc) {
const now = Date.now();
// Remove requests older than 60 seconds
const cutoff = now - 60000;
this.requestTimes = this.requestTimes.filter(t => t > cutoff);
// Check if we need to wait
if (this.requestTimes.length >= this.rpmLimit) {
const waitTime = 60000 - (now - this.requestTimes[0]);
if (waitTime > 0) {
await new Promise(resolve => setTimeout(resolve, waitTime));
}
}
// Make the request
this.requestTimes.push(Date.now());
return await requestFunc();
}
}
// Usage
const rateLimitedClient = new RateLimitedClient(client, 20);
const response = await rateLimitedClient.makeRequest(() =>
client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello!' }]
})
);
```
## Optimization Strategies
### 1. Batch Processing
Group multiple operations when possible:
```python theme={null}
# Instead of multiple separate requests
results = []
for text in texts:
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": f"Analyze: {text}"}]
)
results.append(response)
# Combine into fewer requests
combined_text = "\n---\n".join(texts)
response = client.chat.completions.create(
model="gpt-4o",
messages=[{
"role": "user",
"content": f"Analyze each section:\n{combined_text}"
}]
)
```
### 2. Efficient Model Selection
Choose the right model for your task:
* **GPT-3.5-turbo**: Fast and cost-effective for simple tasks
* **GPT-4o**: Best for complex reasoning and analysis
* **Claude-3-haiku**: Fastest for quick responses
* **Claude-3-5-sonnet**: Balanced performance and capability
### 3. Request Optimization
Optimize your requests to reduce unnecessary calls:
```python theme={null}
# Use system messages efficiently
system_message = "You are a helpful assistant. Always respond concisely."
# Reuse conversations instead of starting fresh
conversation = [
{"role": "system", "content": system_message},
{"role": "user", "content": "First question"},
]
# Add to conversation instead of new requests
conversation.append({"role": "assistant", "content": previous_response})
conversation.append({"role": "user", "content": "Follow-up question"})
```
### 4. Caching Results
Cache responses for repeated queries:
```python theme={null}
import hashlib
import json
from functools import lru_cache
@lru_cache(maxsize=1000)
def cached_completion(model, messages_hash, **kwargs):
return client.chat.completions.create(
model=model,
messages=json.loads(messages_hash),
**kwargs
)
def make_cached_request(model, messages, **kwargs):
# Create hash of messages for caching
messages_str = json.dumps(messages, sort_keys=True)
messages_hash = hashlib.md5(messages_str.encode()).hexdigest()
return cached_completion(model, messages_hash, **kwargs)
```
## Monitoring Usage
### Check Current Usage
Monitor your API usage programmatically:
```python Python Usage Check theme={null}
def check_rate_limit_status(response):
headers = response.response.headers
limit = int(headers.get('x-ratelimit-limit', 0))
remaining = int(headers.get('x-ratelimit-remaining', 0))
reset_time = int(headers.get('x-ratelimit-reset', 0))
print(f"Rate Limit: {limit}")
print(f"Remaining: {remaining}")
print(f"Resets at: {reset_time}")
if remaining < 5:
print("⚠️ Warning: Approaching rate limit!")
```
```javascript Node.js Usage Check theme={null}
function checkRateLimitStatus(response) {
const headers = response.response.headers;
const limit = parseInt(headers['x-ratelimit-limit'] || '0');
const remaining = parseInt(headers['x-ratelimit-remaining'] || '0');
const resetTime = parseInt(headers['x-ratelimit-reset'] || '0');
console.log(`Rate Limit: ${limit}`);
console.log(`Remaining: ${remaining}`);
console.log(`Resets at: ${resetTime}`);
if (remaining < 5) {
console.log('⚠️ Warning: Approaching rate limit!');
}
}
```
### Dashboard Monitoring
Use the [dashboard](https://app.electronhub.ai) to:
* View real-time usage statistics
* Set up usage alerts
* Monitor trends over time
* Identify peak usage periods
## Upgrading Your Plan
### When to Upgrade
Consider upgrading when you:
* Consistently hit rate limits
* Need higher throughput for production
* Want to reduce latency from queuing
* Require dedicated support
### How to Upgrade
1. Visit your [dashboard](https://app.electronhub.ai)
2. Go to "Billing"
3. Select your desired plan
4. Complete the upgrade process
5. New limits take effect immediately
## Best Practices
> **Implement Graceful Degradation**
>
> Design your application to handle rate limits gracefully:
>
> * Show loading states during retries
> * Provide fallback responses when possible
> * Queue non-urgent requests for later processing
> * Inform users about temporary delays
> **Monitor and Alert**
>
> Set up monitoring for rate limit issues:
>
> * Track 429 error rates
> * Alert when approaching limits
> * Monitor request patterns
> * Analyze peak usage times
> **Optimize Request Patterns**
>
> Structure your requests efficiently:
>
> * Batch similar operations
> * Use appropriate models for tasks
> * Cache common responses
> * Implement smart retry logic
> **Plan for Growth**
>
> Prepare for scaling:
>
> * Start with higher limits before launch
> * Monitor usage trends
> * Have upgrade path ready
> * Consider enterprise plans for large scale
## Next Steps
> **[Error Handling](/getting-started/errors)**
>
> Learn how to handle and debug API errors effectively
> **[Best Practices](/guides/best-practices)**
>
> Discover advanced optimization techniques
# Anthropic SDKs
Source: https://docs.electronhub.ai/guides/anthropic-sdks
Learn how to use Anthropic SDKs with Electron Hub as your base URL
Use Electron Hub with the official Anthropic SDKs by simply changing the base URL. This allows you to access Claude models and 450+ other AI models through familiar Anthropic interfaces.
## Claude Code
```json theme={null}
{
"env": {
"ANTHROPIC_BASE_URL": "https://api.electronhub.ai",
"ANTHROPIC_AUTH_TOKEN": "ek-dev-YOUR_KEY",
"ANTHROPIC_MODEL": "glm-5.3:dev",
"ANTHROPIC_DEFAULT_SONNET_MODEL": "glm-5.3:dev",
"ANTHROPIC_DEFAULT_OPUS_MODEL": "glm-5.3:dev",
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "mimo-v2.6-flash:dev"
}
}
```
Base URL is the host only (Claude Code appends `/v1/messages`). Coding Plan keys require `:dev` model IDs.
`glm-5.3:dev` is a Heavy model and holds 2 [concurrency slots](/billing/coding-plan#fair-use) per request. Keeping the Haiku slot on a Flash model lets background tasks run alongside it.
## JavaScript/TypeScript SDK
Install the Anthropic SDK:
```bash theme={null}
npm install @anthropic-ai/sdk
```
Configure it to use Electron Hub:
```javascript theme={null}
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic({
apiKey: 'ek-your-api-key-here',
baseURL: 'https://api.electronhub.ai/v1',
});
// Create a message using Claude
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1000,
temperature: 0,
system: "You are a helpful assistant.",
messages: [
{
role: 'user',
content: 'Hello, Claude!'
}
]
});
console.log(message.content);
```
### Using Different Claude Models
Switch between different Claude models:
```javascript theme={null}
// Latest Claude 3.5 Sonnet
const sonnetResponse = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1000,
messages: [
{ role: 'user', content: 'Explain machine learning briefly' }
]
});
// Claude 3 Opus for complex reasoning
const opusResponse = await anthropic.messages.create({
model: 'claude-3-opus-20240229',
max_tokens: 1000,
messages: [
{ role: 'user', content: 'Write a complex analysis of economic trends' }
]
});
// Claude 3 Haiku for fast responses
const haikuResponse = await anthropic.messages.create({
model: 'claude-3-haiku-20240307',
max_tokens: 1000,
messages: [
{ role: 'user', content: 'Quick summary of the news' }
]
});
```
### Vision Capabilities
Use Claude's vision capabilities with images:
```javascript theme={null}
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1000,
messages: [
{
role: 'user',
content: [
{
type: 'text',
text: 'What do you see in this image?'
},
{
type: 'image',
source: {
type: 'base64',
media_type: 'image/jpeg',
data: '/9j/4AAQSkZJRgABAQEAYABgAAD/2wBD...' // base64 image data
}
}
]
}
]
});
console.log(message.content);
```
### Streaming Responses
Stream responses for real-time output:
```javascript theme={null}
const stream = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1000,
messages: [
{ role: 'user', content: 'Tell me a long story about space exploration' }
],
stream: true
});
for await (const event of stream) {
if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
process.stdout.write(event.delta.text);
}
}
```
## Python SDK
Install the Anthropic Python SDK:
```bash theme={null}
pip install anthropic
```
Configure it for Electron Hub:
```python theme={null}
import anthropic
client = anthropic.Anthropic(
api_key="ek-your-api-key-here",
base_url="https://api.electronhub.ai/v1"
)
# Create a message
message = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=1000,
temperature=0,
system="You are a helpful assistant.",
messages=[
{
"role": "user",
"content": "Hello, Claude!"
}
]
)
print(message.content)
```
### Tool Use (Function Calling)
Use Claude's tool calling capabilities:
```python theme={null}
import json
# Define tools
tools = [
{
"name": "get_weather",
"description": "Get the current weather in a given location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
}
},
"required": ["location"]
}
}
]
message = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=1000,
tools=tools,
messages=[
{
"role": "user",
"content": "What's the weather like in Paris?"
}
]
)
print(message.content)
# Handle tool use
for content in message.content:
if content.type == "tool_use":
print(f"Tool: {content.name}")
print(f"Input: {content.input}")
```
### Streaming with Python
```python theme={null}
stream = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=1000,
messages=[
{"role": "user", "content": "Write a poem about AI"}
],
stream=True
)
for event in stream:
if event.type == "content_block_delta":
if event.delta.type == "text_delta":
print(event.delta.text, end="")
```
## Advanced Features
### Prompt Caching
Reduce costs and improve performance by caching parts of your prompts that don't change between requests. Prompt caching allows you to mark sections of your prompt for caching, with cache writes charged at 1.25x and cache reads at 0.1x the original input price.
> **[Prompt Caching Guide](/guides/prompt-caching)**
>
> Learn how to use prompt caching with Anthropic Claude models, including examples for system and user message caching.
### System Messages
Use system messages to set Claude's behavior:
```javascript theme={null}
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1000,
system: `You are a helpful AI assistant that specializes in explaining complex technical concepts in simple terms. Always:
1. Use analogies and examples
2. Break down complex ideas into steps
3. Ask clarifying questions if needed
4. Provide practical applications`,
messages: [
{
role: 'user',
content: 'Explain quantum computing'
}
]
});
```
### Multi-turn Conversations
Handle multi-turn conversations:
```javascript theme={null}
const conversation = [
{ role: 'user', content: 'What is photosynthesis?' },
{ role: 'assistant', content: 'Photosynthesis is the process by which plants...' },
{ role: 'user', content: 'How does this relate to climate change?' }
];
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1000,
messages: conversation
});
```
### Structured Output
Use Claude for structured data generation:
```javascript theme={null}
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1000,
system: 'You are a JSON generator. Always respond with valid JSON.',
messages: [
{
role: 'user',
content: 'Generate a JSON object with information about a fictional character including name, age, occupation, and three personality traits.'
}
]
});
const characterData = JSON.parse(message.content[0].text);
console.log(characterData);
```
## Error Handling
Handle errors gracefully:
```javascript theme={null}
try {
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1000,
messages: [
{ role: 'user', content: 'Hello!' }
]
});
} catch (error) {
if (error instanceof Anthropic.APIError) {
console.error('Anthropic API Error:', error.message);
console.error('Status:', error.status);
console.error('Type:', error.error?.type);
} else {
console.error('Unexpected error:', error);
}
}
```
## Rate Limiting
Implement rate limiting and retry logic:
```javascript theme={null}
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
async function createMessageWithRetry(params, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await anthropic.messages.create(params);
} catch (error) {
if (error.status === 429 && i < maxRetries - 1) {
// Exponential backoff
const delay = Math.pow(2, i) * 1000;
console.log(`Rate limited. Waiting ${delay}ms before retry...`);
await sleep(delay);
continue;
}
throw error;
}
}
}
```
## Best Practices
### 1. Optimize Token Usage
```javascript theme={null}
// Be specific and concise in prompts
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 500, // Set appropriate limits
messages: [
{
role: 'user',
content: 'Summarize this article in 3 bullet points: [article text]'
}
]
});
```
### 2. Use Appropriate Models
```javascript theme={null}
// Use Haiku for simple tasks
const quickResponse = await anthropic.messages.create({
model: 'claude-3-haiku-20240307',
max_tokens: 100,
messages: [{ role: 'user', content: 'What time is it in UTC?' }]
});
// Use Opus for complex reasoning
const complexAnalysis = await anthropic.messages.create({
model: 'claude-3-opus-20240229',
max_tokens: 2000,
messages: [{ role: 'user', content: 'Analyze the economic implications of...' }]
});
```
### 3. Implement Caching
```javascript theme={null}
const cache = new Map();
async function getCachedResponse(prompt, model = 'claude-sonnet-4-5-20250929') {
const cacheKey = `${model}:${prompt}`;
if (cache.has(cacheKey)) {
return cache.get(cacheKey);
}
const message = await anthropic.messages.create({
model,
max_tokens: 1000,
messages: [{ role: 'user', content: prompt }]
});
cache.set(cacheKey, message);
return message;
}
```
## Integration Examples
### Chatbot Implementation
```javascript theme={null}
class ClaudeChatbot {
constructor() {
this.anthropic = new Anthropic({
apiKey: 'ek-your-api-key-here',
baseURL: 'https://api.electronhub.ai/v1',
});
this.conversation = [];
}
async chat(userMessage) {
this.conversation.push({ role: 'user', content: userMessage });
const message = await this.anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1000,
system: 'You are a helpful assistant.',
messages: this.conversation
});
const assistantMessage = message.content[0].text;
this.conversation.push({ role: 'assistant', content: assistantMessage });
return assistantMessage;
}
clearHistory() {
this.conversation = [];
}
}
// Usage
const chatbot = new ClaudeChatbot();
const response = await chatbot.chat('Hello! How are you?');
console.log(response);
```
### Document Analysis
```javascript theme={null}
async function analyzeDocument(documentText) {
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 2000,
system: 'You are a document analyst. Provide structured analysis of documents.',
messages: [
{
role: 'user',
content: `Please analyze this document and provide:
1. Main topics
2. Key insights
3. Action items
4. Summary
Document: ${documentText}`
}
]
});
return message.content[0].text;
}
```
## Migration from Anthropic Direct
When migrating from Anthropic's direct API to Electron Hub:
1. **Change the base URL** to `https://api.electronhub.ai/v1`
2. **Update your API key** to use your Electron Hub key (starts with `ek-`)
3. **No code changes needed** - All parameters and responses remain the same
4. **Access to more models** - You can also use OpenAI, Google, and other models
5. **Unified billing** - All model usage is billed through Electron Hub
6. **Enhanced features** - Access to additional capabilities like web search
Monitor your usage through the Electron Hub dashboard at `https://app.electronhub.ai`.
# Best Practices
Source: https://docs.electronhub.ai/guides/best-practices
Essential guidelines for using Electron Hub API effectively
Follow these best practices to get the most out of the Electron Hub API while optimizing for performance, cost, and reliability.
## Authentication & Security
### API Key Management
* **Environment Variables**: Store API keys in environment variables, never in code
* **Key Rotation**: Regularly rotate API keys for enhanced security
* **Separate Keys**: Use different keys for development, staging, and production
* **Monitoring**: Monitor API key usage and set up alerts for unusual activity
```bash theme={null}
# Good: Environment variable
export ELECTRONHUB_API_KEY="your_api_key_here"
# Bad: Hardcoded in source
const apiKey = "ek-1234567890abcdef"; // Never do this!
```
### Request Security
* **HTTPS Only**: Always use HTTPS endpoints
* **Input Validation**: Validate and sanitize all user inputs
* **Rate Limiting**: Implement client-side rate limiting
* **Error Handling**: Don't expose sensitive information in error messages
## Performance Optimization
### Request Optimization
* **Batch Requests**: Group multiple operations when possible
* **Streaming**: Use streaming for real-time applications
* **Caching**: Cache responses for repeated queries
* **Connection Pooling**: Reuse HTTP connections
```javascript theme={null}
// Good: Batch embedding requests
const embeddings = await fetch('/v1/embeddings', {
method: 'POST',
body: JSON.stringify({
input: ['text1', 'text2', 'text3'], // Multiple inputs
model: 'text-embedding-3-small'
})
});
// Less efficient: Individual requests
for (const text of texts) {
const embedding = await fetch('/v1/embeddings', {
method: 'POST',
body: JSON.stringify({
input: text,
model: 'text-embedding-3-small'
})
});
}
```
### Model Selection
* **Start Small**: Begin with cost-effective models for prototyping
* **Upgrade Selectively**: Use premium models only when necessary
* **Context Awareness**: Choose models based on context length requirements
* **Task Matching**: Match model capabilities to your specific use case
## Cost Management
### Token Optimization
* **Monitor Usage**: Track token consumption across all endpoints
* **Prompt Engineering**: Write efficient prompts that minimize tokens
* **Context Management**: Remove unnecessary context from conversations
* **Model Scaling**: Use appropriate models for different complexity levels
### Smart Caching
```javascript theme={null}
// Implement response caching
const cache = new Map();
async function getChatCompletion(messages, model) {
const cacheKey = JSON.stringify({ messages, model });
if (cache.has(cacheKey)) {
return cache.get(cacheKey);
}
const response = await electronhub.chat.completions.create({
messages,
model
});
cache.set(cacheKey, response);
return response;
}
```
## Error Handling
### Robust Error Management
* **Retry Logic**: Implement exponential backoff for transient errors
* **Graceful Degradation**: Provide fallbacks for API failures
* **Error Classification**: Handle different error types appropriately
* **User Experience**: Show meaningful error messages to users
```javascript theme={null}
async function makeAPICall(requestFn, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await requestFn();
} catch (error) {
if (error.status === 429) {
// Rate limit - exponential backoff
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
if (error.status >= 500 && attempt < maxRetries) {
// Server error - retry
continue;
}
// Other errors or max retries reached
throw error;
}
}
}
```
### Status Code Handling
* **200-299**: Success - process response
* **400-499**: Client errors - check request format
* **429**: Rate limited - implement backoff
* **500-599**: Server errors - retry with caution
## Prompt Engineering
### Chat Completions
* **Clear Instructions**: Be specific about what you want
* **System Messages**: Use system messages to set context and behavior
* **Few-shot Examples**: Provide examples for complex tasks
* **Format Specification**: Clearly specify desired output format
```javascript theme={null}
// Good: Clear, specific prompt
{
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant that summarizes articles in exactly 3 bullet points."
},
{
"role": "user",
"content": "Summarize this article: [article text]"
}
]
}
// Less effective: Vague prompt
{
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content": "Tell me about this article: [article text]"
}
]
}
```
### Image Generation
* **Descriptive Prompts**: Include details about style, composition, and quality
* **Aspect Ratios**: Specify appropriate sizes for your use case
* **Style Consistency**: Use consistent terminology across related images
* **Quality Settings**: Choose appropriate quality levels for your needs
## Monitoring & Observability
### Usage Tracking
* **Token Metrics**: Monitor token usage per endpoint
* **Error Rates**: Track success/failure rates
* **Response Times**: Measure API latency
* **Cost Analysis**: Monitor spending across different models
### Logging Best Practices
```javascript theme={null}
// Structured logging example
const logger = {
logAPICall: (endpoint, model, tokens, responseTime, status) => {
console.log(JSON.stringify({
timestamp: new Date().toISOString(),
endpoint,
model,
tokens,
responseTime,
status,
environment: process.env.NODE_ENV
}));
}
};
// Usage
const startTime = Date.now();
try {
const response = await electronhub.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: messages
});
logger.logAPICall(
'chat/completions',
'gpt-3.5-turbo',
response.usage.total_tokens,
Date.now() - startTime,
'success'
);
} catch (error) {
logger.logAPICall(
'chat/completions',
'gpt-3.5-turbo',
0,
Date.now() - startTime,
'error'
);
}
```
## Development Workflow
### Testing Strategy
* **Unit Tests**: Test individual API interactions
* **Integration Tests**: Test complete workflows
* **Load Testing**: Verify performance under load
* **Error Scenarios**: Test failure conditions
### Environment Management
* **Development**: Use cheaper models and lower limits
* **Staging**: Mirror production setup for testing
* **Production**: Implement full monitoring and alerting
### Version Control
* **API Versioning**: Always specify API versions
* **Model Versioning**: Pin specific model versions for consistency
* **Configuration Management**: Version control all API configurations
## Compliance & Ethics
### Content Guidelines
* **Content Policy**: Ensure all content complies with usage policies
* **Moderation**: Use the Moderations API for user-generated content
* **Privacy**: Respect user privacy and data protection regulations
* **Transparency**: Be transparent about AI usage with users
### Responsible AI
* **Bias Awareness**: Be aware of potential model biases
* **Human Oversight**: Maintain human review for critical decisions
* **Fallback Plans**: Have non-AI alternatives for critical functions
* **User Control**: Give users control over AI interactions
# In-chat Image Generation
Source: https://docs.electronhub.ai/guides/in-chat-image-generation
Generate images inline during chat using model suffix syntax
Bring images into your ongoing conversations without switching endpoints. In-chat Image Generation lets you request images directly from the `chat/completions` endpoint by selecting a base chat model and an image generation model using a simple suffix syntax.
## How it works
* **Base model**: Your chat model (e.g., `claude-sonnet-4-20250514`)
* **Image model**: Your image generator (e.g., `flux-pro`)
* **Suffix syntax**: `baseModel@imageModel`
**Example suffix**: `claude-sonnet-4-20250514@flux-pro`
When you use a suffixed model with `chat/completions`, the assistant can respond with content that includes generated image(s) inline with its text, keeping the flow immersive for roleplay and storytelling scenarios.
## Example request
```bash theme={null}
curl https://api.electronhub.ai/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4-20250514@flux-pro",
"messages": [
{"role": "system", "content": "You are a narrative game master. Embed images when helpful."},
{"role": "user", "content": "Generate a vivid, cinematic portrait of a cyberpunk detective at night in neon rain."}
]
}'
```
Notes:
* The base chat model drives conversation quality and reasoning.
* The image model controls visual style and fidelity.
* The response may include image URLs or Markdown image formatting inside the assistant message content.
## SillyTavern example
Here’s how this looks in SillyTavern when using a suffixed model:

## Tips
* **Be descriptive**: Specify subject, style, lighting, composition, and mood.
* **Stay consistent**: Reuse key style terms across turns for continuity.
* **Guide placement**: Ask the assistant where to insert images within the story.
# OpenAI SDKs
Source: https://docs.electronhub.ai/guides/openai-sdks
Learn how to use OpenAI SDKs with Electron Hub as your base URL
Use Electron Hub with the official OpenAI SDKs by simply changing the base URL. This allows you to access 450+ AI models through familiar OpenAI interfaces.
## JavaScript/Node.js SDK
Install the OpenAI SDK:
```bash theme={null}
npm install openai
```
Configure it to use Electron Hub:
```javascript theme={null}
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: 'ek-your-api-key-here',
baseURL: 'https://api.electronhub.ai/v1',
});
// Use any model available on Electron Hub
const completion = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "user", content: "Hello, world!" }
],
});
console.log(completion.choices[0].message);
```
### Using Different Models
Switch between any supported model:
```javascript theme={null}
// OpenAI models
const gptResponse = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Explain quantum computing" }],
});
// Anthropic models through OpenAI format
const claudeResponse = await openai.chat.completions.create({
model: "claude-3-5-sonnet-20241022",
messages: [{ role: "user", content: "Write a poem about AI" }],
});
// Google models
const geminiResponse = await openai.chat.completions.create({
model: "gemini-pro",
messages: [{ role: "user", content: "Summarize the news" }],
});
```
### Image Generation
```javascript theme={null}
const image = await openai.images.generate({
model: "dall-e-3",
prompt: "A futuristic city skyline at sunset",
n: 1,
size: "1024x1024",
});
console.log(image.data[0].url);
```
### Embeddings
```javascript theme={null}
const embedding = await openai.embeddings.create({
model: "text-embedding-3-large",
input: "The quick brown fox jumps over the lazy dog",
});
console.log(embedding.data[0].embedding);
```
### Speech-to-Text
```javascript theme={null}
import fs from "fs";
const transcript = await openai.audio.transcriptions.create({
model: "deepgram-nova-3",
file: fs.createReadStream("audio.mp3"),
language: "auto",
});
console.log(transcript.text);
```
See [Speech-to-Text](/api-reference/audio/transcriptions) for formats, caps, and models.
### Moderations
Check content for policy violations using text and image moderation:
```javascript theme={null}
// Single string moderation
const textModeration = await openai.moderations.create({
model: "omni-moderation-latest",
input: "I want to kill them."
});
console.log(textModeration);
```
```javascript theme={null}
// Image and text moderation
const multiModalModeration = await openai.moderations.create({
model: "omni-moderation-latest",
input: [
{
type: "text",
text: "I want to shoot people"
},
{
type: "image_url",
image_url: {
url: "https://example.com/image.jpg"
// can also use base64 encoded image URLs
// url: "data:image/jpeg;base64,abcdefg..."
}
}
]
});
console.log(multiModalModeration);
```
## Python SDK
Install the OpenAI Python SDK:
```bash theme={null}
pip install openai
```
Configure it for Electron Hub:
```python theme={null}
from openai import OpenAI
client = OpenAI(
api_key="ek-your-api-key-here",
base_url="https://api.electronhub.ai/v1"
)
# Chat completion
completion = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "Hello, world!"}
]
)
print(completion.choices[0].message.content)
```
### Streaming Responses
```python theme={null}
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Tell me a story"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
```
### Function Calling
```python theme={null}
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
}
},
"required": ["location"]
}
}
}
]
completion = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What's the weather in Paris?"}],
tools=tools,
tool_choice="auto"
)
print(completion.choices[0].message)
```
### Speech-to-Text
```python theme={null}
with open("audio.mp3", "rb") as f:
transcript = client.audio.transcriptions.create(
model="deepgram-nova-3",
file=f,
language="auto",
)
print(transcript.text)
```
### Moderations
```python theme={null}
# Single string moderation
moderation = client.moderations.create(
model="omni-moderation-latest",
input="I want to kill them."
)
print(moderation)
```
```python theme={null}
# Image and text moderation
response = client.moderations.create(
model="omni-moderation-latest",
input=[
{"type": "text", "text": "I want to shoot people"},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.jpg"
# can also use base64 encoded image URLs
# "url": "data:image/jpeg;base64,abcdefg..."
}
}
]
)
print(response)
```
## Go SDK
```go theme={null}
package main
import (
"context"
"fmt"
"github.com/sashabaranov/go-openai"
)
func main() {
config := openai.DefaultConfig("ek-your-api-key-here")
config.BaseURL = "https://api.electronhub.ai/v1"
client := openai.NewClientWithConfig(config)
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT4o,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleUser,
Content: "Hello, world!",
},
},
},
)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Println(resp.Choices[0].Message.Content)
}
```
## Advanced Features
### Model Selection
Electron Hub provides access to models from multiple providers:
```javascript theme={null}
// Access different model families
const models = {
openai: ['gpt-4o', 'gpt-4', 'gpt-3.5-turbo'],
anthropic: ['claude-3-5-sonnet-20241022', 'claude-3-opus-20240229'],
google: ['gemini-pro', 'gemini-pro-vision'],
meta: ['llama-2-70b-chat', 'llama-2-13b-chat'],
mistral: ['mistral-large', 'mistral-medium'],
};
// Use any model with the same interface
for (const [provider, modelList] of Object.entries(models)) {
for (const model of modelList) {
const response = await openai.chat.completions.create({
model: model,
messages: [{ role: "user", content: "Hello!" }],
max_tokens: 10
});
console.log(`${model}: ${response.choices[0].message.content}`);
}
}
```
### Error Handling
```javascript theme={null}
try {
const completion = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Hello!" }],
});
} catch (error) {
if (error instanceof OpenAI.APIError) {
console.error('OpenAI API Error:', error.message);
console.error('Status:', error.status);
console.error('Code:', error.code);
} else {
console.error('Unexpected error:', error);
}
}
```
## Best Practices
1. **Always handle errors** - API calls can fail for various reasons
2. **Use appropriate timeouts** - Set reasonable timeouts for your requests
3. **Implement rate limiting** - Respect rate limits to avoid throttling
4. **Cache responses** - Cache responses when appropriate to reduce costs
5. **Monitor usage** - Keep track of your token usage and costs
Handle rate limits gracefully:
```javascript theme={null}
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
async function makeRequestWithRetry(requestFn, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await requestFn();
} catch (error) {
if (error.status === 429 && i < maxRetries - 1) {
const delay = Math.pow(2, i) * 1000; // Exponential backoff
await sleep(delay);
continue;
}
throw error;
}
}
}
```
## Migration Notes
When migrating from OpenAI directly to Electron Hub:
1. **Change the base URL** to `https://api.electronhub.ai/v1`
2. **Update your API key** to use your Electron Hub key (starts with `ek-`)
3. **No code changes needed** - All endpoints and parameters remain the same
4. **Access to more models** - You can now use Claude, Gemini, and other models
5. **Unified billing** - All model usage is billed through Electron Hub
# Prompt Caching
Source: https://docs.electronhub.ai/guides/prompt-caching
Use prompt caching with Anthropic Claude models to reduce costs and improve performance
Prompt caching allows you to cache parts of your prompts that don't change between requests, reducing costs and improving response times.
## API Format
```anthropic Anthropic Format theme={null}
Use the `/v1/messages` endpoint with `cache_control` markers in message content blocks.
```
```openai OpenAI Format theme={null}
Use the `/v1/chat/completions` endpoint with the `prompt_caching` helper or `cache_control` markers.
```
> [!NOTE]
>
> Both formats support the same caching functionality. The `prompt_caching` helper in the OpenAI format automatically converts to `cache_control` markers internally. Examples below are organized by format for clarity.
## Pricing
Prompt caching uses a tiered pricing structure based on cache duration and usage type:
| Model | Base Input Tokens | 5m Cache Writes | 1h Cache Writes | Cache Hits & Refreshes | Output Tokens |
| - | - | - | - | - | - |
| Claude Opus 4.5 | \$5 / MTok | \$6.25 / MTok | \$10 / MTok | \$0.50 / MTok | \$25 / MTok |
| Claude Opus 4.1 | \$15 / MTok | \$18.75 / MTok | \$30 / MTok | \$1.50 / MTok | \$75 / MTok |
| Claude Opus 4 | \$15 / MTok | \$18.75 / MTok | \$30 / MTok | \$1.50 / MTok | \$75 / MTok |
| Claude Sonnet 4.5 | \$3 / MTok | \$3.75 / MTok | \$6 / MTok | \$0.30 / MTok | \$15 / MTok |
| Claude Sonnet 4 | \$3 / MTok | \$3.75 / MTok | \$6 / MTok | \$0.30 / MTok | \$15 / MTok |
| Claude Sonnet 3.7 | \$3 / MTok | \$3.75 / MTok | \$6 / MTok | \$0.30 / MTok | \$15 / MTok |
| Claude Haiku 4.5 | \$1 / MTok | \$1.25 / MTok | \$2 / MTok | \$0.10 / MTok | \$5 / MTok |
| Claude Haiku 3.5 | \$0.80 / MTok | \$1 / MTok | \$1.6 / MTok | \$0.08 / MTok | \$4 / MTok |
| Claude Haiku 3 | \$0.25 / MTok | \$0.30 / MTok | \$0.50 / MTok | \$0.03 / MTok | \$1.25 / MTok |
The pricing multipliers are:
* **5-minute cache writes**: 1.25x the base input tokens price
* **1-hour cache writes**: 2x the base input tokens price
* **Cache reads**: 0.1x the base input tokens price
> [!NOTE]
>
> Cache writes occur when content is first cached. Subsequent requests using the cached content are charged at the cache read rate (10% of base input price). The cache lifetime is refreshed each time the cached content is used.
## Limitations
* Maximum **4 cache breakpoints** per request
* Caches expire after **5 minutes** by default
* `cache_control` can only be inserted into **text content blocks**
> [!WARNING]
>
> Reserve cache breakpoints for large, static content like character cards, CSV data, RAG knowledge bases, book chapters, or extensive reference documentation.
## Examples
### System Message Caching
#### Anthropic Format (`/v1/messages`)
```javascript JavaScript theme={null}
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1000,
messages: [
{
role: 'system',
content: [
{
type: 'text',
text: 'You are a historian. You know the following book:'
},
{
type: 'text',
text: 'HUGE TEXT BODY',
cache_control: {
type: 'ephemeral'
}
}
]
},
{
role: 'user',
content: 'What triggered the collapse?'
}
]
});
```
```python Python theme={null}
message = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=1000,
messages=[
{
"role": "system",
"content": [
{
"type": "text",
"text": "You are a historian. You know the following book:"
},
{
"type": "text",
"text": "HUGE TEXT BODY",
"cache_control": {
"type": "ephemeral"
}
}
]
},
{
"role": "user",
"content": "What triggered the collapse?"
}
]
)
```
```bash cURL theme={null}
curl -X POST "https://api.electronhub.ai/v1/messages" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4-5-20250929",
"max_tokens": 1000,
"messages": [
{
"role": "system",
"content": [
{"type": "text", "text": "You are a historian. You know the following book:"},
{"type": "text", "text": "HUGE TEXT BODY", "cache_control": {"type": "ephemeral"}}
]
},
{"role": "user", "content": "What triggered the collapse?"}
]
}'
```
#### OpenAI Format (`/v1/chat/completions`)
```javascript JavaScript theme={null}
const response = await fetch('https://api.electronhub.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'claude-sonnet-4-5-20250929',
messages: [
{
role: 'user',
content: 'You are a historian. You know the following book: HUGE TEXT BODY. What triggered the collapse?'
}
],
max_tokens: 1000,
prompt_caching: {
enabled: true,
ttl: '5m',
cut_after_message_index: 0
},
stream_options: {
include_usage: true
}
})
});
```
```python Python theme={null}
import requests
response = requests.post(
'https://api.electronhub.ai/v1/chat/completions',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'model': 'claude-sonnet-4-5-20250929',
'messages': [
{
'role': 'user',
'content': 'You are a historian. You know the following book: HUGE TEXT BODY. What triggered the collapse?'
}
],
'max_tokens': 1000,
'prompt_caching': {
'enabled': True,
'ttl': '5m',
'cut_after_message_index': 0
},
'stream_options': {
'include_usage': True
}
}
)
```
```bash cURL theme={null}
curl -X POST "https://api.electronhub.ai/v1/chat/completions" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4-5-20250929",
"messages": [
{
"role": "user",
"content": "You are a historian. You know the following book: HUGE TEXT BODY. What triggered the collapse?"
}
],
"max_tokens": 1000,
"prompt_caching": {
"enabled": true,
"ttl": "5m",
"cut_after_message_index": 0
},
"stream_options": {
"include_usage": true
}
}'
```
### User Message Caching
#### Anthropic Format (`/v1/messages`)
```javascript JavaScript theme={null}
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1000,
messages: [
{
role: 'user',
content: [
{type: 'text', text: 'Given the book below:'},
{type: 'text', text: 'HUGE TEXT BODY', cache_control: {type: 'ephemeral'}},
{type: 'text', text: 'Name all the characters'}
]
}
]
});
```
```python Python theme={null}
message = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=1000,
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "Given the book below:"},
{"type": "text", "text": "HUGE TEXT BODY", "cache_control": {"type": "ephemeral"}},
{"type": "text", "text": "Name all the characters"}
]
}]
)
```
#### OpenAI Format (`/v1/chat/completions`)
```javascript JavaScript theme={null}
const response = await fetch('https://api.electronhub.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'claude-sonnet-4-5-20250929',
messages: [
{
role: 'user',
content: [
{type: 'text', text: 'Given the book below:'},
{type: 'text', text: 'HUGE TEXT BODY', cache_control: {type: 'ephemeral'}},
{type: 'text', text: 'Name all the characters'}
]
}
],
max_tokens: 1000,
stream_options: {
include_usage: true
}
})
});
```
```python Python theme={null}
import requests
response = requests.post(
'https://api.electronhub.ai/v1/chat/completions',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'model': 'claude-sonnet-4-5-20250929',
'messages': [
{
'role': 'user',
'content': [
{'type': 'text', 'text': 'Given the book below:'},
{'type': 'text', 'text': 'HUGE TEXT BODY', 'cache_control': {'type': 'ephemeral'}},
{'type': 'text', 'text': 'Name all the characters'}
]
}
],
'max_tokens': 1000,
'stream_options': {
'include_usage': True
}
}
)
```
## Cache Control Options
### Anthropic Format (`/v1/messages`)
**cache\_control.type** `string` *required*
Cache type. Currently only `"ephemeral"` is supported.
**cache\_control.ttl** `string`
Time-to-live. Optional, defaults to 5 minutes. Format: `"5m"` or `"1h"`.
> [!NOTE]
>
> Some models like `claude-3-7-sonnet-20250219` do not support TTL in system messages. TTL is automatically stripped for these models.
### OpenAI Format (`/v1/chat/completions`)
**prompt\_caching.enabled** `boolean` *required*
Enable prompt caching. Set to `true` to enable caching.
**prompt\_caching.ttl** `string`
Time-to-live. Optional, defaults to `"5m"`. Format: `"5m"` or `"1h"`.
**prompt\_caching.cut\_after\_message\_index** `integer` *required*
Zero-based index of the last message to cache. All messages up to and including this index will be cached.
> [!NOTE]
>
> The `prompt_caching` helper automatically converts to `cache_control` markers in message content. You can also use `cache_control` markers directly in message content blocks (same as Anthropic format).
### Using TTL
Specify cache duration with the `ttl` parameter:
#### Anthropic Format (`/v1/messages`)
```javascript JavaScript theme={null}
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1000,
messages: [
{
role: 'system',
content: [
{
type: 'text',
text: 'You are a helpful assistant. Use this knowledge base:'
},
{
type: 'text',
text: 'LARGE KNOWLEDGE BASE TEXT',
cache_control: {
type: 'ephemeral',
ttl: '1h' // Cache for 1 hour instead of default 5 minutes
}
}
]
},
{
role: 'user',
content: 'What is machine learning?'
}
]
});
```
```python Python theme={null}
message = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=1000,
messages=[
{
"role": "system",
"content": [
{"type": "text", "text": "You are a helpful assistant. Use this knowledge base:"},
{
"type": "text",
"text": "LARGE KNOWLEDGE BASE TEXT",
"cache_control": {
"type": "ephemeral",
"ttl": "1h" # Cache for 1 hour instead of default 5 minutes
}
}
]
},
{"role": "user", "content": "What is machine learning?"}
]
)
```
```bash cURL theme={null}
curl -X POST "https://api.electronhub.ai/v1/messages" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4-5-20250929",
"max_tokens": 1000,
"messages": [
{
"role": "system",
"content": [
{"type": "text", "text": "You are a helpful assistant. Use this knowledge base:"},
{
"type": "text",
"text": "LARGE KNOWLEDGE BASE TEXT",
"cache_control": {"type": "ephemeral", "ttl": "1h"}
}
]
},
{"role": "user", "content": "What is machine learning?"}
]
}'
```
#### OpenAI Format (`/v1/chat/completions`)
```javascript JavaScript theme={null}
const response = await fetch('https://api.electronhub.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'claude-sonnet-4-5-20250929',
messages: [
{
role: 'user',
content: 'You are a helpful assistant. Use this knowledge base: LARGE KNOWLEDGE BASE TEXT. What is machine learning?'
}
],
max_tokens: 1000,
prompt_caching: {
enabled: true,
ttl: '1h', // Cache for 1 hour instead of default 5 minutes
cut_after_message_index: 0
},
stream_options: {
include_usage: true
}
})
});
```
```python Python theme={null}
import requests
response = requests.post(
'https://api.electronhub.ai/v1/chat/completions',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'model': 'claude-sonnet-4-5-20250929',
'messages': [
{
'role': 'user',
'content': 'You are a helpful assistant. Use this knowledge base: LARGE KNOWLEDGE BASE TEXT. What is machine learning?'
}
],
'max_tokens': 1000,
'prompt_caching': {
'enabled': True,
'ttl': '1h', # Cache for 1 hour instead of default 5 minutes
'cut_after_message_index': 0
},
'stream_options': {
'include_usage': True
}
}
)
```
```bash cURL theme={null}
curl -X POST "https://api.electronhub.ai/v1/chat/completions" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4-5-20250929",
"messages": [
{
"role": "user",
"content": "You are a helpful assistant. Use this knowledge base: LARGE KNOWLEDGE BASE TEXT. What is machine learning?"
}
],
"max_tokens": 1000,
"prompt_caching": {
"enabled": true,
"ttl": "1h",
"cut_after_message_index": 0
},
"stream_options": {
"include_usage": true
}
}'
```
## Usage Tracking
The API response includes cache usage in the `usage` object. Both endpoints return cache usage information:
#### Anthropic Format (`/v1/messages`)
```json theme={null}
{
"usage": {
"input_tokens": 150,
"output_tokens": 50,
"cache_creation_input_tokens": 2000,
"cache_read_input_tokens": 0,
"cache_creation": {
"ephemeral_5m_input_tokens": 2000,
"ephemeral_1h_input_tokens": 0
}
}
}
```
#### OpenAI Format (`/v1/chat/completions`)
```json theme={null}
{
"usage": {
"prompt_tokens": 150,
"completion_tokens": 50,
"total_tokens": 200,
"cache_creation_input_tokens": 2000,
"cache_read_input_tokens": 0,
"cache_creation": {
"ephemeral_5m_input_tokens": 2000,
"ephemeral_1h_input_tokens": 0
}
}
}
```
For cached requests, `cache_read_input_tokens` will be non-zero instead of `cache_creation_input_tokens`.
> [!NOTE]
>
> The OpenAI format uses `prompt_tokens` and `completion_tokens` instead of `input_tokens` and `output_tokens`, but the cache-related fields are identical across both formats.
## Best Practices
1. **Cache large, static content** that doesn't change frequently
2. **Monitor `cache_read_input_tokens`** to verify cache hits
3. **Respect the 4 breakpoint limit** - prioritize largest, most reused content
4. **Remember cache expiration** - caches expire after 5 minutes (or your TTL)
For more details, see the [Anthropic documentation](https://platform.claude.com/docs/en/build-with-claude/prompt-caching).