大模型从入门到应用——LangChain:代理(Agents)-[计划与执行]

本文深入探讨了如何使用LangChain框架进行基础设置(如安装和配置),构建和定制LLMs,管理记忆,以及实现高级功能如对话代理、规划执行,适用于自然语言处理和AI开发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分类目录:《大模型从入门到应用》总目录

LangChain系列文章:


计划与执行代理通过首先规划要做的事情,然后执行子任务来实现目标。这个想法在很大程度上受到了BabyAGI以及《Plan-and-Solve》论文的启发。

  • 规划几乎总是由一个LLM(语言模型)来完成。
  • 执行通常由一个单独的代理(配备工具)来完成。
# 导入模块
from langchain.chat_models import ChatOpenAI
from langchain.experimental.plan_and_execute import PlanAndExecute, load_agent_executor, load_chat_planner
from langchain.llms import OpenAI
from langchain import SerpAPIWrapper
from langchain.agents.tools import Tool
from langchain import LLMMathChain

# 工具
search = SerpAPIWrapper()
llm = OpenAI(temperature=0)
llm_math_chain = LLMMathChain.from_llm(llm=llm, verbose=True)
tools = [
    Tool(
        name = "Search",
        func=search.run,
        description="useful for when you need to answer questions about current events"
    ),
    Tool(
        name="Calculator",
        func=llm_math_chain.run,
        description="useful for when you need to answer questions about math"
    ),
]

# 规划器(Planner)、执行器(Executor)和代理(Agent)
model = ChatOpenAI(temperature=0)
planner = load_chat_planner(model)
executor = load_agent_executor(model, tools, verbose=True)
agent = PlanAndExecute(planner=planner, executor=executor, verbose=True)

# 执行示例
agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")
Entering new PlanAndExecute chain...
steps=[Step(value="Search for Leo DiCaprio's girlfriend on the internet."), Step(value='Find her current age.'), Step(value='Raise her current age to the 0.43 power using a calculator or programming language.'), Step(value='Output the result.'), Step(value="Given the above steps taken, respond to the user's original question.\n\n")]

日志输出:

日志输出:
Entering new AgentExecutor chain...
Action:

```{
  "action": "Search",
  "action_input": "Who is Leo DiCaprio's girlfriend?"
}```


Observation: DiCaprio broke up with girlfriend Camila Morrone, 25, in the summer of 2022, after dating for four years. He's since been linked to another famous supermodel – Gigi Hadid. The power couple were first supposedly an item in September after being spotted getting cozy during a party at New York Fashion Week.
Thought:Based on the previous observation, I can provide the answer to the current objective. 
Action:
```{
  "action": "Final Answer",
  "action_input": "Leo DiCaprio is currently linked to Gigi Hadid."
}```


Finished chain.
*****

Step: Search for Leo DiCaprio's girlfriend on the internet.

Response: Leo DiCaprio is currently linked to Gigi Hadid.

Entering new AgentExecutor chain...
Action:
```{
  "action": "Search",
  "action_input": "What is Gigi Hadid's current age?"
}```

Observation: 28 years
Thought:Previous steps: steps=[(Step(value="Search for Leo DiCaprio's girlfriend on the internet."), StepResponse(response='Leo DiCaprio is currently linked to Gigi Hadid.'))]

Current objective: value='Find her current age.'

Action:
```{
  "action": "Search",
  "action_input": "What is Gigi Hadid's current age?"
}```


Observation: 28 years
Thought:Previous steps: steps=[(Step(value="Search for Leo DiCaprio's girlfriend on the internet."), StepResponse(response='Leo DiCaprio is currently linked to Gigi Hadid.')), (Step(value='Find her current age.'), StepResponse(response='28 years'))]

Current objective: None

Action:
```{
  "action": "Final Answer",
  "action_input": "Gigi Hadid's current age is 28 years."
}```



Finished chain.
*****

Step: Find her current age.

Response: Gigi Hadid's current age is 28 years.

Entering new AgentExecutor chain...
Action:
```{
  "action": "Calculator",
  "action_input": "28 ** 0.43"
}```


Entering new LLMMathChain chain...
28 ** 0.43
```text28 ** 0.43```
...numexpr.evaluate("28 ** 0.43")...

