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

news2024/10/7 18:28:48

接着前两节的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导入WikipediaAPIWrapper

load_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 send
    r = adapter.send(request, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/requests/adapters.py", line 517, in send
    raise 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 json
    return complexjson.loads(self.text, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/decoder.py", line 337, in decode
    obj, 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_decode
    raise 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.coloradmin.cn/o/1226923.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【算法基础】动态规划

背包问题 01背包 每个物品只能放一次 2. 01背包问题 - AcWing题库 二维dp #include<bits/stdc.h> const int N1010; int f[N][N]; int v[N],w[N]; signed main() {int n,m;std::cin>>n>>m; for(int i1;i<n;i) std::cin>>v[i]>>w[i];for…

穷举法、回溯法、分支界限法解决旅行商(TSP)问题

文章目录 一、问题描述二、穷举法解决2.1 介绍2.2 代码 三、回溯法解决四、分支界限法4.1 介绍4.2 代码 一、问题描述 有一个旅行商由某城市出发&#xff0c;经过所有给定的 n n n 个城市后&#xff0c;再回到出发的城市。除了出发的城市外&#xff0c;其它城市只经过一回。这…

2023.11.19 hadoop之MapReduce

目录 1.简介 2.分布式计算框架-Map Reduce 3.mapreduce的步骤 4.MapReduce底层原理 map阶段 shuffle阶段 reduce阶段 1.简介 Mapreduce是一个分布式运算程序的编程框架&#xff0c;是用户开发“基于hadoop的数据分析应用”的核心框架&#xff1b; Mapreduce核心功能是…

图解系列--认证

单向散列函数 1.什么是单向散列函数 单向散列函数有一个输入和一个输出&#xff0c;其中输入称为消息&#xff0c;输出称为散列值。单向散列函数可以根据消息的内容计算出散列值&#xff0c;而散列值就可以被用来检查消息的完整性。 在指定的散列函数处理下&#xff0c;无论输…

Hive语法,函数--学习笔记

1&#xff0c;排序处理 1.1cluster by排序 &#xff0c;在Hive中使用order by排序时是全表扫描&#xff0c;且仅使用一个Reduce完成。 在海量数据待排序查询处理时&#xff0c;可以采用【先分桶再排序】的策略提升效率。此时&#xff0c; 就可以使用cluster by语法。 cluster…

支持4KHz回报还能无线充电,简约不简单的雷柏VT3S游戏鼠标上手

这两年国产鼠标的表现很让人惊喜&#xff0c;不仅外观做工越来越精细&#xff0c;配置也越来越强大&#xff0c;当然价格依然亲民。现在很容易找到一款搭载高端传感器、响应速度快、电池续航时间长&#xff0c;并且还支持无线充电的全能型鼠标。 我之前用雷柏的鼠标比较多&…

Java 教育局民办教育信息服务与监管平台

1) 项目背景 按照《中华人民共和国民办教育促进法》和《中华人民共和国政府信息公开条例》的相关规定&#xff0c;为满足学生和家长、社会各界获取权威信息的需求&#xff0c;着力解决服务老百姓最后一公里问题&#xff0c;达到宣传民办教育和引导家长择校的效果&#xff0…

Java Swing商品信息查询系统

内容要求 1&#xff09; 本次程序设计是专门针对 Java 课程的,要求使用 Java 语言进行具有一定代码量的程序开发。程序的设计要结合一定的算法&#xff0c;在进行代码编写前要能够设计好自己的算法。 2&#xff09;本次程序设计涉及到 Java 的基本语法&#xff0c;即课堂上所…

3.6-Dockerfile语法梳理及最佳实践

WORKDIR是设置当前docker的工作目录 ADD 和 COPY 为了将本地的一些文件添加到docker image里面&#xff0c;ADD 和 COPY的作用特别像&#xff0c;但是ADD 和 COPY还有一些区别&#xff0c;ADD不仅可以添加本地文件到docker里面&#xff0c;还可以将文件在添加到docker image里面…

Linux进程——system函数、popen函数

system函数&#xff08;执行shell 命令&#xff09; 头文件 #include <stdlib.h> 函数定义 int system(const char * string); 函数说明 system()会调用fork()产生子进程&#xff0c;由子进程来调用/bin/sh-c string来执行参数string字符串所代表的命令&#xff0c;…

4.Pod详解【四】

文章目录 4. Pod详解4.1 Pod介绍4.1.1 Pod结构4.1.2 Pod定义 4.2 Pod配置4.2.1 基本配置4.2.2 镜像拉取4.2.3 启动命令4.2.4 环境变量4.2.5 端口设置4.2.6 资源配额 4.3 Pod生命周期4.3.1 创建和终止4.3.2 初始化容器4.3.3 钩子函数4.3.4 容器探测4.3.5 重启策略 4.4 Pod调度4.…

牛客网刷题笔记三 寻找第K大+两数之和+合并两个排序的链表+用两个栈实现队列

算法题牛客网NC88 寻找第K大 题目&#xff1a; 思路就是做个排序&#xff0c;要求时间复杂度 O ( n log ⁡ n ) O(n\log n) O(nlogn)&#xff0c;因此选用快排。代码&#xff1a; class Solution:def quickSort(self, a, start, end):if start > end:returnval a[start]…

利用SD存储介质扩展MAXQ20000的非易失性数据存储空间

SD存储卡是一种可移动存储介质&#xff0c;通常用于相机、手机、平板电脑等设备中存储照片、视频、音乐等数据。SD存储卡的全称为Secure Digital Memory Card&#xff0c;是由SD Card Association制定的一种标准格式。它具有体积小、存储容量大、读写速度快、价格低廉等优点。目…

Triage沙箱监控

Triage沙箱可以免费分析恶意软件样本。最先进的恶意软件分析沙箱&#xff0c;具有您需要的所有功能。 在可定制的环境中提交大量样本&#xff0c;并对许多恶意软件系列进行检测和配置提取。立即查看公开报告并对您的恶意软件进行分类&#xff01; 官方网址&#xff1a;https:…

关于链表的几道算法题

1.删除链表的倒数第n个节点 力扣https://leetcode.cn/submissions/detail/482739445/ /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val val; }* ListNode(…

Spring Boot中实现支付宝、微信和银联支付的功能

Spring Boot中实现支付宝、微信和银联支付的功能 在Spring Boot中实现支付宝、微信和银联支付的功能&#xff0c;通常需要使用它们各自的SDK&#xff08;Software Development Kit&#xff09;。以下是一个简单的示例代码&#xff0c;演示了如何在Spring Boot项目中集成支付宝…

22. 深度学习 - 自动求导

Hi&#xff0c;你好。我是茶桁。 咱们接着上节课内容继续讲&#xff0c;我们上节课已经了解了拓朴排序的原理&#xff0c;并且简单的模拟实现了。我们这节课就来开始将其中的内容变成具体的计算过程。 linear, sigmoid和loss这三个函数的值具体该如何计算呢&#xff1f; 我们…

使用Spring Boot结合JustAuth实现支付宝、微信、微博扫码登录功能

使用Spring Boot结合JustAuth实现支付宝、微信、微博扫码登录功能 在使用Spring Boot结合JustAuth实现支付宝、微信、微博扫码登录功能之前&#xff0c;需要先确保已经配置好Spring Boot项目&#xff0c;并且添加了JustAuth的依赖。你可以在项目的pom.xml文件中添加如下依赖&a…

麦克风阵列入门

文章引注&#xff1a; http://t.csdnimg.cn/QP7uC 一、麦克风阵列的定义 所谓麦克风阵列其实就是一个声音采集的系统&#xff0c;该系统使用多个麦克风采集来自于不同空间方向的声音。麦克风按照指定要求排列后&#xff0c;加上相应的算法&#xff08;排列算法&#xff09;就可…