diff --git a/main/README.md b/main/README.md index 6f3300238..df4e57a42 100644 --- a/main/README.md +++ b/main/README.md @@ -18,6 +18,6 @@ xiaozhi-esp32-server # 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) diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 7fa8a24ae..21f37c5b7 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -102,6 +102,14 @@ Intent: - change_role - get_weather +# 插件的基础配置 +plugins: + # 获取天气插件的配置,这里填写你的api_key + # 这个密钥是项目共用的key,用多了可能会被限制 + # 想稳定一点就自行申请替换,每天有1000次免费调用 + # 申请地址:https://console.qweather.com/#/apps/create-key/over + get_weather: { "api_key": "a861d0d5e7bf4ee1a83d9a9e4f96d4da", "default_location": "广州" } + Memory: mem0ai: type: mem0ai diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index bfc5c65be..adb52c1ff 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -5,10 +5,12 @@ import time import queue import asyncio import traceback -from config.logger import setup_logging + import threading import websockets from typing import Dict, Any +import plugins_func.loadplugins +from config.logger import setup_logging from core.utils.dialogue import Message, Dialogue from core.handle.textHandle import handleTextMessage 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 core.auth import AuthMiddleware, AuthenticationError from core.utils.auth_code_gen import AuthCodeGenerator -import plugins_func.loadplugins TAG = __name__ @@ -97,8 +98,6 @@ class ConnectionHandler: self.use_function_call_mode = False if self.config["selected_module"]["Intent"] == 'function_call': self.use_function_call_mode = True - - self.func_handler = FunctionHandler(self.config) async def handle_connection(self, ws): try: @@ -106,9 +105,7 @@ class ConnectionHandler: self.headers = dict(ws.request.headers) # 获取客户端ip地址 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"Client ip info: {self.client_ip_info}") # 进行认证 await self.auth.authenticate(self.headers) @@ -152,6 +149,7 @@ class ConnectionHandler: self.welcome_msg["session_id"] = self.session_id await self.websocket.send(json.dumps(self.welcome_msg)) + # 异步初始化 await self.loop.run_in_executor(None, self._initialize_components) # tts 消化线程 @@ -192,7 +190,13 @@ class ConnectionHandler: self.prompt = self.config["prompt"] if self.private_config: 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.func_handler = FunctionHandler(self.config) def change_system_prompt(self, prompt): self.prompt = prompt diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py index a80a8a742..63cb5b9c9 100644 --- a/main/xiaozhi-server/core/utils/util.py +++ b/main/xiaozhi-server/core/utils/util.py @@ -1,6 +1,5 @@ import os import json -from datetime import datetime import yaml import socket import subprocess @@ -74,13 +73,9 @@ def get_ip_info(ip_addr): resp = requests.get(url).json() ip_info = { - "ip": resp.get("ipAddress"), "city": resp.get("cityName"), "region": resp.get("regionName"), - "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 + "country": resp.get("countryName") } return ip_info except Exception as e: diff --git a/main/xiaozhi-server/plugins_func/functions/get_weather.py b/main/xiaozhi-server/plugins_func/functions/get_weather.py index 5b72af328..75c0c1a3c 100644 --- a/main/xiaozhi-server/plugins_func/functions/get_weather.py +++ b/main/xiaozhi-server/plugins_func/functions/get_weather.py @@ -1,7 +1,7 @@ import requests from bs4 import BeautifulSoup -from plugins_func.register import register_function, ToolType, ActionResponse, Action from config.logger import setup_logging +from plugins_func.register import register_function, ToolType, ActionResponse, Action TAG = __name__ logger = setup_logging() @@ -32,8 +32,6 @@ GET_WEATHER_FUNCTION_DESC = { } } -API_KEY = "bdd98ec1d87747f3a2e8b1741a5af796" # TODO: 做成配置项 -DEFAULT_LOCATION = "广州" HEADERS = { 'User-Agent': ( 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' @@ -42,8 +40,8 @@ HEADERS = { } -def fetch_city_info(location): - url = f"https://geoapi.qweather.com/v2/city/lookup?key={API_KEY}&location={location}&lang=zh" +def fetch_city_info(location, api_key): + url = f"https://geoapi.qweather.com/v2/city/lookup?key={api_key}&location={location}&lang=zh" response = requests.get(url, headers=HEADERS).json() 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) 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}") - - city_info = fetch_city_info(location) + + city_info = fetch_city_info(location, api_key) if not city_info: return ActionResponse(Action.REQLLM, f"未找到相关的城市: {location},请确认地点是否正确", None) - + soup = fetch_weather_page(city_info['fxLink']) if not soup: return ActionResponse(Action.REQLLM, None, "请求失败") - + city_name, current_abstract, current_basic, temps_list = parse_weather_info(soup) weather_report = f"根据下列数据,用{lang}回应用户的查询天气请求:\n{city_name}未来7天天气:\n" 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的值不需要报告给用户,每次都报告体感温度,根据语境选择合适的参数内容告知用户,并对参数给出相应评价)" ) - return ActionResponse(Action.REQLLM, weather_report, None) \ No newline at end of file + return ActionResponse(Action.REQLLM, weather_report, None)