from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool import datetime import requests import pytz import yaml from tools.final_answer import FinalAnswerTool import os import json import gradio as gr from langchain_core.tools import tool from Gradio_UI import GradioUI AMAP_API_KEY = os.getenv("AMAP_KEY", "").strip() AMAP_GEOCODE_URL = "https://restapi.amap.com/v3/geocode/geo" def geocode_amap(location: str) -> str: if not AMAP_API_KEY: return json.dumps( { "success": False, "location": location, "message": "未设置环境变量 AMAP_KEY", }, ensure_ascii=False, ) try: resp = requests.get( AMAP_GEOCODE_URL, params={ "key": AMAP_API_KEY, "address": location, "output": "JSON", }, timeout=10, ) resp.raise_for_status() data = resp.json() if data.get("status") != "1": return json.dumps( { "success": False, "location": location, "message": data.get("info", "高德接口返回失败"), "raw": data, }, ensure_ascii=False, ) geocodes = data.get("geocodes", []) if not geocodes: return json.dumps( { "success": False, "location": location, "message": "未找到该地点的经纬度信息", "raw": data, }, ensure_ascii=False, ) first = geocodes[0] loc = first.get("location", "") lon = lat = None if loc and "," in loc: lon_str, lat_str = loc.split(",", 1) lon = float(lon_str) lat = float(lat_str) result = { "success": True, "query": location, "formatted_address": first.get("formatted_address"), "country": first.get("country"), "province": first.get("province"), "city": first.get("city"), "district": first.get("district"), "adcode": first.get("adcode"), "level": first.get("level"), "location": { "longitude": lon, "latitude": lat, "raw": loc, }, } return json.dumps(result, ensure_ascii=False) except requests.RequestException as e: return json.dumps( { "success": False, "location": location, "message": f"网络或接口错误: {str(e)}", }, ensure_ascii=False, ) except Exception as e: return json.dumps( { "success": False, "location": location, "message": f"查询失败: {str(e)}", }, ensure_ascii=False, ) @tool def my_custom_tool(location: str) -> str: """A tool for obtaining the latitude and longitude of a specific geographic location or city. Args: location: Indicates the specific geographic location of a city. """ return geocode_amap(location) @tool def get_current_time_in_timezone(timezone: str) -> str: """A tool that fetches the current local time in a specified timezone. Args: timezone: A string representing a valid timezone (e.g., 'America/New_York'). """ try: # 创建时区对象 tz = pytz.timezone(timezone) # 获取该时区的当前时间 local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") return f"The current local time in {timezone} is: {local_time}" except Exception as e: return f"Error fetching time for timezone '{timezone}': {str(e)}" final_answer = FinalAnswerTool() # 如果代理没有响应,模型可能过载,请使用另一个模型或以下同样包含 qwen2.5 coder 的 Hugging Face 端点: # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' model = HfApiModel( max_tokens=2096, temperature=0.5, model_id='Qwen/Qwen3-Coder-Next',# 这个模型可能会过载 custom_role_conversions=None, ) # Import tool from Hub image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) with open("prompts.yaml", 'r') as stream: prompt_templates = yaml.safe_load(stream) agent = CodeAgent( model=model, tools=[final_answer], # 在此添加你的工具(不要删除最终答案) max_steps=6, verbosity_level=1, grammar=None, planning_interval=None, name=None, description=None, prompt_templates=prompt_templates ) GradioUI(agent).launch()