[BUG] EvaluationTraceCallback registers duplicate event handlers and duplicates recorded tool/LLM trace entries

Đang mở
#9,813 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

@iridite đang làm issue này rồi.

Từ ngày 26/11/2026.

  • #9814 của @iridite — đang mở

Đánh giá

Độ khó
2/5
Thời gian dự kiến
1-3 giờ
Mức phù hợp với người mới
35/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Đình trệ
Công nghệ
python
Lĩnh vực
ai-infra-agents

Hướng nghiên cứu

Read crewai/experimental/evaluation/evaluation_listener.py and the event bus handler registration code mentioned in the issue. Reproduce the duplicate entries with the supplied snippet, then check the linked pull request for the proposed fix and its tests. Done means each emitted tool or LLM event is recorded once, including after scoped handlers are cleared and reattached.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

Description

EvaluationTraceCallback is a singleton subclass of BaseEventListener, whose __init__() already calls self.setup_listeners(crewai_event_bus). However, create_evaluation_callbacks() (called on every AgentEvaluator(...) instantiation) calls callback.setup_listeners(crewai_event_bus) again.

Because EvaluationTraceCallback.setup_listeners() creates new nested closure functions on every call, crewai_event_bus._register_handler() (frozenset | {handler}) treats them as distinct handlers and appends duplicate closures every time:

  • On the first call to create_evaluation_callbacks() / AgentEvaluator(...), handlers are registered twice (BaseEventListener.__init__ + create_evaluation_callbacks()).
  • On each subsequent create_evaluation_callbacks() / AgentEvaluator(...), another full set of closures is added (N + 1 copies total).

As a result, each emitted ToolUsageFinishedEvent, ToolUsageErrorEvent, ToolExecutionErrorEvent, ToolSelectionErrorEvent, ToolValidateInputErrorEvent, and LLMCallCompletedEvent is appended multiple times into trace["tool_uses"] and trace["llm_calls"], skewing tool counts, error rates, and token sums in downstream evaluators (ToolSelectionEvaluator, ParameterExtractionEvaluator, ToolInvocationEvaluator, ReasoningEfficiencyEvaluator).

Steps to Reproduce
from datetime import datetime
from crewai.agent import Agent
from crewai.task import Task
from crewai.events.event_bus import crewai_event_bus
from crewai.events.types.tool_usage_events import ToolUsageFinishedEvent
from crewai.experimental.evaluation.evaluation_listener import (
    EvaluationTraceCallback,
    create_evaluation_callbacks,
)

with crewai_event_bus.scoped_handlers():
    EvaluationTraceCallback._instance = None
    EvaluationTraceCallback._initialized = False

    cb1 = create_evaluation_callbacks()
    cb2 = create_evaluation_callbacks()
    agent = Agent(role="Researcher", goal="Find facts", backstory="Researcher")
    task = Task(description="Check trace", expected_output="Done", agent=agent)
    cb1.on_agent_start(agent, task)

    now = datetime.now()
    crewai_event_bus.emit(
        agent,
        ToolUsageFinishedEvent(
            tool_name="search",
            tool_args={"query": "crewai"},
            output="ok",
            started_at=now,
            finished_at=now,
        ),
    )
    crewai_event_bus.flush()
    print(len(cb1.get_trace(str(agent.id), str(task.id))["tool_uses"]))
    # Prints 3 instead of 1
Expected behavior

Each emitted tool-use or LLM-call event is recorded at most once per EvaluationTraceCallback singleton, regardless of whether create_evaluation_callbacks() / AgentEvaluator() is called once or multiple times, while still re-attaching cleanly if crewai_event_bus.scoped_handlers() clears handlers between runs.

Screenshots/Code snippets

See minimal reproduction snippet above.

Operating System

Other (specify in additional context)

Python Version

3.12

crewAI Version

1.15.45

crewAI Tools Version

N/A (not installed)

Virtual Environment

Venv

Evidence

Reproduced on main @ 77237ae: emitting 2 tool events after two create_evaluation_callbacks() calls records len(trace["tool_uses"]) == 6 (AssertionError: assert 6 == 2).

Possible Solution

Build and cache the listener (event_type, handler) callables once on EvaluationTraceCallback (in _get_listeners()) and register them via event_bus.register_handler(event_type, handler) inside setup_listeners(). Because CrewAIEventsBus._register_handler stores handlers in a frozenset, reusing the same handler references makes repeated setup_listeners(event_bus) calls idempotent while still allowing scoped_handlers() scopes to re-register the singleton handlers once.

Additional context
  • Verified locally on macOS with Python 3.13.14 (uv).
  • Note: AI-assisted diagnosis and test reproduction.
Ngôn ngữ chính
Python
Star
61.2k
Fork
9.2k
Merge trung bình
1 ngày 14 giờ
Pull request đã merge (30 ngày)
180

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của crewAIInc/crewAI

Tất cả issue của crewAIInc/crewAI

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.