import gradio as gr import asyncio import os import sys # 添加项目路径到 sys.path sys.path.append(os.path.dirname(os.path.abspath(__file__))) # 导入天气助手模块 from weather_agent import get_weather, get_datetime, ToolContext, ToolResult # 创建一个简单的聊天机器人接口 class WeatherChatbot: def __init__(self): self.history = [] async def respond(self, message, history): """处理用户消息并返回响应""" # 添加用户消息到历史记录 history.append((message, None)) # 创建工具上下文 context = ToolContext() # 检查消息是否与天气相关 if any(keyword in message.lower() for keyword in ["天气", "weather", "温度", "气温"]): # 提取城市名称(简化版) cities = ["北京", "上海", "广州", "深圳", "纽约", "伦敦", "东京", "巴黎"] city = "北京" # 默认城市 # 简单的城市识别 for c in cities: if c in message: city = c break # 调用天气工具 try: weather_result = await get_weather(context, city) response = f"🌤️ {weather_result.content}" # 添加一些建议 if "晴" in response or "Sunny" in response: response += "\n\n👕 今天天气很好,适合户外活动!记得涂防晒霜。" elif "雨" in response or "Rainy" in response: response += "\n\n☔ 今天有雨,出门记得带伞。" elif "云" in response or "Cloudy" in response: response += "\n\n☁️ 今天多云,温度适中,适合外出。" except Exception as e: response = f"抱歉,获取天气信息时出现错误: {str(e)}" elif any(keyword in message.lower() for keyword in ["时间", "日期", "datetime", "time"]): # 调用时间工具 try: time_result = await get_datetime(context) response = f"⏰ 当前时间: {time_result.content}" except Exception as e: response = f"抱歉,获取时间信息时出现错误: {str(e)}" else: # 默认响应 responses = [ "你好!我可以帮你查询天气和时间信息。你可以问我'北京的天气怎么样?'或'现在几点了?'", "我是天气助手,可以为你提供天气和时间信息。有什么我可以帮你的吗?", "想了解某个城市的天气情况吗?或者需要知道当前时间?尽管问我吧!" ] import random response = random.choice(responses) # 更新历史记录 history[-1] = (history[-1][0], response) return "", history # 创建 Gradio 界面 def create_weather_interface(): chatbot = WeatherChatbot() with gr.Blocks(title="天气助手") as demo: gr.Markdown("# 🌤️ 天气助手") gr.Markdown("我可以帮你查询天气和时间信息。试试问我:'北京的天气怎么样?' 或 '现在几点了?'") # 聊天历史显示区域 chat_history = gr.Chatbot( label="对话记录" ) # 输入区域 with gr.Row(): user_input = gr.Textbox( label="输入消息", placeholder="例如:北京的天气怎么样?", lines=2 ) send_btn = gr.Button("发送 📤", variant="primary") # 功能按钮 with gr.Row(): clear_btn = gr.Button("清空聊天记录 🗑️") greet_btn = gr.Button("打招呼 👋") # 状态显示 status = gr.Textbox(label="状态", interactive=False) # 事件处理函数 async def respond_wrapper(message, history): return await chatbot.respond(message, history) def clear_history(): return [], "聊天记录已清空" def greet(): greeting = "你好!我是天气助手,可以帮你查询天气和时间信息。有什么我可以帮你的吗?" return "", [("助手", greeting)], f"助手说: {greeting}" # 绑定事件 send_btn.click( respond_wrapper, inputs=[user_input, chat_history], outputs=[user_input, chat_history] ) user_input.submit( respond_wrapper, inputs=[user_input, chat_history], outputs=[user_input, chat_history] ) clear_btn.click( clear_history, outputs=[chat_history, status] ) greet_btn.click( greet, outputs=[user_input, chat_history, status] ) return demo # 主函数 # 注意:在Hugging Face Space中,这个模块不应该独立启动