Update flask_Character.py
Browse files- flask_Character.py +23 -8
flask_Character.py
CHANGED
|
@@ -358,7 +358,7 @@ def _generate_response_internal(
|
|
| 358 |
if not email_text:
|
| 359 |
print(f"[{datetime.now()}] _generate_response_internal: Email text is empty.")
|
| 360 |
return "Cannot generate reply for empty email text."
|
| 361 |
-
|
| 362 |
try:
|
| 363 |
llm = ChatGroq(model="meta-llama/llama-4-scout-17b-16e-instruct", temperature=0.7, max_tokens=800, groq_api_key=api_key)
|
| 364 |
prompt_template_str="""
|
|
@@ -581,7 +581,7 @@ async def extract_email_data(request: ProcessEmailRequest):
|
|
| 581 |
"""
|
| 582 |
if extracted_emails_collection is None:
|
| 583 |
raise HTTPException(status_code=503, detail="MongoDB not available.")
|
| 584 |
-
|
| 585 |
current_date = date.today() # Get current date for context
|
| 586 |
|
| 587 |
print(f"[{datetime.now()}] /extract-data: Received request.")
|
|
@@ -589,20 +589,35 @@ async def extract_email_data(request: ProcessEmailRequest):
|
|
| 589 |
print(f"[{datetime.now()}] /extract-data: Calling internal processing function.")
|
| 590 |
# Run blocking LLM call in a thread pool
|
| 591 |
extracted_data = await asyncio.to_thread(_process_email_internal, request.email_text, request.groq_api_key, current_date)
|
| 592 |
-
|
| 593 |
print(f"[{datetime.now()}] /extract-data: Internal processing complete. Preparing for DB insert.")
|
| 594 |
# Convert Pydantic model to dictionary for MongoDB insert, handling _id alias
|
| 595 |
# Use model_dump for Pydantic v2
|
| 596 |
data_to_insert = extracted_data.model_dump(by_alias=True, exclude_none=True, exclude={'id'})
|
| 597 |
|
| 598 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 599 |
# Use asyncio.to_thread for blocking MongoDB insert operation
|
| 600 |
insert_result = await asyncio.to_thread(extracted_emails_collection.insert_one, data_to_insert)
|
| 601 |
-
|
| 602 |
# Update the extracted_data object with the MongoDB-generated ID
|
| 603 |
extracted_data.id = str(insert_result.inserted_id)
|
| 604 |
print(f"[{datetime.now()}] /extract-data: Data inserted into MongoDB. ID: {extracted_data.id}")
|
| 605 |
-
|
| 606 |
return extracted_data
|
| 607 |
except ValueError as ve:
|
| 608 |
raise HTTPException(status_code=400, detail=str(ve))
|
|
@@ -645,7 +660,7 @@ async def query_extracted_emails(query_params: ExtractedEmailQuery = Depends()):
|
|
| 645 |
cursor = await asyncio.to_thread(extracted_emails_collection.find, mongo_query)
|
| 646 |
# Use to_list to limit results and convert to list
|
| 647 |
results = await asyncio.to_thread(lambda: list(cursor.limit(query_params.limit)))
|
| 648 |
-
|
| 649 |
# Convert MongoDB documents to ExtractedData Pydantic models
|
| 650 |
return [ExtractedData(**doc) for doc in results]
|
| 651 |
except Exception as e:
|
|
@@ -683,7 +698,7 @@ async def query_generated_replies(query_params: GeneratedReplyQuery = Depends())
|
|
| 683 |
cursor = await asyncio.to_thread(generated_replies_collection.find, mongo_query)
|
| 684 |
# Use to_list to limit results and convert to list
|
| 685 |
results = await asyncio.to_thread(lambda: list(cursor.limit(query_params.limit)))
|
| 686 |
-
|
| 687 |
# Convert MongoDB documents to GeneratedReplyData Pydantic models
|
| 688 |
return [GeneratedReplyData(**doc) for doc in results]
|
| 689 |
except Exception as e:
|
|
|
|
| 358 |
if not email_text:
|
| 359 |
print(f"[{datetime.now()}] _generate_response_internal: Email text is empty.")
|
| 360 |
return "Cannot generate reply for empty email text."
|
| 361 |
+
|
| 362 |
try:
|
| 363 |
llm = ChatGroq(model="meta-llama/llama-4-scout-17b-16e-instruct", temperature=0.7, max_tokens=800, groq_api_key=api_key)
|
| 364 |
prompt_template_str="""
|
|
|
|
| 581 |
"""
|
| 582 |
if extracted_emails_collection is None:
|
| 583 |
raise HTTPException(status_code=503, detail="MongoDB not available.")
|
| 584 |
+
|
| 585 |
current_date = date.today() # Get current date for context
|
| 586 |
|
| 587 |
print(f"[{datetime.now()}] /extract-data: Received request.")
|
|
|
|
| 589 |
print(f"[{datetime.now()}] /extract-data: Calling internal processing function.")
|
| 590 |
# Run blocking LLM call in a thread pool
|
| 591 |
extracted_data = await asyncio.to_thread(_process_email_internal, request.email_text, request.groq_api_key, current_date)
|
| 592 |
+
|
| 593 |
print(f"[{datetime.now()}] /extract-data: Internal processing complete. Preparing for DB insert.")
|
| 594 |
# Convert Pydantic model to dictionary for MongoDB insert, handling _id alias
|
| 595 |
# Use model_dump for Pydantic v2
|
| 596 |
data_to_insert = extracted_data.model_dump(by_alias=True, exclude_none=True, exclude={'id'})
|
| 597 |
|
| 598 |
+
# --- NEW CONVERSION FOR MONGODB ---
|
| 599 |
+
# MongoDB's BSON doesn't natively support Python's datetime.date type.
|
| 600 |
+
# It expects datetime.datetime. Convert all date fields to datetime.datetime.
|
| 601 |
+
if 'appointments' in data_to_insert:
|
| 602 |
+
for appt in data_to_insert['appointments']:
|
| 603 |
+
if isinstance(appt.get('start_date'), date):
|
| 604 |
+
appt['start_date'] = datetime.combine(appt['start_date'], datetime.min.time())
|
| 605 |
+
if isinstance(appt.get('end_date'), date) and appt.get('end_date') is not None:
|
| 606 |
+
appt['end_date'] = datetime.combine(appt['end_date'], datetime.min.time())
|
| 607 |
+
if 'tasks' in data_to_insert:
|
| 608 |
+
for task_item in data_to_insert['tasks']:
|
| 609 |
+
if isinstance(task_item.get('due_date'), date):
|
| 610 |
+
task_item['due_date'] = datetime.combine(task_item['due_date'], datetime.min.time())
|
| 611 |
+
# --- END NEW CONVERSION ---
|
| 612 |
+
|
| 613 |
+
print(f"[{datetime.now()}] /extract-data: Inserting into MongoDB... Data: {data_to_insert}") # Add data logging
|
| 614 |
# Use asyncio.to_thread for blocking MongoDB insert operation
|
| 615 |
insert_result = await asyncio.to_thread(extracted_emails_collection.insert_one, data_to_insert)
|
| 616 |
+
|
| 617 |
# Update the extracted_data object with the MongoDB-generated ID
|
| 618 |
extracted_data.id = str(insert_result.inserted_id)
|
| 619 |
print(f"[{datetime.now()}] /extract-data: Data inserted into MongoDB. ID: {extracted_data.id}")
|
| 620 |
+
|
| 621 |
return extracted_data
|
| 622 |
except ValueError as ve:
|
| 623 |
raise HTTPException(status_code=400, detail=str(ve))
|
|
|
|
| 660 |
cursor = await asyncio.to_thread(extracted_emails_collection.find, mongo_query)
|
| 661 |
# Use to_list to limit results and convert to list
|
| 662 |
results = await asyncio.to_thread(lambda: list(cursor.limit(query_params.limit)))
|
| 663 |
+
|
| 664 |
# Convert MongoDB documents to ExtractedData Pydantic models
|
| 665 |
return [ExtractedData(**doc) for doc in results]
|
| 666 |
except Exception as e:
|
|
|
|
| 698 |
cursor = await asyncio.to_thread(generated_replies_collection.find, mongo_query)
|
| 699 |
# Use to_list to limit results and convert to list
|
| 700 |
results = await asyncio.to_thread(lambda: list(cursor.limit(query_params.limit)))
|
| 701 |
+
|
| 702 |
# Convert MongoDB documents to GeneratedReplyData Pydantic models
|
| 703 |
return [GeneratedReplyData(**doc) for doc in results]
|
| 704 |
except Exception as e:
|