Anne31415 commited on
Commit
7290aeb
·
1 Parent(s): d34cbb7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +159 -115
app.py CHANGED
@@ -30,118 +30,162 @@ client = openai.Client()
30
 
31
  MODEL = "gpt-4-1106-preview"
32
 
33
-
34
- if "session_id" not in st.session_state:
35
- st.session_state.session_id = str(uuid.uuid4())
36
-
37
- if "run" not in st.session_state:
38
- st.session_state.run = {"status": None}
39
-
40
- if "messages" not in st.session_state:
41
- st.session_state.messages = []
42
-
43
- if "retry_error" not in st.session_state:
44
- st.session_state.retry_error = 0
45
-
46
- st.set_page_config(page_title="OpenAI - Assistent API")
47
- st.sidebar.title("OpenAI - Assistant API🤖")
48
- st.sidebar.markdown("**Model:** gpt-4-1106-preview API")
49
- st.sidebar.markdown("**Version:** 1.1")
50
- st.sidebar.markdown("**Session-ID:**")
51
- st.sidebar.markdown(st.session_state.session_id)
52
- st.sidebar.divider()
53
- st.title("Assitent-Name")
54
- st.text("Beschreibung")
55
-
56
- if "assistant" not in st.session_state:
57
- openai.api_key = api_key
58
- # Load the previously created assistant
59
- st.session_state.assistant = openai.beta.assistants.retrieve(assistant_id)
60
-
61
- # Create a new thread for this session
62
- st.session_state.thread = client.beta.threads.create(
63
- metadata={
64
- 'session_id': st.session_state.session_id,
65
- }
66
- )
67
-
68
- # If the run is completed, display the messages
69
- elif hasattr(st.session_state.run, 'status') and st.session_state.run.status == "completed":
70
- # Retrieve the list of messages
71
- st.session_state.messages = client.beta.threads.messages.list(
72
- thread_id=st.session_state.thread.id
73
- )
74
-
75
- end_time = time.time() # Stop the timer
76
- duration = end_time - start_time # Calculate duration
77
-
78
- st.write(f"Response time: {duration:.2f} seconds")
79
-
80
-
81
- # Display messages
82
- for message in reversed(st.session_state.messages.data):
83
- if message.role in ["user", "assistant"]:
84
- with st.chat_message(message.role):
85
- for content_part in message.content:
86
- if content_part.type == 'text': # For text responses
87
- message_text = content_part.text.value
88
- st.markdown(message_text)
89
- # New code to handle image files
90
- elif hasattr(content_part, 'image_file') and content_part.image_file:
91
- image = handle_and_display_image(content_part.image_file.file_id)
92
- if image:
93
- st.image(image, caption="Generated Image")
94
-
95
- start_time = time.time() # Start the timer
96
-
97
- if prompt := st.chat_input("Wie kann ich dir helfen?"):
98
- with st.chat_message('user'):
99
- st.write(prompt)
100
-
101
- # Add message to the thread
102
- st.session_state.messages = client.beta.threads.messages.create(
103
- thread_id=st.session_state.thread.id,
104
- role="user",
105
- content=prompt
106
- )
107
-
108
- # Do a run to process the messages in the thread
109
- st.session_state.run = client.beta.threads.runs.create(
110
- thread_id=st.session_state.thread.id,
111
- assistant_id=st.session_state.assistant.id,
112
- )
113
- if st.session_state.retry_error < 3:
114
- time.sleep(1) # Wait 1 second before checking run status
115
- st.rerun()
116
-
117
- # Check if 'run' object has 'status' attribute
118
- if hasattr(st.session_state.run, 'status'):
119
- # Handle the 'running' status
120
- if st.session_state.run.status == "running":
121
- with st.chat_message('assistant'):
122
- st.write("Thinking ......")
123
- if st.session_state.retry_error < 3:
124
- time.sleep(1) # Short delay to prevent immediate rerun, adjust as needed
125
- st.rerun()
126
-
127
- # Handle the 'failed' status
128
- elif st.session_state.run.status == "failed":
129
- st.session_state.retry_error += 1
130
- with st.chat_message('assistant'):
131
- if st.session_state.retry_error < 3:
132
- st.write("Run failed, retrying ......")
133
- time.sleep(3) # Longer delay before retrying
134
- st.rerun()
135
- else:
136
- st.error("FAILED: The OpenAI API is currently processing too many requests. Please try again later ......")
137
-
138
- # Handle any status that is not 'completed'
139
- elif st.session_state.run.status != "completed":
140
- # Attempt to retrieve the run again, possibly redundant if there's no other status but 'running' or 'failed'
141
- st.session_state.run = client.beta.threads.runs.retrieve(
142
- thread_id=st.session_state.thread.id,
143
- run_id=st.session_state.run.id,
144
- )
145
- if st.session_state.retry_error < 3:
146
- time.sleep(3)
147
- st.rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  MODEL = "gpt-4-1106-preview"
32
 
