cost-performance-optimizer

AI Cost-Performance Optimizer: integrates dynamic model selection, multi-backend caching (SQLite/Redis/File), budget control, error retry and degradation to automatically balance and optimize model invocation between cost and performance.

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "cost-performance-optimizer" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-b85812a1f054c0beacca3a8090d50f016535baf181f1f3e1f91daa277d2d0837. Verify the upstream source and version against https://skillhub.cn/skills/user_fa4109f3/cost-performance-optimizer before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

skillhub.cn

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

AI Cost-Performance Optimizer: integrates dynamic model selection, multi-backend caching (SQLite/Redis/File), budget control, error retry and degradation to automatically balance and optimize model invocation between cost and performance.

0 Downloads

Introduction source: third_party · user_fa4109f3 · 3.0.0 Reference

SkillPi interpretation

Tasks
Multi-backend cache, history-based model selection, budget control, retry/fallback.
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: cost-performance-optimizer
version: 3.0.0
description: |
  AI Cost-Performance Optimizer - AI 成本性能优化器
  集成动态模型选择、多后端缓存(SQLite/Redis/File)、预算控制、错误重试与降级
triggers:
  - 成本优化
  - 模型选择
  - 缓存优化
  - 预算控制
  - 性能监控
  - cost performance
  - model selection
  - budget control
disable: false

Cost-Performance Optimizer v2.0

Multi-backend cache, history-based model selection, budget control, retry/fallback.

Core Features

1. Multi-Backend Cache System

  • File: JSON files in .cache/ directory
  • SQLite: Persistent cache with auto-expiration (cache_store table)
  • Redis: High-performance distributed cache (requires pip install redis)
  • Tiered: Multi-level L1→L2 cache with automatic backfill

2. History-Based Model Selection

  • Scoring formula: score = success_rate*40 + speed*30 + cost*30
  • Complexity-aware weight adjustment (simple/medium/complex)
  • Budget-aware degradation (auto-switch when over budget)

3. Budget Control Integration

  • Monthly budget tracking (CNY)
  • 80% warning threshold → auto alert
  • 100% exceeded → auto model degradation
  • Monthly auto-recovery

4. Error Handling & Retry

  • @RetryHandler.retry(max_retries=3, backoff_base=1.0, jitter=True)
  • @RetryHandler.fallback(fallback_func)
  • Cache backend auto-degrade: Redis→SQLite→File→None

Usage

Quick Start

from cost_performance_optimizer import CostPerformanceOptimizer, OptimizationConfig

config = OptimizationConfig(
    cache_config={'backend': 'sqlite', 'db_path': '.cache/cpo_cache.db'},
    enable_budget_control=True,
    budget_monthly_cny=500.0
)

optimizer = CostPerformanceOptimizer(config)

# Model selection (with history + budget check)
model = optimizer.select_optimal_model("code", "write a fibonacci function")
print(f"Recommended: {model}")

# Caching
result = optimizer.get_cached_result("gpt-4o", "what is AI?")
if not result:
    result = call_model(...)  # your model call
    optimizer.cache_result("gpt-4o", "what is AI?", result)

# Budget status
status = optimizer.get_budget_status()
print(f"Budget: {status['status']}")

Cache Backend Configuration

# SQLite (default)
config = OptimizationConfig(cache_config={'backend': 'sqlite', 'db_path': '.cache/cpo_cache.db'})

# Redis
config = OptimizationConfig(cache_config={'backend': 'redis', 'redis_url': 'redis://localhost:6379/0'})

# Tiered (L1=Redis, L2=SQLite)
config = OptimizationConfig(cache_config={
    'backend': 'tiered',
    'tiers': [
        {'backend': 'redis', 'redis_url': 'redis://localhost:6379/0'},
        {'backend': 'sqlite', 'db_path': '.cache/cpo_cache.db'}
    ]
})

Integration with PerformanceMonitor & BudgetController

from performance_monitor_enhanced import PerformanceMonitor
from budget_controller import BudgetController
from alert_notifier import AlertNotifier

monitor = PerformanceMonitor()
alert_notifier = AlertNotifier(".cache/alerts.db")
budget = BudgetController(".cache/alerts.db", alert_notifier=alert_notifier)

optimizer = CostPerformanceOptimizer(
    config=config,
    performance_monitor=monitor,
    budget_controller=budget
)

# Now model selection uses real historical data
# Cost tracking writes to both monitor and budget controller

CLI Test

python cost_performance_optimizer.py

Dashboard

Open performance_dashboard_pro.html in browser after starting integration_server.py:

python integration_server.py 8000
# Then open performance_dashboard_pro.html

Report

python send_performance_report.py
# Generates markdown report, saves to .cache/reports/

