当前位置: 首页 > 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

相关文章:

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

接着前两节的Langchain,继续实现Langchain中的Agent LangChain 实现给动物取名字,LangChain 2模块化prompt template并用streamlit生成网站 实现给动物取名字 代码实现 # 从langchain库中导入模块 from langchain.llms import OpenAI # 从langchain.l…...

wpf devexpress绑定grid到总计和分组统计

此主题描述了如何在gridcontrol中的视图模型和显示定义总计和分组统计 在视图模型中指定统计 1、创建 SummaryItemType 枚举你想要在GridControl中显示的统计类型: public enum SummaryItemType { Max, Count, None } 2、创建一个grid统计描述类 public class S…...

嵌入式 Linux 移植与系统启动方法

1、Linux系统启动与U-Boot 所谓移植就是把程序代码从一种运行环境转移到另一种运行环境。对于内核移植来说,主要是从一种硬件平台转移到另一种硬件平台上运行。 体系结构级别的移植是指在不同体系结构平台上Linux内核的移植,例如,在ARM、MI…...

代码随想录算法训练营|五十六天

回文子串 647. 回文子串 - 力扣(LeetCode) dp含义:表示区间内[i,j]是否有回文子串,有true,没有false。 递推公式:当s[i]和s[j]不相等,false;相等时,情况一,…...

基于django水果蔬菜生鲜销售系统

基于django水果蔬菜生鲜销售系统 摘要 基于Django的水果蔬菜生鲜销售系统是一种利用Django框架开发的电子商务平台,旨在提供高效、便捷的购物体验,同时支持水果蔬菜生鲜产品的在线销售。该系统整合了用户管理、产品管理、购物车、订单管理等核心功能&…...

【数据结构】快速排序算法你会写几种?

👦个人主页:Weraphael ✍🏻作者简介:目前正在学习c和算法 ✈️专栏:数据结构 🐋 希望大家多多支持,咱一起进步!😁 如果文章有啥瑕疵 希望大佬指点一二 如果文章对你有帮助…...

C#访问修饰符

C#中的访问修饰符用于控制类型成员(如字段、属性、方法等)的访问级别。以下是C#中常用的访问修饰符: public:公共访问级别,没有任何访问限制。在任何其他类或程序集中都可以访问标记为 public 的成员。 private&#…...

anaconda中安装pytorch和TensorFlow环境并在不同环境中安装kernel