33
+ def page2():
34
+ try:
35
+
36
+ if "session_id" not in st.session_state:
37
+ st.session_state.session_id = str(uuid.uuid4())
38
+
39
+ if "run" not in st.session_state:
40
+ st.session_state.run = {"status": None}
41
+
42
+ if "messages" not in st.session_state:
43
+ st.session_state.messages = []
44
+
45
+ if "retry_error" not in st.session_state:
46
+ st.session_state.retry_error = 0
47
+
48
+
49
+
50
+ if "assistant" not in st.session_state:
51
+ openai.api_key = api_key
52
+ # Load the previously created assistant
53
+ st.session_state.assistant = openai.beta.assistants.retrieve(assistant_id)
54
+
55
+ # Create a new thread for this session
56
+ st.session_state.thread = client.beta.threads.create(
57
+ metadata={
58
+ 'session_id': st.session_state.session_id,
59
+ }
60
+ )
61
+
62
+ # If the run is completed, display the messages
63
+ elif hasattr(st.session_state.run, 'status') and st.session_state.run.status == "completed":
64
+ # Retrieve the list of messages
65
+ st.session_state.messages = client.beta.threads.messages.list(
66
+ thread_id=st.session_state.thread.id
67
+ )
68
+
69
+ end_time = time.time() # Stop the timer
70
+ duration = end_time - start_time # Calculate duration
71
+
72
+ st.write(f"Response time: {duration:.2f} seconds")
73
+
74
+
75
+ # Display messages
76
+ for message in reversed(st.session_state.messages.data):
77
+ if message.role in ["user", "assistant"]:
78
+ with st.chat_message(message.role):
79
+ for content_part in message.content:
80
+ if content_part.type == 'text': # For text responses
81
+ message_text = content_part.text.value
82
+ st.markdown(message_text)
83
+ # New code to handle image files
84
+ elif hasattr(content_part, 'image_file') and content_part.image_file:
85
+ image = handle_and_display_image(content_part.image_file.file_id)
86
+ if image:
87
+ st.image(image, caption="Generated Image")
88
+
89
+ start_time = time.time() # Start the timer
90
+
91
+ if prompt := st.chat_input("Wie kann ich dir helfen?"):
92
+ with st.chat_message('user'):
93
+ st.write(prompt)
94
+
95
+ # Add message to the thread
96
+ st.session_state.messages = client.beta.threads.messages.create(
97
+ thread_id=st.session_state.thread.id,
98
+ role="user",
99
+ content=prompt
100
+ )
101
+
102
+ # Do a run to process the messages in the thread
103
+ st.session_state.run = client.beta.threads.runs.create(
104
+ thread_id=st.session_state.thread.id,
105
+ assistant_id=st.session_state.assistant.id,
106
+ )
107
+ if st.session_state.retry_error < 3:
108
+ time.sleep(1) # Wait 1 second before checking run status
109
+ st.rerun()
110
+
111
+ # Check if 'run' object has 'status' attribute
112
+ if hasattr(st.session_state.run, 'status'):
113
+ # Handle the 'running' status
114
+ if st.session_state.run.status == "running":
115
+ with st.chat_message('assistant'):
116
+ st.write("Thinking ......")
117
+ if st.session_state.retry_error < 3:
118
+ time.sleep(1) # Short delay to prevent immediate rerun, adjust as needed
119
+ st.rerun()
120
+
121
+ # Handle the 'failed' status
122
+ elif st.session_state.run.status == "failed":
123
+ st.session_state.retry_error += 1
124
+ with st.chat_message('assistant'):
125
+ if st.session_state.retry_error < 3:
126
+ st.write("Run failed, retrying ......")
127
+ time.sleep(3) # Longer delay before retrying
128
+ st.rerun()
129
+ else:
130
+ st.error("FAILED: The OpenAI API is currently processing too many requests. Please try again later ......")
131
+
132
+ # Handle any status that is not 'completed'
133
+ elif st.session_state.run.status != "completed":
134
+ # Attempt to retrieve the run again, possibly redundant if there's no other status but 'running' or 'failed'
135
+ st.session_state.run = client.beta.threads.runs.retrieve(
136
+ thread_id=st.session_state.thread.id,
137
+ run_id=st.session_state.run.id,
138
+ )
139
+ if st.session_state.retry_error < 3:
140
+ time.sleep(3)
141
+ st.rerun()
142
+
143
+
144
+ except Exception as e:
145
+ st.error(f"Upsi, an unexpected error occurred: {e}")
146
+
147
+ def page2():
148
+ try:
149
+ hide_streamlit_style = """
150
+ <style>
151
+ #MainMenu {visibility: hidden;}
152
+ footer {visibility: hidden;}
153
+ </style>
154
+ """
155
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)
156
+
157
+ # Create columns for layout
158
+ col1, col2 = st.columns([3, 1]) # Adjust the ratio to your liking
159
+
160
+ with col1:
161
+ st.title("Test Page with Logo!")
162
+
163
+ with col2:
164
+ # Load and display the image in the right column, which will be the top-right corner of the page
165
+ image = Image.open('BinDoc Logo (Quadratisch).png')
166
+ st.image(image, use_column_width='always')
167
+
168
+ except Exception as e:
169
+ st.error(f"Upsi, an unexpected error occurred: {e}")
170
+
171
+
172
+
173
+ def main():
174
+ # Sidebar content
175
+ with st.sidebar:
176
+ st.title('BinDoc GmbH')
177
+ st.markdown("Experience revolutionary interaction with BinDocs Chat App, leveraging state-of-the-art AI technology.")
178
+ add_vertical_space(1)
179
+ page = st.sidebar.selectbox("Choose a page", ["Analysis Bot", "Test Page"])
180
+ add_vertical_space(1)
181
+ st.write('Made with ❤️ by BinDoc GmbH')
182
+
183
+ # Main area content based on page selection
184
+ if page == "Analysis Bot":
185
+ page1()
186
+ elif page == "Test Page":
187
+ page2()
188
+
189
+
190
+ if __name__ == "__main__":
191
+ main()