mirror of
https://github.com/open-webui/computer.git
synced 2026-11-23 06:00:43 -05:00
refac
This commit is contained in:
1 parent
2b32568c37
commit
74a1c26713
3 files changed
+50
-8
No files matched your search
+16
-4
@@ -234,12 +234,18 @@ async def stream_anthropic(
|
||||
logger.info("[stream] anthropic status=%s", resp.status_code)
|
||||
resp.raise_for_status()
|
||||
current_block: dict = {}
|
||||
usage_data: dict = {}
|
||||
async for line in resp.aiter_lines():
|
||||
if not line.startswith("data: "):
|
||||
continue
|
||||
event = json.loads(line[6:])
|
||||
etype = event.get("type")
|
||||
|
||||
if etype == "message_start":
|
||||
msg_usage = event.get("message", {}).get("usage", {})
|
||||
if msg_usage:
|
||||
usage_data["input_tokens"] = msg_usage.get("input_tokens", 0)
|
||||
|
||||
if etype == "content_block_start":
|
||||
block = event["content_block"]
|
||||
current_block = {"type": block["type"], "index": event["index"]}
|
||||
@@ -267,10 +273,11 @@ async def stream_anthropic(
|
||||
}
|
||||
|
||||
elif etype == "message_delta":
|
||||
usage = event.get("usage", {})
|
||||
if usage:
|
||||
delta_usage = event.get("usage", {})
|
||||
if delta_usage:
|
||||
usage_data["output_tokens"] = delta_usage.get("output_tokens", 0)
|
||||
emitted = True
|
||||
yield {"type": "usage", **usage}
|
||||
yield {"type": "usage", **usage_data}
|
||||
|
||||
elif etype == "message_stop":
|
||||
emitted = True
|
||||
@@ -392,8 +399,13 @@ async def stream_openai_completions(
|
||||
}
|
||||
|
||||
if chunk.get("usage"):
|
||||
raw = chunk["usage"]
|
||||
emitted = True
|
||||
yield {"type": "usage", **chunk["usage"]}
|
||||
yield {
|
||||
"type": "usage",
|
||||
"input_tokens": raw.get("prompt_tokens", 0),
|
||||
"output_tokens": raw.get("completion_tokens", 0),
|
||||
}
|
||||
|
||||
emitted = True
|
||||
yield {"type": "done"}
|
||||
|
||||
@@ -726,9 +726,12 @@ async def run_chat_task(
|
||||
if "tool_approval_mode" not in chat_params and "auto_approve_tools" in chat_params:
|
||||
approval_mode = "full" if chat_params["auto_approve_tools"] else "auto"
|
||||
|
||||
last_usage: dict | None = None # real usage from last API call
|
||||
new_messages_since: int = 0 # messages appended since last API call
|
||||
|
||||
for _iteration in range(CHAT_MAX_ITERATIONS):
|
||||
# ── Context compaction: summarize older messages if too large ──
|
||||
if should_compact(messages, system):
|
||||
if should_compact(messages, system, last_usage, new_messages_since):
|
||||
target_keep = max(2, len(messages) * 2 // 5)
|
||||
split_idx = _find_safe_split(messages, target_keep)
|
||||
drop_zone = messages[:split_idx]
|
||||
@@ -749,6 +752,8 @@ async def run_chat_task(
|
||||
system = _load_system_prompt(workspace)
|
||||
system += f"\n\n[CONVERSATION SUMMARY]\n{summary}"
|
||||
messages = keep_zone
|
||||
last_usage = None # reset after compaction
|
||||
new_messages_since = 0
|
||||
|
||||
logger.info(
|
||||
"[task %s] compacted: dropped %d msgs, kept %d, summary=%d chars",
|
||||
@@ -829,6 +834,7 @@ async def run_chat_task(
|
||||
|
||||
# Append to messages for next iteration
|
||||
_append_tool_to_messages(messages, event, result, provider)
|
||||
new_messages_since += 2 # tool_call + tool_result
|
||||
restart = True
|
||||
break
|
||||
|
||||
@@ -852,6 +858,8 @@ async def run_chat_task(
|
||||
elif event["type"] == "usage":
|
||||
_flush_text()
|
||||
usage = {k: v for k, v in event.items() if k != "type"}
|
||||
last_usage = usage
|
||||
new_messages_since = 0
|
||||
logger.info(
|
||||
"[task %s] save (usage): content=%d chars, output=%d items, types=%s",
|
||||
message_id[:8],
|
||||
|
||||
+25
-3
@@ -34,10 +34,32 @@ def estimate_messages_tokens(messages: list[dict]) -> int:
|
||||
return total
|
||||
|
||||
|
||||
def should_compact(messages: list[dict], system_prompt: str) -> bool:
|
||||
"""True when estimated tokens exceed the compact token threshold."""
|
||||
def should_compact(
|
||||
messages: list[dict],
|
||||
system_prompt: str,
|
||||
last_usage: dict | None = None,
|
||||
new_messages_since: int = 0,
|
||||
) -> bool:
|
||||
"""True when estimated tokens exceed the compact token threshold.
|
||||
|
||||
If last_usage is provided (real data from the previous API call),
|
||||
uses actual input_tokens + output_tokens as the base and only
|
||||
estimates the new messages appended since that call.
|
||||
Falls back to full estimation when no usage data exists.
|
||||
"""
|
||||
threshold = _get_threshold()
|
||||
|
||||
if last_usage and last_usage.get("input_tokens"):
|
||||
# Real base from last API call + estimate only new additions
|
||||
base = last_usage["input_tokens"] + last_usage.get("output_tokens", 0)
|
||||
if new_messages_since > 0:
|
||||
new_msgs = messages[-new_messages_since:]
|
||||
base += estimate_messages_tokens(new_msgs)
|
||||
return base > threshold
|
||||
|
||||
# Full estimation fallback
|
||||
total = estimate_tokens(system_prompt) + estimate_messages_tokens(messages)
|
||||
return total > _get_threshold()
|
||||
return total > threshold
|
||||
|
||||
|
||||
def _get_threshold() -> int:
|
||||
|
||||
Reference in new issue
Block a user