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 <module>
    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()