awacke1 commited on
Commit
0db94bc
·
verified ·
1 Parent(s): 9b60602

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -27
app.py CHANGED
@@ -167,35 +167,62 @@ import uuid
167
  def generate_unique_id():
168
  return str(uuid.uuid4())
169
 
 
170
  def save_to_cosmos_db(container, query, response1, response2):
171
- try:
172
- if container:
173
- max_retries = 3
174
- for attempt in range(max_retries):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  try:
176
- record = {
177
- "id": generate_unique_id(),
178
- "query": query,
179
- "response1": response1,
180
- "response2": response2,
181
- "timestamp": datetime.utcnow().isoformat()
182
- }
183
- container.upsert_item(body=record)
184
- st.success(f"Record saved successfully with ID: {record['id']}")
185
- st.session_state.documents = get_documents(container)
186
- break
187
- except exceptions.CosmosHttpResponseError as e:
188
- if e.status_code == 409 and attempt < max_retries - 1: # Conflict error
189
- st.warning(f"ID conflict occurred. Retrying... (Attempt {attempt + 1})")
190
- continue
191
- else:
192
- raise
193
- else:
194
- st.error("Cosmos DB container is not initialized.")
195
- except exceptions.CosmosHttpResponseError as e:
196
- st.error(f"Error saving record to Cosmos DB: {e}")
197
- except Exception as e:
198
- st.error(f"An unexpected error occurred: {str(e)}")
 
 
 
 
 
 
 
 
 
199
 
200
  # Add dropdowns for model and database choices
201
  def search_glossary(query):
 
167
  def generate_unique_id():
168
  return str(uuid.uuid4())
169
 
170
+
171
  def save_to_cosmos_db(container, query, response1, response2):
172
+ max_retries = 5
173
+ base_wait_time = 0.1 # 100 ms
174
+
175
+ def generate_unique_id():
176
+ timestamp = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
177
+ unique_uuid = str(uuid.uuid4())
178
+ return f"{timestamp}-{unique_uuid}"
179
+
180
+ for attempt in range(max_retries):
181
+ try:
182
+ if container:
183
+ base_id = generate_unique_id()
184
+ record = {
185
+ "id": base_id,
186
+ "query": query,
187
+ "response1": response1,
188
+ "response2": response2,
189
+ "timestamp": datetime.utcnow().isoformat()
190
+ }
191
+
192
+ # Check if document with this ID exists
193
  try:
194
+ existing_doc = container.read_item(item=base_id, partition_key=base_id)
195
+ # If it exists, append a random string to the ID
196
+ record["id"] = f"{base_id}-{str(uuid.uuid4())[:8]}"
197
+ except exceptions.CosmosResourceNotFoundError:
198
+ # If it doesn't exist, we can use the original ID
199
+ pass
200
+
201
+ container.upsert_item(body=record)
202
+ st.success(f"Record saved successfully with ID: {record['id']}")
203
+ st.session_state.documents = container.query_items(
204
+ query="SELECT * FROM c ORDER BY c._ts DESC",
205
+ enable_cross_partition_query=True
206
+ )
207
+ return
208
+ else:
209
+ st.error("Cosmos DB container is not initialized.")
210
+ return
211
+ except exceptions.CosmosHttpResponseError as e:
212
+ if e.status_code == 409: # Conflict error
213
+ wait_time = (2 ** attempt) * base_wait_time
214
+ st.warning(f"ID conflict occurred. Retrying in {wait_time:.2f} seconds... (Attempt {attempt + 1})")
215
+ time.sleep(wait_time)
216
+ else:
217
+ st.error(f"Error saving record to Cosmos DB: {e}")
218
+ return
219
+ except Exception as e:
220
+ st.error(f"An unexpected error occurred: {str(e)}")
221
+ return
222
+
223
+ st.error("Failed to save record after maximum retries.")
224
+
225
+
226
 
227
  # Add dropdowns for model and database choices
228
  def search_glossary(query):