mirror of
https://github.com/agent0ai/agent-zero.git
synced 2026-05-04 22:50:54 +00:00
60 lines
2 KiB
Python
60 lines
2 KiB
Python
"""API handler for chat compaction."""
|
|
from helpers.api import ApiHandler, Input, Output, Request, Response
|
|
from agent import AgentContext
|
|
from plugins._chat_compaction.helpers.compactor import (
|
|
get_compaction_stats,
|
|
run_compaction,
|
|
)
|
|
|
|
|
|
class CompactChat(ApiHandler):
|
|
"""Compact the current chat history into a summarized message."""
|
|
|
|
async def process(self, input: Input, request: Request) -> Output:
|
|
ctxid = input.get("context", "")
|
|
action = input.get("action", "compact")
|
|
|
|
if not ctxid:
|
|
return Response("Missing context id", 400)
|
|
|
|
context = AgentContext.get(ctxid)
|
|
if not context:
|
|
return Response("Context not found", 404)
|
|
|
|
if context.is_running():
|
|
return Response("Cannot compact while agent is running", 409)
|
|
|
|
visible_count = len(context.log.logs)
|
|
if visible_count <= 1:
|
|
return Response("Not enough messages to compact", 400)
|
|
|
|
if action == "stats":
|
|
stats = await get_compaction_stats(context)
|
|
return {"ok": True, "stats": stats}
|
|
|
|
elif action == "compact":
|
|
from helpers.plugins import get_plugin_config
|
|
agent = context.agent0
|
|
plugin_config = get_plugin_config("_chat_compaction", agent=agent) or {}
|
|
use_chat_model = plugin_config.get("use_chat_model", True)
|
|
|
|
context.run_task(_run_compaction_task, context, use_chat_model)
|
|
|
|
return {"ok": True, "message": "Compaction started"}
|
|
|
|
else:
|
|
return Response(f"Unknown action: {action}", 400)
|
|
|
|
|
|
async def _run_compaction_task(context, use_chat_model: bool):
|
|
"""Wrapper to run compaction and handle errors."""
|
|
try:
|
|
await run_compaction(context, use_chat_model)
|
|
except Exception as e:
|
|
context.log.log(
|
|
type="error",
|
|
heading="Compaction Failed",
|
|
content=str(e),
|
|
)
|
|
from helpers.state_monitor_integration import mark_dirty_all
|
|
mark_dirty_all(reason="plugins._chat_compaction.compact_chat_error")
|