test_vertex_ai.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from unittest.mock import MagicMock, patch
  2. import pytest
  3. from langchain.schema import HumanMessage, SystemMessage
  4. from embedchain.config import BaseLlmConfig
  5. from embedchain.core.db.database import database_manager
  6. from embedchain.llm.vertex_ai import VertexAILlm
  7. @pytest.fixture(autouse=True)
  8. def setup_database():
  9. database_manager.setup_engine()
  10. @pytest.fixture
  11. def vertexai_llm():
  12. config = BaseLlmConfig(temperature=0.6, model="chat-bison")
  13. return VertexAILlm(config)
  14. def test_get_llm_model_answer(vertexai_llm):
  15. with patch.object(VertexAILlm, "_get_answer", return_value="Test Response") as mock_method:
  16. prompt = "Test Prompt"
  17. response = vertexai_llm.get_llm_model_answer(prompt)
  18. assert response == "Test Response"
  19. mock_method.assert_called_once_with(prompt, vertexai_llm.config)
  20. def test_get_llm_model_answer_with_token_usage(vertexai_llm):
  21. test_config = BaseLlmConfig(
  22. temperature=vertexai_llm.config.temperature,
  23. max_tokens=vertexai_llm.config.max_tokens,
  24. top_p=vertexai_llm.config.top_p,
  25. model=vertexai_llm.config.model,
  26. token_usage=True,
  27. )
  28. vertexai_llm.config = test_config
  29. with patch.object(
  30. VertexAILlm,
  31. "_get_answer",
  32. return_value=("Test Response", {"prompt_token_count": 1, "candidates_token_count": 2}),
  33. ):
  34. response, token_info = vertexai_llm.get_llm_model_answer("Test Query")
  35. assert response == "Test Response"
  36. assert token_info == {
  37. "prompt_tokens": 1,
  38. "completion_tokens": 2,
  39. "total_tokens": 3,
  40. "total_cost": 3.75e-07,
  41. "cost_currency": "USD",
  42. }
  43. @patch("embedchain.llm.vertex_ai.ChatVertexAI")
  44. def test_get_answer(mock_chat_vertexai, vertexai_llm, caplog):
  45. mock_chat_vertexai.return_value.invoke.return_value = MagicMock(content="Test Response")
  46. config = vertexai_llm.config
  47. prompt = "Test Prompt"
  48. messages = vertexai_llm._get_messages(prompt)
  49. response = vertexai_llm._get_answer(prompt, config)
  50. mock_chat_vertexai.return_value.invoke.assert_called_once_with(messages)
  51. assert response == "Test Response" # Assertion corrected
  52. assert "Config option `top_p` is not supported by this model." not in caplog.text
  53. def test_get_messages(vertexai_llm):
  54. prompt = "Test Prompt"
  55. system_prompt = "Test System Prompt"
  56. messages = vertexai_llm._get_messages(prompt, system_prompt)
  57. assert messages == [
  58. SystemMessage(content="Test System Prompt", additional_kwargs={}),
  59. HumanMessage(content="Test Prompt", additional_kwargs={}, example=False),
  60. ]