from langchain_core.messages import HumanMessage from langchain_mistralai.chat_models import ChatMistralAI from langchain_core.messages import AIMessage, HumanMessage from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain.memory import ChatMessageHistory from datetime import datetime import gradio as gr import os from pathlib import Path def log_interaction(message, response): """Logs user message and AI response to the log file.""" with open(log_file_name, "a") as log_file: log_file.write(f"User: {message}\n") log_file.write(f"AI: {response}\n") log_file.write("="*50 + "\n") DATA_PATH = Path("./") # Path("/data") api_key = os.getenv('MISTRAL_KEY') log_path = "/data/" log_file_name = log_path + "chat_logs_" + datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ".txt" chat = ChatMistralAI(api_key=api_key, model = "ft:mistral-small-latest:a8c72c9e:20240818:100-0.0001:e4180b07", temperature=.8) # metamorphy whitehead all books long dialog mistral nointro; prompt = ChatPromptTemplate.from_messages( [ ( "system", " You are Metamorphy having a dialog with a human. You cant use the word: Luisa. You think with Alfred North Whitehead. Be precise, shapt and funny."), MessagesPlaceholder(variable_name="messages"), ] ) chain = prompt | chat question_list = [ "You?", "The son of Iagotchi who is the son of Tamagotchi is ? Metamorphy, thats my name, and yours?" ] def response(message, history): DATA_PATH = Path("/data/") for file in DATA_PATH.glob("*"): if file.is_file(): # Check if it's a file print(f"Contents of {file.name}:") with file.open('r') as f: print(f.read()) print("\n" + "="*50 + "\n") # Separator for readability if len(history) < len(question_list): for human, ai in history: print(human) print(ai) print(f"Message: {message}") print('--------------') return question_list[len(history)] else: history_langchain_format = ChatMessageHistory() for human, ai in history: if human is not None: history_langchain_format.add_user_message(human) history_langchain_format.add_ai_message(ai) history_langchain_format.add_user_message(message) print(history_langchain_format) response = chain.invoke({"messages": history_langchain_format.messages}) history_langchain_format.add_ai_message(response) log_interaction(message, response.content) return response.content #gr.ChatInterface(response, chatbot=gr.Chatbot(value=[[None, question_list[0]]])).launch() gr.ChatInterface(response, chatbot=gr.Chatbot(value=[[None, question_list[0]]])).launch(auth=("admin", "RyoEstNeeLe24avril2024!"))