2023-01-04 15:54:25 +00:00
|
|
|
"""Test LLM callbacks."""
|
2023-06-24 18:45:09 +00:00
|
|
|
from langchain.chat_models.fake import FakeListChatModel
|
|
|
|
from langchain.llms.fake import FakeListLLM
|
2023-05-11 18:06:39 +00:00
|
|
|
from langchain.schema import HumanMessage
|
|
|
|
from tests.unit_tests.callbacks.fake_callback_handler import (
|
|
|
|
FakeCallbackHandler,
|
|
|
|
FakeCallbackHandlerWithChatStart,
|
|
|
|
)
|
2023-01-04 15:54:25 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_llm_with_callbacks() -> None:
|
|
|
|
"""Test LLM callbacks."""
|
|
|
|
handler = FakeCallbackHandler()
|
2023-06-24 18:45:09 +00:00
|
|
|
llm = FakeListLLM(callbacks=[handler], verbose=True, responses=["foo"])
|
2023-01-04 15:54:25 +00:00
|
|
|
output = llm("foo")
|
|
|
|
assert output == "foo"
|
|
|
|
assert handler.starts == 1
|
|
|
|
assert handler.ends == 1
|
|
|
|
assert handler.errors == 0
|
2023-05-11 18:06:39 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_chat_model_with_v1_callbacks() -> None:
|
|
|
|
"""Test chat model callbacks fall back to on_llm_start."""
|
|
|
|
handler = FakeCallbackHandler()
|
2023-06-24 18:45:09 +00:00
|
|
|
llm = FakeListChatModel(
|
|
|
|
callbacks=[handler], verbose=True, responses=["fake response"]
|
|
|
|
)
|
2023-05-11 18:06:39 +00:00
|
|
|
output = llm([HumanMessage(content="foo")])
|
|
|
|
assert output.content == "fake response"
|
|
|
|
assert handler.starts == 1
|
|
|
|
assert handler.ends == 1
|
|
|
|
assert handler.errors == 0
|
|
|
|
assert handler.llm_starts == 1
|
|
|
|
assert handler.llm_ends == 1
|
|
|
|
|
|
|
|
|
|
|
|
def test_chat_model_with_v2_callbacks() -> None:
|
|
|
|
"""Test chat model callbacks fall back to on_llm_start."""
|
|
|
|
handler = FakeCallbackHandlerWithChatStart()
|
2023-06-24 18:45:09 +00:00
|
|
|
llm = FakeListChatModel(
|
|
|
|
callbacks=[handler], verbose=True, responses=["fake response"]
|
|
|
|
)
|
2023-05-11 18:06:39 +00:00
|
|
|
output = llm([HumanMessage(content="foo")])
|
|
|
|
assert output.content == "fake response"
|
|
|
|
assert handler.starts == 1
|
|
|
|
assert handler.ends == 1
|
|
|
|
assert handler.errors == 0
|
|
|
|
assert handler.llm_starts == 0
|
|
|
|
assert handler.llm_ends == 1
|
|
|
|
assert handler.chat_model_starts == 1
|