feat(Agent): 新增维基百科搜索和温度查询工具并实现web界面

- 添加search_wikipedia和get_current_temperature工具函数
- 实现基于Streamlit的web交互界面
- 更新requirements.txt添加相关依赖
- 修复PROMPT_TEMPLATE变量名拼写错误
- 移除不再使用的工具函数
- 添加web界面截图到文档
This commit is contained in:
KMnO4-zx
2025-06-20 12:14:19 +08:00
parent cdf10fea16
commit 28636a0f9b
10 changed files with 249 additions and 41 deletions

View File

@@ -2,11 +2,11 @@ from openai import OpenAI
import json
from typing import List, Dict, Any
from src.utils import function_to_json
from src.tools import get_current_datetime, add, compare, count_letter_in_string
from src.tools import get_current_datetime, add, compare, count_letter_in_string, search_wikipedia, get_current_temperature
import pprint
SYSREM_PROMPT = """
SYSTEM_PROMPT = """
你是一个叫不要葱姜蒜的人工智能助手。你的输出应该与用户的语言保持一致。
当用户的问题需要调用工具时,你可以从提供的工具列表中调用适当的工具函数。
"""
@@ -17,7 +17,7 @@ class Agent:
self.tools = tools
self.model = model
self.messages = [
{"role": "system", "content": SYSREM_PROMPT},
{"role": "system", "content": SYSTEM_PROMPT},
]
self.verbose = verbose

View File

@@ -1,12 +1,14 @@
from datetime import datetime
import datetime
import wikipedia
import requests
# 获取当前日期和时间
def get_current_datetime() -> str:
"""
获取当前日期和时间。
获取真实的当前日期和时间。
:return: 当前日期和时间的字符串表示。
"""
current_datetime = datetime.now()
current_datetime = datetime.datetime.now()
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
return formatted_datetime
@@ -54,3 +56,76 @@ def count_letter_in_string(a: str, b: str):
count = string.count(letter)
return(f"The letter '{letter}' appears {count} times in the string.")
def search_wikipedia(query: str) -> str:
"""
在维基百科中搜索指定查询的前三个页面摘要。
:param query: 要搜索的查询字符串。
:return: 包含前三个页面摘要的字符串。
"""
page_titles = wikipedia.search(query)
summaries = []
for page_title in page_titles[: 3]: # 取前三个页面标题
try:
# 使用 wikipedia 模块的 page 函数,获取指定标题的维基百科页面对象。
wiki_page = wikipedia.page(title=page_title, auto_suggest=False)
# 获取页面摘要
summaries.append(f"页面: {page_title}\n摘要: {wiki_page.summary}")
except (
wikipedia.exceptions.PageError,
wikipedia.exceptions.DisambiguationError,
):
pass
if not summaries:
return "维基百科没有搜索到合适的结果"
return "\n\n".join(summaries)
def get_current_temperature(latitude: float, longitude: float) -> str:
"""
获取指定经纬度位置的当前温度。
:param latitude: 纬度坐标。
:param longitude: 经度坐标。
:return: 当前温度的字符串表示。
"""
# Open Meteo API 的URL
open_meteo_url = "https://api.open-meteo.com/v1/forecast"
# 请求参数
params = {
'latitude': latitude,
'longitude': longitude,
'hourly': 'temperature_2m',
'forecast_days': 1,
}
# 发送 API 请求
response = requests.get(open_meteo_url, params=params)
# 检查响应状态码
if response.status_code == 200:
# 解析 JSON 响应
results = response.json()
else:
# 处理请求失败的情况
raise Exception(f"API Request failed with status code: {response.status_code}")
# 获取当前 UTC 时间
current_utc_time = datetime.datetime.now(datetime.UTC)
# 将时间字符串转换为 datetime 对象
time_list = [datetime.datetime.fromisoformat(time_str).replace(tzinfo=datetime.timezone.utc) for time_str in
results['hourly']['time']]
# 获取温度列表
temperature_list = results['hourly']['temperature_2m']
# 找到最接近当前时间的索引
closest_time_index = min(range(len(time_list)), key=lambda i: abs(time_list[i] - current_utc_time))
# 获取当前温度
current_temperature = temperature_list[closest_time_index]
# 返回当前温度的字符串形式
return f'现在温度是 {current_temperature}°C'