ABAO77 commited on
Commit
ec6867d
·
verified ·
1 Parent(s): 02d6bde

Upload 157 files

Browse files
src/apis/controllers/__pycache__/destination_controller.cpython-311.pyc CHANGED
Binary files a/src/apis/controllers/__pycache__/destination_controller.cpython-311.pyc and b/src/apis/controllers/__pycache__/destination_controller.cpython-311.pyc differ
 
src/apis/controllers/__pycache__/location_controller.cpython-311.pyc CHANGED
Binary files a/src/apis/controllers/__pycache__/location_controller.cpython-311.pyc and b/src/apis/controllers/__pycache__/location_controller.cpython-311.pyc differ
 
src/apis/controllers/destination_controller.py CHANGED
@@ -2,7 +2,24 @@ from typing import List, Dict, Any
2
  import aiohttp
3
  from fastapi import HTTPException
4
  from src.utils.logger import logger
5
- async def destination_suggestion_controller(question: str, top_k: int = 5) -> List[Dict[str, Any]]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  async with aiohttp.ClientSession() as session:
7
  # Get question tags
8
  try:
@@ -16,7 +33,7 @@ async def destination_suggestion_controller(question: str, top_k: int = 5) -> Li
16
  else:
17
  raise HTTPException(
18
  status_code=response_tag.status,
19
- detail=f"Tag request failed with status {response_tag.status}"
20
  )
21
 
22
  # Get destinations list
@@ -30,8 +47,32 @@ async def destination_suggestion_controller(question: str, top_k: int = 5) -> Li
30
  else:
31
  raise HTTPException(
32
  status_code=response.status,
33
- detail=f"Destinations request failed with status {response.status}"
34
  )
35
-
36
  except aiohttp.ClientError as e:
37
- raise HTTPException(status_code=500, detail=f"Request failed: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import aiohttp
3
  from fastapi import HTTPException
4
  from src.utils.logger import logger
5
+ import json
6
+ from src.langgraph.langchain.prompt import (
7
+ routing_recommender_chain,
8
+ characteristic_extractor_chain,
9
+ RoutingRecommender,
10
+ CharacteristicExtractor,
11
+ )
12
+ from src.apis.controllers.location_controller import (
13
+ get_lat_long_location,
14
+ get_places,
15
+ )
16
+ from src.langgraph.config.constant import available_categories
17
+
18
+
19
+ async def destination_suggestion_controller(
20
+ question: str, top_k: int = 5
21
+ ) -> List[Dict[str, Any]]:
22
+
23
  async with aiohttp.ClientSession() as session:
24
  # Get question tags
25
  try:
 
33
  else:
34
  raise HTTPException(
35
  status_code=response_tag.status,
36
+ detail=f"Tag request failed with status {response_tag.status}",
37
  )
38
 
39
  # Get destinations list
 
47
  else:
48
  raise HTTPException(
49
  status_code=response.status,
50
+ detail=f"Destinations request failed with status {response.status}",
51
  )
52
+
53
  except aiohttp.ClientError as e:
54
+ raise HTTPException(status_code=500, detail=f"Request failed: {str(e)}")
55
+
56
+
57
+ async def destination_recommendation_func(query, top_k=5):
58
+ routing: RoutingRecommender = routing_recommender_chain.invoke({"query": query})
59
+ print("label", routing.label)
60
+ if routing.label == "characteristic":
61
+ output = await destination_suggestion_controller(query, top_k)
62
+ return output
63
+ characteristic_extract_response: CharacteristicExtractor = (
64
+ await characteristic_extractor_chain.ainvoke({"query": query})
65
+ )
66
+ print("characterist", characteristic_extract_response)
67
+ lat, lon = get_lat_long_location(characteristic_extract_response.main_place)
68
+ response = get_places(
69
+ lat,
70
+ lon,
71
+ 5000,
72
+ available_categories.get(characteristic_extract_response.kind, None),
73
+ top_k,
74
+ )
75
+ response = json.loads(response.body)
76
+ output = [i.get("Accommodation_Name", None) for i in response]
77
+
78
+ return output
src/apis/controllers/location_controller.py CHANGED
@@ -40,7 +40,6 @@ def get_nearby_places(lat, long, radius, kinds):
40
  "apikey": api_key,
41
  }
