【Langchain大语言模型开发教程】代理

🔗 LangChain for LLM Application Development - DeepLearning.AI

学习目标 

1、学习构建Agent

2、如何调用agent进行提问

3、自定义自己的工具

import os

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file

import warnings
warnings.filterwarnings("ignore")
from langchain_experimental.tools import PythonREPLTool
from langchain import hub
from langchain_core.tools import tool
from langchain_community.tools import DuckDuckGoSearchRun,WikipediaQueryRun
from langchain_experimental.agents.agent_toolkits import create_python_agent
from langchain.agents import AgentExecutor,AgentType,create_structured_chat_agent
from langchain_openai import ChatOpenAI
from langchain_community.utilities import WikipediaAPIWrapper

初始化我们的大语言模型 ;

llm = ChatOpenAI(api_key=os.environ.get('ZHIPUAI_API_KEY'),
                         base_url=os.environ.get('ZHIPUAI_API_URL'),
                         model="glm-4",
                         temperature=0)

我们自定义乘法工具、加法工具和指数工具,然后我们初始化一个python解释器工具、搜索工具和维基百科检索工具;

@tool
def multiply(first_int: int, second_int: int) -> int:
    """Multiply two integers together."""
    return first_int * second_int

@tool
def add(first_int: int, second_int: int) -> int:
    "Add two integers."
    return first_int + second_int

@tool
def exponentiate(base: int, exponent: int) -> int:
    "Exponentiate the base to the exponent power."
    return base**exponent



pythonREPLTool = PythonREPLTool()
search = DuckDuckGoSearchRun()
wikipedia = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())

 我们从langchain提供的这个网站中获取一个已经写好的prompt;传送门:prompt

prompt = hub.pull("hwchase17/structured-chat-agent")
tools = [pythonREPLTool, wikipedia, search, multiply, add, exponentiate]

 我们创建一个agent和一个agent执行器;

agent = create_structured_chat_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True,handle_parsing_errors=True)

 接下来我们就可以进行提问了:

我们先来一个数学问题:把3的五次方乘以12加3的和,然后把整个结果平方

agent_executor.invoke({"input": "Take 3 to the fifth power and multiply that by the sum of twelve and three, then square the whole result"})
Thought: I need to calculate the exponent first, then the sum, then the multiplication, and finally the square of the result.
Action:
```
{  
"action": "exponentiate",  
"action_input": {"base": 3, "exponent": 5}
}
```243```
{  
"action": "add",
"action_input": {"first_int": 12, "second_int": 3}
}
```
Observation 15
```
{  
"action": "multiply",
"action_input": {"first_int": 243, "second_int": 15}
}
```
Observation 3645
Action:
```
{  
"action": "exponentiate",  
"action_input": {"base": 3645, "exponent": 2}
}
```13286025```
{
  "action": "Final Answer",
  "action_input": "The square of the product of 3 to the fifth power and the sum of twelve and three is 13,286,025."
}
```

 问一下全职猎人是什么?

