当前位置: 首页 > news >正文

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

相关文章:

  • IntelliJ IDEA插件开发入门实战
  • 可拖动、可靠边的 popupWindow 实现
  • 数据结构及八种常用数据结构简介
  • 使用软路由(openWrt)安装openVPN搭建局域网连接
  • 【C++】入门三
  • 机器学习与图像识别(二)—— OpenCV环境折腾。。
  • 【Linux】20、进程状态:不可中断进程、iowait、僵尸进程、dstat strace pstree
  • oracle-buffer cache
  • 华为模拟器dhcp实验
  • X3DAudio1_7.dll丢失原因,X3DAudio1_7.dll丢失怎样解决分享
  • 星火模型(Spark)的langchain 实现
  • TDengine 跨版本迁移实战
  • lambda表达式c++
  • php mysql 如何处理查询中存在正则特殊字符的查询
  • 十、Linux运行级别
  • 77. Combinations
  • C++类中的特殊成员函数
  • canvas绘制圆角头像
  • CentOS7 安装JDK
  • Flannel解读
  • Java 网络编程(2):UDP 的使用
  • oldjun 检测网站的经验
  • Vue.js 移动端适配之 vw 解决方案
  • 等保2.0 | 几维安全发布等保检测、等保加固专版 加速企业等保合规
  • 关于Flux,Vuex,Redux的思考
  • 理解 C# 泛型接口中的协变与逆变(抗变)
  • 悄悄地说一个bug
  • 通过来模仿稀土掘金个人页面的布局来学习使用CoordinatorLayout
  • 用Visual Studio开发以太坊智能合约
  • No resource identifier found for attribute,RxJava之zip操作符
  • #{}和${}的区别?
  • #我与Java虚拟机的故事#连载16:打开Java世界大门的钥匙
  • (2)(2.4) TerraRanger Tower/Tower EVO(360度)
  • (Matlab)基于蝙蝠算法实现电力系统经济调度
  • (八)c52学习之旅-中断实验
  • (二)斐波那契Fabonacci函数
  • (一)使用IDEA创建Maven项目和Maven使用入门(配图详解)
  • (转)详解PHP处理密码的几种方式
  • (转)一些感悟
  • (转贴)用VML开发工作流设计器 UCML.NET工作流管理系统
  • .NET / MSBuild 扩展编译时什么时候用 BeforeTargets / AfterTargets 什么时候用 DependsOnTargets?
  • .NET Core/Framework 创建委托以大幅度提高反射调用的性能
  • .NET/C# 判断某个类是否是泛型类型或泛型接口的子类型
  • @TableId注解详细介绍 mybaits 实体类主键注解
  • [ solr入门 ] - 利用solrJ进行检索
  • [ vulhub漏洞复现篇 ] Celery <4.0 Redis未授权访问+Pickle反序列化利用
  • [ vulhub漏洞复现篇 ] Jetty WEB-INF 文件读取复现CVE-2021-34429
  • [8481302]博弈论 斯坦福game theory stanford week 1
  • [ANT] 项目中应用ANT
  • [APIO2015]巴厘岛的雕塑
  • [BZOJ] 2006: [NOI2010]超级钢琴
  • [C/C++] C/C++中数字与字符串之间的转换
  • [c++] 自写 MyString 类
  • [C++打怪升级]--学习总目录
  • [CSS3备忘] transform animation 等