Answer: 4.1906168361987195
Finished chain.

Observation: Answer: 4.1906168361987195
Thought:The next step is to provide the answer to the user's question.

Action:
```{
  "action": "Final Answer",
  "action_input": "Gigi Hadid's current age raised to the 0.43 power is approximately 4.19."
}```



Finished chain.
*****

Step: Raise her current age to the 0.43 power using a calculator or programming language.

Response: Gigi Hadid's current age raised to the 0.43 power is approximately 4.19.

Entering new AgentExecutor chain...
Action:
```{
  "action": "Final Answer",
  "action_input": "The result is approximately 4.19."
}```


Finished chain.
*****

Step: Output the result.

Response: The result is approximately 4.19.

Entering new AgentExecutor chain...
Action:
```{
  "action": "Final Answer",
  "action_input": "Gigi Hadid's current age raised to the 0.43 power is approximately 4.19."
}```


Finished chain.
*****

Step: Given the above steps taken, respond to the user's original question.



Response: Gigi Hadid's current age raised to the 0.43 power is approximately 4.19.
Finished chain.

输出:

"Gigi Hadid's current age raised to the 0.43 power is approximately 4.19."

参考文献:
[1] LangChain官方网站:https://www.langchain.com/
[2] LangChain 🦜️🔗 中文网,跟着LangChain一起学LLM/GPT开发:https://www.langchain.com.cn/
[3] LangChain中文网 - LangChain 是一个用于开发由语言模型驱动的应用程序的框架:http://www.cnlangchain.com/

### 关于 LangChain入门教程 #### 了解 LangChain 基本概念和核心功能 LangChain 是一种用于构建语言模型应用的强大框架,旨在简化开发者创建复杂自然语言处理系统的流程。该框架不仅提供了多种预训练的大规模语言模型(LLMs),还支持定制化的提示模板(Prompt Templates)、代理Agents)、记忆(Memory)、索引(Indexes)以及链条(Chains)。这些特性使得开发人员能够更灵活地设计对话系统和其他基于文本的应用程序[^1]。 #### 组件详解 - **Models**: 支持不同种类的语言模型,如 ChatGPT、ChatGLM 和 T5 等。 - **Prompts**: 提供管理和自定义提示的功能,有助于优化 LLMs 的交互效果。 - **Agents**: 负责决策并执行特定任务,允许大型语言模型访问外部工具和服务。 - **Memory**: 记录会话历史记录,保持上下文连贯性。 - **Indexes**: 对文档进行结构化处理,便于后续查询操作。 - **Chains**: 定义了一系列组件之间的调用顺序,形成完整的业务逻辑流[^4]。 #### 实际应用场景展示——简单问答系统 为了更好地理解如何利用 LangChain 创建实际项目,在此提供了一个简易版的问答系统实例: ```python from langchain import LangChain, PromptTemplate, LLMMemory, SimpleIndexCreator, AgentExecutor import json # 加载配置文件中的参数设置 with open('config.json', 'r') as f: config = json.load(f) # 初始化内存对象来存储聊天记录 memory = LLMMemory() # 设置索引来加速检索过程 index_creator = SimpleIndexCreator() indexes = index_creator.create_indexes(config['documents']) # 配置提示模板以指导模型生成合适的回复 prompt_template = PromptTemplate( input_variables=["history", "input"], template="Based on the following conversation history:\n{history}\nThe user asks: {input}" ) # 构造Agent执行器来进行具体的操作 agent_executor = AgentExecutor.from_llm_and_tools(llm=config['llm'], tools=[...], memory=memory) while True: question = input("Ask a question:") # 获取当前对话的历史作为背景信息的一部分 context = agent_executor.memory.get_context(inputs={"question": question}) # 将问题传递给Agent执行器获取答案 response = agent_executor.run(prompt=prompt_template.format(history=context["history"], input=question)) print(response) ``` 这段代码片段展示了如何结合多个 LangChain 组件建立一个可以持续互动的基础架构,并通过循环读取用户的输入来维持整个交流的过程[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

von Neumann

您的赞赏是我创作最大的动力~

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

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

打赏作者

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

抵扣说明:

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

余额充值