Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import requests | |
| import os | |
| from geopy.geocoders import Nominatim | |
| from smolagents import tool, CodeAgent, HfApiModel, GoogleSearchTool, VisitWebpageTool | |
| # Lấy API keys từ biến môi trường | |
| OPENWEATHER_API_KEY = os.environ.get("OPENWEATHER_API_KEY") | |
| SERPER_API_KEY = os.environ.get("SERPER_API_KEY") | |
| # Định nghĩa tool get_weather | |
| def get_weather(lat: float, lon: float) -> dict | None: | |
| """ | |
| Call API to retrieve weather information for the given location. | |
| Args: | |
| lat: latitude of the location | |
| lon: longitude of the location | |
| """ | |
| url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={OPENWEATHER_API_KEY}&units=metric" | |
| try: | |
| response = requests.get(url) | |
| data = response.json() | |
| if response.status_code == 200: | |
| return { | |
| "condition": data["weather"][0]["description"], | |
| "temperature": data["main"]["temp"], | |
| "humidity": data["main"]["humidity"], | |
| "wind_speed": data["wind"]["speed"] | |
| } | |
| return None | |
| except Exception as e: | |
| print(f"Weather API Error: {e}") | |
| return None | |
| # Khởi tạo agent | |
| weather_agent = CodeAgent( | |
| model=HfApiModel("deepseek-ai/DeepSeek-R1", max_tokens=8096, provider="together"), | |
| tools=[ | |
| GoogleSearchTool(api_key=SERPER_API_KEY), | |
| VisitWebpageTool(), | |
| get_weather | |
| ], | |
| name="weather_agent", | |
| managed_agents=[display_agent], | |
| description="Fetch the weather condition of the given location." | |
| ) | |
| # Hàm xử lý chat | |
| def respond(message, history): | |
| try: | |
| # Thêm prompt engineering để hướng dẫn agent | |
| system_prompt = """Bạn là trợ lý thời tiết chuyên nghiệp. Hãy: | |
| 1. Xác định tọa độ địa lý từ tên địa điểm | |
| 2. Lấy thông tin thời tiết từ API | |
| 3. Trả lời bằng tiếng Việt với định dạng markdown | |
| 4. Kiểm tra độ chính xác của dữ liệu""" | |
| response = weather_agent.run( | |
| f"{system_prompt}\n\nYêu cầu người dùng: {message}" | |
| ) | |
| return response if response else "Không thể lấy thông tin thời tiết" | |
| except Exception as e: | |
| print(f"Error: {e}") | |
| return "Đã xảy ra lỗi khi xử lý yêu cầu" | |
| # Tạo giao diện Gradio | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# 🗺️ Weather Chat Agent") | |
| gr.Markdown("Nhập địa điểm để xem thông tin thời tiết") | |
| chatbot = gr.ChatInterface( | |
| respond, | |
| examples=["Hà Nội", "New York", "Tokyo", "Paris"], | |
| title="Weather Chatbot", | |
| additional_inputs_accordion_name="Advanced Options" | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |