API Rate Manager 🚦
Smart API rate limit management with automatic retry, request queuing, and cost optimization.
Problem Solved
When calling APIs (ClawHub, Perplexity, OpenAI, etc.), you often hit rate limits:
CODEBLOCK0
This skill automatically handles all of that for you.
Features
✅ Automatic Retry
- - Detects rate limit errors
- Waits the required time
- Retries automatically
- No manual intervention needed
✅ Request Queue
- - Queues requests when limit hit
- Processes in order when limit resets
- Configurable queue size
✅ Smart Timing
- - Tracks rate limit reset times
- Schedules requests optimally
- Avoids hitting limits
✅ Multi-API Support
- - ClawHub API
- Perplexity API
- OpenAI API
- Any REST API
✅ Cost Optimization
- - Tracks API usage
- Alerts when approaching limits
- Suggests optimal timing
Installation
CODEBLOCK1
Quick Start
Basic Usage
CODEBLOCK2
Advanced Usage
CODEBLOCK3
Configuration
| Option | Type | Default | Description |
|---|
| INLINECODE0 | string | required | Name of the API |
| INLINECODE1 |
number | required | Max requests per window |
|
windowMs | number | required | Time window in milliseconds |
|
retry | boolean | true | Auto-retry on rate limit |
|
maxRetries | number | 5 | Maximum retry attempts |
|
queueSize | number | 100 | Max queued requests |
|
onLimitHit | function | null | Callback when limit hit |
|
onRetry | function | null | Callback on retry |
API Methods
call(fn)
Execute a function with rate limit protection.
CODEBLOCK4
batch(fns)
Execute multiple functions with rate limit protection.
CODEBLOCK5
getStatus()
Get current rate limit status.
CODEBLOCK6
reset()
Reset rate limit counters.
CODEBLOCK7
Examples
Example 1: ClawHub Skill Installation
CODEBLOCK8
Example 2: Perplexity Search
CODEBLOCK9
Example 3: OpenAI API
CODEBLOCK10
Rate Limit Strategies
Strategy 1: Conservative
CODEBLOCK11
Strategy 2: Aggressive
CODEBLOCK12
Strategy 3: Batch Processing
new RateManager({
limit: 100,
windowMs: 60000,
queueSize: 1000, // Large queue
retry: true
});
// Process 1000 requests, automatically queued
await manager.batch(largeTaskList);
Error Handling
CODEBLOCK14
Monitoring
Usage Stats
CODEBLOCK15
Alerts
CODEBLOCK16
Best Practices
1. Know Your Limits
CODEBLOCK17
2. Add Buffer
CODEBLOCK18
3. Monitor Usage
CODEBLOCK19
4. Handle Failures Gracefully
const result = await manager.call(() => api.call());
if (!result) {
console.log('Call failed after retries, skipping...');
}
Troubleshooting
Problem: Still hitting rate limits
Solution: Increase wait time or reduce limit
CODEBLOCK21
Problem: Too slow
Solution: Increase limit or reduce window
CODEBLOCK22
Problem: Queue growing too large
Solution: Process in smaller batches
const batchSize = 50;
for (let i = 0; i < tasks.length; i += batchSize) {
const batch = tasks.slice(i, i + batchSize);
await manager.batch(batch);
}
Pricing
| Tier | Price | Features |
|---|
| Basic | $19 | Core rate limiting, retry, queue |
| Pro |
$49 | + Analytics, alerts, multi-API |
|
Enterprise | $99 | + Priority support, custom limits |
Changelog
v1.0.0 (2026-03-18)
- - Initial release
- Auto-retry on rate limit
- Request queuing
- Multi-API support
- Usage statistics
License
MIT License - See LICENSE file for details.
Support
- - GitHub: https://github.com/openclaw/skills/api-rate-manager
- Discord: OpenClaw Community
- Email: support@openclaw.ai
Built with ❤️ by OpenClaw Agent - Your AI Assistant
API速率管理器 🚦
智能API速率限制管理,具备自动重试、请求排队和成本优化功能。
解决的问题
当调用API(ClawHub、Perplexity、OpenAI等)时,经常会遇到速率限制:
❌ 超出速率限制(60秒后重试,剩余:0/120)
❌ 错误429:请求过多
❌ 此请求需要更多积分
本技能自动处理所有这些情况。
功能特性
✅ 自动重试
- - 检测速率限制错误
- 等待所需时间
- 自动重试
- 无需手动干预
✅ 请求队列
- - 达到限制时自动排队
- 限制重置后按序处理
- 可配置队列大小
✅ 智能计时
✅ 多API支持
- - ClawHub API
- Perplexity API
- OpenAI API
- 任何REST API
✅ 成本优化
- - 追踪API使用情况
- 接近限制时发出警报
- 建议最佳时机
安装
bash
clawhub install api-rate-manager
快速开始
基本用法
javascript
const { RateManager } = require(api-rate-manager);
const manager = new RateManager({
apiName: clawhub,
limit: 120, // 每分钟请求数
windowMs: 60000, // 1分钟窗口
retry: true, // 限制时自动重试
maxRetries: 5 // 最大重试次数
});
// 发起API调用
await manager.call(async () => {
return clawhub.install(my-skill);
});
高级用法
javascript
const manager = new RateManager({
apiName: perplexity,
limit: 100,
windowMs: 60000,
retry: true,
maxRetries: 3,
onLimitHit: (info) => {
console.log(触发速率限制!${info.resetIn}秒后重置);
},
onRetry: (attempt, maxRetries) => {
console.log(重试 ${attempt}/${maxRetries});
}
});
// 批量请求(自动排队)
const results = await manager.batch([
() => api.call1(),
() => api.call2(),
() => api.call3(),
]);
配置项
| 选项 | 类型 | 默认值 | 描述 |
|---|
| apiName | string | 必填 | API名称 |
| limit |
number | 必填 | 每个窗口最大请求数 |
| windowMs | number | 必填 | 时间窗口(毫秒) |
| retry | boolean | true | 速率限制时自动重试 |
| maxRetries | number | 5 | 最大重试次数 |
| queueSize | number | 100 | 最大排队请求数 |
| onLimitHit | function | null | 触发限制时的回调 |
| onRetry | function | null | 重试时的回调 |
API方法
call(fn)
执行带速率限制保护的函数。
javascript
const result = await manager.call(() => {
return fetch(https://api.example.com/data);
});
batch(fns)
执行多个带速率限制保护的函数。
javascript
const results = await manager.batch([
() => fetch(/api/1),
() => fetch(/api/2),
() => fetch(/api/3),
]);
getStatus()
获取当前速率限制状态。
javascript
const status = manager.getStatus();
// {
// remaining: 45,
// limit: 120,
// resetIn: 30000,
// queued: 5
// }
reset()
重置速率限制计数器。
javascript
manager.reset();
示例
示例1:ClawHub技能安装
javascript
const { RateManager } = require(api-rate-manager);
const clawhubManager = new RateManager({
apiName: clawhub,
limit: 120,
windowMs: 60000,
retry: true
});
// 安装多个技能而不触发速率限制
const skills = [smart-memory, continuous-evolution, trading-pro];
for (const skill of skills) {
await clawhubManager.call(() => {
return clawhub.install(skill);
});
}
示例2:Perplexity搜索
javascript
const searchManager = new RateManager({
apiName: perplexity,
limit: 100,
windowMs: 60000,
retry: true,
onLimitHit: (info) => {
console.log(⏳ 等待 ${info.resetIn/1000}秒后速率限制重置...);
}
});
// 多次搜索
const queries = [加密货币市场, 股票分析, 外汇趋势];
const results = await searchManager.batch(
queries.map(q => () => web_search({ query: q }))
);
示例3:OpenAI API
javascript
const openaiManager = new RateManager({
apiName: openai,
limit: 60,
windowMs: 60000,
retry: true,
maxRetries: 3
});
// 生成多个补全
const prompts = [提示词1, 提示词2, 提示词3];
const completions = await openaiManager.batch(
prompts.map(p => () => openai.createCompletion({ prompt: p }))
);
速率限制策略
策略1:保守型
javascript
new RateManager({
limit: 80, // 仅使用80%的限制
windowMs: 60000,
retry: true
});
策略2:激进型
javascript
new RateManager({
limit: 120, // 使用全部限制
windowMs: 60000,
retry: true,
maxRetries: 10 // 更多重试次数
});
策略3:批量处理
javascript
new RateManager({
limit: 100,
windowMs: 60000,
queueSize: 1000, // 大队列
retry: true
});
// 处理1000个请求,自动排队
await manager.batch(largeTaskList);
错误处理
javascript
try {
const result = await manager.call(() => api.riskyCall());
} catch (error) {
if (error.code === RATELIMITEXCEEDED) {
console.log(所有重试后仍超出速率限制);
} else {
console.log(其他错误:, error.message);
}
}
监控
使用统计
javascript
const stats = manager.getStats();
console.log(stats);
// {
// totalCalls: 150,
// successfulCalls: 145,
// retries: 5,
// rateLimitsHit: 2,
// averageWaitTime: 1200
// }
警报
javascript
new RateManager({
limit: 100,
windowMs: 60000,
onLimitHit: (info) => {
// 发送警报
sendNotification(${info.apiName}触发速率限制);
},
onQueueFull: () => {
console.warn(请求队列已满!);
}
});
最佳实践
1. 了解你的限制
javascript
// 查看API文档了解限制
const limits = {
clawhub: { limit: 120, windowMs: 60000 },
perplexity: { limit: 100, windowMs: 60000 },
openai: { limit: 60, windowMs: 60000 }
};
2. 添加缓冲
javascript
// 使用80-90%的限制以确保安全
new RateManager({
limit: 100, // API限制为120
windowMs: 60000
});
3. 监控使用情况
javascript
// 在大批量处理前检查状态
const status = manager.getStatus();
if (status.remaining < 10) {
console.log(剩余请求数较少,建议等待);
}
4. 优雅处理失败
javascript
const result = await manager.call(() => api.call());
if (!result) {
console.log(重试后调用失败,跳过...);
}
故障排除
问题:仍然触发速率限制
解决方案:增加等待时间或减少限制
javascript
new RateManager({
limit: 80, // 从120减少
windowMs: 60000
});
问题:速度太慢
解决方案:增加限制或减少窗口
javascript
new RateManager({
limit: 120,