学习链接:2025最新LangChain实战入门教程,从零到开始快速入门及底层原理,结合RAG构建一个完整的问答系统!赶快收藏吧!全网都没有这么全的教程!_哔哩哔哩_bilibili
Agent
Agent,代理、智能体,通过学习了解到,可以把Agent 想象成一个聪明的小助手,它能像人一样思考,帮你解决各种各样的问题。之前学的链就像是按照固定的路线走,一步接着一步,流程是提前设定好的。但是 Agent 会灵活一些,它可以根据你具体的问题动态地调整自己的行动,选择不同的工具,Agent不仅将LLM用于文本输出,还用于决策,这就是Agent的强大之处。
类型 |🦜️🔗 LangChain 语言链 --- Types | 🦜️🔗 LangChain这里可以看agent的类型。
所以工具是Agent最核心的组件,比如,你问 Agent:“今天娄底的天气怎么样,适合出去运动吗?” 它会先意识到需要查询天气信息,然后调用天气查询的工具,得到娄底今天的天气情况。接着,它会根据这个天气情况,结合自己关于运动和天气关系的 “知识”,判断是否适合出去运动,最后把答案告诉你。
接下来实现Langchain+通义千问来实现一个小Agent,功能是实现天气查询,使用阿里云的 DashScope API 来调用通义千问模型。
from langchain.tools import Tool
from langchain.agents import initialize_agent
获取DashScope API Key:https://bailian.console.aliyun.com/
天气工具:这里调用高德地图 API 获取指定城市的天气信息。
获取 高德地图 API:高德控制台,访问控制台——我的应用——添加应用——选Web服务
adcode:
行政区划代码(Administrative Division Code),是国家为了对各个行政区划进行统一、规范的标识而制定的一套代码体系。在高德地图的相关服务里,adcode
是对城市、地区进行唯一标识的关键代码。当调用高德地图的各类 API时,需要使用 adcode
来精准指定具体的地理位置。
通过映射把城市名称和对应的adcode
关联起来。
为什么要映射?
高德地图的天气查询 API 需要使用adcode
作为城市的标识,而用户在提问时往往使用的是城市名称,像 “北京市”“上海市” 这种。所以要把城市名称转换为对应的adcode
,这样才能正确调用 API。
定义一个加载映射表函数,加载城市名称到 adcode 的映射。
def load_city_adcode_mapping(file_path):
mapping = {} # 初始化空字典用于存储映射
try:
# 以UTF-8编码打开CSV文件
with open(file_path, mode='r', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile) # 将CSV读取为字典形式(键为表头)
for row in reader: # 遍历每一行数据
# 将CSV中的"城市"列作为键,"adcode"列作为值,存入字典
mapping[row['城市']] = row['adcode']
except Exception as e: # 捕获文件读取或解析时的异常
print(f"Error loading city-adcode mapping: {e}") # 打印错误
return mapping # 返回
# 调用函数加载映射表
CITY_ADMAPPING = load_city_adcode_mapping("AMap_adcode_citycode.csv")
在代码里,通过load_city_adcode_mapping
函数加载了一个映射表CITY_ADMAPPING
,它是一个字典,键是城市名称,值是对应的adcode
。在get_weather
函数中,会先从这个映射表中查找输入城市名称对应的adcode
,要是找到了,就用这个adcode
调用高德地图 API;要是没找到,就会返回相应的错误信息。同时在此之前要在工作目录下创建一个.csv的文件夹,
格式要与load_city_adcode_mapping
函数的格式对应
接下来定义天气工具,这是这个agent的核心
def get_weather(location):
# 将城市名称映射为 adcode
adcode = CITY_ADMAPPING.get(location)
if not adcode:
return f"'{location}' 未能在映射表中找到相应映射"
# 调用高德地图 API 获取天气数据
params = {
"city": adcode,
"key": "xxxxxxxxxxxxxxxxxxx",
"extensions": "base" # 获取实况天气信息
}
response = requests.get("https://restapi.amap.com/v3/weather/weatherInfo", params=params)
data = response.json()
if data["status"] == "1":
weather_info = data["lives"][0]["weather"]
temperature = data["lives"][0]["temperature"]
return f"{location}的天气为{weather_info},温度为{temperature}"
else:
return f"获得{location}该地天气信息失败: {data['info']}"
其中的参数,可参考基础 API 文档-开发指南-Web服务 API | 高德地图API来选择,这里请求的是extension,获取天气信息
完整代码:
import requests
from langchain.tools import Tool
from langchain.agents import initialize_agent
from langchain_community.chat_models.tongyi import ChatTongyi
import csv
# 初始化 ChatTongyi 模型
llm = ChatTongyi(
api_key="xxxxxxxxxxxxxxxxxxx",
model="qwen-plus"
)
def load_city_adcode_mapping(file_path):
mapping = {}
try:
with open(file_path, mode='r', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
mapping[row['城市']] = row['adcode']
except Exception as e:
print(f"Error loading city-adcode mapping: {e}")
return mapping
# 加载映射表
CITY_ADMAPPING = load_city_adcode_mapping("AMap_adcode_citycode.csv")
def get_weather(location):
# 将城市名称映射为 adcode
adcode = CITY_ADMAPPING.get(location)
if not adcode:
return f"'{location}' 未能在映射表中找到相应映射"
# 调用高德地图 API 获取天气数据
params = {
"city": adcode,
"key": "xxxxxxxxxxxxxxxxxx",
"extensions": "base" # 获取实况天气信息
}
response = requests.get("https://restapi.amap.com/v3/weather/weatherInfo", params=params)
data = response.json()
if data["status"] == "1":
weather_info = data["lives"][0]["weather"]
temperature = data["lives"][0]["temperature"]
return f"{location}的天气为{weather_info},温度为{temperature}"
else:
return f"获得{location}该地天气信息失败: {data['info']}"
# 创建工具
weather_tool = Tool(
name="get_weather",
func=get_weather,
description="获取指定地点的当前天气"
)
# 初始化 Agent,将工具绑定到模型
agent = initialize_agent([weather_tool], llm=llm, verbose=True)
# 调用 Agent 并传入问题
response = agent.run("娄底市今天的天气如何?适合什么户外运动?")
print("Response:", response)