update:天气查询优化

This commit is contained in:
hrz 2025-03-17 14:19:29 +08:00
parent ab5c61a61c
commit 9a4782fa15
5 changed files with 31 additions and 24 deletions

View file

@ -18,6 +18,6 @@ xiaozhi-esp32-server
# manager-web 、manager-api接口协议 # manager-web 、manager-api接口协议
[manager前后端接口协议](https://app.apifox.com/invite/project?token=H_8qhgfjUeaAL0wybghgU) [manager前后端接口协议](https://app.apifox.com/invite/project?token=eXg2_tUv85q-gc3ZRowmn)
[前端页面设计图](https://codesign.qq.com/app/s/526108506410828) [前端页面设计图](https://codesign.qq.com/app/s/526108506410828)

View file

@ -102,6 +102,14 @@ Intent:
- change_role - change_role
- get_weather - get_weather
# 插件的基础配置
plugins:
# 获取天气插件的配置,这里填写你的api_key
# 这个密钥是项目共用的key,用多了可能会被限制
# 想稳定一点就自行申请替换,每天有1000次免费调用
# 申请地址:https://console.qweather.com/#/apps/create-key/over
get_weather: { "api_key": "a861d0d5e7bf4ee1a83d9a9e4f96d4da", "default_location": "广州" }
Memory: Memory:
mem0ai: mem0ai:
type: mem0ai type: mem0ai

View file

@ -5,10 +5,12 @@ import time
import queue import queue
import asyncio import asyncio
import traceback import traceback
from config.logger import setup_logging
import threading import threading
import websockets import websockets
from typing import Dict, Any from typing import Dict, Any
import plugins_func.loadplugins
from config.logger import setup_logging
from core.utils.dialogue import Message, Dialogue from core.utils.dialogue import Message, Dialogue
from core.handle.textHandle import handleTextMessage from core.handle.textHandle import handleTextMessage
from core.utils.util import get_string_no_punctuation_or_emoji, extract_json_from_string, get_ip_info from core.utils.util import get_string_no_punctuation_or_emoji, extract_json_from_string, get_ip_info
@ -20,7 +22,6 @@ from plugins_func.register import Action
from config.private_config import PrivateConfig from config.private_config import PrivateConfig
from core.auth import AuthMiddleware, AuthenticationError from core.auth import AuthMiddleware, AuthenticationError
from core.utils.auth_code_gen import AuthCodeGenerator from core.utils.auth_code_gen import AuthCodeGenerator
import plugins_func.loadplugins
TAG = __name__ TAG = __name__
@ -97,8 +98,6 @@ class ConnectionHandler:
self.use_function_call_mode = False self.use_function_call_mode = False
if self.config["selected_module"]["Intent"] == 'function_call': if self.config["selected_module"]["Intent"] == 'function_call':
self.use_function_call_mode = True self.use_function_call_mode = True
self.func_handler = FunctionHandler(self.config)
async def handle_connection(self, ws): async def handle_connection(self, ws):
try: try:
@ -106,9 +105,7 @@ class ConnectionHandler:
self.headers = dict(ws.request.headers) self.headers = dict(ws.request.headers)
# 获取客户端ip地址 # 获取客户端ip地址
self.client_ip = ws.remote_address[0] self.client_ip = ws.remote_address[0]
self.client_ip_info = get_ip_info(self.client_ip)
self.logger.bind(tag=TAG).info(f"{self.client_ip} conn - Headers: {self.headers}") self.logger.bind(tag=TAG).info(f"{self.client_ip} conn - Headers: {self.headers}")
self.logger.bind(tag=TAG).info(f"Client ip info: {self.client_ip_info}")
# 进行认证 # 进行认证
await self.auth.authenticate(self.headers) await self.auth.authenticate(self.headers)
@ -152,6 +149,7 @@ class ConnectionHandler:
self.welcome_msg["session_id"] = self.session_id self.welcome_msg["session_id"] = self.session_id
await self.websocket.send(json.dumps(self.welcome_msg)) await self.websocket.send(json.dumps(self.welcome_msg))
# 异步初始化
await self.loop.run_in_executor(None, self._initialize_components) await self.loop.run_in_executor(None, self._initialize_components)
# tts 消化线程 # tts 消化线程
@ -192,7 +190,13 @@ class ConnectionHandler:
self.prompt = self.config["prompt"] self.prompt = self.config["prompt"]
if self.private_config: if self.private_config:
self.prompt = self.private_config.private_config.get("prompt", self.prompt) self.prompt = self.private_config.private_config.get("prompt", self.prompt)
self.client_ip_info = get_ip_info(self.client_ip)
self.logger.bind(tag=TAG).info(f"Client ip info: {self.client_ip_info}")
self.prompt = self.prompt + f"\n我在:{self.client_ip_info}"
self.dialogue.put(Message(role="system", content=self.prompt)) self.dialogue.put(Message(role="system", content=self.prompt))
self.func_handler = FunctionHandler(self.config)
def change_system_prompt(self, prompt): def change_system_prompt(self, prompt):
self.prompt = prompt self.prompt = prompt

View file

@ -1,6 +1,5 @@
import os import os
import json import json
from datetime import datetime
import yaml import yaml
import socket import socket
import subprocess import subprocess
@ -74,13 +73,9 @@ def get_ip_info(ip_addr):
resp = requests.get(url).json() resp = requests.get(url).json()
ip_info = { ip_info = {
"ip": resp.get("ipAddress"),
"city": resp.get("cityName"), "city": resp.get("cityName"),
"region": resp.get("regionName"), "region": resp.get("regionName"),
"country": resp.get("countryName"), "country": resp.get("countryName")
"country_code": resp.get("countryCode"),
"loc": f"{resp.get('latitude')},{resp.get('longitude')}",
"timezone": resp.get("timeZones")[0] if resp.get("timeZones") else None
} }
return ip_info return ip_info
except Exception as e: except Exception as e:

View file

@ -1,7 +1,7 @@
import requests import requests
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from plugins_func.register import register_function, ToolType, ActionResponse, Action
from config.logger import setup_logging from config.logger import setup_logging
from plugins_func.register import register_function, ToolType, ActionResponse, Action
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
@ -32,8 +32,6 @@ GET_WEATHER_FUNCTION_DESC = {
} }
} }
API_KEY = "bdd98ec1d87747f3a2e8b1741a5af796" # TODO: 做成配置项
DEFAULT_LOCATION = "广州"
HEADERS = { 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,8 +40,8 @@ HEADERS = {
} }
def fetch_city_info(location): def fetch_city_info(location, api_key):
url = f"https://geoapi.qweather.com/v2/city/lookup?key={API_KEY}&location={location}&lang=zh" url = f"https://geoapi.qweather.com/v2/city/lookup?key={api_key}&location={location}&lang=zh"
response = requests.get(url, headers=HEADERS).json() response = requests.get(url, headers=HEADERS).json()
return response.get('location', [])[0] if response.get('location') else None return response.get('location', [])[0] if response.get('location') else None
@ -78,17 +76,19 @@ def parse_weather_info(soup):
@register_function('get_weather', GET_WEATHER_FUNCTION_DESC, ToolType.SYSTEM_CTL) @register_function('get_weather', GET_WEATHER_FUNCTION_DESC, ToolType.SYSTEM_CTL)
def get_weather(conn, location: str = None, lang: str = "zh_CN"): def get_weather(conn, location: str = None, lang: str = "zh_CN"):
location = location or conn.client_ip_info.get("city") or DEFAULT_LOCATION api_key = conn.config["plugins"]["get_weather"]["api_key"]
default_location = conn.config["plugins"]["get_weather"]["default_location"]
location = location or conn.client_ip_info.get("city") or default_location
logger.bind(tag=TAG).debug(f"获取天气: {location}") logger.bind(tag=TAG).debug(f"获取天气: {location}")
city_info = fetch_city_info(location) city_info = fetch_city_info(location, api_key)
if not city_info: if not city_info:
return ActionResponse(Action.REQLLM, f"未找到相关的城市: {location},请确认地点是否正确", None) return ActionResponse(Action.REQLLM, f"未找到相关的城市: {location},请确认地点是否正确", None)
soup = fetch_weather_page(city_info['fxLink']) soup = fetch_weather_page(city_info['fxLink'])
if not soup: if not soup:
return ActionResponse(Action.REQLLM, None, "请求失败") return ActionResponse(Action.REQLLM, None, "请求失败")
city_name, current_abstract, current_basic, temps_list = parse_weather_info(soup) city_name, current_abstract, current_basic, temps_list = parse_weather_info(soup)
weather_report = f"根据下列数据,用{lang}回应用户的查询天气请求:\n{city_name}未来7天天气:\n" weather_report = f"根据下列数据,用{lang}回应用户的查询天气请求:\n{city_name}未来7天天气:\n"
for i, (date, high, low) in enumerate(temps_list): for i, (date, high, low) in enumerate(temps_list):
@ -101,4 +101,4 @@ def get_weather(conn, location: str = None, lang: str = "zh_CN"):
"参数为0的值不需要报告给用户,每次都报告体感温度,根据语境选择合适的参数内容告知用户,并对参数给出相应评价)" "参数为0的值不需要报告给用户,每次都报告体感温度,根据语境选择合适的参数内容告知用户,并对参数给出相应评价)"
) )
return ActionResponse(Action.REQLLM, weather_report, None) return ActionResponse(Action.REQLLM, weather_report, None)