API Endpoints (via integration_server)

  • POST /optimizer/model-select — Select optimal model
  • GET /optimizer/cache-stats — Cache statistics
  • GET /optimizer/budget-status — Budget status
  • GET /optimizer/report — Full optimization report
  • POST /optimizer/cache-clear — Clear cache

Architecture

CostPerformanceOptimizer
├── CacheManager (CacheBackend)
│   ├── FileCacheBackend
│   ├── SQLiteCacheBackend
│   ├── RedisCacheBackend
│   └── TieredCacheBackend
├── HistoryBasedModelSelector
│   └── PerformanceMonitor (data source)
├── PromptOptimizer
├── RetryHandler (@retry, @fallback)
└── BudgetController (injected)

动态模型选择策略

基于任务复杂度选择

任务类型 推荐模型 成本考量
简单任务(文件整理、日程提醒) Claude Haiku / Kimi K2.5 低价模型足够
中等任务(代码生成、数据处理) Claude Sonnet / Kimi K2 平衡性能和成本
复杂任务(策略优化、多轮推理) Claude Opus / GPT-4 高成本但高准确

分级模型策略

# 分级模型选择示例
def select_model(task_complexity, budget_remaining):
    if budget_remaining < 10:  # 预算不足
        return "claude-haiku"
    elif task_complexity == "simple":
        return "claude-sonnet"
    elif task_complexity == "complex":
        return "claude-opus"
    else:
        return "claude-sonnet"

成本优化技巧

  1. 任务合并:多个小任务合并成一次 API 调用
  2. 缓存复用:相同数据不重复生成
  3. Prompt 压缩:结构化表达,减少冗余信息
  4. 监控告警:设置每日/每周 Token 消耗上限

实战案例:量化策略自动优化

案例背景

使用 AI 自动优化量化交易策略,涉及:

  • 数据准备(行情数据获取)
  • 因子研究(MACD、均线等技术指标)
  • 策略构建(选股、仓位、风控)
  • 回测验证(历史数据测试)

成本控制策略

阶段 模型选择 成本优化
数据准备 Haiku 批量获取,简单处理
因子检验 Sonnet 统计分析需要一定推理
策略优化 Opus 复杂逻辑需要强推理
结果分析 Sonnet 总结分析

优化效果

  • 原始策略:9万条信号,无执行条件
  • 优化后:1.5万条信号,具备执行条件
  • 周利率:2.27%,胜率 52.11%
  • 交易成本:通过模型自动加入佣金、印花税计算

关键洞察

  1. AI 补齐的是执行力:想法验证不再依赖程序员
  2. 碎片时间利用:任务下达 → 结果回传,实现闭环
  3. 判断比执行重要:AI 生成的回测结果需要人工判别是否过拟合

更新日志

v3.0.0 (2026-07-09)

  • 新增动态模型选择策略:基于任务复杂度分级选择
  • 新增分级模型策略配置
  • 新增成本优化技巧:任务合并、缓存复用、Prompt 压缩
  • 新增实战案例:量化策略自动优化
  • 新增成本控制表格:不同阶段模型选择
  • 强调"判断比执行重要"的 AI 时代核心原则

Current listing version

3.0.0

Verify the source revision ↗

Safety and assessment details

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value92/100

Highlights

  • 集成动态模型选择、多后端缓存、预算控制、错误重试与降级等核心功能
  • 提供量化策略自动优化等实战案例,展示实际应用场景
  • 解决用户在 AI 使用中的核心痛点:成本控制与性能优化
Trigger Precision95/100

Highlights

  • 触发词覆盖成本优化、模型选择、缓存优化、预算控制等核心场景
  • 中英文触发词完整,边界清晰,用户易于理解和使用
Structure and Standards93/100

Areas to improve

  • 缺少 When to Use 章节 Reported severity: Minor

    文档中缺少明确的 When to Use 使用场景说明章节

    Recommendation: 建议添加 When to Use 章节,明确说明该 Skill 的适用场景和使用时机

  • 文档过长 Reported severity: Minor

    文档内容较为详尽,可能影响用户快速获取关键信息

    Recommendation: 建议适当精简文档,突出核心功能和快速上手指南

Highlights

  • 文档结构清晰,包含核心功能、使用示例、配置说明、架构图等完整内容
  • 提供详细的实战案例和成本控制策略,增强实用性
  • frontmatter 完整,版本信息和触发词定义清晰
Execution Reliability91/100

Highlights

  • 工具来源明确,提供完整的 Python 实现和配置示例
  • 覆盖主要异常处理机制:重试、降级、缓存后端自动降级
  • 提供 CLI 测试、API 端点和仪表板,便于验证和监控
Evidence Verifiability (mean of the first four)93/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

  • Install or fetch external dependencies

    Use official sources and pin versions. Check install scripts in an isolated environment. This document check does not cover code downloaded later.

    Mentioned in main document · lines 28

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.