之前的博客中为了获取实时天气,写了两个tool:get_adcode_by_location和get_live_weather。其中,get_live_weather可以获取单独的城市名和adcode,但是传入“杭州市西湖区”这种组合式的城市名则会报错,无法获取,因此,增加了get_adcode_by_location方法,可以模糊识别组合城市名,获取adcode。

        一般的流程是:LLM -> get_adcode_by_location() -> get_live_weather(),如果输入的是单独的城市,则可以直接调用get_live_weather()。具体一点来说,LLM需要理解调用哪个工具(是否需要调用先调用get_adcode_by_location() ,还是直接调用get_live_weather()),再解析返回结构。也就是,让LLM来做流程控制,这不仅会增加出错概率,还会增加token成本(思考决策过程)。

        可以将获取天气的步骤封装为一个函数式skill,内部自动进行如下流程:location → adcode → 高德API → 格式化输出,LLM只需要调用一次。


from agent.tools.weather_tool import get_adcode_by_location, get_live_weather
from langchain.tools import tool

@tool
def get_weather_by_location(location: str) -> dict:
    '''
    查询指定位置实时天气,必须用于实时天气问题,而非天气预报。
    Args:
        location: 位置名称(如"杭州市"、"西湖区"、"浙江省杭州市西湖区")或是adcode(如"330100"->"杭州市")
    Returns:
        格式化的天气信息字符串,失败时返回友好提示
    '''
    adcode_result = get_adcode_by_location(location)
    if "error" in adcode_result:
        return adcode_result["error"]
    
    adcode = adcode_result["adcode"]
    weather_result = get_live_weather(adcode)
    
    return weather_result

        需要将原本那两个工具的@tool装饰器删除。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