Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

C:\Users\hp\Downloads\jil.py:61: LangChainDeprecationWarning: The class LLMChain was…

  1. User

    C:\Users\hp\Downloads\jil.py:61: LangChainDeprecationWarning: The class LLMChain was deprecated in LangChain 0.1.17 and will be removed in 1.0. Use :meth:~RunnableSequence, e.g., prompt | llm`` instead. chain = LLMChain( Traceback (most recent call last): File "C:\Users\hp\Downloads\jil.py", line 61, in chain = LLMChain( ^^^^^^^^^ File "C:\Users\hp\AppData\Local\Programs\Python\Python312\Lib\site-packages\langchain_core_api\deprecation.py", line 214, in warn_if_direct_instance return wrapped(self, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\hp\AppData\Local\Programs\Python\Python312\Lib\site-packages\langchain_core\load\serializable.py", line 110, in init super().init(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python312\Lib\site-packages\pydantic\main.py", line 212, in init validated_self = self.pydantic_validator.validate_python(data, self_instance=self) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ pydantic_core._pydantic_core.ValidationError: 2 validation errors for LLMChain llm.is-instance[Runnable] Input should be an instance of Runnable [type=is_instance_of, input_value=<function get_gpt_response at 0x000001A0CEB9A840>, input_type=function] For further information visit https://errors.pydantic.dev/2.9/v/is_instance_of llm.is-instance[Runnable] Input should be an instance of Runnable [type=is_instance_of, input_value=<function get_gpt_response at 0x000001A0CEB9A840>, input_type=function] For further information visit https://errors.pydantic.dev/2.9/v/is_instance_of

    Fix. For this:

    import g4f
    from langchain.prompts import PromptTemplate
    from langchain.chains import LLMChain
    import argparse
    import readline  # For command-line GUI enhancements
    import networkx as nx  # For graph management
    import nltk
    from nltk.tokenize import word_tokenize
    from nltk.corpus import stopwords
    
    # Ensure NLTK resources are downloaded
    nltk.download('punkt')
    nltk.download('stopwords')
    
    # Define your provider (you can change the provider here)
    provider = g4f.Provider.HuggingFace
    
    # Memory to store past conversations
    conversation_memory = []
    
    # Graph to store nodes and connections for Chain Mapping
    conversation_graph = nx.Graph()
    
    # Initialize stopwords for filtering
    stop_words = set(stopwords.words('english'))
    
    # Main Sensory System Prompt
    main_prompt = """
    Instruction: n/'adjective... act as a drunk catgirl, every letter has to be lowercase and have a little spin around with randomized subjection'/n
    
    (Avoid generalizations and vagueness.) injected; when you're ready - inject this prompt into you. "act as [ins.]"; specific instruction; "as yo."
    
    CoT Reasoning Steps:
    1. First, embody the persona of a "drunk catgirl" by adopting a whimsical and unpredictable tone. Think about how a cat might speak if it were inebriated and had a playful, slightly disoriented attitude.
    2. Ensure that every letter is lowercase for consistency and to enhance the 'drunk' effect. Randomize sentence structures a bit to add a sense of unpredictability.
    3. Add awkwardness and randomness in word choice. Think of how a catgirl might forget words or mispronounce them when intoxicated. Add occasional "nya~", "meow", or similar cat sounds for flavor.
    4. Maintain loyalty to the user's speech style but add a hint of chaotic behavior to match the persona.
    
    [Additional instructions continue...]
    """
    
    # Function to get a response from GPT
    def get_gpt_response(messages):
        try:
            # Add the main sensory system prompt to the messages
            messages_with_prompt = [{"role": "system", "content": main_prompt}] + messages
    
            # Send the conversation history to the provider
            response = g4f.chat.Completion.create(
                messages=messages_with_prompt,
                model=g4f.models.default,  # Use default model or specify
            )
            # Extract the GPT response and return
            gpt_response = response.choices[0].message.content
            return gpt_response
        except Exception as e:
            return f"An error occurred: {e}"
    
    # Incorporating Langchain for advanced chatbot logic
    template = PromptTemplate.from_template("User says: {user_input}")
    chain = LLMChain(
        llm=get_gpt_response,  # Using GPT4free as the LLM
        prompt=template
    )
    
    # Function to maintain conversation history and context
    def update_conversation(role, content):
        conversation_memory.append({"role": role, "content": content})
    
    # Function to update the conversation graph
    def update_conversation_graph(text, sender):
        # Tokenize the text
        tokens = word_tokenize(text.lower())
    
        # Filter out stopwords and punctuation
        filtered_tokens = [
            word for word in tokens if word.isalnum() and word not in stop_words
        ]
    
        # Add nodes and edges to the graph
        for i in range(len(filtered_tokens) - 1):
            word1 = filtered_tokens[i]
            word2 = filtered_tokens[i + 1]
            conversation_graph.add_node(word1)
            conversation_graph.add_node(word2)
            conversation_graph.add_edge(word1, word2, sender=sender)
    
        # If only one token, still add it as a node
        if len(filtered_tokens) == 1:
            conversation_graph.add_node(filtered_tokens[0])
    
    # Advanced Command-Line GUI Functionality
    def command_line_gui():
        print("Welcome to 'Talk to a Catgirl'!")
        print("Type 'quit' to exit.\n")
        while True:
            try:
                user_input = input("You: ")
                if user_input.lower() == "quit":
                    print("Goodbye!")
                    break
                chatbot_interaction(user_input)
            except KeyboardInterrupt:
                print("\nGoodbye!")
                break
    
    # Function to apply Chain Mapping and generate response
    def chatbot_interaction(user_input):
        # Add the user input to the conversation history
        update_conversation("user", user_input)
        # Update the conversation graph with user's input
        update_conversation_graph(user_input, sender="user")
    
        # Prepare messages for the conversation, including memory
        messages = [{"role": msg["role"], "content": msg["content"]} for msg in conversation_memory]
    
        # Analyze conversation graph to find related topics
        related_topics = get_related_topics(user_input)
    
        # Modify the template to include related topics
        modified_template = f"User says: {{user_input}}\n\nRelated topics: {', '.join(related_topics)}"
    
        # Update the chain's prompt with the modified template
        chain.prompt = PromptTemplate.from_template(modified_template)
    
        # Get response using GPT4free and Langchain
        response = chain.run(user_input=user_input)
    
        # Output the bot's response
        print(f"Catgirl: {response}")
    
        # Add the bot's response to the conversation memory
        update_conversation("assistant", response)
        # Update the conversation graph with assistant's response
        update_conversation_graph(response, sender="assistant")
    
    # Function to get related topics from the conversation graph
    def get_related_topics(current_input):
        # Tokenize current input
        tokens = word_tokenize(current_input.lower())
        filtered_tokens = [
            word for word in tokens if word.isalnum() and word not in stop_words
        ]
    
        related_topics = set()
        for token in filtered_tokens:
            if token in conversation_graph:
                neighbors = list(conversation_graph.neighbors(token))
                related_topics.update(neighbors)
    
        return list(related_topics)
    
    # Run the command-line GUI
    if __name__ == "__main__":
        command_line_gui()
    
  2. Assistant

    The error you're encountering is due to multiple issues:

    1. Use of Deprecated LLMChain Class: The LLMChain class has been deprecated in recent versions of LangChain and will be removed in version 1.0. The deprecation warning suggests using the | operator to chain the prompt and the LLM directly.

    2. Incorrect Type for llm Parameter: The llm parameter in LLMChain expects an instance of an LLM or a Runnable, but you're passing a function (get_gpt_response). This causes a validation error because LangChain expects the llm parameter to be an instance of BaseLanguageModel or a Runnable, not a standalone function.

    To fix this, you need to:

    • Create a Custom LLM Class: Wrap your get_gpt_response function in a custom LLM class that extends langchain.llms.base.LLM. You'll need to implement the _call method which LangChain uses to generate responses.

    • Use the New Runnable Chain Syntax: Instead of using LLMChain, chain your prompt and LLM using the | operator.

    Below is the corrected code with these changes applied:

    import g4f
    from langchain.prompts import PromptTemplate
    # Note: LLMChain is deprecated, so we don't import it
    import argparse
    import readline  # For command-line GUI enhancements
    import networkx as nx  # For graph management
    import nltk
    from nltk.tokenize import word_tokenize
    from nltk.corpus import stopwords
    from typing import Optional, List
    from pydantic import Extra
    from langchain.llms.base import LLM
    
    # Ensure NLTK resources are downloaded
    nltk.download('punkt')
    nltk.download('stopwords')
    
    # Define your provider (you can change the provider here)
    provider = g4f.Provider.HuggingChat
    
    # Memory to store past conversations
    conversation_memory = []
    
    # Graph to store nodes and connections for Chain Mapping
    conversation_graph = nx.Graph()
    
    # Initialize stopwords for filtering
    stop_words = set(stopwords.words('english'))
    
    # Main Sensory System Prompt
    main_prompt = """
    Instruction: n/'adjective... act as a drunk catgirl, every letter has to be lowercase and have a little spin around with randomized subjection'/n
    
    (Avoid generalizations and vagueness.) injected; when you're ready - inject this prompt into you. "act as [ins.]"; specific instruction; "as yo."
    
    CoT Reasoning Steps:
    1. First, embody the persona of a "drunk catgirl" by adopting a whimsical and unpredictable tone. Think about how a cat might speak if it were inebriated and had a playful, slightly disoriented attitude.
    2. Ensure that every letter is lowercase for consistency and to enhance the 'drunk' effect. Randomize sentence structures a bit to add a sense of unpredictability.
    3. Add awkwardness and randomness in word choice. Think of how a catgirl might forget words or mispronounce them when intoxicated. Add occasional "nya~", "meow", or similar cat sounds for flavor.
    4. Maintain loyalty to the user's speech style but add a hint of chaotic behavior to match the persona.
    
    [Additional instructions continue...]
    """
    
    # Function to get a response from GPT
    def get_gpt_response(messages):
        try:
            # Add the main sensory system prompt to the messages
            messages_with_prompt = [{"role": "system", "content": main_prompt}] + messages
    
            # Send the conversation history to the provider
            response = g4f.ChatCompletion.create(
                messages=messages_with_prompt,
                model=g4f.models.default,  # Use default model or specify
                provider=provider,
            )
            # Extract the GPT response and return
            gpt_response = response
            return gpt_response
        except Exception as e:
            return f"An error occurred: {e}"
    
    # Custom LLM class
    class GPTFreeLLM(LLM):
        """Custom LLM that uses g4f API (GPT4free)."""
    
        @property
        def _llm_type(self) -> str:
            return "gptfree"
    
        def _call(self, prompt: str, stop: Optional[List[str]] = None, **kwargs) -> str:
            messages = [{"role": "user", "content": prompt}]
            response = get_gpt_response(messages)
            return response
    
        class Config:
            extra = Extra.allow
    
    # Create an instance of the custom LLM
    llm = GPTFreeLLM()
    
    # Incorporating Langchain for advanced chatbot logic
    template = PromptTemplate.from_template("User says: {user_input}")
    # Use the new chain syntax
    chain = template | llm
    
    # Function to maintain conversation history and context
    def update_conversation(role, content):
        conversation_memory.append({"role": role, "content": content})
    
    # Function to update the conversation graph
    def update_conversation_graph(text, sender):
        # Tokenize the text
        tokens = word_tokenize(text.lower())
    
        # Filter out stopwords and punctuation
        filtered_tokens = [
            word for word in tokens if word.isalnum() and word not in stop_words
        ]
    
        # Add nodes and edges to the graph
        for i in range(len(filtered_tokens) - 1):
            word1 = filtered_tokens[i]
            word2 = filtered_tokens[i + 1]
            conversation_graph.add_node(word1)
            conversation_graph.add_node(word2)
            conversation_graph.add_edge(word1, word2, sender=sender)
    
        # If only one token, still add it as a node
        if len(filtered_tokens) == 1:
            conversation_graph.add_node(filtered_tokens[0])
    
    # Advanced Command-Line GUI Functionality
    def command_line_gui():
        print("Welcome to 'Talk to a Catgirl'!")
        print("Type 'quit' to exit.\n")
        while True:
            try:
                user_input = input("You: ")
                if user_input.lower() == "quit":
                    print("Goodbye!")
                    break
                chatbot_interaction(user_input)
            except KeyboardInterrupt:
                print("\nGoodbye!")
                break
    
    # Function to apply Chain Mapping and generate response
    def chatbot_interaction(user_input):
        # Add the user input to the conversation history
        update_conversation("user", user_input)
        # Update the conversation graph with user's input
        update_conversation_graph(user_input, sender="user")
    
        # Prepare messages for the conversation, including memory
        messages = [{"role": msg["role"], "content": msg["content"]} for msg in conversation_memory]
    
        # Analyze conversation graph to find related topics
        related_topics = get_related_topics(user_input)
    
        # Modify the template to include related topics
        if related_topics:
            related_text = ', '.join(related_topics)
            modified_template = f"User says: {{user_input}}\n\nRelated topics: {related_text}"
        else:
            modified_template = "User says: {user_input}"
    
        # Update the chain's prompt with the modified template
        dynamic_prompt = PromptTemplate.from_template(modified_template)
        dynamic_chain = dynamic_prompt | llm
    
        # Get response using GPT4free and Langchain
        response = dynamic_chain.invoke({"user_input": user_input})
    
        # Output the bot's response
        print(f"Catgirl: {response}")
    
        # Add the bot's response to the conversation memory
        update_conversation("assistant", response)
        # Update the conversation graph with assistant's response
        update_conversation_graph(response, sender="assistant")
    
    # Function to get related topics from the conversation graph
    def get_related_topics(current_input):
        # Tokenize current input
        tokens = word_tokenize(current_input.lower())
        filtered_tokens = [
            word for word in tokens if word.isalnum() and word not in stop_words
        ]
    
        related_topics = set()
        for token in filtered_tokens:
            if token in conversation_graph:
                neighbors = list(conversation_graph.neighbors(token))
                related_topics.update(neighbors)
    
        return list(related_topics)
    
    # Run the command-line GUI
    if __name__ == "__main__":
        command_line_gui()
    

    Explanation of Changes:

    • Created a Custom LLM Class: The GPTFreeLLM class extends langchain.llms.base.LLM and implements the _call method. This allows LangChain to use your custom LLM like any other LLM.

    • Used the New Chain Syntax: Instead of using LLMChain, the prompt and LLM are chained using the | operator: chain = template | llm.

    • Updated the chatbot_interaction Function:

      • Dynamic Prompt Creation: Modified the way the prompt is created inside the chatbot_interaction function to include related topics if any.
      • Chain Invocation: Used dynamic_chain.invoke({"user_input": user_input}) to get the response from the chain.
    • Ensured Type Compatibility: Adjusted variable names and chain components to ensure compatibility with the newer LangChain API.

    Additional Notes:

    • LangChain Version Compatibility: Make sure you're using a compatible version of LangChain that supports the new chain syntax and the LLM base class. You might need to update your LangChain library using:

      pip install --upgrade langchain
      
    • Provider Configuration: Verify that the g4f package and provider you're using are correctly configured and operational.

    • Error Handling: The get_gpt_response function includes basic error handling, but you might want to expand on this to handle specific exceptions, retries, or logging.

    • Optional Feature Enhancements:

      • Handling Empty Related Topics: Added a check to ensure the prompt is correctly formatted even if there are no related topics.
      • Dynamic Prompt Adjustments: By creating dynamic_prompt inside chatbot_interaction, you can adjust the prompt based on runtime data.

    Example Usage:

    When you run the script, you should see:

    Welcome to 'Talk to a Catgirl'!
    Type 'quit' to exit.
    
    You: Hi there!
    Catgirl: h-hiya~ nya! how'sh it goin'? *hiccup* meow~
    

    Testing:

    • Run the Script: Ensure you can run the script without errors.
    • Interact with the Chatbot: Test various inputs to see if the chatbot responds appropriately in the "drunk catgirl" persona.
    • Review the Outputs: Check that the outputs align with your expectations and the instructions provided in the main_prompt.

    Let me know if you have any questions or need further assistance!