Imtaiz commited on
Commit
8ea5be9
·
verified ·
1 Parent(s): 7aa8ce0

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +62 -0
app.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import time
3
+ from openai import OpenAI
4
+ import os
5
+ from config import * # Import all configurations
6
+ from customcss1 import CUSTOM_CSS
7
+
8
+ my_secret = os.environ['OPENAI_API_KEY']
9
+ client = OpenAI(api_key=my_secret)
10
+
11
+ # Thinking Animation
12
+ THINKING_DOTS = ["", ".", "..", "..."]
13
+ THINKING_INTERVAL = 0.5 # seconds
14
+
15
+ def ensure_single_thread_id():
16
+ if "thread_id" not in st.session_state:
17
+ thread = client.beta.threads.create()
18
+ st.session_state.thread_id = thread.id
19
+ return st.session_state.thread_id
20
+
21
+ def get_avatar(role):
22
+ return AVATAR_CONFIG.get(role)
23
+
24
+ def get_assistant_response(prompt, thread_id, assistant_id):
25
+ message_placeholder = st.empty()
26
+ i = 0
27
+
28
+ # Create message
29
+ client.beta.threads.messages.create(
30
+ thread_id=thread_id,
31
+ role="user",
32
+ content=prompt
33
+ )
34
+
35
+ # Start streaming
36
+ stream = client.beta.threads.runs.create(
37
+ thread_id=thread_id,
38
+ assistant_id=assistant_id,
39
+ stream=True
40
+ )
41
+
42
+ full_response = ""
43
+
44
+ # Stream the response
45
+ for event in stream:
46
+ if not full_response:
47
+ message_placeholder.markdown(f"*Thinking{THINKING_DOTS[i % len(THINKING_DOTS)]}*", unsafe_allow_html=True)
48
+ i += 1
49
+ time.sleep(THINKING_INTERVAL)
50
+
51
+ if event.data.object == "thread.message.delta":
52
+ for content in event.data.delta.content:
53
+ if content.type == 'text':
54
+ full_response += content.text.value
55
+ formatted_response = f'<div class="fade-in assistant-message">{full_response}▌</div>'
56
+ message_placeholder.markdown(formatted_response, unsafe_allow_html=True)
57
+ time.sleep(0.01)
58
+
59
+ # Final display without cursor
60
+ formatted_response = f'<div class="fade-in assistant-message">{full_response}</div>'
61
+ message_placeholder.markdown(formatted_response, unsafe_allow_html=True)
62
+ return full_response