JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(jiuwenclaw): add model call token and cost data
chenchunzhou36135dd54ef9
diff --git a/jiuwenclaw/agentserver/deep_agent/interface_deep.py b/jiuwenclaw/agentserver/deep_agent/interface_deep.pyindex a5c39de9b7..d48c59b2bc 100644--- a/jiuwenclaw/agentserver/deep_agent/interface_deep.py+++ b/jiuwenclaw/agentserver/deep_agent/interface_deep.py@@ -392,7 +392,6 @@ class JiuWenClawDeepAdapter:return self._model_request_config.model or "unknown"return "unknown"-@staticmethoddef _browser_runtime_enabled() -> bool:"""Whether browser runtime support is enabled for DeepAgent subagent wiring."""@@ -432,7 +431,6 @@ class JiuWenClawDeepAdapter:return value.strip()return ""-@staticmethoddef _is_subagent_enabled(subagent_cfg: Any) -> bool:"""Treat only explicit `enabled: true` as enabled."""@@ -852,8 +850,8 @@ class JiuWenClawDeepAdapter:sandbox_type = _sandbox_config.get("type", None)if sandbox_url and sandbox_type:gateway_config = SandboxGatewayConfig(- isolation=SandboxIsolationConfig(container_scope=ContainerScope.SYSTEM),- launcher_config=PreDeployLauncherConfig(+ isolation=SandboxIsolationConfig(container_scope=ContainerScope.SYSTEM),+ launcher_config=PreDeployLauncherConfig(base_url=sandbox_url,sandbox_type=sandbox_type,idle_ttl_seconds=600,@@ -1086,7 +1084,7 @@ class JiuWenClawDeepAdapter:rail = Nonereturn rail- def _build_agent_rails(self, config: dict[str, Any], config_base: dict[str, Any], *,+ def _build_agent_rails(self, config: dict[str, Any], config_base: dict[str, Any], *,mode: str = "agent.plan") -> list[Any]:"""Build DeepAgent rails consistently for cold start and hot reload."""@@ -1267,8 +1265,8 @@ class JiuWenClawDeepAdapter:# 付费搜索工具:有任意一个付费 key 就注册if any(- os.environ.get(key)- for key in ("BOCHA_API_KEY", "PERPLEXITY_API_KEY", "SERPER_API_KEY", "JINA_API_KEY")+ os.environ.get(key)+ for key in ("BOCHA_API_KEY", "PERPLEXITY_API_KEY", "SERPER_API_KEY", "JINA_API_KEY")):self._paid_search_tool = WebPaidSearchTool(language=self._resolve_runtime_language(), agent_id=agent_id)Runner.resource_mgr.add_tool(self._paid_search_tool)@@ -1647,9 +1645,9 @@ class JiuWenClawDeepAdapter:async def _update_agent_mode_rails(self) -> None:"""agent 模式:卸载 plan 专属 rails,按需注册 agent 专属 rails。"""for attr, label in (- ("_task_planning_rail", "TaskPlanningRail"),- ("_skill_evolution_rail", "SkillEvolutionRail"),- ("_subagent_rail", "SubagentRail"),+ ("_task_planning_rail", "TaskPlanningRail"),+ ("_skill_evolution_rail", "SkillEvolutionRail"),+ ("_subagent_rail", "SubagentRail"),):rail = getattr(self, attr)if rail is not None:@@ -1901,15 +1899,15 @@ class JiuWenClawDeepAdapter:if perm_ctx is not None:# 判断是否为群聊数字分身模式is_group_digital_avatar = (- perm_ctx.group_digital_avatar- and perm_ctx.avatar_mode+ perm_ctx.group_digital_avatar+ and perm_ctx.avatar_mode)# 判断是否为记忆完全禁用(三个条件同时满足)should_disable_memory = (- not perm_ctx.enable_memory- and perm_ctx.group_digital_avatar- and perm_ctx.avatar_mode+ not perm_ctx.enable_memory+ and perm_ctx.group_digital_avatar+ and perm_ctx.avatar_mode)# 场景2:记忆完全禁用 - 移除所有记忆工具@@ -2483,8 +2481,8 @@ class JiuWenClawDeepAdapter:if dry_run:return {"output": (- f"**Skill '{skill_name}' 整理预览(dry-run,未执行):**\n\n"- + "\n".join(summary_lines)+ f"**Skill '{skill_name}' 整理预览(dry-run,未执行):**\n\n"+ + "\n".join(summary_lines)),"result_type": "answer",}@@ -2494,8 +2492,8 @@ class JiuWenClawDeepAdapter:)return {"output": (- f"**Skill '{skill_name}' 整理完成:** {result_text}\n\n"- f"**操作详情:**\n" + "\n".join(summary_lines)+ f"**Skill '{skill_name}' 整理完成:** {result_text}\n\n"+ f"**操作详情:**\n" + "\n".join(summary_lines)),"result_type": "answer",}@@ -2729,7 +2727,7 @@ class JiuWenClawDeepAdapter:# Team 模式处理if mode == "team":from jiuwenclaw.agentserver.deep_agent.team_helpers import process_team_message_stream-+async for chunk in process_team_message_stream(request, inputs, self._instance):yield chunkreturn@@ -2767,6 +2765,14 @@ class JiuWenClawDeepAdapter:accumulated_reasoning = ""evolution_status_started = Falseevolution_status_ended = False+ usage_accumulator = {+ "input_tokens": 0,+ "output_tokens": 0,+ "total_tokens": 0,+ "input_cost": 0.0,+ "output_cost": 0.0,+ "total_cost": 0.0,+ }cron_context_tokens = self._bind_runtime_cron_context(channel_id=request.channel_id,@@ -2817,6 +2823,23 @@ class JiuWenClawDeepAdapter:chunk_type = chunk.type+ if chunk_type == "llm_usage":+ logger.info(f"[JiuWenClawDeepAdapter] llm_usage chunk: {chunk}")+ usage_meta = chunk.payload.get("usage_metadata", {}) if isinstance(chunk.payload, dict) else {}+ if isinstance(usage_meta, dict):+ for token in ("input_tokens", "output_tokens", "total_tokens"):+ usage_accumulator[token] += usage_meta.get(token, 0) or 0+ for cost in ("input_cost", "output_cost", "total_cost"):+ usage_accumulator[cost] += usage_meta.get(cost, 0.0) or 0.0+ yield AgentResponseChunk(+ request_id=rid,+ channel_id=cid,+ payload={"event_type": "chat.usage_metadata", "metadata": chunk.payload,+ "session_id": session_id},+ is_complete=False,+ )+ continue+if chunk_type == "llm_reasoning":content = ((chunk.payload.get("content", "") or chunk.payload.get("output", ""))@@ -2988,6 +3011,33 @@ class JiuWenClawDeepAdapter:cleanup_permission_context(token_perm)self._reset_runtime_cron_context(cron_context_tokens)+ summary = {+ "input_tokens": usage_accumulator["input_tokens"],+ "output_tokens": usage_accumulator["output_tokens"],+ "total_tokens": usage_accumulator["total_tokens"],+ }+ if usage_accumulator["input_cost"] > 0:+ summary["input_cost"] = round(usage_accumulator["input_cost"], 6)+ if usage_accumulator["output_cost"] > 0:+ summary["output_cost"] = round(usage_accumulator["output_cost"], 6)+ if usage_accumulator["total_cost"] > 0:+ summary["total_cost"] = round(usage_accumulator["total_cost"], 6)++ logger.info("[JiuWenClawDeepAdapter] llm_usage summary: request_id=%s session_id=%s usage=%s",+ rid, session_id, summary)++ if usage_accumulator["total_tokens"] > 0:+ yield AgentResponseChunk(+ request_id=rid,+ channel_id=cid,+ payload={+ "event_type": "chat.usage_summary",+ "session_id": session_id,+ "usage": summary,+ },+ is_complete=False,+ )+yield AgentResponseChunk(request_id=rid,channel_id=cid,diff --git a/jiuwenclaw/channel/web_channel.py b/jiuwenclaw/channel/web_channel.pyindex d4991649c0..db9b36634b 100644--- a/jiuwenclaw/channel/web_channel.py+++ b/jiuwenclaw/channel/web_channel.py@@ -99,14 +99,14 @@ class WebChannel(BaseChannel):# ── 帧发送 API(公开给处理器使用)─────────────────────async def send_response(- self,- ws: Any,- req_id: str,- *,- ok: bool,- payload: dict[str, Any] | None = None,- error: str | None = None,- code: str | None = None,+ self,+ ws: Any,+ req_id: str,+ *,+ ok: bool,+ payload: dict[str, Any] | None = None,+ error: str | None = None,+ code: str | None = None,) -> None:"""向指定客户端发送 ``res`` 帧."""frame: dict[str, Any] = {@@ -128,13 +128,13 @@ class WebChannel(BaseChannel):raiseasync def send_event(- self,- ws: Any,- event: str,- payload: dict[str, Any],- *,- seq: int | None = None,- stream_id: str | None = None,+ self,+ ws: Any,+ event: str,+ payload: dict[str, Any],+ *,+ seq: int | None = None,+ stream_id: str | None = None,) -> None:"""向指定客户端发送 ``event`` 帧."""frame: dict[str, Any] = {"type": "event", "event": event, "payload": payload}@@ -151,12 +151,12 @@ class WebChannel(BaseChannel):raiseasync def broadcast_event(- self,- event: str,- payload: dict[str, Any],- *,- seq: int | None = None,- stream_id: str | None = None,+ self,+ event: str,+ payload: dict[str, Any],+ *,+ seq: int | None = None,+ stream_id: str | None = None,) -> None:"""向所有已连接客户端广播 ``event`` 帧."""frame: dict[str, Any] = {"type": "event", "event": event, "payload": payload}@@ -311,11 +311,12 @@ class WebChannel(BaseChannel):if isinstance(msg.payload, dict):# 对于需要传递完整结构化数据的事件类型if event_name in ("connection.ack", "todo.updated", "chat.tool_call", "chat.tool_result",- "chat.processing_status", "chat.interrupt_result", "chat.evolution_status",- "chat.error", "heartbeat.relay",- "context.compressed", "chat.ask_user_question", "chat.subtask_update",- "history.message",- "chat.session_result") or event_name.startswith("team."):+ "chat.processing_status", "chat.interrupt_result", "chat.evolution_status",+ "chat.error", "heartbeat.relay",+ "context.compressed", "chat.ask_user_question", "chat.subtask_update",+ "history.message",+ "chat.session_result", "chat.usage_metadata",+ "chat.usage_summary") or event_name.startswith("team."):# 传递完整 payload,保留所有字段payload = {**msg.payload}# 确保包含 session_iddiff --git a/jiuwenclaw/jiuwen_core_patch.py b/jiuwenclaw/jiuwen_core_patch.pyindex a8b48e6ce2..b1ba6ff517 100644--- a/jiuwenclaw/jiuwen_core_patch.py+++ b/jiuwenclaw/jiuwen_core_patch.py@@ -95,11 +95,17 @@ class PatchOpenAIModelClient(OpenAIModelClient):# Build usage_metadata (usually only in the last chunk)usage_metadata = Noneif hasattr(chunk, 'usage') and chunk.usage:+ # Extract cost information if available+ input_cost, output_cost, total_cost = self._extract_cost_info(chunk.usage)+usage_metadata = UsageMetadata(model_name=self.model_config.model_name,input_tokens=getattr(chunk.usage, 'prompt_tokens', 0) or 0,output_tokens=getattr(chunk.usage, 'completion_tokens', 0) or 0,- total_tokens=getattr(chunk.usage, 'total_tokens', 0) or 0+ total_tokens=getattr(chunk.usage, 'total_tokens', 0) or 0,+ input_cost=input_cost,+ output_cost=output_cost,+ total_cost=total_cost,)return AssistantMessageChunk(diff --git a/jiuwenclaw/schema/message.py b/jiuwenclaw/schema/message.pyindex 7370d9cc18..e50fb2c72f 100644--- a/jiuwenclaw/schema/message.py+++ b/jiuwenclaw/schema/message.py@@ -119,6 +119,8 @@ class EventType(Enum):HELLO = "hello"CHAT_DELTA = "chat.delta"CHAT_REASONING = "chat.reasoning"+ CHAT_USAGE_METADATA = "chat.usage_metadata"+ CHAT_USAGE_SUMMARY = "chat.usage_summary"CHAT_FINAL = "chat.final"CHAT_MEDIA = "chat.media"CHAT_FILE = "chat.file"diff --git a/jiuwenclaw/web/src/components/ChatPanel/MessageItem.tsx b/jiuwenclaw/web/src/components/ChatPanel/MessageItem.tsxindex c4b410baa1..7003057bd3 100644--- a/jiuwenclaw/web/src/components/ChatPanel/MessageItem.tsx+++ b/jiuwenclaw/web/src/components/ChatPanel/MessageItem.tsx@@ -420,6 +420,24 @@ export function MessageItem({ message, autoSpeak = false }: MessageItemProps) {)}</div>+ {/* Token usage summary */}+ {!isUser && !isStreaming && message.usageSummary && message.usageSummary.total_tokens > 0 && (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-0.5 text-xs text-text-muted mt-1 mb-0.5">+ <span>+ {message.usageSummary.input_tokens.toLocaleString()} in /{' '}+ {message.usageSummary.output_tokens.toLocaleString()} out /{' '}+ {message.usageSummary.total_tokens.toLocaleString()} total+ </span>+ {message.usageSummary.total_cost != null && message.usageSummary.total_cost > 0 && (+ <span>+ ${message.usageSummary.input_cost?.toFixed(4)} in /{' '}+ ${message.usageSummary.output_cost?.toFixed(4)} out /{' '}+ ${message.usageSummary.total_cost.toFixed(4)} total+ </span>+ )}+ </div>+ )}+{/* 时间戳和操作 */}<divclassName={clsx(@@ -467,4 +485,4 @@ export function MessageItem({ message, autoSpeak = false }: MessageItemProps) {</div></div>);-}+}\ No newline at end of filediff --git a/jiuwenclaw/web/src/features/historyRestore.ts b/jiuwenclaw/web/src/features/historyRestore.tsindex 572d8fa18d..96ff573cb5 100644--- a/jiuwenclaw/web/src/features/historyRestore.ts+++ b/jiuwenclaw/web/src/features/historyRestore.ts@@ -1,4 +1,4 @@-import { Message, MessageRole, WsEvent } from '../types';+import { Message, MessageRole, UsageSummary, WsEvent } from '../types';import { webClient } from '../services/webClient';import { normalizeFinalContent } from '../utils/finalContent';@@ -10,6 +10,7 @@ const ALLOWED_ASSISTANT_EVENT_TYPES = new Set(['chat.final','chat.tool_call','chat.tool_result',+ 'chat.usage_summary',]);/** 后端约定:最后一帧 `history.message` 使用 `payload.status: done`(兼容旧版 `payload.content: done`) */@@ -26,7 +27,8 @@ export interface HistoryToolReplayItem {type HistoryTimelineEntry =| { kind: 'message'; message: Message }| { kind: 'tool_call'; at: string; payload: Record<string, unknown> }- | { kind: 'tool_result'; at: string; payload: Record<string, unknown> };+ | { kind: 'tool_result'; at: string; payload: Record<string, unknown> }+ | { kind: 'usage_summary'; at: string; usage: UsageSummary };interface BeginHistoryRestoreOptions {sessionId: string;@@ -232,6 +234,22 @@ function parseHistoryTimelineEntry(return { kind: 'tool_result', at, payload };}+ if (eventType === 'chat.usage_summary') {+ const rawUsage = payload.usage;+ if (isRecord(rawUsage)) {+ const usage: UsageSummary = {+ input_tokens: typeof rawUsage.input_tokens === 'number' ? rawUsage.input_tokens : 0,+ output_tokens: typeof rawUsage.output_tokens === 'number' ? rawUsage.output_tokens : 0,+ total_tokens: typeof rawUsage.total_tokens === 'number' ? rawUsage.total_tokens : 0,+ };+ if (typeof rawUsage.input_cost === 'number') usage.input_cost = rawUsage.input_cost;+ if (typeof rawUsage.output_cost === 'number') usage.output_cost = rawUsage.output_cost;+ if (typeof rawUsage.total_cost === 'number') usage.total_cost = rawUsage.total_cost;+ return { kind: 'usage_summary', at, usage };+ }+ return null;+ }+return null;}@@ -371,6 +389,13 @@ export function beginHistoryRestore(options: BeginHistoryRestoreOptions): Historfor (const e of entries) {if (e.kind === 'message') {messages.push(e.message);+ } else if (e.kind === 'usage_summary') {+ for (let i = messages.length - 1; i >= 0; i--) {+ if (messages[i].role === 'assistant') {+ messages[i] = { ...messages[i], usageSummary: e.usage };+ break;+ }+ }} else {toolReplay.push({ kind: e.kind, at: e.at, payload: e.payload });}@@ -489,6 +514,13 @@ export function fetchHistoryPage(options: FetchHistoryPageOptions): HistoryRestofor (const e of entries) {if (e.kind === 'message') {messages.push(e.message);+ } else if (e.kind === 'usage_summary') {+ for (let i = messages.length - 1; i >= 0; i--) {+ if (messages[i].role === 'assistant') {+ messages[i] = { ...messages[i], usageSummary: e.usage };+ break;+ }+ }} else {toolReplay.push({ kind: e.kind, at: e.at, payload: e.payload });}@@ -507,4 +539,4 @@ export function fetchHistoryPage(options: FetchHistoryPageOptions): HistoryRestoactiveRestore = handle;activePageFetchDispose = dispose;return handle;-}+}\ No newline at end of filediff --git a/jiuwenclaw/web/src/hooks/useWebSocket.ts b/jiuwenclaw/web/src/hooks/useWebSocket.tsindex 4655d0933c..d992f6624e 100644--- a/jiuwenclaw/web/src/hooks/useWebSocket.ts+++ b/jiuwenclaw/web/src/hooks/useWebSocket.ts@@ -21,6 +21,7 @@ import {Session,ToolResult,ToolCall,+ UsageSummary,} from '../types';import { useChatStore, useTodoStore, useSessionStore } from '../stores';import { webClient } from '../services/webClient';@@ -966,6 +967,32 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {}}}),+ webClient.on('chat.usage_summary', ({ payload }) => {+ console.log('[usage_summary] received:', payload);+ if (!shouldHandleSessionEvent(payload)) {+ console.log('[usage_summary] filtered by session check');+ return;+ }+ const usage = payload.usage as UsageSummary | undefined;+ if (!usage) {+ console.log('[usage_summary] no usage field in payload');+ return;+ }+ const { currentStreamId, messages } = useChatStore.getState();+ let targetId = currentStreamId;+ if (!targetId) {+ for (let i = messages.length - 1; i >= 0; i--) {+ if (messages[i].role === 'assistant') {+ targetId = messages[i].id;+ break;+ }+ }+ }+ console.log('[usage_summary] targetId:', targetId, 'usage:', usage);+ if (targetId) {+ useChatStore.getState().setUsageSummary(targetId, usage);+ }+ }),];return () => {@@ -1116,4 +1143,4 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {sendUserAnswer,getInflightCount: () => webClient.getInflightCount(),};-}+}\ No newline at end of filediff --git a/jiuwenclaw/web/src/stores/chatStore.ts b/jiuwenclaw/web/src/stores/chatStore.tsindex 8486103a08..d32fc77f48 100644--- a/jiuwenclaw/web/src/stores/chatStore.ts+++ b/jiuwenclaw/web/src/stores/chatStore.ts@@ -12,6 +12,7 @@ import {InterruptResultPayload,SubtaskUpdatePayload,AskUserQuestionPayload,+ UsageSummary,} from '../types';import { useTodoStore } from './todoStore';@@ -97,6 +98,8 @@ interface ChatState {setPendingQuestion: (question: AskUserQuestionPayload | null) => void;// 输入框相关setInputValue: (value: string) => void;+ // Usage summary+ setUsageSummary: (messageId: string, usage: UsageSummary) => void;}export const useChatStore = create<ChatState>((set, get) => ({@@ -518,4 +521,12 @@ export const useChatStore = create<ChatState>((set, get) => ({setInputValue: (value) => {set({ inputValue: value });},-}));++ setUsageSummary: (messageId, usage) => {+ set((state) => ({+ messages: state.messages.map((msg) =>+ msg.id === messageId ? { ...msg, usageSummary: usage } : msg+ ),+ }));+ },+}));\ No newline at end of filediff --git a/jiuwenclaw/web/src/types/message.ts b/jiuwenclaw/web/src/types/message.tsindex 25fb700920..6e42a4dd8e 100644--- a/jiuwenclaw/web/src/types/message.ts+++ b/jiuwenclaw/web/src/types/message.ts@@ -12,6 +12,15 @@ export interface MediaItem {url?: string;}+export interface UsageSummary {+ input_tokens: number;+ output_tokens: number;+ total_tokens: number;+ input_cost?: number;+ output_cost?: number;+ total_cost?: number;+}+export interface Message {id: string;role: MessageRole;@@ -25,6 +34,7 @@ export interface Message {toolResult?: ToolResult;// 是否正在流式输出isStreaming?: boolean;+ usageSummary?: UsageSummary;}export interface ToolCall {@@ -62,4 +72,4 @@ export interface Conversation {messages: Message[];createdAt: string;updatedAt: string;-}+}\ No newline at end of file