Ghmustafa11 commited on
Commit
d40fc3c
Β·
verified Β·
1 Parent(s): 740aa8f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -45
app.py CHANGED
@@ -1,64 +1,55 @@
1
  import streamlit as st
2
- from transformers import AutoModelForCausalLM, AutoTokenizer
3
- import torch
4
 
5
- # Load the chatbot model
6
- @st.cache_resource
7
- def load_model():
8
- model_name = "microsoft/DialoGPT-medium" # Conversational model
9
- tokenizer = AutoTokenizer.from_pretrained(model_name)
10
- model = AutoModelForCausalLM.from_pretrained(model_name)
11
- return tokenizer, model
12
 
13
- # Initialize model and tokenizer
14
- tokenizer, model = load_model()
15
-
16
- # Session state for chat history
17
  if "chat_history" not in st.session_state:
18
- st.session_state["chat_history"] = []
 
 
19
 
20
  # Streamlit App Layout
21
  st.title("πŸ€— GM Chatbot")
22
- st.markdown("Hi there! I'm **GM Chatbot**. I can answer your questions, chat with you, and keep the conversation friendly! 😊")
23
 
24
  # User input
25
- user_input = st.text_input("Your Message:", placeholder="Ask me anything or just say hello!")
26
 
27
- # Chatbot Response Logic
28
  if user_input:
29
  # Add user input to chat history
30
- st.session_state["chat_history"].append(f"You: {user_input}")
31
-
32
- # Prepare input for the model
33
- chat_history_str = "\n".join(st.session_state["chat_history"])
34
- inputs = tokenizer.encode(chat_history_str + tokenizer.eos_token, return_tensors="pt")
35
-
36
- # Generate chatbot response
37
- response = model.generate(
38
- inputs,
39
- max_length=100,
40
- pad_token_id=tokenizer.eos_token_id,
41
- temperature=0.7,
42
- top_p=0.9,
43
- do_sample=True
44
- )
45
- bot_reply = tokenizer.decode(response[:, inputs.shape[-1]:][0], skip_special_tokens=True)
46
-
47
- # Add bot reply to chat history
48
- st.session_state["chat_history"].append(f"GM Chatbot: {bot_reply}")
49
-
50
- # Display chat history
51
- for message in st.session_state["chat_history"]:
52
- if message.startswith("GM Chatbot"):
53
- st.write(f"πŸ€– {message}")
54
- else:
55
- st.write(f"πŸ™‚ {message}")
56
 
57
  # Reset Chat Button
58
  if st.button("Reset Chat"):
59
- st.session_state["chat_history"] = []
 
 
60
  st.write("Chat reset! Let's start fresh. 😊")
61
 
62
  # Footer
63
  st.markdown("---")
64
- st.caption("Powered by Hugging Face and Streamlit")
 
1
  import streamlit as st
2
+ import openai
 
3
 
4
+ # Set your OpenAI API key
5
+ openai.api_key = "YOUR_OPENAI_API_KEY" # Replace with your OpenAI API key
 
 
 
 
 
6
 
7
+ # Initialize chat history
 
 
 
8
  if "chat_history" not in st.session_state:
9
+ st.session_state["chat_history"] = [
10
+ {"role": "system", "content": "You are a friendly and knowledgeable assistant. Answer questions accurately and helpfully. Always reply directly and avoid vague or unclear responses."}
11
+ ]
12
 
13
  # Streamlit App Layout
14
  st.title("πŸ€— GM Chatbot")
15
+ st.markdown("Hi! I'm **GM Chatbot**, your friendly assistant. Ask me anything! 😊")
16
 
17
  # User input
18
+ user_input = st.text_input("Your Message:", placeholder="Type your question or start a conversation...")
19
 
 
20
  if user_input:
21
  # Add user input to chat history
22
+ st.session_state["chat_history"].append({"role": "user", "content": user_input})
23
+
24
+ # Generate response from OpenAI GPT
25
+ try:
26
+ response = openai.ChatCompletion.create(
27
+ model="gpt-4", # Use "gpt-3.5-turbo" if GPT-4 is unavailable
28
+ messages=st.session_state["chat_history"],
29
+ temperature=0.7,
30
+ max_tokens=150
31
+ )
32
+ bot_reply = response['choices'][0]['message']['content']
33
+
34
+ # Add bot reply to chat history
35
+ st.session_state["chat_history"].append({"role": "assistant", "content": bot_reply})
36
+
37
+ # Display chat history
38
+ for message in st.session_state["chat_history"]:
39
+ if message["role"] == "assistant":
40
+ st.write(f"πŸ€– GM Chatbot: {message['content']}")
41
+ elif message["role"] == "user":
42
+ st.write(f"πŸ™‚ You: {message['content']}")
43
+ except Exception as e:
44
+ st.error(f"Something went wrong: {e}")
 
 
 
45
 
46
  # Reset Chat Button
47
  if st.button("Reset Chat"):
48
+ st.session_state["chat_history"] = [
49
+ {"role": "system", "content": "You are a friendly and knowledgeable assistant. Answer questions accurately and helpfully. Always reply directly and avoid vague or unclear responses."}
50
+ ]
51
  st.write("Chat reset! Let's start fresh. 😊")
52
 
53
  # Footer
54
  st.markdown("---")
55
+ st.caption("Powered by OpenAI GPT and Streamlit")