Live Demo
Real-time Chat with Streaming & Billing
Welcome! Send a message to start. The response will stream token-by-token with real-time billing.
| Status | Waiting for request |
Architecture
From Python to C++ — The Full Pipeline
Python — Network I/O & Demo Shell
Manages API calls, SSE streaming, and the web UI. Passes raw JSON responses to C++ for billing.
- FastAPI web server with SSE endpoints
- OpenAI SDK for DeepSeek API calls
- Mock mode for offline demos
pybind11 — Language Boundary
Converts Python dicts↔JSON strings↔nlohmann::json. Releases GIL during C++ computation.
- All enums, structs, and services bound
- GIL released on ComputeFromRawResponse
- Thread-safe shared_mutex pattern
C++ Core — OOP Design at Its Heart
Interfaces, strategy classes, template method, factory patterns — all in C++.
- IUsageParser, ICachePolicy, IPointsPolicy
- AgentBase template method + hooks
- Integer math (micro_yuan), no float errors
Ledger — From Single Bill to Monthly Credits
Aggregates per-request ChargeBreakdown into conversation summaries and credit tiers.
- UsageLedger with shared_mutex
- SummarizeConversation API
- MonthlyCreditCalculator tier system
Multi-Agent
Visual Agent Collaboration Engine
Agent Factory
No agents yet
Collaboration Strategy
Billing Simulator
Interactive Cache Policy Explorer
Credit System
Monthly Token Credit Calculator
Budget Management
Observer Pattern & Cost Prediction
Budget Status
No data yet
Cost Prediction
Run agents to see predictions
C++ Object-Oriented Design
Core OOP Architecture — Classes, Interfaces & Relationships
🎯 面向对象程序设计核心
本项目的C++核心层充分运用了面向对象程序设计的核心思想:抽象、封装、继承、多态。通过精心设计的类层次结构和接口体系,实现了高内聚、低耦合的架构。
核心接口设计 (Core Interfaces)
IUsageParser
职责:解析 API 响应 JSON,提取 token 用量信息
核心方法:
virtual TokenUsage Parse(const json& response) = 0;
派生类:
- OpenAIResponsesParser
- OpenAIChatParser
- DashScopeParser
💡 OOP原则:策略模式 + 多态,不同API格式各自实现
ICachePolicy
职责:根据缓存模式计算输入 token 计费
核心方法:
virtual InputChargeBreakdown ComputeInputCharge(...) = 0;
派生类:
- NoCachePolicy (无缓存)
- ImplicitCachePolicy (隐式缓存)
- ExplicitCachePolicy (显式缓存)
- SessionCachePolicy (会话缓存)
💡 OOP原则:开放封闭原则,新增缓存策略无需修改现有代码
IPointsPolicy
职责:将成本(微元)转换为积分
核心方法:
virtual int64_t ComputePoints(int64_t cost_micro_yuan) = 0;
派生类:
- FixedRatePointsPolicy (固定比率)
💡 OOP原则:依赖倒置,高层模块不依赖具体实现
IPrefixCache
职责:本地前缀缓存(预测缓存命中)
核心方法:
virtual bool TryHit(const string& fingerprint, size_t length);
virtual void Store(...);
派生类:
- LruPrefixCache (LRU)
- LfuPrefixCache (LFU)
- TtlPrefixCache (TTL过期)
💡 OOP原则:接口隔离,缓存逻辑与计费逻辑解耦
类与类之间的关系 (Class Relationships)
所有具体解析器(OpenAIResponsesParser, DashScopeParser...)继承自抽象基类 IUsageParser,实现多态的 Parse() 方法。
class OpenAIResponsesParser : public IUsageParser {
TokenUsage Parse(const json& resp) override { /*...*/ }
};
TokenBillingService 组合了多个组件:
PricingCatalog— 定价目录UsageLedger— 用量账本map<string, unique_ptr<IUsageParser>>— 解析器注册表map<CacheMode, unique_ptr<ICachePolicy>>— 缓存策略注册表
💡 外观模式 (Facade):TokenBillingService 对外提供统一接口,内部协调各子系统。
TokenBillingService::ComputeFromRawResponse() 方法依赖于:
- IUsageParser 解析 JSON
- ICachePolicy 计算输入成本
- PricingCatalog 查询价格阶梯
💡 依赖注入:解析器和策略通过注册表动态选择,而非硬编码。
UsageLedger 与 ChargeBreakdown 之间存在一对多关联:
class UsageLedger {
map<string, vector<ChargeBreakdown>> ledger_;
};
每个 conversation_id 关联多个请求的 ChargeBreakdown。
设计模式应用 (Design Patterns)
策略模式 (Strategy Pattern)
通过 ICachePolicy 接口,4种缓存计费策略可互换使用,无需修改调用代码。
policy->ComputeInputCharge(usage, tier)
模板方法 (Template Method)
AgentBase::Execute() 定义执行骨架:PreProcess → Call API → PostProcess,子类可覆盖钩子方法。
工厂模式 (Factory Pattern)
ConfigurableAgentFactory::CreateAgent(config) 根据配置创建不同类型的 Agent。
观察者模式 (Observer Pattern)
BudgetManager 作为主题,IBudgetObserver 作为观察者,预算超限时自动通知。
外观模式 (Facade Pattern)
TokenBillingService 封装复杂的解析、计费、账本操作,对外提供简单接口。
访问者模式 (Visitor Pattern)
IReportVisitor 接口支持多种报告格式(HTML, JSON, CSV),无需修改数据类。
C++ 与 Python 的关系 (C++/Python Integration)
🔗 pybind11 绑定层
使用 pybind11 将C++类和函数暴露给Python:
PYBIND11_MODULE(token_billing_core, m) {
py::class_<TokenBillingService>(m, "TokenBillingService")
.def("compute_from_raw_response", &TokenBillingService::ComputeFromRawResponse,
py::call_guard<py::gil_scoped_release>());
}
📌 GIL释放:py::gil_scoped_release 允许C++代码并行运行,提高性能。
🐍 Python 调用 C++
Python脚本通过绑定模块调用C++核心:
# Python
import token_billing_core as tbc
service = tbc.TokenBillingService()
breakdown = service.compute_from_raw_response(response_json, context)
📌 Python负责网络I/O、Web服务,C++负责高性能计算。
📊 数据契约 (JSON)
两层之间的数据格式契约:
- Python将API响应转为dict → JSON字符串 → C++ nlohmann::json
- C++返回ChargeBreakdown结构体 → pybind11自动转为Python对象
📌 枚举类型绑定:CacheMode::None 在Python中映射为 CacheMode.NoCache
核心函数设计 (Core Function Design)
TokenBillingService::ComputeFromRawResponse
签名:
ChargeBreakdown ComputeFromRawResponse(
const nlohmann::json& response,
const RequestContext& ctx
);
流程:
- 根据
ctx.api_flavor选择解析器 - 解析器提取
TokenUsage - 根据
ctx.cache_mode选择缓存策略 - 缓存策略计算输入成本
- 查询价格阶梯,计算总成本和积分
- 记录到账本 (UsageLedger)
ICachePolicy::ComputeInputCharge
签名:
virtual InputChargeBreakdown ComputeInputCharge(
const TokenUsage& usage,
const PricingTier& tier
) = 0;
多态行为:
- NoCachePolicy: 所有input token全额计费
- SessionCachePolicy: cached token × 折扣系数,cache_creation token × 创建系数
💡 继承与重写实现不同计费逻辑
🎓 面向对象设计的优势总结
封装 (Encapsulation)
每个类职责单一,内部实现细节对外隐藏。例如 PricingCatalog 的阶梯查找算法不会泄露给调用者。
继承 (Inheritance)
通过基类定义共同接口,派生类复用代码。Agent类层次中,AgentBase定义通用Execute流程。
多态 (Polymorphism)
通过虚函数实现运行时多态。同一接口(如IUsageParser::Parse),不同实现自动选择。
可扩展性 (Extensibility)
新增缓存策略、解析器无需修改现有代码,符合开放封闭原则(OCP)。
知识图谱
你需要点亮的 技能树
本项目综合运用了面向对象程序设计的核心理念,从基础到进阶,从实现到思考,涵盖了三个层次的技能:
基础核心
MUST MASTER · 必须掌握
类与对象:万物皆对象,深刻理解其创建逻辑与生命周期。
项目实践: TokenBillingService, UsageLedger, PricingCatalog 等核心业务类,每个对象有明确的职责和生命周期管理。
封装:实现数据隐藏与访问控制,构建健壮对象。
项目实践: 使用 private 成员变量 + public 方法,如 UsageLedger 内部的 ledger_ 映射表仅通过 AddEntry() 和 SummarizeConversation() 访问。
继承:通过继承建立类关系,最大化实现代码复用。
项目实践: IUsageParser 基类 → OpenAIResponsesParser, DashScopeParser 等派生类,复用共同接口,各自实现 Parse()。
多态:利用方法重写与接口回调,实现灵活行为。
项目实践: ICachePolicy 虚函数接口,运行时根据 CacheMode 动态调用 NoCachePolicy 或 SessionCachePolicy 的 ComputeInputCharge()。
进阶技术
FLEXIBLE USE · 灵活运用
抽象类与接口:定义系统的顶层规范,实现业务逻辑与具体实现的解耦。
项目实践: 4大核心接口 (IUsageParser, ICachePolicy, IPointsPolicy, IPrefixCache),每个接口定义纯虚函数,强制派生类实现。
异常处理:捕获并处理运行时异常,保证程序的稳定性与容错性。
项目实践: JSON解析失败、价格阶梯未找到等场景使用 try-catch,抛出自定义异常并在Python层捕获,返回友好错误信息。
集合框架:熟练掌握 List、Map、Set 等容器,高效管理复杂数据。
项目实践: std::map<string, vector<ChargeBreakdown>> 管理账本,std::map<CacheMode, unique_ptr<ICachePolicy>> 注册缓存策略。
设计思想
IN-DEPTH REFLECTION · 深度体现
经典设计模式应用
在项目中至少应用一种设计模式(如:单例模式、工厂模式、观察者模式等),解决特定场景下的架构问题,展现你对代码解耦、扩展性和可维护性的深刻理解。
🎯 项目技术亮点汇总
💡 为什么选择面向对象设计?
| 维度 | 面向过程 (Procedural) | 面向对象 (OOP) ✓ |
|---|---|---|
| 代码组织 | 函数堆砌,全局变量,难以维护 | 类+对象,职责清晰,高内聚低耦合 ✓ |
| 扩展性 | 添加新功能需修改大量函数 | 新增派生类即可,符合开放封闭原则 ✓ |
| 可复用性 | 复制粘贴代码,重复度高 | 继承+多态,代码复用率高 ✓ |
| 多人协作 | 文件冲突频繁,难以并行开发 | 接口定义清晰,团队协作效率高 ✓ |
| 测试 | 全局状态依赖,单元测试困难 | Mock对象注入,测试覆盖率高 ✓ |