diff --git a/claude_bridge_glm.py b/claude_bridge_glm.py index 8ef791a..bfa2fe5 100644 --- a/claude_bridge_glm.py +++ b/claude_bridge_glm.py @@ -740,6 +740,7 @@ async def stream_claude( # Stream from GLM API full_response = "" + _qa_usage: dict = {} proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") try: async with httpx.AsyncClient(timeout=120, proxy=proxy) as client: @@ -750,6 +751,8 @@ async def stream_claude( "model": ZAI_MODEL, "messages": messages, "stream": True, + # usage в финальном чанке стрима (OpenAI-совм.) — питает учёт llm_usage (Ф2). + "stream_options": {"include_usage": True}, "temperature": 0.1, "max_tokens": 4096, "thinking": {"type": "disabled"}, @@ -765,6 +768,16 @@ async def stream_claude( break try: chunk = json.loads(data_str) + if chunk.get("usage"): + # финальный usage-чанк (choices пуст) — переводим в Anthropic-формат Ф2 + _qa_usage = { + "input_tokens": chunk["usage"].get("prompt_tokens", 0), + "cache_read_input_tokens": + (chunk["usage"].get("prompt_tokens_details") or {}).get("cached_tokens", 0), + "output_tokens": chunk["usage"].get("completion_tokens", 0), + } + if not chunk.get("choices"): + continue delta = chunk["choices"][0].get("delta", {}) # GLM-5.1: skip reasoning_content (internal thinking), use only content text = delta.get("content", "") @@ -794,7 +807,10 @@ async def stream_claude( # Assistant response is persisted to the DB by main._stream_and_save — # no separate in-memory history to maintain here. - yield f"event: done\ndata: {json.dumps({'result': full_response}, ensure_ascii=False)}\n\n" + # usage/provider/model — учёт стоимости Ф2 (суффикс '-qa' → path='qa' в llm_usage). + yield ("event: done\ndata: " + json.dumps( + {"result": full_response, "usage": _qa_usage, + "provider": "deepseek-qa", "model": ZAI_MODEL}, ensure_ascii=False) + "\n\n") def list_user_files(username: str, tab_id: str = "default") -> list[dict]: