tool_events.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """工具调用事件追踪"""
  2. from __future__ import annotations
  3. import logging
  4. import re
  5. from pathlib import Path
  6. from threading import Lock
  7. from typing import Any, Callable, Optional
  8. logger = logging.getLogger(__name__)
  9. class ToolCallTracker:
  10. """收集 Agent 工具调用事件,供日志与前端展示"""
  11. def __init__(self, notes_workspace: Optional[str] = None) -> None:
  12. self._notes_workspace = notes_workspace
  13. self._events: list[dict[str, Any]] = []
  14. self._cursor = 0
  15. self._lock = Lock()
  16. self._event_sink: Optional[Callable[[dict[str, Any]], None]] = None
  17. def record(self, payload: dict[str, Any]) -> None:
  18. agent_name = str(payload.get("agent_name") or "unknown")
  19. tool_name = str(payload.get("tool_name") or "unknown")
  20. parameters = payload.get("parsed_parameters") or {}
  21. if not isinstance(parameters, dict):
  22. parameters = {}
  23. result_text = str(payload.get("result") or "")
  24. note_id = None
  25. if tool_name == "note":
  26. note_id = parameters.get("note_id") or self._extract_note_id(result_text)
  27. event = {
  28. "id": len(self._events) + 1,
  29. "agent": agent_name,
  30. "tool": tool_name,
  31. "parameters": parameters,
  32. "result": result_text[:500],
  33. "note_id": note_id,
  34. }
  35. with self._lock:
  36. self._events.append(event)
  37. logger.info("Tool call: agent=%s tool=%s note_id=%s",
  38. agent_name, tool_name, note_id)
  39. if self._event_sink:
  40. self._event_sink(event)
  41. def drain(self) -> list[dict[str, Any]]:
  42. with self._lock:
  43. new = self._events[self._cursor:]
  44. self._cursor = len(self._events)
  45. return new
  46. def set_event_sink(self, sink: Optional[Callable[[dict[str, Any]], None]]) -> None:
  47. self._event_sink = sink
  48. def as_dicts(self) -> list[dict[str, Any]]:
  49. with self._lock:
  50. return list(self._events)
  51. @staticmethod
  52. def _extract_note_id(response: str) -> Optional[str]:
  53. if not response:
  54. return None
  55. match = re.search(r"ID:\s*([^\n]+)", response)
  56. return match.group(1).strip() if match else None