abdullah1234khan commited on
Commit
1e25c22
·
verified ·
1 Parent(s): a4ffb69

Upload Adv_chatbot.py

Browse files
Files changed (1) hide show
  1. Adv_chatbot.py +68 -0
Adv_chatbot.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_core.prompts import ChatPromptTemplate
2
+ from langchain_core.output_parsers import StrOutputParser
3
+ from langchain_community.llms import Ollama
4
+ import streamlit as st
5
+ import os
6
+ from dotenv import load_dotenv
7
+
8
+ # Load environment variables
9
+ load_dotenv()
10
+
11
+ # Streamlit config
12
+ st.set_page_config(page_title="Llama3 Chatbot", layout="centered")
13
+ st.title("🦙 LangChain Chatbot with Memory")
14
+
15
+ # Apply basic styling
16
+ st.markdown("""
17
+ <style>
18
+ .reportview-container {
19
+ background-color: #f5f5f5;
20
+ }
21
+ .stTextInput>div>div>input {
22
+ font-size: 18px;
23
+ }
24
+ </style>
25
+ """, unsafe_allow_html=True)
26
+
27
+ # Initialize chat history
28
+ if "chat_history" not in st.session_state:
29
+ st.session_state.chat_history = [("system", "You are a helpful AI assistant. Please respond to the user's queries clearly and concisely.")]
30
+
31
+ # Temperature control
32
+ temperature = st.slider("🔧 Set Model Temperature", 0.0, 1.0, 0.7)
33
+
34
+ # Model and parser setup
35
+ llm = Ollama(model="llama3.2:1b", temperature=temperature)
36
+ output_parser = StrOutputParser()
37
+
38
+ # Clear Chat Button
39
+ if st.button("🗑️ Clear Chat"):
40
+ st.session_state.chat_history = [("system", "You are a helpful AI assistant. Please respond to the user's queries clearly and concisely.")]
41
+ st.rerun()
42
+
43
+ # Chat history display
44
+ for role, message in st.session_state.chat_history:
45
+ if role == "user":
46
+ st.markdown(f"**You:** {message}")
47
+ elif role == "assistant":
48
+ st.markdown(f"**Bot:** {message}")
49
+
50
+ # 👉 Input field shown **after** chat history
51
+ with st.form("chat_form", clear_on_submit=True):
52
+ user_input = st.text_input("💬 Type your next message here", key="user_input")
53
+ submitted = st.form_submit_button("Send")
54
+
55
+ # If message submitted
56
+ if submitted and user_input:
57
+ st.session_state.chat_history.append(("user", user_input))
58
+ prompt = ChatPromptTemplate.from_messages(st.session_state.chat_history)
59
+ chain = prompt | llm | output_parser
60
+
61
+ with st.spinner("🤔 Thinking..."):
62
+ try:
63
+ response = chain.invoke({})
64
+ st.session_state.chat_history.append(("assistant", response))
65
+ st.rerun() # Refresh to show response and move input down
66
+ except Exception as e:
67
+ st.session_state.chat_history.append(("assistant", f"Error: {e}"))
68
+ st.rerun()