anonymous commited on
Commit
1f9735b
Β·
verified Β·
1 Parent(s): 01bf753

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +134 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,136 @@
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 streamlit as st
2
+ from bs4 import BeautifulSoup
3
+ from openai import OpenAI
4
+ from dotenv import load_dotenv
5
+ import os
6
 
7
+ # ==== Load API Key from .env ====
8
+ load_dotenv()
9
+ hf_api_key = os.getenv("HUGGINGFACE_API_KEY")
10
+
11
+ if not hf_api_key:
12
+ st.error("❌ API key not found. Please set HUGGINGFACE_API_KEY in your .env file.")
13
+ st.stop()
14
+
15
+ # ==== Initialize Client ====
16
+ client = OpenAI(
17
+ base_url="https://router.huggingface.co/v1",
18
+ api_key=hf_api_key,
19
+ )
20
+
21
+ # ==== Streamlit Page Setup ====
22
+ st.set_page_config(page_title="OSS ChatGPT", layout="wide")
23
+ st.title("πŸ€– ChatGPT")
24
+
25
+ # ==== Sidebar ====
26
+ st.sidebar.title("πŸ› οΈ Settings")
27
+ model_choice = st.sidebar.selectbox("Choose a model", [
28
+ "openai/gpt-oss-20b:hyperbolic",
29
+ "openai/gpt-oss-120b:hyperbolic"
30
+ ])
31
+
32
+
33
+
34
+ if st.sidebar.button("🧹 Clear Chat"):
35
+ st.session_state.messages = []
36
+ st.rerun()
37
+
38
+ # ==== Session Initialization ====
39
+ if "messages" not in st.session_state:
40
+ st.session_state.messages = []
41
+
42
+ # ==== LaTeX Rendering Helper ====
43
+ def render_markdown_with_latex(text: str):
44
+ mathjax_script = """
45
+ <script type="text/javascript">
46
+ MathJax = {
47
+ tex: {
48
+ inlineMath: [['$', '$']],
49
+ displayMath: [['$$', '$$']]
50
+ },
51
+ svg: {
52
+ fontCache: 'global'
53
+ }
54
+ };
55
+ </script>
56
+ <script async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script>
57
+ """
58
+ st.markdown(mathjax_script, unsafe_allow_html=True)
59
+ st.markdown(text, unsafe_allow_html=True)
60
+ # ... (keep all your existing imports and setup code until the message display section)
61
+ # ... (keep all your existing imports and setup code until the message display section)
62
+
63
+ # ==== Display Chat History ====
64
+ for i, msg in enumerate(st.session_state.messages):
65
+ with st.chat_message(msg["role"]):
66
+ if msg["role"] == "assistant":
67
+ # Check if content contains thinking pattern
68
+ if msg["content"].startswith("<think>") and "</think>" in msg["content"]:
69
+ # Extract thinking and response parts
70
+ thinking_part = msg["content"].split("<think>")[1].split("</think>")[0].strip()
71
+ response_part = msg["content"].split("</think>")[1].strip()
72
+
73
+ # Display the main response
74
+ render_markdown_with_latex(response_part)
75
+
76
+ # Create expander for thinking
77
+ with st.expander("πŸ’­ Show Thinking"):
78
+ st.markdown(f"<span style='color: #666; font-style: italic'>{thinking_part}</span>",
79
+ unsafe_allow_html=True)
80
+ else:
81
+ render_markdown_with_latex(msg["content"])
82
+ else:
83
+ # Display user messages
84
+ render_markdown_with_latex(msg["content"])
85
+
86
+ # ==== Chat Input ====
87
+ st.write("Akshay")
88
+ if prompt := st.chat_input("Type your message...",key="unique_chat_input_key"):
89
+ print(f"=> {prompt}")
90
+ with st.chat_message("user"):
91
+ st.markdown(prompt)
92
+
93
+ # Add user message to history
94
+ st.session_state.messages.append({"role": "user", "content": prompt})
95
+
96
+ try:
97
+ with st.chat_message("assistant"):
98
+ response_placeholder = st.empty()
99
+
100
+ with st.spinner("Thinking..."):
101
+ completion = client.chat.completions.create(
102
+ model=model_choice,
103
+ messages=[
104
+ {"role": m["role"], "content": m["content"]}
105
+ for m in st.session_state.messages
106
+ ]
107
+ )
108
+ raw = completion.choices[0].message.content
109
+
110
+ # Parse thinking and response
111
+ if "<think>" in raw and "</think>" in raw:
112
+ thinking_part = raw.split("<think>")[1].split("</think>")[0].strip()
113
+ response_part = raw.split("</think>")[1].strip()
114
+
115
+ # Display main response
116
+ clean_response = BeautifulSoup(response_part, "html.parser").get_text()
117
+ with st.expander("πŸ’­ Show Thinking"):
118
+ st.markdown(f"<span style='color: #666; font-style: italic'>{thinking_part}</span>",
119
+ unsafe_allow_html=True)
120
+ response_placeholder.markdown(clean_response)
121
+ # Store both parts in history
122
+ full_content = f"<think>{thinking_part}</think>{clean_response}"
123
+
124
+ else:
125
+ clean_response = BeautifulSoup(raw, "html.parser").get_text()
126
+ response_placeholder.markdown(clean_response)
127
+ full_content = clean_response
128
+
129
+ # Add assistant response to history
130
+ st.session_state.messages.append({"role": "assistant", "content": full_content})
131
+
132
+ except Exception as e:
133
+ error_msg = f"❌ Error: {str(e)}"
134
+ with st.chat_message("assistant"):
135
+ st.error(error_msg)
136
+ st.session_state.messages.append({"role": "assistant", "content": error_msg})