|
| 1 | +from typing import Dict, List, Optional |
| 2 | +import enum |
| 3 | + |
| 4 | +from mem0.configs.llms.base import BaseLlmConfig |
| 5 | +from mem0.llms.base import LLMBase |
| 6 | + |
| 7 | +# Default import for langchain_community |
| 8 | +try: |
| 9 | + from langchain_community import chat_models |
| 10 | +except ImportError: |
| 11 | + raise ImportError("langchain_community not found. Please install it with `pip install langchain-community`") |
| 12 | + |
| 13 | +# Provider-specific package mapping |
| 14 | +PROVIDER_PACKAGES = { |
| 15 | + # "Anthropic": "langchain_anthropic", # Special handling for Anthropic with Pydantic v2 |
| 16 | + "MistralAI": "langchain_mistralai", |
| 17 | + "Fireworks": "langchain_fireworks", |
| 18 | + "AzureOpenAI": "langchain_openai", |
| 19 | + "OpenAI": "langchain_openai", |
| 20 | + "Together": "langchain_together", |
| 21 | + "VertexAI": "langchain_google_vertexai", |
| 22 | + "GoogleAI": "langchain_google_genai", |
| 23 | + "Groq": "langchain_groq", |
| 24 | + "Cohere": "langchain_cohere", |
| 25 | + "Bedrock": "langchain_aws", |
| 26 | + "HuggingFace": "langchain_huggingface", |
| 27 | + "NVIDIA": "langchain_nvidia_ai_endpoints", |
| 28 | + "Ollama": "langchain_ollama", |
| 29 | + "AI21": "langchain_ai21", |
| 30 | + "Upstage": "langchain_upstage", |
| 31 | + "Databricks": "databricks_langchain", |
| 32 | + "Watsonx": "langchain_ibm", |
| 33 | + "xAI": "langchain_xai", |
| 34 | + "Perplexity": "langchain_perplexity", |
| 35 | +} |
| 36 | + |
| 37 | + |
| 38 | +class LangchainProvider(enum.Enum): |
| 39 | + Abso = "ChatAbso" |
| 40 | + AI21 = "ChatAI21" |
| 41 | + Alibaba = "ChatAlibabaCloud" |
| 42 | + Anthropic = "ChatAnthropic" |
| 43 | + Anyscale = "ChatAnyscale" |
| 44 | + AzureAIChatCompletionsModel = "AzureAIChatCompletionsModel" |
| 45 | + AzureOpenAI = "AzureChatOpenAI" |
| 46 | + AzureMLEndpoint = "ChatAzureMLEndpoint" |
| 47 | + Baichuan = "ChatBaichuan" |
| 48 | + Qianfan = "ChatQianfan" |
| 49 | + Bedrock = "ChatBedrock" |
| 50 | + Cerebras = "ChatCerebras" |
| 51 | + CloudflareWorkersAI = "ChatCloudflareWorkersAI" |
| 52 | + Cohere = "ChatCohere" |
| 53 | + ContextualAI = "ChatContextualAI" |
| 54 | + Coze = "ChatCoze" |
| 55 | + Dappier = "ChatDappier" |
| 56 | + Databricks = "ChatDatabricks" |
| 57 | + DeepInfra = "ChatDeepInfra" |
| 58 | + DeepSeek = "ChatDeepSeek" |
| 59 | + EdenAI = "ChatEdenAI" |
| 60 | + EverlyAI = "ChatEverlyAI" |
| 61 | + Fireworks = "ChatFireworks" |
| 62 | + Friendli = "ChatFriendli" |
| 63 | + GigaChat = "ChatGigaChat" |
| 64 | + Goodfire = "ChatGoodfire" |
| 65 | + GoogleAI = "ChatGoogleAI" |
| 66 | + VertexAI = "VertexAI" |
| 67 | + GPTRouter = "ChatGPTRouter" |
| 68 | + Groq = "ChatGroq" |
| 69 | + HuggingFace = "ChatHuggingFace" |
| 70 | + Watsonx = "ChatWatsonx" |
| 71 | + Jina = "ChatJina" |
| 72 | + Kinetica = "ChatKinetica" |
| 73 | + Konko = "ChatKonko" |
| 74 | + LiteLLM = "ChatLiteLLM" |
| 75 | + LiteLLMRouter = "ChatLiteLLMRouter" |
| 76 | + Llama2Chat = "Llama2Chat" |
| 77 | + LlamaAPI = "ChatLlamaAPI" |
| 78 | + LlamaEdge = "ChatLlamaEdge" |
| 79 | + LlamaCpp = "ChatLlamaCpp" |
| 80 | + Maritalk = "ChatMaritalk" |
| 81 | + MiniMax = "ChatMiniMax" |
| 82 | + MistralAI = "ChatMistralAI" |
| 83 | + MLX = "ChatMLX" |
| 84 | + ModelScope = "ChatModelScope" |
| 85 | + Moonshot = "ChatMoonshot" |
| 86 | + Naver = "ChatNaver" |
| 87 | + Netmind = "ChatNetmind" |
| 88 | + NVIDIA = "ChatNVIDIA" |
| 89 | + OCIModelDeployment = "ChatOCIModelDeployment" |
| 90 | + OCIGenAI = "ChatOCIGenAI" |
| 91 | + OctoAI = "ChatOctoAI" |
| 92 | + Ollama = "ChatOllama" |
| 93 | + OpenAI = "ChatOpenAI" |
| 94 | + Outlines = "ChatOutlines" |
| 95 | + Perplexity = "ChatPerplexity" |
| 96 | + Pipeshift = "ChatPipeshift" |
| 97 | + PredictionGuard = "ChatPredictionGuard" |
| 98 | + PremAI = "ChatPremAI" |
| 99 | + PromptLayerOpenAI = "PromptLayerChatOpenAI" |
| 100 | + QwQ = "ChatQwQ" |
| 101 | + Reka = "ChatReka" |
| 102 | + RunPod = "ChatRunPod" |
| 103 | + SambaNovaCloud = "ChatSambaNovaCloud" |
| 104 | + SambaStudio = "ChatSambaStudio" |
| 105 | + SeekrFlow = "ChatSeekrFlow" |
| 106 | + SnowflakeCortex = "ChatSnowflakeCortex" |
| 107 | + Solar = "ChatSolar" |
| 108 | + SparkLLM = "ChatSparkLLM" |
| 109 | + Nebula = "ChatNebula" |
| 110 | + Hunyuan = "ChatHunyuan" |
| 111 | + Together = "ChatTogether" |
| 112 | + TongyiQwen = "ChatTongyiQwen" |
| 113 | + Upstage = "ChatUpstage" |
| 114 | + Vectara = "ChatVectara" |
| 115 | + VLLM = "ChatVLLM" |
| 116 | + VolcEngine = "ChatVolcEngine" |
| 117 | + Writer = "ChatWriter" |
| 118 | + xAI = "ChatXAI" |
| 119 | + Xinference = "ChatXinference" |
| 120 | + Yandex = "ChatYandex" |
| 121 | + Yi = "ChatYi" |
| 122 | + Yuan2 = "ChatYuan2" |
| 123 | + ZhipuAI = "ChatZhipuAI" |
| 124 | + |
| 125 | + |
| 126 | +class LangchainLLM(LLMBase): |
| 127 | + def __init__(self, config: Optional[BaseLlmConfig] = None): |
| 128 | + super().__init__(config) |
| 129 | + |
| 130 | + provider = self.config.langchain_provider |
| 131 | + if provider not in LangchainProvider.__members__: |
| 132 | + raise ValueError(f"Invalid provider: {provider}") |
| 133 | + model_name = LangchainProvider[provider].value |
| 134 | + |
| 135 | + try: |
| 136 | + # Check if this provider needs a specialized package |
| 137 | + if provider in PROVIDER_PACKAGES: |
| 138 | + package_name = PROVIDER_PACKAGES[provider] |
| 139 | + try: |
| 140 | + # Import the model class directly from the package |
| 141 | + module_path = f"{package_name}" |
| 142 | + model_class = __import__(module_path, fromlist=[model_name]) |
| 143 | + model_class = getattr(model_class, model_name) |
| 144 | + except ImportError: |
| 145 | + raise ImportError( |
| 146 | + f"Package {package_name} not found. " f"Please install it with `pip install {package_name}`" |
| 147 | + ) |
| 148 | + except AttributeError: |
| 149 | + raise ImportError(f"Model {model_name} not found in {package_name}") |
| 150 | + else: |
| 151 | + # Use the default langchain_community module |
| 152 | + if not hasattr(chat_models, model_name): |
| 153 | + raise ImportError(f"Provider {provider} not found in langchain_community.chat_models") |
| 154 | + |
| 155 | + model_class = getattr(chat_models, model_name) |
| 156 | + |
| 157 | + # Initialize the model with relevant config parameters |
| 158 | + self.langchain_model = model_class( |
| 159 | + model=self.config.model, |
| 160 | + temperature=self.config.temperature, |
| 161 | + max_tokens=self.config.max_tokens, |
| 162 | + api_key=self.config.api_key, |
| 163 | + ) |
| 164 | + except (ImportError, AttributeError, ValueError) as e: |
| 165 | + raise ImportError(f"Error setting up langchain model for provider {provider}: {str(e)}") |
| 166 | + |
| 167 | + def generate_response( |
| 168 | + self, |
| 169 | + messages: List[Dict[str, str]], |
| 170 | + response_format=None, |
| 171 | + tools: Optional[List[Dict]] = None, |
| 172 | + tool_choice: str = "auto", |
| 173 | + ): |
| 174 | + """ |
| 175 | + Generate a response based on the given messages using langchain_community. |
| 176 | +
|
| 177 | + Args: |
| 178 | + messages (list): List of message dicts containing 'role' and 'content'. |
| 179 | + response_format (str or object, optional): Format of the response. Not used in Langchain. |
| 180 | + tools (list, optional): List of tools that the model can call. Not used in Langchain. |
| 181 | + tool_choice (str, optional): Tool choice method. Not used in Langchain. |
| 182 | +
|
| 183 | + Returns: |
| 184 | + str: The generated response. |
| 185 | + """ |
| 186 | + try: |
| 187 | + # Convert the messages to LangChain's tuple format |
| 188 | + langchain_messages = [] |
| 189 | + for message in messages: |
| 190 | + role = message["role"] |
| 191 | + content = message["content"] |
| 192 | + |
| 193 | + if role == "system": |
| 194 | + langchain_messages.append(("system", content)) |
| 195 | + elif role == "user": |
| 196 | + langchain_messages.append(("human", content)) |
| 197 | + elif role == "assistant": |
| 198 | + langchain_messages.append(("ai", content)) |
| 199 | + |
| 200 | + if not langchain_messages: |
| 201 | + raise ValueError("No valid messages found in the messages list") |
| 202 | + |
| 203 | + ai_message = self.langchain_model.invoke(langchain_messages) |
| 204 | + |
| 205 | + return ai_message.content |
| 206 | + |
| 207 | + except Exception as e: |
| 208 | + raise Exception(f"Error generating response using langchain model: {str(e)}") |
0 commit comments