当前位置: 首页 > 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的背景色,然…...

ubuntu搭建nfs服务centos挂载访问

在Ubuntu上设置NFS服务器 在Ubuntu上,你可以使用apt包管理器来安装NFS服务器。打开终端并运行: sudo apt update sudo apt install nfs-kernel-server创建共享目录 创建一个目录用于共享,例如/shared: sudo mkdir /shared sud…...

ESP32读取DHT11温湿度数据

芯片:ESP32 环境:Arduino 一、安装DHT11传感器库 红框的库,别安装错了 二、代码 注意,DATA口要连接在D15上 #include "DHT.h" // 包含DHT库#define DHTPIN 15 // 定义DHT11数据引脚连接到ESP32的GPIO15 #define D…...

智能在线客服平台:数字化时代企业连接用户的 AI 中枢

随着互联网技术的飞速发展,消费者期望能够随时随地与企业进行交流。在线客服平台作为连接企业与客户的重要桥梁,不仅优化了客户体验,还提升了企业的服务效率和市场竞争力。本文将探讨在线客服平台的重要性、技术进展、实际应用,并…...

k8s业务程序联调工具-KtConnect

概述 原理 工具作用是建立了一个从本地到集群的单向VPN,根据VPN原理,打通两个内网必然需要借助一个公共中继节点,ktconnect工具巧妙的利用k8s原生的portforward能力,简化了建立连接的过程,apiserver间接起到了中继节…...

Spring Cloud Gateway 中自定义验证码接口返回 404 的排查与解决

Spring Cloud Gateway 中自定义验证码接口返回 404 的排查与解决 问题背景 在一个基于 Spring Cloud Gateway WebFlux 构建的微服务项目中,新增了一个本地验证码接口 /code,使用函数式路由(RouterFunction)和 Hutool 的 Circle…...

Python ROS2【机器人中间件框架】 简介

销量过万TEEIS德国护膝夏天用薄款 优惠券冠生园 百花蜂蜜428g 挤压瓶纯蜂蜜巨奇严选 鞋子除臭剂360ml 多芬身体磨砂膏280g健70%-75%酒精消毒棉片湿巾1418cm 80片/袋3袋大包清洁食品用消毒 优惠券AIMORNY52朵红玫瑰永生香皂花同城配送非鲜花七夕情人节生日礼物送女友 热卖妙洁棉…...

C#学习第29天:表达式树(Expression Trees)

目录 什么是表达式树? 核心概念 1.表达式树的构建 2. 表达式树与Lambda表达式 3.解析和访问表达式树 4.动态条件查询 表达式树的优势 1.动态构建查询 2.LINQ 提供程序支持: 3.性能优化 4.元数据处理 5.代码转换和重写 适用场景 代码复杂性…...

关于easyexcel动态下拉选问题处理

前些日子突然碰到一个问题,说是客户的导入文件模版想支持部分导入内容的下拉选,于是我就找了easyexcel官网寻找解决方案,并没有找到合适的方案,没办法只能自己动手并分享出来,针对Java生成Excel下拉菜单时因选项过多导…...

git: early EOF

macOS报错: Initialized empty Git repository in /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core/.git/ remote: Enumerating objects: 2691797, done. remote: Counting objects: 100% (1760/1760), done. remote: Compressing objects: 100% (636/636…...

【Post-process】【VBA】ETABS VBA FrameObj.GetNameList and write to EXCEL

ETABS API实战:导出框架元素数据到Excel 在结构工程师的日常工作中,经常需要从ETABS模型中提取框架元素信息进行后续分析。手动复制粘贴不仅耗时,还容易出错。今天我们来用简单的VBA代码实现自动化导出。 🎯 我们要实现什么? 一键点击,就能将ETABS中所有框架元素的基…...