0%

gpt入门langchain之Agent介绍

hello 大家好我是Monday,今天给大家介绍gpt入门langchain之Agent介绍。

1、前言:

Agent模块可以说是LangChain的最重要的模块之一了,在LangChain框架中负责决策制定以及工具组的串联,可以根据用户的输入决定调用哪个工具。正确的使用Agent,才能够更好的使用LangChain+LLM的强大能力。

2、什么是Agents?

我们来看官网介绍:

Some applications will require not just a predetermined chain of calls to LLMs/other tools, but potentially an unknown chain that depends on the user’s input. In these types of chains, there is a “agent” which has access to a suite of tools. Depending on the user input, the agent can then decide which, if any, of these tools to call.

We split the documentation into the following sections:

有些应用不仅需要一个预先确定的调用LLM/其他工具的链,还可能需要一个取决于用户输入的未知链。在这些类型的链中,有一个 “代理”,它可以访问一整套的工具。根据用户的输入,代理可以决定调用这些工具中的哪一个(如果有的话)

有些应用需要根据用户的输入,灵活地调用LLM和其他工具的链条。代理人接口为这类应用提供了灵活性。一个代理可以访问一套工具,并根据用户的输入来决定使用哪些工具。代理人可以使用多个工具,并将一个工具的输出作为下一个工具的输入。

3、关于 Agents 有以下几个核心概念:

Tools

How language models interact with other resources.

语言模型如何与其他资源互动。

Agents

The language model that drives decision making.

推动决策的语言模型。

Toolkits

Sets of tools that when used together can accomplish a specific task.

一套工具在一起使用时可以完成一项特定的任务。

Agent Executor

The logic for running agents with tools.

用工具运行代理的逻辑。

4、开始实操:

(1)注册 Serpapi

在 Serpapi网站注册账号[3],可以使用 GitHub 账号或者 Google 账号。注册完成后可以在首页获取SERPAPI_API_KEY,保存备用。

这里我直接使用的github账号;

(2)官网代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import os
from env import getEnv
from src.hack.config import openai_api_key, serper_api_key
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import OpenAI

os.environ['SERPAPI_API_KEY'] = serper_api_key
os.environ['OPENAI_API_KEY'] = openai_api_key

# 加载将要用来控制 Agents 的语言模型
llm = OpenAI(temperature=0)

# 加载一些要使用的工具
tools = load_tools(["serpapi", "llm-math"], llm=llm)

# 初始化 Agents
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

# 测试一下!
agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")

(3)执行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22


> Entering new AgentExecutor chain...
I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power.
Action: Search
Action Input: "Leo DiCaprio girlfriend"
Observation: Camila Morrone
Thought: I need to find out Camila Morrone's age
Action: Search
Action Input: "Camila Morrone age"
Observation: 25 years
Thought: I need to calculate 25 raised to the 0.43 power
Action: Calculator
Action Input: 25^0.43
Observation: Answer: 3.991298452658078

Thought: I now know the final answer
Final Answer: Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078.

> Finished chain.

"Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078."

(4)从结果返回意思来看:

1
2
3
4
5
action 就是调用的tool

action input是 执行tool所需要的输入

Observation是返回结果

相对应:

1
2
3
Action: Search
Action Input: "Leo DiCaprio girlfriend"
Observation: Camila Morrone

(5)上面代码块给出的就是LLM的思考过程:

  • 观察:从问题中获取到关键信息:29岁

  • 问题拆分:I need to find out who Leo DiCaprio’s girlfriend is and then calculate her age raised to the 0.43 power.

    (1) Leo DiCaprio’s girlfriend is

    (2) Leo DiCaprio’s girlfriend age

    (2) Leo DiCaprio’s girlfriend age raised to the 0.43 power

  • 思考:我需要知道Leo DiCaprio女朋友是谁 ,那么我需要选用哪个工具呢?

  • 行为确认:LLM需要使用 谷歌搜索serpapi Tool执行计算操作,输入为:”Leo DiCaprio girlfriend”

  • 观察:结果为Camila Morrone

  • 思考:我需要知道Leo DiCaprio女朋友年龄 ,那么我需要选用哪个工具呢?

  • 行为确认:LLM需要使用 谷歌搜索serpapi Tool执行计算操作,输入为:”Camila Morrone age”

  • 观察:结果为25 years

  • 思考:我需要I need to calculate 25 raised to the 0.43 power ,那么我需要选用哪个工具呢?

  • 行为确认:LLM需要使用计算器Tool执行计算操作 ,输入为:25^0.43

  • 观察:结果为3.991298452658078

  • 思考:我已经拿到最终结果,不需要继续执行后续的操作;

  • 最终结果:”Camila Morrone is Leo DiCaprio’s girlfriend and her current age raised to the 0.43 power is 3.991298452658078.”

  • Chain的执行成功,并输出结果

如果我们的任务有很多,如何提高执行效率?当当当——-异步执行;

(6)批量任务异步实行代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from typing import List, Tuple, Any, Union
from langchain.schema import AgentAction, AgentFinish
from langchain.agents import Tool, AgentExecutor, BaseMultiActionAgent
from langchain import OpenAI, SerpAPIWrapper
from src.hack.config import openai_api_key, serper_api_key
import os

os.environ['SERPAPI_API_KEY'] = serper_api_key
os.environ['OPENAI_API_KEY'] = openai_api_key

questions = [
"Who won the US Open men's final in 2019? What is his age raised to the 0.334 power?",
"Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?",
"Who won the most recent formula 1 grand prix? What is their age raised to the 0.23 power?",
"Who won the US Open women's final in 2019? What is her age raised to the 0.34 power?",
"Who is Beyonce's husband? What is his age raised to the 0.19 power?"
]


async def task_run(questions):
llm = OpenAI(temperature=0)
tools = load_tools(["serpapi", "llm-math"], llm=llm)
agent = initialize_agent(
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)
s = time.perf_counter()
# If running this outside of Jupyter, use asyncio.run or loop.run_until_complete
tasks = [agent.arun(q) for q in questions]
await asyncio.gather(*tasks)
elapsed = time.perf_counter() - s
print(f"Concurrent executed in {elapsed:0.2f} seconds.")


loop = asyncio.get_event_loop()
loop.run_until_complete(task_run(questions))
# print('再看下运行情况:', task_run)
# loop.close()

【1】官网介绍:

https://docs.langchain.com/docs/components/agents/

https://python.langchain.com/docs/modules/agents.html

【2】 Serpapi网站注册账号

https://serpapi.com/

结束语

​ 今天的分享就到这里了,欢迎大家关注微信公众号”菜鸟童靴