vertex_ai.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import importlib
  2. import logging
  3. from typing import Optional
  4. from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
  5. from langchain_google_vertexai import ChatVertexAI
  6. from embedchain.config import BaseLlmConfig
  7. from embedchain.helpers.json_serializable import register_deserializable
  8. from embedchain.llm.base import BaseLlm
  9. @register_deserializable
  10. class VertexAILlm(BaseLlm):
  11. def __init__(self, config: Optional[BaseLlmConfig] = None):
  12. try:
  13. importlib.import_module("vertexai")
  14. except ModuleNotFoundError:
  15. raise ModuleNotFoundError(
  16. "The required dependencies for VertexAI are not installed."
  17. 'Please install with `pip install --upgrade "embedchain[vertexai]"`'
  18. ) from None
  19. super().__init__(config=config)
  20. def get_llm_model_answer(self, prompt):
  21. return VertexAILlm._get_answer(prompt=prompt, config=self.config)
  22. @staticmethod
  23. def _get_answer(prompt: str, config: BaseLlmConfig) -> str:
  24. if config.top_p and config.top_p != 1:
  25. logging.warning("Config option `top_p` is not supported by this model.")
  26. messages = BaseLlm._get_messages(prompt, system_prompt=config.system_prompt)
  27. if config.stream:
  28. callbacks = config.callbacks if config.callbacks else [StreamingStdOutCallbackHandler()]
  29. llm = ChatVertexAI(
  30. temperature=config.temperature, model=config.model, callbacks=callbacks, streaming=config.stream
  31. )
  32. else:
  33. llm = ChatVertexAI(temperature=config.temperature, model=config.model)
  34. return llm.invoke(messages).content