Spaces:
Running
Running
File size: 12,402 Bytes
7cc8bc0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
from typing import List, Dict
from abc import ABC, abstractmethod
from openai import OpenAI
import logging
import httpx
class LLMInterface(ABC):
@abstractmethod
def generate(self, prompt: str) -> str:
pass
class DeepseekInterface(LLMInterface):
def __init__(self, api_key: str, base_url: str, model: str):
self.api_key = api_key
self.base_url = base_url
self.model = model
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
def _build_system_prompt(self, role: str) -> str:
"""构建系统提示词"""
roles = {
"summarizer": "You are a professional tourism content analyst, good at extracting and summarizing key tourism-related information. Please answer in English",
"planner": "You are a professional travel planner who is good at making detailed travel plans. Please answer in English"
}
return roles.get(role, "You are a professional AI assistant. Please answer in English")
def generate(self, prompt: str, role: str = "planner") -> str:
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
session = requests.Session()
retries = Retry(
total=3,
backoff_factor=1,
status_forcelist=[500, 502, 503, 504]
)
session.mount('https://', HTTPAdapter(max_retries=retries))
payload = {
"model": self.model,
"messages": [
{
"role": "system",
"content": self._build_system_prompt(role)
},
{
"role": "user",
"content": prompt
}
],
"temperature": 0.7,
"max_tokens": 2000
}
try:
response = session.post(
f"{self.base_url}/v1/chat/completions",
headers=self.headers,
json=payload,
timeout=(10, 60)
)
response.raise_for_status()
return response.json()['choices'][0]['message']['content']
except requests.exceptions.Timeout:
print("Deepseek API request timeout, retrying...")
return "Sorry, due to network issues, content generation is temporarily unavailable. Please try again later."
except requests.exceptions.RequestException as e:
print(f"Error calling Deepseek API: {str(e)}")
return "Sorry, an error occurred while generating content. Please try again later."
def summarize_document(self, content: str, title: str, url: str) -> str:
"""使用 Deepseek 总结文档"""
prompt = f"""Please analyze the following tourism web content and generate a rich summary paragraph.
Web Title: {title}
Web Link: {url}
Web Content:
{content[:4000]}
Requirements:
1. The summary should be between 300-500 words
2. Keep the most important tourism information (attractions, suggestions, tips, etc.)
3. Use an objective tone
4. Information should be accurate and practical
5. Remove marketing and advertising content
6. Maintain logical coherence
Please return the summary content directly, without any other explanation."""
return self.generate(prompt, role="summarizer")
def generate_travel_plan(self, query: str, context: List[Dict]) -> str:
# 构建更结构化的上下文
context_text = "\n\n".join([
f"Source {i+1} ({doc.get('title', 'Unknown Title')}):\n{doc['passage']}"
for i, doc in enumerate(context)
])
prompt = f"""As a professional travel planner, please create a detailed travel plan based on the user's needs and reference materials.
User Needs: {query}
Reference Materials:
{context_text}
Please provide the following content:
1. Itinerary Overview (Overall arrangement and key attractions)
2. Daily detailed itinerary (includes specific time, location, and transportation methods)
3. Traffic suggestions (includes practical APP recommendations)
4. Accommodation recommendations (includes specific areas and hotel suggestions)
5. Food recommendations (includes specialty restaurants and snacks)
6. Practical tips (weather, clothing, essential items, etc.)
Requirements:
1. The itinerary should be reasonable, considering the distance between attractions
2. Provide specific time points
3. Include detailed traffic guidance
4. Suggestions should be specific and practical
5. Consider actual conditions (e.g., opening hours of attractions)
Please return the travel plan content directly, without any other explanation."""
return self.generate(prompt, role="planner")
class OllamaInterface(LLMInterface):
def __init__(self, base_url: str, model: str):
self.base_url = base_url.rstrip('/')
self.model = model
self.headers = {
"Content-Type": "application/json"
}
def _build_system_prompt(self, role: str) -> str:
"""构建系统提示词"""
roles = {
"summarizer": "You are a professional tourism content analyst, good at extracting and summarizing key tourism-related information. Please answer in English",
"planner": "You are a professional travel planner who is good at making detailed travel plans. Please answer in English"
}
return roles.get(role, "You are a professional AI assistant. Please answer in English")
def generate(self, prompt: str, role: str = "planner") -> str:
import requests
payload = {
"model": self.model,
"messages": [
{
"role": "system",
"content": self._build_system_prompt(role)
},
{
"role": "user",
"content": prompt
}
],
"stream": False
}
try:
response = requests.post(
f"{self.base_url}/api/chat",
headers=self.headers,
json=payload,
timeout=(10, 60)
)
response.raise_for_status()
return response.json()['message']['content']
except Exception as e:
print(f"Error calling Ollama API: {str(e)}")
return "Sorry, an error occurred while generating content. Please try again later."
def summarize_document(self, content: str, title: str, url: str) -> str:
"""使用 Ollama 总结文档"""
prompt = f"""Please analyze the following tourism web content and generate a rich summary paragraph.
Web Title: {title}
Web Link: {url}
Web Content:
{content[:4000]}
Requirements:
1. The summary should be between 300-500 words
2. Keep the most important tourism information (attractions, suggestions, tips, etc.)
3. Use an objective tone
4. Information should be accurate and practical
5. Remove marketing and advertising content
6. Maintain logical coherence
Please return the summary content directly, without any other explanation."""
return self.generate(prompt, role="summarizer")
def generate_travel_plan(self, query: str, context: List[Dict]) -> str:
# 构建更结构化的上下文
context_text = "\n\n".join([
f"来源 {i+1} ({doc.get('title', '未知标题')}):\n{doc['passage']}"
for i, doc in enumerate(context)
])
prompt = f"""As a professional travel planner, please create a detailed travel plan based on the user's needs and reference materials.
User Needs: {query}
Reference Materials:
{context_text}
Please provide the following content:
1. Itinerary Overview (Overall arrangement and key attractions)
2. Daily detailed itinerary (includes specific time, location, and transportation methods)
3. Traffic suggestions (includes practical APP recommendations)
4. Accommodation recommendations (includes specific areas and hotel suggestions)
5. Food recommendations (includes specialty restaurants and snacks)
6. Practical tips (weather, clothing, essential items, etc.)
Requirements:
1. The itinerary should be reasonable, considering the distance between attractions
2. Provide specific time points
3. Include detailed traffic guidance
4. Suggestions should be specific and practical
5. Consider actual conditions (e.g., opening hours of attractions)
Please return the travel plan content directly, without any other explanation."""
return self.generate(prompt, role="planner")
class OpenAIInterface(LLMInterface):
def __init__(self, api_key: str, model: str = "gpt-4o", base_url: str = "https://api.feidaapi.com/v1"):
self.api_key = api_key
self.model = model
self.client = OpenAI(api_key=api_key, base_url=base_url)
def _build_system_prompt(self, role: str) -> str:
"""构建系统提示词"""
roles = {
"summarizer": "You are a professional tourism content analyst, good at extracting and summarizing key tourism-related information. Please answer in English",
"planner": "You are a professional travel planner who is good at making detailed travel plans. Please answer in English"
}
return roles.get(role, "You are a professional AI assistant. Please answer in English")
def generate(self, prompt: str, role: str = "planner") -> str:
try:
messages = [
{"role": "system", "content": self._build_system_prompt(role)},
{"role": "user", "content": prompt}
]
response = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=0.7,
max_tokens=2000
)
return response.choices[0].message.content
except Exception as e:
logging.error(f"Error calling OpenAI API: {str(e)}")
return "Sorry, an error occurred while generating content. Please try again later."
def summarize_document(self, content: str, title: str, url: str) -> str:
"""使用 OpenAI 总结文档"""
prompt = f"""Please analyze the following tourism web content and generate a rich summary paragraph.
Web Title: {title}
Web Link: {url}
Web Content:
{content[:4000]}
Requirements:
1. The summary should be between 300-500 words
2. Keep the most important tourism information (attractions, suggestions, tips, etc.)
3. Use an objective tone
4. Information should be accurate and practical
5. Remove marketing and advertising content
6. Maintain logical coherence
Please return the summary content directly, without any other explanation."""
return self.generate(prompt, role="summarizer")
def generate_travel_plan(self, query: str, context: List[Dict]) -> str:
# 构建更结构化的上下文
context_text = "\n\n".join([
f"Source {i+1} ({doc.get('title', 'Unknown Title')}):\n{doc['passage']}"
for i, doc in enumerate(context)
])
prompt = f"""As a professional travel planner, please create a detailed travel plan based on the user's needs and reference materials.
User Needs: {query}
Reference Materials:
{context_text}
Please provide the following content:
1. Itinerary Overview (Overall arrangement and key attractions)
2. Daily detailed itinerary (includes specific time, location, and transportation methods)
3. Traffic suggestions (includes practical APP recommendations)
4. Accommodation recommendations (includes specific areas and hotel suggestions)
5. Food recommendations (includes specialty restaurants and snacks)
6. Practical tips (weather, clothing, essential items, etc.)
Requirements:
1. The itinerary should be reasonable, considering the distance between attractions
2. Provide specific time points
3. Include detailed traffic guidance
4. Suggestions should be specific and practical
5. Consider actual conditions (e.g., opening hours of attractions)
Please return the travel plan content directly, without any other explanation."""
return self.generate(prompt, role="planner") |