LangChain 3使用Agent访问Wikipedia和llm-math计算狗的平均年龄

接着前两节的Langchain,继续实现Langchain中的Agent

  1. LangChain 实现给动物取名字,
  2. LangChain 2模块化prompt template并用streamlit生成网站 实现给动物取名字

在这里插入图片描述

代码实现

# 从langchain库中导入模块
from langchain.llms import OpenAI  # 从langchain.llms导入OpenAI模块
from langchain.prompts import PromptTemplate  # 从langchain.prompts导入PromptTemplate模块
from langchain.chains import LLMChain  # 从langchain.chains导入LLMChain模块
from dotenv import load_dotenv  # 从dotenv导入load_dotenv,用于加载环境变量
from langchain.agents import load_tools  # 从langchain.agents导入load_tools函数
from langchain.agents import initialize_agent  # 从langchain.agents导入initialize_agent函数
from langchain.agents import AgentType  # 从langchain.agents导入AgentType枚举类
from langchain.tools import WikipediaQueryRun  # 从langchain.tools导入WikipediaQueryRun
from langchain.utilities import WikipediaAPIWrapper  # 从langchain.utilities导入WikipediaAPIWrapperload_dotenv()  # 加载.env文件中的环境变量def langchain_agent():llm = OpenAI(temperature=0.5)  # 创建OpenAI模型实例,设置temperature参数为0.5以调整响应的多样性tools = load_tools(["wikipedia", "llm-math"], llm=llm)  # 加载wikipedia和llm-math工具,与OpenAI模型实例一起使用agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True  # 使用指定的工具、模型、agent类型和详细模式初始化agent)result = agent.run("What is the average age of a dog? Multiply the age by 3"  # 使用一个提示语来运行agent进行处理)print(result)  # 打印agent的输出# 主执行检查
if __name__ == "__main__":langchain_agent()  # 如果脚本是主程序,则运行langchain_agent函数

安装lib

pip install wikipedia  

运行代码

 python langchain_helper.py> Entering new AgentExecutor chain...I need to find out the average age of a dog first.
Action: Wikipedia
Action Input: Average age of a dog
Observation: Page: Aging in dogs
Summary: Aging in dogs varies from breed to breed, and affects the dog's health and physical ability. As with humans, advanced years often bring changes in a dog's ability to hear, see, and move about easily. Skin condition, appetite, and energy levels often degrade with geriatric age. Medical conditions such as cancer, kidney failure, arthritis, dementia, and joint conditions, and other signs of old age may appear.
The aging profile of dogs varies according to their adult size (often determined by their breed): smaller dogs often live over 1516 years (sometimes longer than 20 years), medium and large size dogs typically 10 to 20 years, and some giant dog breeds such as mastiffs, often only 7 to 8 years. The latter reach maturity at a slightly older age than smaller breeds—giant breeds becoming adult around two years old compared to the norm of around 1315 months for other breeds.Page: Dog
Summary: The dog (Canis familiaris or Canis lupus familiaris) is a domesticated descendant of the wolf. Also called the domestic dog, it is derived from extinct Pleistocene wolves, and the modern wolf is the dog's nearest living relative. The dog was the first species to be domesticated by humans. Hunter-gatherers did this, over 15,000 years ago in Germany, which was before the development of agriculture. Due to their long association with humans, dogs have expanded to a large number of domestic individuals and gained the ability to thrive on a starch-rich diet that would be inadequate for other canids.The dog has been selectively bred over millennia for various behaviors, sensory capabilities, and physical attributes. Dog breeds vary widely in shape, size, and color. They perform many roles for humans, such as hunting, herding, pulling loads, protection, assisting police and the military, companionship, therapy, and aiding disabled people. Over the millennia, dogs became uniquely adapted to human behavior, and the human–canine bond has been a topic of frequent study. This influence on human society has given them the sobriquet of "man's best friend".Page: Bluey (dog)
Summary: Bluey (7 June 191014 November 1939) was a female Australian Cattle Dog owned by Les and Rosalie Hall of Rochester, Victoria. She previously held the Guinness World Records as the oldest dog to ever live, until being surpassed by Bobi from Portugal in 2023.
Thought: I now know the average age of a dog.
Action: Calculator
Action Input: Multiply the average age of a dog by 3
Observation: Answer: 45.0
Thought: I now know the final answer.
Final Answer: The average age of a dog multiplied by 3 is 45.0 years.> Finished chain.
The average age of a dog multiplied by 3 is 45.0 years.

如果运行发生如下两种错误

错误一

