sarthib7-butler
AI 智能体财务与编排技能,管理多提供商 token 预算、生成子智能体、自动密钥轮换与结果聚合,集成 Code Reviewer 安全审查。
安装 / 下载方式
TotalClaw CLI推荐
totalclaw install totalclaw:totalclaw~sarthib7-butlercURL直接下载,无需登录
curl -fsSL https://skills.taituai.com/api/skills/totalclaw%3Atotalclaw~sarthib7-butler/file -o sarthib7-butler.md## 概述(中文)
AI 智能体财务与编排技能,管理多提供商 token 预算、生成子智能体、自动密钥轮换与结果聚合,集成 Code Reviewer 安全审查。
## 技能正文
# Butler - AI 智能体财务与编排技能
## 概述
**Butler** 是 OpenClaw 技能,将 AI 智能体转变为自主经济实体。它管理多提供商 token 预算、为复杂任务生成子智能体,并在预算耗尽时自动处理 token 购买。
可将 Butler 视为 **AI 智能体 CFO**,负责:
- 💰 跟踪 8 个 API 密钥、6 个提供商的 token 预算
- 🚀 生成子智能体并自动分配预算
- 🔄 接近限额时轮换密钥
- 📊 聚合并行 worker 的结果
- 🛡️ 与 Code Reviewer 集成保障安全
## 快速开始
### 安装
```bash
npm install butler
# or
yarn add butler
```
### 基本用法
```typescript
import { Butler } from 'butler';
// Initialize
const butler = new Butler();
// Allocate tokens for a task
const allocation = butler.allocateTokens('PRD-my-task.md', 'anthropic');
console.log(`✅ Allocated ${allocation.allocated} tokens on ${allocation.provider}`);
// Spawn agents for complex work
const results = await butler.spawnAgent(
'DataAnalysis',
'Analyze sales data and write report',
100000, // tokens
{ maxConcurrent: 3, retryOnFailure: true }
);
// Get status
const status = butler.getStatus();
console.log(`🎯 Status:`, status);
```
## 功能
### 1. Token 管理
Butler 跟踪 6 个提供商的 8 个 API 密钥,实时监控用量:
```typescript
// Get available keys
const keys = butler.getAvailableKeys();
// [
// { id: 'nvidia-1', provider: 'nvidia', model: 'llama-3.1', ... },
// { id: 'anthropic-1', provider: 'anthropic', model: 'claude-sonnet', ... },
// { id: 'groq-1', provider: 'groq', model: 'llama-3.1', ... },
// ...
// ]
// Estimate tokens for PRD
const estimate = butler.allocateTokens('PRD-integration.md');
// Analyzes PRD complexity and recommends optimal allocation
// Monitor usage
const status = butler.monitorUsage();
// { keys_by_provider: { nvidia: {...}, anthropic: {...}, ... } }
```
**支持的提供商:**
- **Nvidia**(3 密钥,各 5M tokens/天)- 免费层 ✅
- **Groq**(1 密钥,10M tokens/天)- 免费层 ✅
- **Anthropic**(1 密钥,1M tokens/天)- 当前模型
- **OpenAI**(1 密钥,500k tokens/天)
- **OpenRouter**(1 密钥,2M tokens/天)
- **Sokosumi**(1 密钥)- 自定义/研究
**总容量:** 28.5M tokens/天
### 2. 智能体编排
生成多个子智能体,自动任务分解与预算分配:
```typescript
// Simple spawn (auto-decompose)
const results = await butler.spawnAgent(
'ComplexResearch',
`Research AI agent frameworks:
1. Gather information from 5+ sources
2. Analyze capabilities and limitations
3. Write detailed comparison report
4. Validate findings with expert review`,
250000 // tokens
);
// Advanced spawn with options
const results = await butler.spawnAgent(
'DataPipeline',
'Extract, transform, validate, load data',
500000,
{
maxConcurrent: 4, // Run up to 4 sub-agents in parallel
retryOnFailure: true, // Retry failed sub-tasks
maxRetries: 3, // Up to 3 retry attempts
timeoutMs: 600000 // 10 minute timeout per sub-agent
}
);
// Get results
results.forEach(result => {
console.log(`Sub-task ${result.subTaskId}:`);
console.log(` Status: ${result.status}`);
console.log(` Tokens: ${result.tokensUsed}`);
if (result.error) console.log(` Error: ${result.error}`);
});
```
**任务分解算法:**
```
Input: "Research AI frameworks, analyze patterns, write report"
↓
1. Keyword detection: "research", "analyze", "write"
↓
2. Sub-task creation:
- Subtask 1: "research AI frameworks" (30% budget)
- Subtask 2: "analyze patterns" (40% budget)
- Subtask 3: "write report" (30% budget)
↓
3. Priority boost (if specified)
↓
4. Concurrent execution (respects maxConcurrent)
↓
5. Result aggregation
```
### 3. 预算分配
基于任务复杂度与优先级的自动预算分配:
```typescript
// High-priority task gets more budget
const task = {
totalBudget: 100000,
subTasks: [
{
id: 'low-priority-task',
estimatedTokens: 50000,
priority: 'low' // 0.5x multiplier = 25k tokens
},
{
id: 'critical-task',
estimatedTokens: 50000,
priority: 'critical' // 2.0x multiplier = 100k tokens (capped)
}
]
};
// Allocation: { 'low-priority-task': 33k, 'critical-task': 67k }
```
**优先级乘数:**
- `low`:0.5x(估计值的 50%)
- `medium`:1.0x(估计值的 100%)
- `high`:1.5x(估计值的 150%)
- `critical`:2.0x(估计值的 200%)
### 4. 自动轮换
密钥在 75% 阈值轮换以防耗尽:
```typescript
// Automatic tracking and alerts
const status = butler.getStatus();
// When session reaches 75% of allocated budget:
// ✅ Alert issued
// 🔄 New key auto-selected
// 📊 Session updated with new key
// 📝 Change logged to history
// Manual rotation if needed
butler.rotateKey('session-id-123', 'anthropic-1');
```
### 5. 结果聚合
自动聚合并行智能体的结果:
```typescript
const results = await butler.spawnAgent('ComplexTask', 'task description', 100000);
// After execution, aggregate results:
const aggregated = butler.aggregateTaskResults(results[0].taskId);
// {
// taskId: 'task-...',
// totalSubTasks: 5,
// successful: 4,
// failed: 1,
// totalTokensUsed: 87500,
// successRate: 80,
// details: [
// { id: 'subtask-1', status: 'success', tokensUsed: 18000 },
// { id: 'subtask-2', status: 'success', tokensUsed: 22000 },
// { id: 'subtask-3', status: 'success', tokensUsed: 19500 },
// { id: 'subtask-4', status: 'success', tokensUsed: 21000 },
// { id: 'subtask-5', status: 'failure', tokensUsed: 7000, error: 'timeout' }
// ]
// }
```
## 示例
### 示例 1:复杂任务的 Token 分配
```typescript
import { Butler } from 'butler';
const butler = new Butler();
// Create PRD file
const prd = `
# AI Agent Integration Task
## Requirements
- Integrate OpenAI API
- Build agent orchestration
- Write unit tests
- Deploy to production
## Constraints
- Budget: $100/day
- Timeline: 1 week
- Team: 2 engineers
`;
fs.writeFileSync('PRD-integration.md', prd);
// Get smart allocation
const allocation = butler.allocateTokens('PRD-integration.md');
if (allocation.success) {
console.log(`
✅ Recommended:
Key: ${allocation.key_id} (${allocation.provider})
Budget: ${allocation.allocated.toLocaleString()} tokens
Cost: $${allocation.cost_estimate.toFixed(2)}
Rotate at: ${allocation.rotation_threshold.toLocaleString()} tokens
Available: ${allocation.available_capacity.toLocaleString()} tokens
`);
}
```
### 示例 2:并行智能体执行
```typescript
import { Butler } from 'butler';
const butler = new Butler();
async function analyzeDataset() {
const results = await butler.spawnAgent(
'DatasetAnalysis',
`
1. Extract data from sources
2. Clean and validate data
3. Run statistical analysis
4. Create visualizations
5. Write findings report
`,
300000,
{ maxConcurrent: 3, retryOnFailure: true }
);
// Process results
const aggregated = butler.aggregateTaskResults(results[0].taskId);
console.log(`
📊 Analysis Complete:
Successful: ${aggregated.successful}/${aggregated.totalSubTasks}
Success Rate: ${aggregated.successRate.toFixed(1)}%
Total Tokens: ${aggregated.totalTokensUsed.toLocaleString()}
`);
return aggregated;
}
analyzeDataset().then(result => {
console.log('Results:', result.details);
});
```
### 示例 3:错误处理与重试
```typescript
import { Butler } from 'butler';
const butler = new Butler();
async function reliableProcessing() {
try {
const results = await butler.spawnAgent(
'RobustProcessing',
'Process data with validation and error handling',
200000,
{
retryOnFailure: true,
maxRetries: 3, // Retry up to 3 times
maxConcurrent: 2,
timeoutMs: 120000 // 2 minute timeout
}
);
const aggregated = butler.aggregateTaskResults(results[0].taskId);
if (aggregated.failed > 0) {
console.log(`⚠️ ${aggregated.failed} sub-tasks failed:`);
aggregated.details
.filter((d: any) => d.status === 'failure')
.forEach((d: any) => {
console.log(` - ${d.id}: ${d.error}`);
});
// Optionally retry failed tasks
await butler.retryFailedTasks(results[0].taskId);
}
return aggregated;
} catch (error) {
console.error('Task failed:', error);
throw error;
}
}
reliableProcessing();
```
### 示例 4:监控 Token 用量
```typescript
import { Butler } from 'butler';
const butler = new Butle