42
  response = requests.get(url, params=params, headers={"accept": "application/json"})
43
- # print(response.json())
44
  if response.status_code == 200:
45
  logger.info("Places fetched successfully")
46
  return JSONResponse(
@@ -59,7 +58,6 @@ def get_places(lat, long, radius, categories, limit=20):
59
  response = requests.get(url)
60
  if response.status_code == 200:
61
  response = response.json().get("features", [])
62
- # logger.info(f"RESPONSE:{response}")
63
  if response:
64
  response = format_geoapify_response(response, long, lat)
65
  return JSONResponse(content=response, status_code=200)
@@ -113,11 +111,5 @@ def get_geometry_nearby_places(lat, lon, radius, kinds):
113
  res = get_nearby_places(lat=lat, long=lon, radius=radius, kinds=kinds)
114
  data = json.loads(res.body)
115
  recommend_places = data.get("places", [])
116
- recommend_places = [
117
- {
118
- "name": place["properties"]["name"],
119
- "link_google_map": get_google_map_url(place["geometry"]["coordinates"]),
120
- }
121
- for place in recommend_places
122
- ]
123
  return recommend_places
 
40
  "apikey": api_key,
41
  }
42
  response = requests.get(url, params=params, headers={"accept": "application/json"})
 
43
  if response.status_code == 200:
44
  logger.info("Places fetched successfully")
45
  return JSONResponse(
 
58
  response = requests.get(url)
59
  if response.status_code == 200:
60
  response = response.json().get("features", [])
 
61
  if response:
62
  response = format_geoapify_response(response, long, lat)
63
  return JSONResponse(content=response, status_code=200)
 
111
  res = get_nearby_places(lat=lat, long=lon, radius=radius, kinds=kinds)
112
  data = json.loads(res.body)
113
  recommend_places = data.get("places", [])
114
+ recommend_places = [place["properties"]["name"] for place in recommend_places]
 
 
 
 
 
 
115
  return recommend_places
src/apis/routes/__pycache__/travel_dest_route.cpython-311.pyc CHANGED
Binary files a/src/apis/routes/__pycache__/travel_dest_route.cpython-311.pyc and b/src/apis/routes/__pycache__/travel_dest_route.cpython-311.pyc differ
 
src/apis/routes/travel_dest_route.py CHANGED
@@ -8,9 +8,11 @@ from src.apis.middlewares.auth_middleware import get_current_user
8
  from src.utils.logger import logger
9
  from src.apis.controllers.destination_controller import (
10
  destination_suggestion_controller,
 
11
  )
12
  from fastapi.responses import JSONResponse
13
  from src.utils.mongo import DestinationCRUD
 
14
  router = APIRouter(prefix="/dest", tags=["Destination"])
15
 
16
  user_dependency = Annotated[User, Depends(get_current_user)]
@@ -53,7 +55,7 @@ def get_tourist(page: int = Query(default=1, ge=1)):
53
  async def get_tourist_names():
54
  try:
55
  destination_data = await DestinationCRUD.find_all()
56
-
57
  # Drop the fields created_at, updated_at, expire_at from each item
58
 
59
  serialized_data = []
@@ -74,4 +76,4 @@ async def get_tourist_names():
74
 
75
  @router.get("/suggest")
76
  async def destination_suggestion(question: str, top_k: int = Query(default=5, ge=1)):
77
- return JSONResponse(await destination_suggestion_controller(question, top_k))
 
8
  from src.utils.logger import logger
9
  from src.apis.controllers.destination_controller import (
10
  destination_suggestion_controller,
11
+ destination_recommendation_func,
12
  )
13
  from fastapi.responses import JSONResponse
14
  from src.utils.mongo import DestinationCRUD
15
+
16
  router = APIRouter(prefix="/dest", tags=["Destination"])
17
 
18
  user_dependency = Annotated[User, Depends(get_current_user)]
 
55
  async def get_tourist_names():
56
  try:
57
  destination_data = await DestinationCRUD.find_all()
58
+
59
  # Drop the fields created_at, updated_at, expire_at from each item
60
 
61
  serialized_data = []
 
76
 
77
  @router.get("/suggest")
78
  async def destination_suggestion(question: str, top_k: int = Query(default=5, ge=1)):
79
+ return JSONResponse(await destination_recommendation_func(question))
src/langgraph/config/__pycache__/constant.cpython-311.pyc CHANGED
Binary files a/src/langgraph/config/__pycache__/constant.cpython-311.pyc and b/src/langgraph/config/__pycache__/constant.cpython-311.pyc differ
 
src/langgraph/config/constant.py CHANGED
@@ -21,3 +21,17 @@ class MongoCfg:
21
  MAX_HISTORY_SIZE: int = 15
22
  class RedisCfg:
23
  REDIS_URL: str = os.getenv("REDIS_URL")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  MAX_HISTORY_SIZE: int = 15
22
  class RedisCfg:
23
  REDIS_URL: str = os.getenv("REDIS_URL")
24
+
25
+ available_categories = {
26
+ "food_and_beverage": "catering",
27
+ "accommodation": "accommodation",
28
+ "entertainment": "entertainment",
29
+ "leisure": "leisure",
30
+ "natural": "natural",
31
+ "national_park": "national_park",
32
+ "tourism": "tourism",
33
+ "camping": "camping",
34
+ "religion": "religion",
35
+ "sport": "sport",
36
+ "commercial": "commercial",
37
+ }
src/langgraph/langchain/__pycache__/prompt.cpython-311.pyc CHANGED
Binary files a/src/langgraph/langchain/__pycache__/prompt.cpython-311.pyc and b/src/langgraph/langchain/__pycache__/prompt.cpython-311.pyc differ
 
src/langgraph/langchain/prompt.py CHANGED
@@ -1,4 +1,4 @@
1
- from langchain.prompts import ChatPromptTemplate
2
  from datetime import datetime
3
  from pydantic import BaseModel, Field
4
  from langchain_core.messages import HumanMessage
@@ -7,6 +7,8 @@ import pytz
7
  from src.langgraph.state import State
8
  from src.utils.logger import logger
9
  from langchain_core.prompts import PromptTemplate
 
 
10
 
11
  vietnam_timezone = pytz.timezone("Asia/Ho_Chi_Minh")
12
  vietnam_time = datetime.now(vietnam_timezone).strftime("%Y-%m-%d %H:%M:%S")
@@ -138,6 +140,53 @@ book_hotel_prompt = ChatPromptTemplate.from_messages(
138
  ]
139
  ).partial(current_time=vietnam_time)
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
  class CompleteOrRoute(BaseModel):
