sharadrajore commited on
Commit
a20ebf5
·
verified ·
1 Parent(s): d043e47

updated the code

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +90 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,92 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
 
4
  import streamlit as st
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from typing import Any
3
+ from dotenv import load_dotenv
4
+
5
  import streamlit as st
6
 
7
+ load_dotenv()
8
+
9
+ from langchain_core.prompts import ChatPromptTemplate
10
+ #from langchain_ollama import ChatOllama
11
+ from langchain_google_genai import ChatGoogleGenerativeAI
12
+
13
+
14
+ # -------------------------------
15
+ # LLM Initialization
16
+ # -------------------------------
17
+ @st.cache_resource
18
+ def initialize_llm() -> ChatGoogleGenerativeAI:
19
+ try:
20
+ return ChatGoogleGenerativeAI(model="gemini-3-flash-preview")
21
+ except Exception as e:
22
+ st.error(f"Failed to initialize LLM: {e}")
23
+ st.stop()
24
+
25
+
26
+ # -------------------------------
27
+ # Prompt (Memory-enabled)
28
+ # -------------------------------
29
+ def create_prompt() -> ChatPromptTemplate:
30
+ return ChatPromptTemplate.from_messages([
31
+ ("system", "You are a helpful assistant."),
32
+ ("placeholder", "{messages}")
33
+ ])
34
+
35
+
36
+ # -------------------------------
37
+ # Chain Builder
38
+ # -------------------------------
39
+ def build_chain(prompt: ChatPromptTemplate, llm: ChatGoogleGenerativeAI) -> Any:
40
+ return prompt | llm
41
+
42
+
43
+ # -------------------------------
44
+ # App UI
45
+ # -------------------------------
46
+ def run_streamlit_app():
47
+ st.set_page_config(page_title="Chatbot", layout="centered")
48
+
49
+ st.title("💬 AI Chatbot")
50
+
51
+ llm = initialize_llm()
52
+ prompt = create_prompt()
53
+ chain = build_chain(prompt, llm)
54
+
55
+ # ✅ Session-based memory (equivalent to messages = [])
56
+ if "messages" not in st.session_state:
57
+ st.session_state.messages = []
58
+
59
+ # Display chat history
60
+ for role, content in st.session_state.messages:
61
+ with st.chat_message(role):
62
+ st.markdown(content)
63
+
64
+ # Input box
65
+ user_input = st.chat_input("Type your message...")
66
+
67
+ if user_input:
68
+ # Add user message
69
+ st.session_state.messages.append(("user", user_input))
70
+
71
+ with st.chat_message("user"):
72
+ st.markdown(user_input)
73
+
74
+ # Generate response
75
+ try:
76
+ response = chain.invoke({"messages": st.session_state.messages})
77
+ response_text = response.content
78
+ except Exception as e:
79
+ response_text = f"Error: {e}"
80
+
81
+ # Add assistant response
82
+ st.session_state.messages.append(("assistant", response_text))
83
+
84
+ with st.chat_message("assistant"):
85
+ st.markdown(response_text)
86
+
87
+
88
+ # -------------------------------
89
+ # Entry Point
90
+ # -------------------------------
91
+ if __name__ == "__main__":
92
+ run_streamlit_app()