Anne31415 commited on
Commit
20bf4f9
·
1 Parent(s): 648a531

Update app.py

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