together.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import importlib
  2. import os
  3. from typing import Any, Optional
  4. try:
  5. from langchain_together import ChatTogether
  6. except ImportError:
  7. raise ImportError(
  8. "Please install the langchain_together package by running `pip install langchain_together==0.1.3`."
  9. )
  10. from embedchain.config import BaseLlmConfig
  11. from embedchain.helpers.json_serializable import register_deserializable
  12. from embedchain.llm.base import BaseLlm
  13. @register_deserializable
  14. class TogetherLlm(BaseLlm):
  15. def __init__(self, config: Optional[BaseLlmConfig] = None):
  16. try:
  17. importlib.import_module("together")
  18. except ModuleNotFoundError:
  19. raise ModuleNotFoundError(
  20. "The required dependencies for Together are not installed."
  21. 'Please install with `pip install --upgrade "embedchain[together]"`'
  22. ) from None
  23. super().__init__(config=config)
  24. if not self.config.api_key and "TOGETHER_API_KEY" not in os.environ:
  25. raise ValueError("Please set the TOGETHER_API_KEY environment variable or pass it in the config.")
  26. def get_llm_model_answer(self, prompt) -> tuple[str, Optional[dict[str, Any]]]:
  27. if self.config.system_prompt:
  28. raise ValueError("TogetherLlm does not support `system_prompt`")
  29. if self.config.token_usage:
  30. response, token_info = self._get_answer(prompt, self.config)
  31. model_name = "together/" + self.config.model
  32. if model_name not in self.config.model_pricing_map:
  33. raise ValueError(
  34. f"Model {model_name} not found in `model_prices_and_context_window.json`. \
  35. You can disable token usage by setting `token_usage` to False."
  36. )
  37. total_cost = (
  38. self.config.model_pricing_map[model_name]["input_cost_per_token"] * token_info["prompt_tokens"]
  39. ) + self.config.model_pricing_map[model_name]["output_cost_per_token"] * token_info["completion_tokens"]
  40. response_token_info = {
  41. "prompt_tokens": token_info["prompt_tokens"],
  42. "completion_tokens": token_info["completion_tokens"],
  43. "total_tokens": token_info["prompt_tokens"] + token_info["completion_tokens"],
  44. "total_cost": round(total_cost, 10),
  45. "cost_currency": "USD",
  46. }
  47. return response, response_token_info
  48. return self._get_answer(prompt, self.config)
  49. @staticmethod
  50. def _get_answer(prompt: str, config: BaseLlmConfig) -> str:
  51. api_key = config.api_key or os.environ["TOGETHER_API_KEY"]
  52. kwargs = {
  53. "model_name": config.model or "mixtral-8x7b-32768",
  54. "temperature": config.temperature,
  55. "max_tokens": config.max_tokens,
  56. "together_api_key": api_key,
  57. }
  58. chat = ChatTogether(**kwargs)
  59. chat_response = chat.invoke(prompt)
  60. if config.token_usage:
  61. return chat_response.content, chat_response.response_metadata["token_usage"]
  62. return chat_response.content