vertex_ai.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import importlib
  2. import logging
  3. from typing import Any, 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. logger = logging.getLogger(__name__)
  10. @register_deserializable
  11. class VertexAILlm(BaseLlm):
  12. def __init__(self, config: Optional[BaseLlmConfig] = None):
  13. try:
  14. importlib.import_module("vertexai")
  15. except ModuleNotFoundError:
  16. raise ModuleNotFoundError(
  17. "The required dependencies for VertexAI are not installed."
  18. 'Please install with `pip install --upgrade "embedchain[vertexai]"`'
  19. ) from None
  20. super().__init__(config=config)
  21. def get_llm_model_answer(self, prompt) -> tuple[str, Optional[dict[str, Any]]]:
  22. if self.config.token_usage:
  23. response, token_info = self._get_answer(prompt, self.config)
  24. model_name = "vertexai/" + self.config.model
  25. if model_name not in self.config.model_pricing_map:
  26. raise ValueError(
  27. f"Model {model_name} not found in `model_prices_and_context_window.json`. \
  28. You can disable token usage by setting `token_usage` to False."
  29. )
  30. total_cost = (
  31. self.config.model_pricing_map[model_name]["input_cost_per_token"] * token_info["prompt_token_count"]
  32. ) + self.config.model_pricing_map[model_name]["output_cost_per_token"] * token_info[
  33. "candidates_token_count"
  34. ]
  35. response_token_info = {
  36. "prompt_tokens": token_info["prompt_token_count"],
  37. "completion_tokens": token_info["candidates_token_count"],
  38. "total_tokens": token_info["prompt_token_count"] + token_info["candidates_token_count"],
  39. "total_cost": round(total_cost, 10),
  40. "cost_currency": "USD",
  41. }
  42. return response, response_token_info
  43. return self._get_answer(prompt, self.config)
  44. @staticmethod
  45. def _get_answer(prompt: str, config: BaseLlmConfig) -> str:
  46. if config.top_p and config.top_p != 1:
  47. logger.warning("Config option `top_p` is not supported by this model.")
  48. if config.stream:
  49. callbacks = config.callbacks if config.callbacks else [StreamingStdOutCallbackHandler()]
  50. llm = ChatVertexAI(
  51. temperature=config.temperature, model=config.model, callbacks=callbacks, streaming=config.stream
  52. )
  53. else:
  54. llm = ChatVertexAI(temperature=config.temperature, model=config.model)
  55. messages = VertexAILlm._get_messages(prompt)
  56. chat_response = llm.invoke(messages)
  57. if config.token_usage:
  58. return chat_response.content, chat_response.response_metadata["usage_metadata"]
  59. return chat_response.content