143
  """Call this function to complete the current assistant's task and route the conversation back to the primary assistant."""
 
1
+ from langchain.prompts import ChatPromptTemplate, PromptTemplate
2
  from datetime import datetime
3
  from pydantic import BaseModel, Field
4
  from langchain_core.messages import HumanMessage
 
7
  from src.langgraph.state import State
8
  from src.utils.logger import logger
9
  from langchain_core.prompts import PromptTemplate
10
+ from .llm import llm, llm_flash
11
+ from src.langgraph.config.constant import available_categories
12
 
13
  vietnam_timezone = pytz.timezone("Asia/Ho_Chi_Minh")
14
  vietnam_time = datetime.now(vietnam_timezone).strftime("%Y-%m-%d %H:%M:%S")
 
140
  ]
141
  ).partial(current_time=vietnam_time)
142
 
143
+ routing_recommender_prompt = PromptTemplate.from_template(
144
+ """You are a tour guide.
145
+ ### Instruction:
146
+ You are given a query sentence
147
+ Classify the query as 'characteristic' or 'geographic' based on its content.
148
+
149
+ - 'Characteristic' if it asks about a place's features (e.g., camping, relaxing, scenic).
150
+ - 'Geographic' if it involves location specifics (e.g., near a city, in a province, on a road).
151
+
152
+ ###
153
+ Query sentence: {query}
154
+ """
155
+ )
156
+ characteristic_extractor_prompt = PromptTemplate.from_template(
157
+ """You are a tour guide.
158
+ ### Instruction:
159
+ Read the sentence carefully
160
+ Given a query about a destination, extract two things:
161
+ 1. **Kind**: Choose one from {available_categories}.
162
+ 2. **Main Place**: Identify the main place mentioned in the query. Include 'Quy Nhon' or 'Binh Dinh' term in the main place response
163
+
164
+ Query sentence: {query}
165
+ ."""
166
+ ).partial(available_categories=list(available_categories.keys()))
167
+
168
+
169
+ class RoutingRecommender(BaseModel):
170
+ label: str = Field(..., description="is 'characteristic' or 'geographic'")
171
+
172
+
173
+ class CharacteristicExtractor(BaseModel):
174
+ kind: str = Field(
175
+ ...,
176
+ description=f"Choose one from {list(available_categories.keys())}",
177
+ )
178
+ main_place: str = Field(..., description="main place mentioned in the query")
179
+
180
+
181
+ routing_recommender_chain = (
182
+ routing_recommender_prompt | llm_flash.with_structured_output(RoutingRecommender)
183
+ )
184
+
185
+ characteristic_extractor_chain = (
186
+ characteristic_extractor_prompt
187
+ | llm_flash.with_structured_output(CharacteristicExtractor)
188
+ )
189
+
190
 