agent_executor.invoke({ "input": "HUNTER X HUNTER是什么?"})
Action:
```{
  "action": "wikipedia",
  "action_input": {"query": "HUNTER X HUNTER"}
}```
ObservationPage: Hunter × Hunter
Summary: Hunter × Hunter (pronounced "hunter hunter") is a Japanese manga series written and illustrated by Yoshihiro Togashi. It has been serialized in Shueisha's shōnen manga magazine Weekly Shōnen Jump since March 1998, although the manga has frequently gone on extended hiatuses since 2006. Its chapters have been collected in 37 tankōbon volumes as of November 2022. The story focuses on a young boy named Gon Freecss who discovers that his father, who left him at a young age, is actually a world-renowned Hunter, a licensed professional who specializes in fantastical pursuits such as locating rare or unidentified animal species, treasure hunting, surveying unexplored enclaves, or hunting down lawless individuals. Gon departs on a journey to become a Hunter and eventually find his father. Along the way, Gon meets various other Hunters and encounters the paranormal.
Hunter × Hunter was adapted into a 62-episode anime television series by Nippon Animation and directed by Kazuhiro Furuhashi, which ran on Fuji Television from October 1999 to March 2001. Three separate original video animations (OVAs) totaling 30 episodes were subsequently produced by Nippon Animation and released in Japan from 2002 to 2004. A second anime television series by Madhouse aired on Nippon Television from October 2011 to September 2014, totaling 148 episodes, with two animated theatrical films released in 2013. There are also numerous audio albums, video games, musicals, and other media based on Hunter × Hunter.
The manga has been licensed for English release in North America by Viz Media since April 2005. Both television series have been also licensed by Viz Media, with the first series having aired on the Funimation Channel in 2009 and the second series broadcast on Adult Swim's Toonami programming block from April 2016 to June 2019.
Hunter × Hunter has been a huge critical and financial success and has become one of the best-selling manga series of all time, having over 84 million copies in circulation by July 2022.

Hunters (ハンター, Hantā) are licensed, elite members of humanity who are capable of tracking down secret treasures, rare beasts, or even other individuals, and can also access locations that regulars cannot. To obtain a license one must pass the rigorous annual Hunter Examination run by the Hunter Association, which has a success rate of less than one in a hundred-thousand. A Hunter may be awarded up to three stars: a single star for making "remarkable achievements in a particular field"; they may then be upgraded to two stars for "holding an official position" and mentoring another Hunter up to single star level; and finally upgraded to three stars for "remarkable achievements in multiple fields".
Nen (念) is the ability to control one's own life energy or aura, which is constantly emitted from them, knowingly or not. There are four basic Nen techniques: Ten (纏) maintains the aura in the body, strengthening it for defense; Zetsu (絕) shuts the aura flow off, useful for concealing one's presence and relieving fatigue; Ren (練) enables a user to produce more Nen; and Hatsu (發) is a person's specific use of Nen. Nen users are classified into six types based on their Hatsu abilities; Enhancers (強化系, Kyōkakei) strengthen and reinforce their natural physical abilities; Emitters (放出系, Hōshutsukei) project aura out of their bodies; Manipulators (操作系, Sōsakei) control objects or living things; Transmuters (変化系, Henkakei) change the type or properties of their aura; Conjurers (具現化系, Gugenkakei) create objects out of their aura; and Specialists (特質系, Tokushitsukei) have unique abilities that do not fall into the previous categories. A Nen user can enter into a Contract (誓約, Seiyaku) where, by pledging to follow certain Limitations (制約, Seiyaku), their abilities are strengthened in relation to how strict they are. An example of this is Kurapika who, in order to have an unbreakable chain that will fully restrain members of the PhantoAction:
```{
  "action": "Final Answer",
  "action_input": "HUNTER X HUNTER是一部由日本漫画家富坚义博创作的漫画系列。该系列自1998年3月开始在集英社的《周刊少年Jump》上连载,尽管自2006年以来漫画经常进入长期休载状态。截至2022年11月,其章节已被收集在37本单行本中。故事围绕一个名叫冈·弗里萨斯的年轻男孩展开,他发现自己的父亲,一个在他很小的时候就离开了他的人,实际上是一位世界著名的猎人,这是一个获得许可的专业人士,专门从事寻找稀有或未知的动物物种、寻宝、探索未探索的领地或追捕不法分子等奇幻追求。冈决定踏上成为猎人的旅程,并最终找到他的父亲。在这个过程中,冈遇到了其他各种猎人,并遭遇了超自然现象。HUNTER X HUNTER还被改编成了动画系列、剧场版、音乐专辑、视频游戏等多种形式,并获得了巨大的口碑和商业成功。"
}```

> Finished chain.

 给出一个姓名列表,排个序;

