MCPcopy
hub / github.com/lobehub/lobehub / CostTrackingAgent

Class CostTrackingAgent

packages/agent-runtime/src/core/__tests__/runtime.test.ts:800–852  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

798 it('should track usage and cost through agent methods', async () => {
799 // Create agent with cost calculation methods
800 class CostTrackingAgent implements Agent {
801 tools = {
802 test_tool: async () => ({ result: 'success' }),
803 };
804
805 async runner(context: AgentRuntimeContext, state: AgentState) {
806 switch (context.phase) {
807 case 'user_input': {
808 return { type: 'call_llm' as const, payload: { messages: state.messages } };
809 }
810 default: {
811 return {
812 type: 'finish' as const,
813 reason: 'completed' as const,
814 reasonDetail: 'Done',
815 };
816 }
817 }
818 }
819
820 calculateUsage(
821 operationType: 'llm' | 'tool' | 'human_interaction',
822 operationResult: any,
823 previousUsage: Usage,
824 ): Usage {
825 const newUsage = structuredClone(previousUsage);
826
827 if (operationType === 'llm') {
828 newUsage.llm.tokens.input += 100;
829 newUsage.llm.tokens.output += 50;
830 newUsage.llm.tokens.total += 150;
831 newUsage.llm.apiCalls += 1;
832 newUsage.llm.processingTimeMs += 1000;
833 }
834
835 return newUsage;
836 }
837
838 calculateCost(context: CostCalculationContext): Cost {
839 const newCost = structuredClone(context.previousCost || (context.usage as any));
840
841 // Simple cost calculation: $0.01 per 1000 tokens
842 const tokenCost = (context.usage.llm.tokens.total / 1000) * 0.01;
843 newCost.llm.total = tokenCost;
844 newCost.total = tokenCost;
845 newCost.calculatedAt = new Date().toISOString();
846
847 return newCost;
848 }
849 modelRuntime = async function* () {
850 yield { content: 'test response' };
851 };
852 }
853
854 const agent = new CostTrackingAgent();
855 const runtime = new AgentRuntime(agent);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected