taspol commited on
Commit
4564d70
·
1 Parent(s): d3d6761

feat: improve error handling

Browse files
Files changed (1) hide show
  1. app.py +54 -29
app.py CHANGED
@@ -6,11 +6,16 @@ from utils.llm_caller import LLMCaller
6
  import asyncio
7
  import time
8
  from datetime import datetime
 
 
9
 
10
  app = FastAPI()
11
  data_importer = DataImporter()
12
  agent = LLMCaller()
13
 
 
 
 
14
  @app.get("/")
15
  def root():
16
  """Root endpoint - Hugging Face checks this"""
@@ -29,11 +34,6 @@ def health_check():
29
  "service": "PAN-SEA Travel Planning API"
30
  }
31
 
32
- @app.get("/ready")
33
- def ready_check():
34
- """Simple ready check for Hugging Face"""
35
- return {"ready": True, "status": "ok"}
36
-
37
  @app.get("/v1")
38
  def greet_json():
39
  start_time = time.time()
@@ -57,30 +57,37 @@ def generate_trip_plan(request: PlanRequest):
57
  preparation=trip_plan.preparation,
58
  meta={"status": "success", "timestamp": datetime.utcnow().isoformat()})
59
  except Exception as e:
60
- print(f"Error in generate_trip_plan: {e}")
61
- # Return error response
62
- return PlanResponse(
63
- tripOverview=f"Error: {str(e)}",
64
- query_params=request,
65
- retrieved_data=[],
66
- trip_plan=TripPlan(tripOverview="Error occurred", timeline=[], spots=[], budget={}, permits={}, safety={}, contact={}, safetyContacts={}),
67
- preparation=None,
68
- meta={"status": "error", "error": str(e)}
69
  )
70
 
 
71
  @app.post("/v1/addYoutubeLink", response_model=YoutubeLinkResponse)
72
  def add_youtube_link(request: YoutubeLinkRequest):
73
  try:
74
  data_importer.insert_from_youtube(request.video_id)
75
- except Exception as e:
76
  return YoutubeLinkResponse(
77
- message="Failed to add YouTube link",
78
- video_url= None
 
 
 
 
 
 
 
 
 
 
 
 
79
  )
80
- return YoutubeLinkResponse(
81
- message="add successfully",
82
- video_url=f"https://www.youtube.com/watch?v={request.video_id}"
83
- )
84
 
85
  @app.post("/v1/searchSimilar", response_model=list[dict])
86
  def search_similar(request: YoutubeLinkRequest):
@@ -88,15 +95,33 @@ def search_similar(request: YoutubeLinkRequest):
88
  results = data_importer.search_similar(query=request.video_id)
89
  return results
90
  except Exception as e:
91
- print(f"Error during search: {e}")
92
- return {"error": "Search failed"}
93
- return []
 
 
 
 
 
 
94
 
95
  @app.post("/v1/basicChat", response_model=str)
96
  def basic_chat(request: ChatRequest):
97
- user_message = request.message
98
- llm_response = asyncio.run(agent.basic_query(
99
- user_prompt=user_message
100
- ))
101
- return llm_response
 
 
 
 
 
 
 
 
 
 
 
 
102
 
 
6
  import asyncio
7
  import time
8
  from datetime import datetime
9
+ from fastapi import FastAPI, HTTPException
10
+ import logging
11
 
12
  app = FastAPI()
13
  data_importer = DataImporter()
14
  agent = LLMCaller()
15
 
16
+ logging.basicConfig(level=logging.INFO)
17
+ logger = logging.getLogger(__name__)
18
+
19
  @app.get("/")
20
  def root():
21
  """Root endpoint - Hugging Face checks this"""
 
34
  "service": "PAN-SEA Travel Planning API"
35
  }
36
 
 
 
 
 
 
37
  @app.get("/v1")
38
  def greet_json():
39
  start_time = time.time()
 
57
  preparation=trip_plan.preparation,
58
  meta={"status": "success", "timestamp": datetime.utcnow().isoformat()})
59
  except Exception as e:
60
+ logger.error(f"Error in generate_trip_plan: {e}")
61
+ raise HTTPException(
62
+ status_code=500,
63
+ detail={
64
+ "error": "Internal server error",
65
+ "message": "Failed to generate trip plan",
66
+ "details": str(e)
67
+ }
 
68
  )
69
 
70
+
71
  @app.post("/v1/addYoutubeLink", response_model=YoutubeLinkResponse)
72
  def add_youtube_link(request: YoutubeLinkRequest):
73
  try:
74
  data_importer.insert_from_youtube(request.video_id)
 
75
  return YoutubeLinkResponse(
76
+ message="add successfully",
77
+ video_url=f"https://www.youtube.com/watch?v={request.video_id}"
78
+ )
79
+ except ValueError as e:
80
+ raise HTTPException(status_code=400, detail=f"Invalid video ID: {str(e)}")
81
+ except Exception as e:
82
+ logger.error(f"Error adding YouTube link: {e}")
83
+ raise HTTPException(
84
+ status_code=500,
85
+ detail={
86
+ "error": "Internal server error",
87
+ "message": "Failed to add YouTube link",
88
+ "details": str(e)
89
+ }
90
  )
 
 
 
 
91
 
92
  @app.post("/v1/searchSimilar", response_model=list[dict])
93
  def search_similar(request: YoutubeLinkRequest):
 
95
  results = data_importer.search_similar(query=request.video_id)
96
  return results
97
  except Exception as e:
98
+ logger.error(f"Error during search: {e}")
99
+ raise HTTPException(
100
+ status_code=500,
101
+ detail={
102
+ "error": "Search failed",
103
+ "message": "Unable to search similar content",
104
+ "details": str(e)
105
+ }
106
+ )
107
 
108
  @app.post("/v1/basicChat", response_model=str)
109
  def basic_chat(request: ChatRequest):
110
+ try:
111
+ user_message = request.message
112
+ llm_response = asyncio.run(agent.basic_query(
113
+ user_prompt=user_message
114
+ ))
115
+ return llm_response
116
+ except Exception as e:
117
+ logger.error(f"Error in basic_chat: {e}")
118
+ raise HTTPException(
119
+ status_code=500,
120
+ detail={
121
+ "error": "Internal server error",
122
+ "message": "Failed to process chat request",
123
+ "details": str(e)
124
+ }
125
+ )
126
+
127