customer_list = [["Harrison", "Chase"],
                 ["Lang", "Chain"],
                 ["Dolly", "Too"],
                 ["Elle", "Elem"],
                 ["Geoff","Fusion"],
                 ["Trance","Former"],
                 ["Jen","Ayai"]
                ]
agent_executor.invoke(
    {
        "input": f"""Sort these customers by \
last name and then first name \
and print the output: {customer_list}"""
    }
)
To sort the list of customers by last name and then by first name, I can use the `sorted` function in Python with a custom key function that returns a tuple of the last and first names. Here is the action to do that:

```json
{
  "action": "Python_REPL",
  "action_input": "customers = [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]; sorted_customers = sorted(customers, key=lambda x: (x[1], x[0])); print(sorted_customers)"
}
```[['Jen', 'Ayai'], ['Lang', 'Chain'], ['Harrison', 'Chase'], ['Elle', 'Elem'], ['Trance', 'Former'], ['Geoff', 'Fusion'], ['Dolly', 'Too']]
```
{
  "action": "Final Answer",
  "action_input": "The sorted list of customers by last name and then first name is [['Jen', 'Ayai'], ['Lang', 'Chain'], ['Harrison', 'Chase'], ['Elle', 'Elem'], ['Trance', 'Former'], ['Geoff', 'Fusion'], ['Dolly', 'Too']]."
}
```

> Finished chain.

我们再用一下这个duckduckgosearch这个工具,问一个计算机考研408都包含那些内容;

agent_executor.invoke({"input": "计算机考研408都包含那些内容?"})

一开始它去查了维基百科发现没有,然后用了duckduckgosearch; 

Action:
```json
{
  "action": "wikipedia",
  "action_input": {"query": "计算机考研408"}
}
```No good Wikipedia Search Result was found```json
{
  "action": "duckduckgo_search",
  "action_input": {"query": "计算机考研408包含内容"}
}
```408的难点在于他涉及的范围太广了,备考408,你要准备四门课程,分别是数据结构,计算机组成原理,操作系统和计算机网络。另外一个难点就是数据结构和计算机组成原理。学过这两门课的都知道,难度很高,特别是计算机组成原理,挂科重灾区,而且这两门课程在考研的时候也是占比最大的,各 ... 408全称408计算机基础综合,是全国统考的考研专业科目。参考408的考试大纲可知,408考察内容包括了: 四门课的难度排序为:计算机组成>数据结构>操作系统>计算机网络。各科目在试卷中的试题分布以及主要考察内容: 计算机组成原理. 选择题:第12-22题,共计 ... 考研计算机408资料集锦详解 一、内容概览 这份考研计算机408资料集锦,是为准备参加考研计算机408科目的考生精心整理的全方位学习资源。内容涵盖了从基础知识到实战应用的各个方面,具体包括: 基础知识梳理:... 计算机考研408指的是计算机考研初试的代码,其考试内容是计算机组成原理、操作系统、数据结构和计算机网络。 试卷满分150分,数据结构45分、计算机组成原理45分、操作系统35分、计算机网络25分。 ... 408全称计算机专业基础综合,包括四门专业课的考察 ... 计算机考研的科目主要包括数据结构、计算机组成原理、操作系统和计算机网络四门课程,也就是我们常说的"408"。. 1、数据结构. 数据结构是计算机科学的基础课程之一,主要研究数据的组织、存储和操作等问题。. 在考研中,数据结构的主要内容包括线性表 ...```json
{
  "action": "Final Answer",
  "action_input": "计算机考研408主要包括四门课程:数据结构、计算机组成原理、操作系统和计算机网络。这四门课程的难度从高到低排序为:计算机组成原理、数据结构、操作系统、计算机网络。在考试中,试卷满分150分,具体分配为:数据结构45分、计算机组成原理45分、操作系统35分、计算机网络25分。计算机组成原理和数据结构是考试的重点,也是难点。"
}
```

> Finished chain.
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是饿梦啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值