Spaces:
Running
Running
| /** | |
| * Token Cost Guard SDK (Typescript) | |
| * Usage: npm install token-cost-guard | |
| */ | |
| export interface LogEntry { | |
| step: string; | |
| agent: string; | |
| prompt_tokens: number; | |
| completion_tokens: number; | |
| model: string; | |
| input: string; | |
| output: string; | |
| } | |
| export class TokenCostGuard { | |
| private apiKey: string; | |
| private endpoint: string = "https://your-domain.com/api/v1"; | |
| constructor(apiKey: string) { | |
| if (!apiKey.startsWith("TCG-")) { | |
| throw new Error("Invalid API Key format"); | |
| } | |
| this.apiKey = apiKey; | |
| } | |
| /** | |
| * Optimize a set of agent logs and return the execution plan | |
| */ | |
| async optimize(logs: LogEntry[]) { | |
| const response = await fetch(`${this.endpoint}/optimize`, { | |
| method: "POST", | |
| headers: { | |
| "Content-Type": "application/json", | |
| "Authorization": `Bearer ${this.apiKey}` | |
| }, | |
| body: JSON.stringify({ logs }) | |
| }); | |
| if (!response.ok) { | |
| const err = await response.json(); | |
| throw new Error(err.error || "Optimization failed"); | |
| } | |
| return response.json(); | |
| } | |
| /** | |
| * Get current usage and savings stats | |
| */ | |
| async getStats() { | |
| const response = await fetch(`${this.endpoint}/usage`, { | |
| headers: { | |
| "Authorization": `Bearer ${this.apiKey}` | |
| } | |
| }); | |
| return response.json(); | |
| } | |
| } | |
| // Example Integration for AutoGen / LangChain | |
| /* | |
| const guardian = new TokenCostGuard("TCG-PRO-xxxx-xxxx"); | |
| async function onWorkflowComplete(logs) { | |
| const plan = await guardian.optimize(logs); | |
| console.log("Optimized Plan Readiness:", plan.actions); | |
| // Apply plan.executable_patch to the next run | |
| } | |
| */ | |