forked from langchain-ai/langchain
-
Notifications
You must be signed in to change notification settings - Fork 0
fix(core): async tracer on_chat_model_start fallback in sync context
#7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
DhirenMhatre
wants to merge
1
commit into
master
Choose a base branch
from
mdrxy/async-tracer
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
155 changes: 155 additions & 0 deletions
155
libs/core/tests/unit_tests/callbacks/test_handle_event.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| """Tests for the `on_chat_model_start` fallback in `handle_event`.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import TYPE_CHECKING, Any | ||
| from uuid import UUID, uuid4 | ||
|
|
||
| from langchain_core.callbacks.manager import handle_event | ||
| from langchain_core.messages import HumanMessage, SystemMessage | ||
| from langchain_core.tracers.base import AsyncBaseTracer | ||
|
|
||
| if TYPE_CHECKING: | ||
| import pytest | ||
|
|
||
| from langchain_core.tracers.schemas import Run | ||
|
|
||
| SERIALIZED = {"id": ["chat_model"]} | ||
|
|
||
|
|
||
| class _NoOpAsyncTracer(AsyncBaseTracer): | ||
| """Async tracer that does NOT override `on_chat_model_start`. | ||
|
|
||
| Records `on_llm_start` calls so the test can verify the fallback fired. | ||
| """ | ||
|
|
||
| def __init__(self) -> None: | ||
| super().__init__() | ||
| self.runs: list[Run] = [] | ||
| self.llm_start_calls: list[dict[str, Any]] = [] | ||
|
|
||
| async def _persist_run(self, run: Run) -> None: | ||
| self.runs.append(run) | ||
|
|
||
| async def on_llm_start( | ||
| self, | ||
| serialized: dict[str, Any], | ||
| prompts: list[str], | ||
| *, | ||
| run_id: UUID, | ||
| **_kwargs: Any, | ||
| ) -> None: | ||
| self.llm_start_calls.append( | ||
| { | ||
| "serialized": serialized, | ||
| "prompts": prompts, | ||
| "run_id": run_id, | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| class _WorkingAsyncTracer(AsyncBaseTracer): | ||
| """Async tracer that DOES override `on_chat_model_start`. | ||
|
|
||
| Used to verify the normal (non-fallback) path still works. | ||
| """ | ||
|
|
||
| def __init__(self) -> None: | ||
| super().__init__() | ||
| self.runs: list[Run] = [] | ||
| self.chat_model_start_calls: list[dict[str, Any]] = [] | ||
|
|
||
| async def _persist_run(self, run: Run) -> None: | ||
| self.runs.append(run) | ||
|
|
||
| async def on_chat_model_start( | ||
| self, | ||
| serialized: dict[str, Any], | ||
| messages: list[list[Any]], | ||
| *, | ||
| run_id: UUID, | ||
| **_kwargs: Any, | ||
| ) -> None: | ||
| self.chat_model_start_calls.append( | ||
| { | ||
| "serialized": serialized, | ||
| "messages": messages, | ||
| "run_id": run_id, | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| def test_async_tracer_falls_back_to_on_llm_start_in_sync_context() -> None: | ||
| """Async tracer without `on_chat_model_start` falls back. | ||
|
|
||
| When `handle_event` is called synchronously with an | ||
| `AsyncBaseTracer` that doesn't implement `on_chat_model_start`, | ||
| the `on_llm_start` callback should fire as a fallback. | ||
| """ | ||
| tracer = _NoOpAsyncTracer() | ||
| run_id = uuid4() | ||
| messages = [[SystemMessage(content="sys"), HumanMessage(content="hi")]] | ||
|
|
||
| handle_event( | ||
| [tracer], | ||
| "on_chat_model_start", | ||
| "ignore_chat_model", | ||
| SERIALIZED, | ||
| messages, | ||
| run_id=run_id, | ||
| ) | ||
|
|
||
| assert len(tracer.llm_start_calls) == 1 | ||
| call = tracer.llm_start_calls[0] | ||
| assert call["serialized"] == SERIALIZED | ||
| # The fallback converts messages to strings via get_buffer_string | ||
| assert isinstance(call["prompts"], list) | ||
| assert len(call["prompts"]) == 1 | ||
| assert isinstance(call["prompts"][0], str) | ||
|
|
||
|
|
||
| def test_async_tracer_no_fallback_when_implemented() -> None: | ||
| """Async tracer WITH `on_chat_model_start` does not fall back. | ||
|
|
||
| When the handler implements `on_chat_model_start`, no fallback | ||
| should be triggered. | ||
| """ | ||
| tracer = _WorkingAsyncTracer() | ||
| run_id = uuid4() | ||
| messages = [[HumanMessage(content="hello")]] | ||
|
|
||
| handle_event( | ||
| [tracer], | ||
| "on_chat_model_start", | ||
| "ignore_chat_model", | ||
| SERIALIZED, | ||
| messages, | ||
| run_id=run_id, | ||
| ) | ||
|
|
||
| assert len(tracer.chat_model_start_calls) == 1 | ||
| call = tracer.chat_model_start_calls[0] | ||
| assert call["serialized"] == SERIALIZED | ||
| assert call["messages"] == messages | ||
|
|
||
|
|
||
| def test_async_tracer_fallback_no_error_logged( | ||
| caplog: pytest.LogCaptureFixture, | ||
| ) -> None: | ||
| """The fallback path should not produce any warning/error logs.""" | ||
| tracer = _NoOpAsyncTracer() | ||
| messages = [[HumanMessage(content="test")]] | ||
|
|
||
| with caplog.at_level("WARNING", logger="langchain_core.callbacks.manager"): | ||
| handle_event( | ||
| [tracer], | ||
| "on_chat_model_start", | ||
| "ignore_chat_model", | ||
| SERIALIZED, | ||
| messages, | ||
| run_id=uuid4(), | ||
| ) | ||
|
|
||
| assert not caplog.records, ( | ||
| f"Expected no warnings but got: {[r.message for r in caplog.records]}" | ||
| ) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
_NoOpAsyncTracerclass inherits fromAsyncBaseTracer, which provides a fully workingon_chat_model_startimplementation. This prevents the intended fallback mechanism from being tested, as the fallback toon_llm_startonly triggers whenon_chat_model_startraisesNotImplementedError. To properly exercise the fallback code path,_NoOpAsyncTracershould inherit fromAsyncCallbackHandlerinstead, which raisesNotImplementedErrorforon_chat_model_start.Also reported at:
libs/core/tests/unit_tests/callbacks/test_handle_event.pyL136–L155Prompt for AI assistance
Copy the prompt below and paste it into ChatGPT, Claude, or any LLM: