Toursim-Test / src /core /plan_generator.py
zhuhai111's picture
Upload 43 files
7cc8bc0 verified
from typing import List, Dict
from src.api.llm_api import LLMInterface
import logging
class PlanGenerator:
def __init__(self, llm: LLMInterface):
self.llm = llm
def generate_plan(self, query: str, context: List[Dict]) -> Dict:
"""生成旅行计划"""
# 确保查询包含香港关键词
if "Hong Kong" not in query:
query = f"Hong Kong Tourism {query}"
logging.info(f"Generating plan for query: {query}")
logging.info(f"Number of reference documents: {len(context)}")
# 构建提示词
prompt = self._build_prompt(query, context)
# 生成计划
plan = self.llm.generate_travel_plan(query, context)
# 记录来源
sources = []
for doc in context:
if doc.get('url'):
sources.append({
'url': doc['url'],
'title': doc.get('title', 'Unknown Title'),
'relevance_score': doc.get('relevance_score', 0)
})
return {
'query': query,
'plan': plan,
'sources': sources
}
def _build_prompt(self, query: str, context: List[Dict]) -> str:
"""构建提示词"""
# 提取查询中的关键信息
days = self._extract_days(query)
prompt = f"""Please create a detailed Hong Kong travel plan based on the following information.
User Needs: {query}
Reference Materials:
"""
# 添加上下文信息
for i, doc in enumerate(context, 1):
prompt += f"\nSource {i}:\n{doc['passage']}\n"
prompt += f"""
Please provide a detailed itinerary for a {days}-day trip to Hong Kong, including the following content:
1. Itinerary Overview:
- Overall itinerary arrangement
- Key attractions introduction
- Time allocation suggestions
2. Daily detailed itinerary:
- Morning activities and attractions
- Afternoon activities and attractions
- Evening activities and attractions
- Specific time allocation
- Traffic suggestions
3. Traffic Suggestions:
- Return transportation plan
- City transportation suggestions
- Traffic card purchase suggestions
- Practical traffic APP recommendations
4. Accommodation Recommendations:
- Recommended area
- Specific hotel suggestions
- Booking considerations
5. Food Recommendations:
- Specialty restaurants
- Recommended restaurants
- Snack street recommendations
6. Practical Tips:
- Weather suggestions
- Clothing suggestions
- Essential items
- Considerations
- Consumer budget
Please ensure:
1. The itinerary is reasonable, considering the distance between attractions and the time for visiting
2. Provide specific time allocation
3. Include practical local suggestions
4. Consider actual conditions (e.g., traffic time, attraction opening hours, etc.)
5. Provide detailed traffic guidance
Please return the travel plan content directly, without any other explanation."""
return prompt
def _extract_days(self, query: str) -> int:
"""从查询中提取天数"""
import re
# 匹配常见的天数表达方式
patterns = [
r'(\d+)\s*[天日]',
r'(\d+)\s*-*\s*days?',
r'(\d+)\s*-*\s*d'
]
for pattern in patterns:
match = re.search(pattern, query.lower())
if match:
return int(match.group(1))
# 默认返回3天
return 3