resp = self.send(File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/requests/sessions.py", line 645, in sendr = adapter.send(request, **kwargs)File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/requests/adapters.py", line 517, in sendraise SSLError(e, request=request)requests.exceptions.SSLError: HTTPSConnectionPool(host='en.wikipedia.org', port=443): Max retries exceeded with url: /w/api.php?prop=info%7Cpageprops&inprop=url&ppprop=disambiguation&redirects=&titles=Aging+in+dogs&format=json&action=query (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:997)')))

错误二

Action Input: Average age of a dogTraceback (most recent call last):File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/requests/models.py", line 910, in jsonreturn complexjson.loads(self.text, **kwargs)File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/__init__.py", line 346, in loadsreturn _default_decoder.decode(s)File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/decoder.py", line 337, in decodeobj, end = self.raw_decode(s, idx=_w(s, 0).end())File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/decoder.py", line 355, in raw_decoderaise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

莫慌,笔者尝试问GPT4和google得到的答案都不正确。解决方案是切换梯子到不同的国家试试。笔者试了目前德国是好的。美国、香港、日本、新加坡是有问题的。

参考

  1. https://github.com/zgpeace/pets-name-langchain/tree/feature/agent
  2. https://youtu.be/lG7Uxts9SXs?si=H1CISGkoYiKRSF5V

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/194221.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

在线识别二维码工具

具体请前往:在线二维码识别解码工具--在线识别并解码二维码网址等内容

【C++】【Opencv】cv::Canny()边缘检测函数详解和示例

Canny边缘检测是一种流行的边缘检测算法,由John F. Canny在1986年开发。它是一种多阶段过程,包括噪声滤波、计算图像强度的梯度、非最大值抑制以及双阈值检测。本文通过函数原型解读和示例对cv::Canny()函数进行详解,以帮助大家理解和使用。 …

洛谷 P1064 [NOIP2006 提高组] 金明的预算方案 python解析

P1064 [NOIP2006 提高组] 金明的预算方案 时间:2023.11.19 题目地址:[NOIP2006 提高组] 金明的预算方案 题目分析 动态规划的0-1背包,采用动态数组。如果不了解的话,可以先看看这个背包DP。 这个是0-1背包的标准状态转移方程 f…

腾讯微服务平台TSF学习笔记(一)--如何使用TSF的Sidecar过滤器实现mesh应用的故障注入

Mesh应用的故障注入 故障注入前世今生Envoy设置故障注入-延迟类型设置故障注入-延迟类型并带有自定义状态码总结 故障注入前世今生 故障注入是一种系统测试方法,通过引入故障来找到系统的bug,验证系统的稳健性。istio支持延迟故障注入和异常故障注入。 …

大模型的交互能力

摘要: 基础大模型显示出明显的潜力,可以改变AI系统的开发人员和用户体验:基础模型降低了原型设计和构建AI应用程序的难度阈值,因为它们在适应方面的样本效率,并提高了新用户交互的上限,因为它们的多模式和生…

RobotFramework之用例执行时添加命令行参数(十三)

学习目录 引言 标签tag 设置变量 随机执行顺序 设置监听器 输出日志目录和文件 引言 Robot Framework 提供了许多命令行选项,可用于控制测试用例的执行方式以及生成的输出。本节介绍一些常用的选项语法。 标签tag 之前文章我们介绍过,在测试套件…

浅谈滑动窗口

滑动窗口是什么? 滑动窗口其实是一个想象出来的数据结构。有左边界L和有边界R。 举例来说:数组 arr {3,1,5,7,6,5,8}; 其窗口就是我们规定的一个运动轨迹。 最开始时,边界LR都在数组的最左侧,此时没有包住任何数。 此时规定&…

线性变换概论

线性变换 定义 设 V V V 和 W W W 都是在域 K K K上定义的向量空间, T : V → W T :V \rightarrow W T:V→W 对任二向量 x , y ∈ V x,y \in V x,y∈V,与任何标量 a ∈ K a \in K a∈K,满足: T ( x y ) T ( x ) T ( y ) T(xy)T(x)T(…

Windows 的 WSL 中运行 EasyConnect

Windows 的 WSL 中运行 EasyConnect docker-easyconnect 安装 Docker Desktop 通过 Docker 的官网 Docker Desktop 下载并安装. 安装过程一直下一步即可, 默认推荐 WSL 模式 初始化过程需要梯子 安装完后在搜索框搜索 docker-easyconnect hagb/docker-easyconnect 就是需要…

Spring Boot中使用Redis进行大数据缓存

Spring Boot中使用Redis进行大数据缓存 在Spring Boot中使用Redis进行大数据缓存是一种常见的做法,因为Redis是一种高性能的内存数据库,适用于缓存大量数据。以下是说明和示例代码,演示如何在Spring Boot项目中使用Redis进行大数据缓存。 步…

【Spring总结】注解开发

本篇讲的内容主要是基于Spring v2.5的注解来完成bean的定义 之前都是使用纯配置的方式来定义的bean 文章目录 前言1. Spring v2.5 注解开发定义bean第一步:在需要定义的类上写上注解Component第二步:在Spring Config中定义扫描包第三步:主方法…