eagle0504 commited on
Commit
c1458e2
·
verified ·
1 Parent(s): 8932bb7

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +94 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,96 @@
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
+ # streamlit_app.py
2
+
3
+ import os
4
+ import time
5
+ import requests
6
  import streamlit as st
7
+ from datetime import datetime
8
+ from typing import Generator, Dict, Any
9
+ from requests.exceptions import RequestException
10
+
11
+ # ----------------- Configuration -----------------
12
+ st.set_page_config(page_title="Perplexity Chat", layout="wide")
13
+
14
+ # ----------------- Sidebar Settings -----------------
15
+ st.sidebar.header("Settings")
16
+ default_date = datetime.strptime("2023-01-01", "%Y-%m-%d").date()
17
+ start_date = st.sidebar.date_input("Start Date", default_date)
18
+ search_after_date_filter = start_date.strftime("%-m/%-d/%Y")
19
+
20
+ # Load API key from environment variable
21
+ api_key = os.environ["PERPLEXITY_API_KEY"]
22
+
23
+ if not api_key:
24
+ st.error("Environment variable PERPLEXITY_API_KEY not found.")
25
+ st.stop()
26
+
27
+ model = "sonar-deep-research"
28
+ search_mode = "sec"
29
+
30
+ # ----------------- Session State -----------------
31
+ if "messages" not in st.session_state:
32
+ st.session_state.messages = []
33
+
34
+ # ----------------- Chat UI -----------------
35
+ st.title("📚 Perplexity AI Chat Interface")
36
+ st.caption("Ask questions and get responses powered by Perplexity AI.")
37
+
38
+ # Display chat history
39
+ for msg in st.session_state.messages:
40
+ with st.chat_message(msg["role"]):
41
+ st.markdown(msg["content"])
42
+
43
+ # ----------------- Streaming Response -----------------
44
+ def stream_response(response_text: str) -> Generator[str, None, None]:
45
+ """Yield the response one word at a time for streaming effect."""
46
+ for word in response_text.split():
47
+ yield word + " "
48
+ time.sleep(0.03)
49
+
50
+ def call_perplexity_api(user_query: str) -> str:
51
+ """Send user query to Perplexity API with retry logic."""
52
+ url = "https://api.perplexity.ai/chat/completions"
53
+ headers = {
54
+ "accept": "application/json",
55
+ "authorization": f"Bearer {api_key}",
56
+ "content-type": "application/json"
57
+ }
58
+ payload = {
59
+ "model": model,
60
+ "messages": [{"role": "user", "content": user_query}],
61
+ "stream": False,
62
+ "search_mode": search_mode,
63
+ "search_after_date_filter": search_after_date_filter
64
+ }
65
+
66
+ retries = 3
67
+ for attempt in range(retries):
68
+ try:
69
+ response = requests.post(url, headers=headers, json=payload, timeout=120)
70
+ response.raise_for_status()
71
+ return response.json()["choices"][0]["message"]["content"]
72
+ except RequestException as err:
73
+ if attempt < retries - 1:
74
+ wait_time = 2 ** attempt
75
+ time.sleep(wait_time)
76
+ else:
77
+ raise err
78
+
79
+ # ----------------- Chat Input -----------------
80
+ user_input = st.chat_input("Enter your question here...")
81
+
82
+ if user_input:
83
+ # Display user message
84
+ with st.chat_message("user"):
85
+ st.markdown(user_input)
86
+ st.session_state.messages.append({"role": "user", "content": user_input})
87
 
88
+ # Display assistant response with spinner
89
+ with st.chat_message("assistant"):
90
+ with st.spinner("Thinking..."):
91
+ try:
92
+ full_response = call_perplexity_api(user_input)
93
+ streamed = st.write_stream(stream_response(full_response))
94
+ st.session_state.messages.append({"role": "assistant", "content": full_response})
95
+ except requests.RequestException as err:
96
+ st.error(f"Error: {err}")