❤️觉得内容不错的话,欢迎点赞收藏加关注😊😊😊,后续会继续输入更多优质内容❤️ 👉有问题欢迎大家加关注私戳或者评论(包括但不限于NLP算法相关,linux学习相关,读研读博…...

记一次解决Pyqt6/Pyside6添加QTreeView或QTreeWidget导致窗口卡死(未响应)的新路历程,打死我都想不到是这个原因

文章目录 💢 问题 💢🏡 环境 🏡📄 代码💯 解决方案 💯⚓️ 相关链接 ⚓️💢 问题 💢 我在窗口中添加了一个 QTreeWidget控件 ,但是程序在运行期间,只要鼠标进入到 QTreeWidget控件 内进行操作,时间超过几秒中就会出现窗口 未响应卡死的 状态 🏡 环境 �…...

用照片预测人的年龄【图像回归】

在图像分类任务中,卷积神经网络 (CNN) 是非常强大的神经网络架构。 然而,鲜为人知的是,它们同样能够执行图像回归任务。 图像分类和图像回归任务之间的基本区别在于分类任务中的目标变量(我们试图预测的东西)不是连续…...

Fork项目新分支如何同步

这里以seata项目为示例: 一、添加Fork仓库的源仓库 git remote add seata gitgithub.com:seata/seata.git二、fetch git fetch seata...

Linux 常用压缩格式

Linux 常用压缩格式简介 Linux系统用户可以根据自己的需求选择合适的压缩工具来进行文件压缩和解压操作。Linux系统中常用的压缩软件都有相应的命令行工具,并且可以通过软件包管理器进行安装。主要有gzip、bzip2、zip、tar、7z。 gzip:gzip是一个广泛使…...

高效背单词——单词APP安利

大英赛,CET四六级,以及考研英语,都在不远的未来再度来临,年复一年的考试不曾停息,想要取得好成绩,需要我们的重视并赋予相应的努力。对于应试英语,词汇量是不可忽略的硬性要求。相比于传统默写&…...

力扣 字母异位词分组 哈表 集合

👨‍🏫 力扣 字母异位词分组 ⭐ 思路 由于互为字母异位词的两个字符串包含的字母相同,因此对两个字符串分别进行排序之后得到的字符串一定是相同的,故可以将排序之后的字符串作为哈希表的键。 🍑 AC code class Solut…...

⑩⑤【DB】详解MySQL存储过程:变量、游标、存储函数、循环,判断语句、参数传递..

个人简介:Java领域新星创作者;阿里云技术博主、星级博主、专家博主;正在Java学习的路上摸爬滚打,记录学习的过程~ 个人主页:.29.的博客 学习社区:进去逛一逛~ MySQL存储过程 1. 介绍2. 使用3. 变量①系统变…...

使用SpringBoot进行游戏服务器开发

背景: 之前一直只考虑用JavaSe进行游戏服务器开发,目前项目使用了Spring,发现还是非常好的,好处如下: 好处1:依赖注入非常方便,我们只使用Spring最基本的功能即可,这样子就算是有一些模块不使用Spring管理…...

数据结构——树状数组

文章目录 前言问题引入问题分析树状数组lowbit树状数组特性初始化一个树状数组更新操作前缀和计算区间查询 总结 前言 原题的连接 最近刷leetcode的每日一题的时候,遇到了一个区间查询的问题,使用了一种特殊的数据结构树状数组,学习完之后我…...

Untiy 使用RotateAround()方法实现物体围绕某个点或者某个物体旋转

Untiy 实现物体围绕指定点或者某个物体旋转,可使用RotateAround()方法。 语法: public void RotateAround(Vector3 point, Vector3 axis, float angle); 其中,point:旋转中心点位置; axis:要围绕的轴,如x,y,z angel…...

图像分类(五) 全面解读复现ResNet

解读 Abstract—摘要 翻译 更深的神经网络往往更难以训练,我们在此提出一个残差学习的框架,以减轻网络的训练负担,这是个比以往的网络要深的多的网络。我们明确地将层作为输入学习残差函数,而不是学习未知的函数。我们提供了非…...

使用html2canvas转换table为图片时合并单元格rowspan失效,无边框显示问题解决(React实现)

最近使用 html2canvas导出Table表单为图片,但是转换出的图片被合并的单元格没有显示边框 查了原因是因为我为tr设置了背景色,然后td设置了rowspan,设置了rowspan的单元格就会出现边框不显示的问题。 解决方法就是取消tr的背景色,然…...

pandas教程:Time Series Basics 时间序列基础

文章目录 11.2 Time Series Basics(时间序列基础)1 Indexing, Selection, Subsetting(索引,选择,取子集)2 Time Series with Duplicate Indices(重复索引的时间序列) 11.2 Time Seri…...

【C++初阶】STL详解(四)vector的模拟实现

本专栏内容为:C学习专栏,分为初阶和进阶两部分。 通过本专栏的深入学习,你可以了解并掌握C。 💓博主csdn个人主页:小小unicorn ⏩专栏分类:C 🚚代码仓库:小小unicorn的代码仓库&…...

Zookeeper学习笔记(2)—— Zookeeper API简单操作

前置知识&#xff1a;Zookeeper学习笔记&#xff08;1&#xff09;—— 基础知识-CSDN博客 Zookeeper集群搭建部分 前提&#xff1a;保证zookeeper集群处于启动状态 环境搭建 依赖配置 <dependencies><dependency><groupId>junit</groupId><arti…...

YOLOv8-Seg改进:Backbone改进 |Next-ViT堆栈NCB和NTB 构建先进的CNN-Transformer混合架构

🚀🚀🚀本文改进:Next-ViT堆栈NCB和NTB 构建先进的CNN-Transformer混合架构,包括nextvit_small, nextvit_base, nextvit_large,相比较yolov8-seg各个版本如下: layersparametersgradientsGFLOPsnextvit_small61033841075...

DocCMS keyword SQL注入漏洞复现 [附POC]

文章目录 DocCMS keyword SQL注入漏洞复现 [附POC]0x01 前言0x02 漏洞描述0x03 影响版本0x04 漏洞环境0x05 漏洞复现1.访问漏洞环境2.构造POC3.复现 0x06 修复建议 DocCMS keyword SQL注入漏洞复现 [附POC] 0x01 前言 免责声明&#xff1a;请勿利用文章内的相关技术从事非法测…...

利用(Transfer Learning)迁移学习在IMDB数据上训练一个文本分类模型

1. 背景 有些场景下&#xff0c;开始的时候数据量很小&#xff0c;如果我们用一个几千条数据训练一个全新的深度机器学习的文本分类模型&#xff0c;效果不会很好。这个时候你有两种选择&#xff0c;1.用传统的机器学习训练&#xff0c;2.利用迁移学习在一个预训练的模型上训练…...

pom.xml格式化快捷键

在软件开发和编程领域&#xff0c;"格式化"通常指的是将代码按照一定的规范和风格进行排列&#xff0c;以提高代码的可读性和维护性。格式化代码有助于使代码结构清晰、统一&#xff0c;并符合特定的编码规范。 格式化可以包括以下方面&#xff1a; 缩进&#xff1a…...

【短文】【踩坑】可以在Qt Designer给QTableWidge添加右键菜单吗?

2023年11月18日&#xff0c;周六上午 今天早上在网上找了好久都没找到教怎么在Qt Designer给QTableWidge添加右键菜单的文章 答案是&#xff1a;不可以 在Qt Designer中无法直接为QTableWidget添加右键菜单。 Qt Designer主要用于创建界面布局和设计&#xff0c;无法直接添加…...

Git常用配置

git log 美化输出 全局配置参数 git config --global alias.lm "log --no-merges --color --dateformat:%Y-%m-%d %H:%M:%S --authorghost --prettyformat:%Cred%h%Creset - %Cgreen(%cd)%C(yellow)%d%Cblue %s %C(bold blue)<%an>%Creset --abbrev-commit"…...

力扣每日一题-数位和相等数对的最大和-2023.11.18

力扣每日一题&#xff1a;数位和相等数对的最大和 开篇 这道每日一题还是挺需要思考的&#xff0c;我绕晕了好久&#xff0c;根据题解的提示才写出来。 题目链接:2342.数位和相等数对的最大和 题目描述 代码思路 1.创建一个数组存储每个数位的数的最大值&#xff0c;创建一…...