AyoubChLin commited on
Commit
9fa982f
·
verified ·
1 Parent(s): 99b7a5d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -0
app.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import getpass
3
+ import streamlit as st
4
+ from typing import List
5
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
6
+ from langchain_core.messages import HumanMessage, AIMessage
7
+ from langchain_google_genai import ChatGoogleGenerativeAI
8
+
9
+ class Chat:
10
+ def __init__(self):
11
+ self.chat = ChatGoogleGenerativeAI(model="gemini-pro", convert_system_message_to_human=True)
12
+ self.history = []
13
+
14
+ if "GOOGLE_API_KEY" not in os.environ:
15
+ os.environ["GOOGLE_API_KEY"] = st.text_input("Provide your API key: ", type="password")
16
+
17
+ self.prompt = ChatPromptTemplate.from_messages([
18
+ ("system", "You are a senior software engineer. Answer all questions to the best of your ability."),
19
+ MessagesPlaceholder(variable_name="messages"),
20
+ ])
21
+
22
+ def add_message(self, message: str):
23
+ self.history.append(HumanMessage(content=message))
24
+
25
+ def add_ai_message(self, message: str):
26
+ self.history.append(AIMessage(content=message))
27
+
28
+ def chat_with_user(self):
29
+ st.title("Chat with AI")
30
+
31
+ user_input = st.text_input("You: ", "")
32
+ if st.button("Send"):
33
+ if user_input:
34
+ self.add_message(user_input)
35
+ response = self.chat.invoke(self.prompt.format_prompt(messages=self.history).to_messages())
36
+ self.add_ai_message(response.content)
37
+
38
+ st.write(f"AI: {response.content}")
39
+
40
+ # Display chat history
41
+ for msg in self.history:
42
+ if isinstance(msg, HumanMessage):
43
+ st.write(f"User: {msg.content}")
44
+ else:
45
+ st.write(f"AI: {msg.content}")
46
+
47
+ if __name__ == "__main__":
48
+ chat_instance = Chat()
49
+ chat_instance.chat_with_user()