together.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import json
  2. from typing import Dict, List, Optional
  3. try:
  4. from together import Together
  5. except ImportError:
  6. raise ImportError("Together requires extra dependencies. Install with `pip install together`") from None
  7. from mem0.llms.base import LLMBase
  8. from mem0.configs.llms.base import BaseLlmConfig
  9. class TogetherLLM(LLMBase):
  10. def __init__(self, config: Optional[BaseLlmConfig] = None):
  11. super().__init__(config)
  12. if not self.config.model:
  13. self.config.model="mistralai/Mixtral-8x7B-Instruct-v0.1"
  14. self.client = Together()
  15. def _parse_response(self, response, tools):
  16. """
  17. Process the response based on whether tools are used or not.
  18. Args:
  19. response: The raw response from API.
  20. tools: The list of tools provided in the request.
  21. Returns:
  22. str or dict: The processed response.
  23. """
  24. if tools:
  25. processed_response = {
  26. "content": response.choices[0].message.content,
  27. "tool_calls": []
  28. }
  29. if response.choices[0].message.tool_calls:
  30. for tool_call in response.choices[0].message.tool_calls:
  31. processed_response["tool_calls"].append({
  32. "name": tool_call.function.name,
  33. "arguments": json.loads(tool_call.function.arguments)
  34. })
  35. return processed_response
  36. else:
  37. return response.choices[0].message.content
  38. def generate_response(
  39. self,
  40. messages: List[Dict[str, str]],
  41. response_format=None,
  42. tools: Optional[List[Dict]] = None,
  43. tool_choice: str = "auto",
  44. ):
  45. """
  46. Generate a response based on the given messages using TogetherAI.
  47. Args:
  48. messages (list): List of message dicts containing 'role' and 'content'.
  49. response_format (str or object, optional): Format of the response. Defaults to "text".
  50. tools (list, optional): List of tools that the model can call. Defaults to None.
  51. tool_choice (str, optional): Tool choice method. Defaults to "auto".
  52. Returns:
  53. str: The generated response.
  54. """
  55. params = {
  56. "model": self.config.model,
  57. "messages": messages,
  58. "temperature": self.config.temperature,
  59. "max_tokens": self.config.max_tokens,
  60. "top_p": self.config.top_p
  61. }
  62. if response_format:
  63. params["response_format"] = response_format
  64. if tools:
  65. params["tools"] = tools
  66. params["tool_choice"] = tool_choice
  67. response = self.client.chat.completions.create(**params)
  68. return self._parse_response(response, tools)