191
  class CompleteOrRoute(BaseModel):
192
  """Call this function to complete the current assistant's task and route the conversation back to the primary assistant."""
src/langgraph/models/__pycache__/model_validator.cpython-311.pyc CHANGED
Binary files a/src/langgraph/models/__pycache__/model_validator.cpython-311.pyc and b/src/langgraph/models/__pycache__/model_validator.cpython-311.pyc differ
 
src/langgraph/models/model_validator.py CHANGED
@@ -1,5 +1,6 @@
1
  from pydantic import BaseModel, Field, EmailStr
2
 
 
3
  # from typing import Optional
4
  # from datetime import datetime, timezone
5
 
@@ -65,4 +66,6 @@ class NearlyDestinationRecommendation(BaseModel):
65
  )
66
 
67
  class Config:
68
- schema_extra = {"example": {"query": "Địa điểm gần Hà Nội" "places" "Hà Nội"}}
 
 
 
1
  from pydantic import BaseModel, Field, EmailStr
2
 
3
+
4
  # from typing import Optional
5
  # from datetime import datetime, timezone
6
 
 
66
  )
67
 
68
  class Config:
69
+ json_schema_extra = {
70
+ "example": {"query": "Địa điểm gần Hà Nội" "places" "Hà Nội"}
71
+ }
src/langgraph/multi_agent/chat/__pycache__/chat_flow.cpython-311.pyc CHANGED
Binary files a/src/langgraph/multi_agent/chat/__pycache__/chat_flow.cpython-311.pyc and b/src/langgraph/multi_agent/chat/__pycache__/chat_flow.cpython-311.pyc differ
 
src/langgraph/multi_agent/chat/chat_flow.py CHANGED
@@ -16,12 +16,12 @@ from src.langgraph.utils_function.function_graph import (
16
  get_history,
17
  save_history,
18
  )
19
- from src.langgraph.tools.destination_tools import destination_recommendation, nearly_destination_recommendation
20
  from src.utils.logger import logger
21
 
22
  primary_assistant_tools = [
23
  TavilySearchResults(max_results=2),
24
- destination_recommendation,nearly_destination_recommendation
25
  ]
26
 
27
  assistant_runnable = primary_assistant_prompt | llm.bind_tools(
@@ -58,7 +58,6 @@ class ChatBot:
58
  self.primary_assistant_tools = [
59
  TavilySearchResults(max_results=2),
60
  destination_recommendation,
61
- nearly_destination_recommendation
62
  ]
63
  self.assistant_runnable = assistant_runnable
64
 
 
16
  get_history,
17
  save_history,
18
  )
19
+ from src.langgraph.tools.destination_tools import destination_recommendation
20
  from src.utils.logger import logger
21
 
22
  primary_assistant_tools = [
23
  TavilySearchResults(max_results=2),
24
+ destination_recommendation,
25
  ]
26
 
