mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Update test_place_search.py
This commit is contained in:
parent
215deef6ff
commit
8c457b1966
1 changed files with 288 additions and 131 deletions
|
|
@ -1,20 +1,70 @@
|
||||||
#!/usr/bin/env python3
|
import requests
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
|
|
||||||
"""
|
|
||||||
测试PlaceSearchService类的功能
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import json
|
import json
|
||||||
|
import re
|
||||||
|
from typing import Dict, List, Optional, Union, Any
|
||||||
|
|
||||||
|
# 假设这些导入存在于项目中
|
||||||
|
try:
|
||||||
|
from config.logger import setup_logging
|
||||||
|
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
||||||
|
from core.utils.util import get_ip_info
|
||||||
|
except ImportError:
|
||||||
|
# 导入失败时的兼容处理
|
||||||
|
print("警告: 部分模块导入失败,可能需要调整导入路径")
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
|
||||||
|
# 尝试设置日志
|
||||||
|
try:
|
||||||
|
logger = setup_logging()
|
||||||
|
except:
|
||||||
|
# 简单的日志后备方案
|
||||||
|
import logging
|
||||||
|
logger = logging.getLogger(TAG)
|
||||||
|
logger.setLevel(logging.INFO)
|
||||||
|
|
||||||
|
# 添加bind方法模拟structured logger
|
||||||
|
def _bind(self, **kwargs):
|
||||||
|
return self
|
||||||
|
logger.bind = _bind.__get__(logger)
|
||||||
|
|
||||||
|
# 添加debug/info/error方法的后备
|
||||||
|
if not hasattr(logger, "error"):
|
||||||
|
logger.error = logger.warning
|
||||||
|
|
||||||
|
|
||||||
|
# 简化函数描述定义,避免多行字符串语法错误
|
||||||
|
GET_PLACE_INFO_FUNCTION_DESC = {
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "get_place_info",
|
||||||
|
"description": "获取附近的商铺信息。基于用户位置(自动获取IP或用户指定)搜索附近商铺、餐厅、景点。例如用户说'附近有什么好吃的'或'杭州西湖附近有什么景点'。",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"location": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "地点名,例如杭州。可选参数,如果不提供则通过IP定位,如果没有指定特定的地点,例如街道,城市,乡村等;那就直接返回空"
|
||||||
|
},
|
||||||
|
"keyword": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "搜索关键词,例如餐厅、咖啡厅、景点等"
|
||||||
|
},
|
||||||
|
"radius": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "搜索半径,默认1000米"
|
||||||
|
},
|
||||||
|
"lang": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "返回用户使用的语言code,例如zh_CN/zh_HK/en_US/ja_JP等,默认zh_CN"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["keyword", "lang"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
# 添加项目根目录到PATH
|
|
||||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
parent_dir = os.path.dirname(current_dir)
|
|
||||||
sys.path.append(parent_dir)
|
|
||||||
|
|
||||||
# 创建一个简化版的PlaceSearchService类,不依赖项目的logger等组件
|
|
||||||
class PlaceSearchService:
|
class PlaceSearchService:
|
||||||
"""
|
"""
|
||||||
场所搜索服务类,封装根据IP获取经纬度和搜索附近店铺的功能
|
场所搜索服务类,封装根据IP获取经纬度和搜索附近店铺的功能
|
||||||
|
|
@ -27,7 +77,7 @@ class PlaceSearchService:
|
||||||
Args:
|
Args:
|
||||||
api_key: 高德地图API密钥
|
api_key: 高德地图API密钥
|
||||||
"""
|
"""
|
||||||
self.api_key = api_key
|
self.api_key = "1ba9b66a094a5a86b22e6c7425a4f33b"
|
||||||
self.headers = {
|
self.headers = {
|
||||||
"User-Agent": (
|
"User-Agent": (
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||||
|
|
@ -42,28 +92,71 @@ class PlaceSearchService:
|
||||||
|
|
||||||
def get_location_by_ip(self, client_ip):
|
def get_location_by_ip(self, client_ip):
|
||||||
"""
|
"""
|
||||||
根据IP地址获取城市信息
|
根据IP地址获取城市信息和经纬度
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
client_ip: 客户端IP地址
|
client_ip: 客户端IP地址
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
dict: 包含城市等信息的字典
|
dict: 包含城市和经纬度等信息的字典
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# 公共API,获取IP地址的位置信息
|
# 尝试使用API获取IP地址的位置和经纬度信息
|
||||||
url = f"https://whois.pconline.com.cn/ipJson.jsp?json=true&ip={client_ip}"
|
url = f"https://restapi.amap.com/v3/ip"
|
||||||
import requests
|
params = {
|
||||||
response = requests.get(url)
|
"key": self.api_key,
|
||||||
if response.status_code == 200:
|
"ip": client_ip,
|
||||||
data = response.json()
|
"output": "json"
|
||||||
return {
|
}
|
||||||
|
|
||||||
|
response = requests.get(url, params=params, headers=self.headers)
|
||||||
|
data = response.json()
|
||||||
|
|
||||||
|
logger.bind(tag=TAG).error(f"高德API获取IP信息: {data}")
|
||||||
|
|
||||||
|
if data.get("status") == "1":
|
||||||
|
result = {
|
||||||
|
"province": data.get("province", ""),
|
||||||
"city": data.get("city", ""),
|
"city": data.get("city", ""),
|
||||||
"province": data.get("pro", ""),
|
"adcode": data.get("adcode", ""),
|
||||||
|
"rectangle": data.get("rectangle", ""), # 城市边界矩形,格式为"lng_min,lat_min;lng_max,lat_max"
|
||||||
|
"ip": client_ip
|
||||||
|
}
|
||||||
|
|
||||||
|
# 如果有rectangle信息,提取中心点作为经纬度
|
||||||
|
if result.get("rectangle"):
|
||||||
|
try:
|
||||||
|
rect_parts = result["rectangle"].split(";")
|
||||||
|
if len(rect_parts) == 2:
|
||||||
|
# 取两个点的平均值作为中心点
|
||||||
|
min_lng, min_lat = map(float, rect_parts[0].split(","))
|
||||||
|
max_lng, max_lat = map(float, rect_parts[1].split(","))
|
||||||
|
|
||||||
|
result["longitude"] = (min_lng + max_lng) / 2
|
||||||
|
result["latitude"] = (min_lat + max_lat) / 2
|
||||||
|
result["location"] = f"{result['longitude']},{result['latitude']}"
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"解析rectangle失败: {e}")
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
# 如果高德API失败,尝试备用方法
|
||||||
|
backup_url = f"https://whois.pconline.com.cn/ipJson.jsp?json=true&ip={client_ip}"
|
||||||
|
response = requests.get(backup_url)
|
||||||
|
|
||||||
|
if response.status_code == 200:
|
||||||
|
backup_data = response.json()
|
||||||
|
logger.bind(tag=TAG).error(f"备用API获取IP信息: {backup_data}")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"city": backup_data.get("city", ""),
|
||||||
|
"province": backup_data.get("pro", ""),
|
||||||
"ip": client_ip
|
"ip": client_ip
|
||||||
}
|
}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"获取IP信息出错: {e}")
|
logger.bind(tag=TAG).error(f"获取IP信息失败: {e}")
|
||||||
|
|
||||||
|
# 如果所有方法都失败,返回空的结果
|
||||||
return {"city": "", "province": "", "ip": client_ip}
|
return {"city": "", "province": "", "ip": client_ip}
|
||||||
|
|
||||||
def get_location_by_name(self, location_name):
|
def get_location_by_name(self, location_name):
|
||||||
|
|
@ -84,12 +177,9 @@ class PlaceSearchService:
|
||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import requests
|
|
||||||
response = requests.get(url, params=params, headers=self.headers)
|
response = requests.get(url, params=params, headers=self.headers)
|
||||||
data = response.json()
|
data = response.json()
|
||||||
|
|
||||||
print(f"地理编码API响应: {json.dumps(data, ensure_ascii=False)}")
|
|
||||||
|
|
||||||
if data.get("status") == "1" and data.get("geocodes") and len(data["geocodes"]) > 0:
|
if data.get("status") == "1" and data.get("geocodes") and len(data["geocodes"]) > 0:
|
||||||
return {
|
return {
|
||||||
"location": data["geocodes"][0]["location"], # 格式:"116.481488,39.990464"
|
"location": data["geocodes"][0]["location"], # 格式:"116.481488,39.990464"
|
||||||
|
|
@ -98,14 +188,12 @@ class PlaceSearchService:
|
||||||
"city": data["geocodes"][0]["city"],
|
"city": data["geocodes"][0]["city"],
|
||||||
"district": data["geocodes"][0]["district"]
|
"district": data["geocodes"][0]["district"]
|
||||||
}
|
}
|
||||||
elif data.get("status") == "0":
|
|
||||||
print(f"API返回错误: {data.get('info')}")
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"获取地点经纬度失败: {e}")
|
logger.bind(tag=TAG).error(f"获取地点经纬度失败: {e}")
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def search_places_by_keyword(self, lng, lat, keyword, radius=1000, page=1, page_size=20):
|
def search_places_by_keyword(self, lng, lat, keyword, radius=1000, page=1, page_size=5):
|
||||||
"""
|
"""
|
||||||
根据经纬度和关键词搜索附近场所
|
根据经纬度和关键词搜索附近场所
|
||||||
|
|
||||||
|
|
@ -131,22 +219,14 @@ class PlaceSearchService:
|
||||||
"extensions": "all",
|
"extensions": "all",
|
||||||
}
|
}
|
||||||
|
|
||||||
print(f"请求附近场所API: {url}")
|
|
||||||
print(f"参数: {params}")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import requests
|
|
||||||
response = requests.get(url, params=params, headers=self.headers)
|
response = requests.get(url, params=params, headers=self.headers)
|
||||||
data = response.json()
|
data = response.json()
|
||||||
|
|
||||||
print(f"附近场所API响应: {json.dumps(data, ensure_ascii=False, indent=2)[:500]}...")
|
|
||||||
|
|
||||||
if data.get("status") == "1":
|
if data.get("status") == "1":
|
||||||
return data.get("pois", [])
|
return data.get("pois", [])
|
||||||
elif data.get("status") == "0":
|
|
||||||
print(f"API返回错误: {data.get('info')}")
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"搜索附近场所失败: {e}")
|
logger.bind(tag=TAG).error(f"搜索附近场所失败: {e}")
|
||||||
|
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
|
@ -175,14 +255,13 @@ class PlaceSearchService:
|
||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import requests
|
|
||||||
response = requests.get(url, params=params, headers=self.headers)
|
response = requests.get(url, params=params, headers=self.headers)
|
||||||
data = response.json()
|
data = response.json()
|
||||||
|
|
||||||
if data.get("status") == "1":
|
if data.get("status") == "1":
|
||||||
return data.get("pois", [])
|
return data.get("pois", [])
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"搜索城市内场所失败: {e}")
|
logger.bind(tag=TAG).error(f"搜索城市内场所失败: {e}")
|
||||||
|
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
|
@ -220,101 +299,179 @@ class PlaceSearchService:
|
||||||
result += "如需了解更多信息,请告诉我具体的场所名称。"
|
result += "如需了解更多信息,请告诉我具体的场所名称。"
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def test_get_location_by_name():
|
|
||||||
"""测试根据地名获取位置信息"""
|
|
||||||
# 从环境变量或配置文件获取API密钥
|
|
||||||
api_key = os.environ.get("GD_KEY", "你的高德地图API密钥") # 替换为实际的API密钥
|
|
||||||
|
|
||||||
service = PlaceSearchService(api_key)
|
|
||||||
location = "杭州西湖"
|
|
||||||
result = service.get_location_by_name(location)
|
|
||||||
|
|
||||||
print(f"\n=== 测试根据地名获取位置信息 ===")
|
|
||||||
print(f"位置名称: {location}")
|
|
||||||
|
|
||||||
if result:
|
|
||||||
print(f"获取成功!")
|
|
||||||
print(f"格式化地址: {result.get('formatted_address')}")
|
|
||||||
print(f"经纬度: {result.get('location')}")
|
|
||||||
print(f"省份: {result.get('province')}")
|
|
||||||
print(f"城市: {result.get('city')}")
|
|
||||||
print(f"区县: {result.get('district')}")
|
|
||||||
else:
|
|
||||||
print(f"获取位置信息失败")
|
|
||||||
|
|
||||||
def test_search_places_by_keyword():
|
def is_nearby_query(query: str) -> bool:
|
||||||
"""测试根据经纬度和关键词搜索场所"""
|
"""
|
||||||
api_key = os.environ.get("GD_KEY", "你的高德地图API密钥") # 替换为实际的API密钥
|
判断用户查询是否是关于"附近"的查询
|
||||||
|
|
||||||
service = PlaceSearchService(api_key)
|
Args:
|
||||||
# 杭州西湖的经纬度
|
query: 用户查询文本
|
||||||
lng, lat = 120.14, 30.24
|
|
||||||
keyword = "咖啡厅"
|
Returns:
|
||||||
radius = 1000
|
bool: 是否是附近查询
|
||||||
|
"""
|
||||||
|
nearby_patterns = [
|
||||||
|
r'附近',
|
||||||
|
r'我附近',
|
||||||
|
r'周边',
|
||||||
|
r'我周边',
|
||||||
|
r'周围',
|
||||||
|
r'我周围',
|
||||||
|
r'就近',
|
||||||
|
r'身边',
|
||||||
|
r'我身边'
|
||||||
|
]
|
||||||
|
|
||||||
print(f"\n=== 测试根据经纬度搜索场所 ===")
|
# 检查查询中是否包含"附近"相关的词语
|
||||||
print(f"位置: 经度={lng}, 纬度={lat}")
|
for pattern in nearby_patterns:
|
||||||
print(f"关键词: {keyword}")
|
if re.search(pattern, query):
|
||||||
print(f"半径: {radius}米")
|
return True
|
||||||
|
|
||||||
places = service.search_places_by_keyword(lng, lat, keyword, radius)
|
return False
|
||||||
|
|
||||||
if places:
|
|
||||||
print(f"搜索成功! 找到{len(places)}个结果")
|
|
||||||
result_text = service.format_search_results(places, "杭州西湖")
|
|
||||||
print(result_text)
|
|
||||||
else:
|
|
||||||
print("搜索场所失败或未找到结果")
|
|
||||||
|
|
||||||
def test_search_places_by_city():
|
|
||||||
"""测试根据城市名和关键词搜索场所"""
|
|
||||||
api_key = os.environ.get("GD_KEY", "你的高德地图API密钥") # 替换为实际的API密钥
|
|
||||||
|
|
||||||
service = PlaceSearchService(api_key)
|
|
||||||
city = "北京"
|
|
||||||
keyword = "火锅"
|
|
||||||
|
|
||||||
print(f"\n=== 测试根据城市名搜索场所 ===")
|
|
||||||
print(f"城市: {city}")
|
|
||||||
print(f"关键词: {keyword}")
|
|
||||||
|
|
||||||
places = service.search_places_by_city(city, keyword)
|
|
||||||
|
|
||||||
if places:
|
|
||||||
print(f"搜索成功! 找到{len(places)}个结果")
|
|
||||||
result_text = service.format_search_results(places, city)
|
|
||||||
print(result_text)
|
|
||||||
else:
|
|
||||||
print("搜索场所失败或未找到结果")
|
|
||||||
|
|
||||||
def test_get_location_by_ip():
|
def is_vague_location(location: str) -> bool:
|
||||||
"""测试根据IP地址获取位置信息"""
|
"""
|
||||||
api_key = os.environ.get("GD_KEY", "你的高德地图API密钥") # 替换为实际的API密钥
|
判断location是否是模糊位置词
|
||||||
|
|
||||||
service = PlaceSearchService(api_key)
|
Args:
|
||||||
# 随便一个IP地址,这里使用百度的公共DNS
|
location: 位置字符串
|
||||||
ip = "180.76.76.76"
|
|
||||||
|
Returns:
|
||||||
|
bool: 是否是模糊位置词
|
||||||
|
"""
|
||||||
|
if not location:
|
||||||
|
return False
|
||||||
|
|
||||||
|
vague_locations = [
|
||||||
|
'附近', '周边', '周围', '身边', '就近',
|
||||||
|
'这里', '这儿', '这边', '我这里', '我这儿', '我这边',
|
||||||
|
'当前位置', '我当前位置', '我的位置', '当前地点'
|
||||||
|
]
|
||||||
|
# 精确匹配这些模糊词
|
||||||
|
if location.strip() in vague_locations:
|
||||||
|
return True
|
||||||
|
|
||||||
print(f"\n=== 测试根据IP地址获取位置信息 ===")
|
return False
|
||||||
print(f"IP地址: {ip}")
|
|
||||||
|
|
||||||
result = service.get_location_by_ip(ip)
|
|
||||||
|
|
||||||
print(f"位置信息: {json.dumps(result, ensure_ascii=False, indent=2)}")
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
print("开始测试PlaceSearchService类...")
|
def parse_location_from_query(query: str) -> Optional[str]:
|
||||||
|
"""
|
||||||
|
从查询中解析出具体的位置名称
|
||||||
|
|
||||||
# 可以选择单独运行某个测试或全部测试
|
Args:
|
||||||
test_get_location_by_ip()
|
query: 用户查询文本
|
||||||
os.environ["GD_KEY"] = "1ba9b66a094a5a86b22e6c7425a4f33b"
|
|
||||||
# 如果有设置API密钥,再测试需要密钥的功能
|
Returns:
|
||||||
if os.environ.get("GD_KEY"):
|
Optional[str]: 解析出的位置名称,如果没有则为None
|
||||||
test_get_location_by_name()
|
"""
|
||||||
test_search_places_by_keyword()
|
# 如果是纯粹的"附近"查询,不包含具体位置名称
|
||||||
test_search_places_by_city()
|
if is_nearby_query(query) and not re.search(r'[在于]([\u4e00-\u9fa5a-zA-Z0-9]+)(附近|周边|周围)', query):
|
||||||
else:
|
return None
|
||||||
print("\n注意: 未设置GD_KEY环境变量,跳过需要API密钥的测试")
|
|
||||||
print("请设置环境变量 GD_KEY=你的高德地图API密钥 再运行完整测试")
|
|
||||||
|
|
||||||
print("\n测试完成!")
|
# 尝试匹配"XX附近"模式
|
||||||
|
location_match = re.search(r'([在于]?)([^在于]{2,}?)(附近|周边|周围)', query)
|
||||||
|
if location_match and location_match.group(2):
|
||||||
|
return location_match.group(2).strip()
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
@register_function("get_place_info", GET_PLACE_INFO_FUNCTION_DESC, ToolType.SYSTEM_CTL)
|
||||||
|
def get_place_info(conn, location: str = None, keyword: str = "餐厅", radius: int = 1000, lang: str = "zh_CN"):
|
||||||
|
"""
|
||||||
|
获取附近场所信息的函数
|
||||||
|
|
||||||
|
Args:
|
||||||
|
conn: 连接对象
|
||||||
|
location: 地点名称,可选
|
||||||
|
keyword: 搜索关键词,默认为"餐厅"
|
||||||
|
radius: 搜索半径,默认1000米
|
||||||
|
lang: 语言代码,默认zh_CN
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
ActionResponse: 动作响应对象
|
||||||
|
"""
|
||||||
|
# 获取配置中的高德地图API密钥
|
||||||
|
api_key = "1ba9b66a094a5a86b22e6c7425a4f33b"#conn.config["plugins"].get("get_place_info", {}).get("api_key", "")
|
||||||
|
default_city = "上海"
|
||||||
|
|
||||||
|
# 检查API密钥是否存在
|
||||||
|
if not api_key:
|
||||||
|
return ActionResponse(
|
||||||
|
Action.REQLLM, "抱歉,未配置高德地图API密钥,无法获取位置信息。", None
|
||||||
|
)
|
||||||
|
|
||||||
|
# 获取用户原始查询,用于判断是否是"附近"查询
|
||||||
|
user_query = conn.get_last_user_message() if hasattr(conn, "get_last_user_message") else ""
|
||||||
|
|
||||||
|
# 判断是否是纯粹的"附近"查询
|
||||||
|
if user_query and is_nearby_query(user_query) and not parse_location_from_query(user_query):
|
||||||
|
# 对于纯粹的"附近"查询,强制将location设为None
|
||||||
|
location = None
|
||||||
|
|
||||||
|
# 检查location是否为模糊位置词("附近"等),如果是则设为None
|
||||||
|
if location and is_vague_location(location):
|
||||||
|
logger.bind(tag=TAG).error(f"获取位置: {location}")
|
||||||
|
location = None
|
||||||
|
|
||||||
|
# 初始化场所搜索服务
|
||||||
|
place_service = PlaceSearchService(api_key)
|
||||||
|
client_ip = conn.client_ip
|
||||||
|
|
||||||
|
# 1. 优先使用用户提供的location参数
|
||||||
|
if location:
|
||||||
|
# 获取位置的地理编码信息
|
||||||
|
geo_info = place_service.get_location_by_name(location)
|
||||||
|
if not geo_info:
|
||||||
|
return ActionResponse(
|
||||||
|
Action.REQLLM, f"抱歉,无法找到位置:{location},请提供更准确的位置信息。", None
|
||||||
|
)
|
||||||
|
|
||||||
|
# 解析经纬度
|
||||||
|
lng, lat = geo_info["location"].split(",")
|
||||||
|
location_desc = geo_info["formatted_address"]
|
||||||
|
|
||||||
|
# 搜索附近场所
|
||||||
|
places = place_service.search_places_by_keyword(lng, lat, keyword, radius)
|
||||||
|
|
||||||
|
# 2. 如果没有提供location,尝试通过IP地址定位
|
||||||
|
elif client_ip:
|
||||||
|
# 获取IP对应的位置信息
|
||||||
|
ip_info = place_service.get_location_by_ip(client_ip)
|
||||||
|
logger.bind(tag=TAG).error(f"获取IP: {ip_info}")
|
||||||
|
|
||||||
|
# 如果IP地址能够解析出经纬度,直接使用经纬度搜索
|
||||||
|
if ip_info and "location" in ip_info:
|
||||||
|
lng, lat = ip_info["location"].split(",")
|
||||||
|
city_name = ip_info.get("city") if ip_info and "city" in ip_info else default_city
|
||||||
|
location_desc = city_name
|
||||||
|
|
||||||
|
# 使用经纬度搜索附近场所
|
||||||
|
places = place_service.search_places_by_keyword(lng, lat, keyword, radius)
|
||||||
|
logger.bind(tag=TAG).error(f"使用IP经纬度搜索: {lng},{lat}")
|
||||||
|
else:
|
||||||
|
# 如果没有经纬度,则使用城市名搜索
|
||||||
|
city_name = ip_info.get("city") if ip_info and "city" in ip_info else default_city
|
||||||
|
|
||||||
|
if not city_name:
|
||||||
|
city_name = default_city
|
||||||
|
|
||||||
|
# 根据城市名搜索场所
|
||||||
|
places = place_service.search_places_by_city(city_name, keyword)
|
||||||
|
location_desc = city_name
|
||||||
|
logger.bind(tag=TAG).error(f"使用城市名搜索: {city_name}")
|
||||||
|
|
||||||
|
# 3. 兜底:使用默认城市
|
||||||
|
else:
|
||||||
|
places = place_service.search_places_by_city(default_city, keyword)
|
||||||
|
location_desc = default_city
|
||||||
|
|
||||||
|
# 格式化搜索结果
|
||||||
|
result_text = place_service.format_search_results(places, location_desc)
|
||||||
|
|
||||||
|
return ActionResponse(Action.REQLLM, result_text, None)
|
||||||
|
except Exception as e:
|
||||||
|
# 捕获注册函数可能的异常
|
||||||
|
print(f"注册get_place_info函数失败: {e}")
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue