mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Update get_place_info.py
This commit is contained in:
parent
5d30c1ed59
commit
215deef6ff
1 changed files with 183 additions and 58 deletions
|
|
@ -1,11 +1,37 @@
|
|||
import requests
|
||||
import json
|
||||
from config.logger import setup_logging
|
||||
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
||||
from core.utils.util import get_ip_info
|
||||
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__
|
||||
logger = setup_logging()
|
||||
|
||||
# 尝试设置日志
|
||||
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 = {
|
||||
|
|
@ -18,7 +44,7 @@ GET_PLACE_INFO_FUNCTION_DESC = {
|
|||
"properties": {
|
||||
"location": {
|
||||
"type": "string",
|
||||
"description": "地点名,例如杭州。可选参数,如果不提供则通过IP定位"
|
||||
"description": "地点名,例如杭州。可选参数,如果不提供则通过IP定位,如果没有指定特定的地点,例如街道,城市,乡村等;那就直接返回附近"
|
||||
},
|
||||
"keyword": {
|
||||
"type": "string",
|
||||
|
|
@ -38,6 +64,7 @@ GET_PLACE_INFO_FUNCTION_DESC = {
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
class PlaceSearchService:
|
||||
"""
|
||||
场所搜索服务类,封装根据IP获取经纬度和搜索附近店铺的功能
|
||||
|
|
@ -50,7 +77,7 @@ class PlaceSearchService:
|
|||
Args:
|
||||
api_key: 高德地图API密钥
|
||||
"""
|
||||
self.api_key = api_key
|
||||
self.api_key = "1ba9b66a094a5a86b22e6c7425a4f33b"
|
||||
self.headers = {
|
||||
"User-Agent": (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
|
|
@ -73,8 +100,12 @@ class PlaceSearchService:
|
|||
Returns:
|
||||
dict: 包含城市等信息的字典
|
||||
"""
|
||||
try:
|
||||
ip_info = get_ip_info(client_ip, logger)
|
||||
return ip_info
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"获取IP信息失败: {e}")
|
||||
return {}
|
||||
|
||||
def get_location_by_name(self, location_name):
|
||||
"""
|
||||
|
|
@ -217,8 +248,87 @@ class PlaceSearchService:
|
|||
return result
|
||||
|
||||
|
||||
@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"):
|
||||
def is_nearby_query(query: str) -> bool:
|
||||
"""
|
||||
判断用户查询是否是关于"附近"的查询
|
||||
|
||||
Args:
|
||||
query: 用户查询文本
|
||||
|
||||
Returns:
|
||||
bool: 是否是附近查询
|
||||
"""
|
||||
nearby_patterns = [
|
||||
r'附近',
|
||||
r'我附近',
|
||||
r'周边',
|
||||
r'我周边',
|
||||
r'周围',
|
||||
r'我周围',
|
||||
r'就近',
|
||||
r'身边',
|
||||
r'我身边'
|
||||
]
|
||||
|
||||
# 检查查询中是否包含"附近"相关的词语
|
||||
for pattern in nearby_patterns:
|
||||
if re.search(pattern, query):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def is_vague_location(location: str) -> bool:
|
||||
"""
|
||||
判断location是否是模糊位置词
|
||||
|
||||
Args:
|
||||
location: 位置字符串
|
||||
|
||||
Returns:
|
||||
bool: 是否是模糊位置词
|
||||
"""
|
||||
if not location:
|
||||
return False
|
||||
|
||||
vague_locations = [
|
||||
'附近', '周边', '周围', '身边', '就近',
|
||||
'这里', '这儿', '这边', '我这里', '我这儿', '我这边',
|
||||
'当前位置', '我当前位置', '我的位置', '当前地点'
|
||||
]
|
||||
|
||||
# 精确匹配这些模糊词
|
||||
if location.strip() in vague_locations:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def parse_location_from_query(query: str) -> Optional[str]:
|
||||
"""
|
||||
从查询中解析出具体的位置名称
|
||||
|
||||
Args:
|
||||
query: 用户查询文本
|
||||
|
||||
Returns:
|
||||
Optional[str]: 解析出的位置名称,如果没有则为None
|
||||
"""
|
||||
# 如果是纯粹的"附近"查询,不包含具体位置名称
|
||||
if is_nearby_query(query) and not re.search(r'[在于]([\u4e00-\u9fa5a-zA-Z0-9]+)(附近|周边|周围)', query):
|
||||
return None
|
||||
|
||||
# 尝试匹配"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"):
|
||||
"""
|
||||
获取附近场所信息的函数
|
||||
|
||||
|
|
@ -233,8 +343,8 @@ def get_place_info(conn, location: str = None, keyword: str = "餐厅", radius:
|
|||
ActionResponse: 动作响应对象
|
||||
"""
|
||||
# 获取配置中的高德地图API密钥
|
||||
api_key = conn.config["plugins"].get("get_place_info", {}).get("api_key", "")
|
||||
default_city = conn.config["plugins"].get("get_place_info", {}).get("default_city", "北京")
|
||||
api_key = "1ba9b66a094a5a86b22e6c7425a4f33b"#conn.config["plugins"].get("get_place_info", {}).get("api_key", "")
|
||||
default_city = "上海"
|
||||
|
||||
# 检查API密钥是否存在
|
||||
if not api_key:
|
||||
|
|
@ -242,6 +352,18 @@ def get_place_info(conn, location: str = None, keyword: str = "餐厅", radius:
|
|||
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):
|
||||
location = None
|
||||
|
||||
# 初始化场所搜索服务
|
||||
place_service = PlaceSearchService(api_key)
|
||||
client_ip = conn.client_ip
|
||||
|
|
@ -284,3 +406,6 @@ def get_place_info(conn, location: str = None, keyword: str = "餐厅", radius:
|
|||
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