27
  assistant_runnable = primary_assistant_prompt | llm.bind_tools(
 
58
  self.primary_assistant_tools = [
59
  TavilySearchResults(max_results=2),
60
  destination_recommendation,
 
61
  ]
62
  self.assistant_runnable = assistant_runnable
63
 
src/langgraph/tools/__pycache__/destination_tools.cpython-311.pyc CHANGED
Binary files a/src/langgraph/tools/__pycache__/destination_tools.cpython-311.pyc and b/src/langgraph/tools/__pycache__/destination_tools.cpython-311.pyc differ
 
src/langgraph/tools/destination_tools.py CHANGED
@@ -1,6 +1,7 @@
1
  from langchain_core.tools import tool
2
  from src.apis.controllers.destination_controller import (
3
  destination_suggestion_controller,
 
4
  )
5
  from langchain_core.runnables.config import RunnableConfig
6
  from src.utils.logger import logger
@@ -11,7 +12,12 @@ from src.apis.controllers.location_controller import (
11
  )
12
  from src.langgraph.models.model_validator import NearlyDestinationRecommendation
13
  from src.utils.helper import get_google_map_url
14
-
 
 
 
 
 
15
  import json
16
 
17
 
@@ -19,21 +25,11 @@ import json
19
  async def destination_recommendation(query: str, config: RunnableConfig):
20
  """Call tool when user want to recommend a travel destination(tourist attractions, restaurants). Not require user typing anything.
21
  Args:
22
- query (str): query related to wanting to go somewhere. Auto extracted from user's message. Using Vietnamese language for better results.
23
- Output: A list of recommended destinations.
24
  """
25
  logger.info(f"Destination recommendation query: {query}")
26
- output = await destination_suggestion_controller(query, 3)
 
27
  return output
28
 
29
-
30
- @tool(args_schema=NearlyDestinationRecommendation)
31
- async def nearly_destination_recommendation(
32
- query: str, places, kinds, config: RunnableConfig
33
- ):
34
- """Gọi tool này khi query đề cập đến việc tìm địa điểm gần một khu vực/ địa điểm nào đó"""
35
- radius = 1000
36
- lat, lon = get_lat_long_location(places)
37
- recommend_places = get_geometry_nearby_places(lat, lon, radius, kinds)
38
- logger.info(f"Nearly Destination recommendation: {places} >> {kinds} >> {recommend_places}")
39
- return recommend_places
 
1
  from langchain_core.tools import tool
2
  from src.apis.controllers.destination_controller import (
3
  destination_suggestion_controller,
4
+ destination_recommendation_func,
5
  )
6
  from langchain_core.runnables.config import RunnableConfig
7
  from src.utils.logger import logger
 
12
  )
13
  from src.langgraph.models.model_validator import NearlyDestinationRecommendation
14
  from src.utils.helper import get_google_map_url
15
+ from src.langgraph.langchain.prompt import (
16
+ routing_recommender_chain,
17
+ characteristic_extractor_chain,
18
+ RoutingRecommender,
19
+ CharacteristicExtractor,
20
+ )
21
  import json
22
 
23
 
 
25
  async def destination_recommendation(query: str, config: RunnableConfig):
26
  """Call tool when user want to recommend a travel destination(tourist attractions, restaurants). Not require user typing anything.
27
  Args:
28
+ query (str): query related to wanting to go somewhere locations near a certain area/location or location's characteristics user want to go. Auto extracted from user's message.
29
+ Using Vietnamese language for better results
30
  """
31
  logger.info(f"Destination recommendation query: {query}")
32
+ output = await destination_recommendation_func(query)
33
+ logger.info(f"Destination recommendation output: {output}")
34
  return output
35
 
 
 
 
 
 
 
 
 
 
 
 
src/utils/__pycache__/helper.cpython-311.pyc CHANGED
Binary files a/src/utils/__pycache__/helper.cpython-311.pyc and b/src/utils/__pycache__/helper.cpython-311.pyc differ
 
src/utils/helper.py CHANGED
@@ -104,7 +104,7 @@ def format_geoapify_response(
104
  if include_latnlong:
105
  formatted_item["lat"] = place_lat
106
  formatted_item["lon"] = place_lon
107
- formatted_item["Accommodation Name"] = feature["properties"]["address_line1"]
108
  formatted_item["Address"] = feature["properties"]["formatted"]
109
  formatted_item["distance_km"] = str(round(distance, 2)) + " km"
110
 
 
104
  if include_latnlong:
105
  formatted_item["lat"] = place_lat
106
  formatted_item["lon"] = place_lon
107
+ formatted_item["Accommodation_Name"] = feature["properties"]["address_line1"]
108
  formatted_item["Address"] = feature["properties"]["formatted"]
109
  formatted_item["distance_km"] = str(round(distance, 2)) + " km"
110