0

0

浪链部分构建强大的链和代理

王林

王林

发布时间:2024-07-31 18:01:03

|

1068人浏览过

|

来源于dev.to

转载

浪链部分构建强大的链和代理

在langchain中构建强大的链和代理

在这篇综合指南中,我们将深入探讨langchain的世界,重点关注构建强大的链和代理。我们将涵盖从理解链的基础知识到将其与大型语言模型(llm)相结合以及引入用于自主决策的复杂代理的所有内容。

1. 理解链

1.1 浪链中什么是链?

langchain 中的链是按特定顺序处理数据的操作或任务序列。它们允许模块化和可重用的工作流程,从而更轻松地处理复杂的数据处理和语言任务。链是创建复杂的人工智能驱动系统的构建块。

1.2 链条的类型

langchain 提供多种类型的链,每种类型适合不同的场景:

  1. 顺序链:这些链以线性顺序处理数据,其中一个步骤的输出作为下一步的输入。它们非常适合简单、分步的流程。

  2. 映射/归约链:这些链涉及将函数映射到一组数据,然后将结果归约为单个输出。它们非常适合并行处理大型数据集。

  3. 路由器链:这些链根据特定条件将输入直接输入到不同的子链,从而允许更复杂的分支工作流程。

1.3 创建自定义链

创建自定义链涉及定义将成为链一部分的特定操作或功能。这是自定义顺序链的示例:

from langchain.chains import llmchain
from langchain.llms import openai
from langchain.prompts import prompttemplate

class customchain:
    def __init__(self, llm):
        self.llm = llm
        self.steps = []

    def add_step(self, prompt_template):
        prompt = prompttemplate(template=prompt_template, input_variables=["input"])
        chain = llmchain(llm=self.llm, prompt=prompt)
        self.steps.append(chain)

    def execute(self, input_text):
        for step in self.steps:
            input_text = step.run(input_text)
        return input_text

# initialize the chain
llm = openai(temperature=0.7)
chain = customchain(llm)

# add steps to the chain
chain.add_step("summarize the following text in one sentence: {input}")
chain.add_step("translate the following english text to french: {input}")

# execute the chain
result = chain.execute("langchain is a powerful framework for building ai applications.")
print(result)

此示例创建一个自定义链,首先汇总输入文本,然后将其翻译为法语。

2. 连锁学与法学硕士的结合

2.1 将链与提示和 llm 集成

chains 可以与提示和 llm 无缝集成,以创建更强大、更灵活的系统。这是一个例子:

from langchain import prompttemplate, llmchain
from langchain.llms import openai
from langchain.chains import simplesequentialchain

llm = openai(temperature=0.7)

# first chain: generate a topic
first_prompt = prompttemplate(
    input_variables=["subject"],
    template="generate a random {subject} topic:"
)
first_chain = llmchain(llm=llm, prompt=first_prompt)

# second chain: write a paragraph about the topic
second_prompt = prompttemplate(
    input_variables=["topic"],
    template="write a short paragraph about {topic}:"
)
second_chain = llmchain(llm=llm, prompt=second_prompt)

# combine the chains
overall_chain = simplesequentialchain(chains=[first_chain, second_chain], verbose=true)

# run the chain
result = overall_chain.run("science")
print(result)

这个示例创建了一个链,该链生成一个随机科学主题,然后写一个关于它的段落。

Imagine By Magic Studio
Imagine By Magic Studio

AI图片生成器,用文字制作图片

下载

2.2 调试和优化链-llm 交互

要调试和优化链-llm 交互,您可以使用详细参数和自定义回调:

from langchain.callbacks import stdoutcallbackhandler
from langchain.chains import llmchain
from langchain.llms import openai
from langchain.prompts import prompttemplate

class customhandler(stdoutcallbackhandler):
    def on_llm_start(self, serialized, prompts, **kwargs):
        print(f"llm started with prompt: {prompts[0]}")

    def on_llm_end(self, response, **kwargs):
        print(f"llm finished with response: {response.generations[0][0].text}")

llm = openai(temperature=0.7, callbacks=[customhandler()])
template = "tell me a {adjective} joke about {subject}."
prompt = prompttemplate(input_variables=["adjective", "subject"], template=template)
chain = llmchain(llm=llm, prompt=prompt, verbose=true)

result = chain.run(adjective="funny", subject="programming")
print(result)

此示例使用自定义回调处理程序来提供有关 llm 输入和输出的详细信息。

3. 代理介绍

3.1 浪链中的代理是什么?

浪链中的代理是自治实体,可以使用工具并做出决策来完成任务。他们将法学硕士与外部工具相结合来解决复杂的问题,从而实现更具动态性和适应性的人工智能系统。

3.2 内置代理及其功能

langchain 提供了多种内置代理,例如 zero-shot-react-description 代理:

from langchain.agents import load_tools, initialize_agent, agenttype
from langchain.llms import openai

llm = openai(temperature=0)
tools = load_tools(["wikipedia", "llm-math"], llm=llm)

agent = initialize_agent(
    tools, 
    llm, 
    agent=agenttype.zero_shot_react_description,
    verbose=true
)

result = agent.run("what is the square root of the year plato was born?")
print(result)

此示例创建一个可以使用维基百科并执行数学计算来回答复杂问题的代理。

3.3 创建自定义代理

您可以通过定义自己的工具和代理类来创建自定义代理。这允许针对特定任务或领域定制高度专业化的代理。

这是自定义代理的示例:

from langchain.agents import Tool, AgentExecutor, LLMSingleActionAgent
from langchain.prompts import StringPromptTemplate
from langchain import OpenAI, SerpAPIWrapper, LLMChain
from typing import List, Union
from langchain.schema import AgentAction, AgentFinish
import re

# Define custom tools
search = SerpAPIWrapper()
tools = [
    Tool(
        name="Search",
        func=search.run,
        description="Useful for answering questions about current events"
    )
]

# Define a custom prompt template
template = """Answer the following questions as best you can:

{input}

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: {input}
Thought: To answer this question, I need to search for current information.
{agent_scratchpad}"""

class CustomPromptTemplate(StringPromptTemplate):
    template: str
    tools: List[Tool]

    def format(self, **kwargs) -> str:
        intermediate_steps = kwargs.pop("intermediate_steps")
        thoughts = ""
        for action, observation in intermediate_steps:
            thoughts += action.log
            thoughts += f"\nObservation: {observation}\nThought: "
        kwargs["agent_scratchpad"] = thoughts
        kwargs["tool_names"] = ", ".join([tool.name for tool in self.tools])
        return self.template.format(**kwargs)

prompt = CustomPromptTemplate(
    template=template,
    tools=tools,
    input_variables=["input", "intermediate_steps"]
)

# Define a custom output parser
class CustomOutputParser:
    def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]:
        if "Final Answer:" in llm_output:
            return AgentFinish(
                return_values={"output": llm_output.split("Final Answer:")[-1].strip()},
                log=llm_output,
            )

        action_match = re.search(r"Action: (\w+)", llm_output, re.DOTALL)
        action_input_match = re.search(r"Action Input: (.*)", llm_output, re.DOTALL)

        if not action_match or not action_input_match:
            raise ValueError(f"Could not parse LLM output: `{llm_output}`")

        action = action_match.group(1).strip()
        action_input = action_input_match.group(1).strip(" ").strip('"')

        return AgentAction(tool=action, tool_input=action_input, log=llm_output)

# Create the custom output parser
output_parser = CustomOutputParser()

# Define the LLM chain
llm = OpenAI(temperature=0)
llm_chain = LLMChain(llm=llm, prompt=prompt)

# Define the custom agent
agent = LLMSingleActionAgent(
    llm_chain=llm_chain,
    output_parser=output_parser,
    stop=["\nObservation:"],
    allowed_tools=[tool.name for tool in tools]
)

# Create an agent executor
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, , verbose=True)
# Run the agent
result = agent_executor.run(“What’s the latest news about AI?”)

print(result)

结论

langchain 的链和代理为构建复杂的人工智能驱动系统提供了强大的功能。当与大型语言模型 (llm) 集成时,它们可以创建适应性强的智能应用程序,旨在解决各种任务。当您在 langchain 之旅中不断进步时,请随意尝试不同的链类型、代理设置和自定义模块,以充分利用该框架的潜力。

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

76

2026.03.11

Go高并发任务调度与Goroutine池化实践
Go高并发任务调度与Goroutine池化实践

本专题围绕 Go 语言在高并发任务处理场景中的实践展开,系统讲解 Goroutine 调度模型、Channel 通信机制以及并发控制策略。内容包括任务队列设计、Goroutine 池化管理、资源限制控制以及并发任务的性能优化方法。通过实际案例演示,帮助开发者构建稳定高效的 Go 并发任务处理系统,提高系统在高负载环境下的处理能力与稳定性。

38

2026.03.10

Kotlin Android模块化架构与组件化开发实践
Kotlin Android模块化架构与组件化开发实践

本专题围绕 Kotlin 在 Android 应用开发中的架构实践展开,重点讲解模块化设计与组件化开发的实现思路。内容包括项目模块拆分策略、公共组件封装、依赖管理优化、路由通信机制以及大型项目的工程化管理方法。通过真实项目案例分析,帮助开发者构建结构清晰、易扩展且维护成本低的 Android 应用架构体系,提升团队协作效率与项目迭代速度。

83

2026.03.09

JavaScript浏览器渲染机制与前端性能优化实践
JavaScript浏览器渲染机制与前端性能优化实践

本专题围绕 JavaScript 在浏览器中的执行与渲染机制展开,系统讲解 DOM 构建、CSSOM 解析、重排与重绘原理,以及关键渲染路径优化方法。内容涵盖事件循环机制、异步任务调度、资源加载优化、代码拆分与懒加载等性能优化策略。通过真实前端项目案例,帮助开发者理解浏览器底层工作原理,并掌握提升网页加载速度与交互体验的实用技巧。

97

2026.03.06

Rust内存安全机制与所有权模型深度实践
Rust内存安全机制与所有权模型深度实践

本专题围绕 Rust 语言核心特性展开,深入讲解所有权机制、借用规则、生命周期管理以及智能指针等关键概念。通过系统级开发案例,分析内存安全保障原理与零成本抽象优势,并结合并发场景讲解 Send 与 Sync 特性实现机制。帮助开发者真正理解 Rust 的设计哲学,掌握在高性能与安全性并重场景中的工程实践能力。

223

2026.03.05

PHP高性能API设计与Laravel服务架构实践
PHP高性能API设计与Laravel服务架构实践

本专题围绕 PHP 在现代 Web 后端开发中的高性能实践展开,重点讲解基于 Laravel 框架构建可扩展 API 服务的核心方法。内容涵盖路由与中间件机制、服务容器与依赖注入、接口版本管理、缓存策略设计以及队列异步处理方案。同时结合高并发场景,深入分析性能瓶颈定位与优化思路,帮助开发者构建稳定、高效、易维护的 PHP 后端服务体系。

458

2026.03.04

AI安装教程大全
AI安装教程大全

2026最全AI工具安装教程专题:包含各版本AI绘图、AI视频、智能办公软件的本地化部署手册。全篇零基础友好,附带最新模型下载地址、一键安装脚本及常见报错修复方案。每日更新,收藏这一篇就够了,让AI安装不再报错!

169

2026.03.04

Swift iOS架构设计与MVVM模式实战
Swift iOS架构设计与MVVM模式实战

本专题聚焦 Swift 在 iOS 应用架构设计中的实践,系统讲解 MVVM 模式的核心思想、数据绑定机制、模块拆分策略以及组件化开发方法。内容涵盖网络层封装、状态管理、依赖注入与性能优化技巧。通过完整项目案例,帮助开发者构建结构清晰、可维护性强的 iOS 应用架构体系。

246

2026.03.03

C++高性能网络编程与Reactor模型实践
C++高性能网络编程与Reactor模型实践

本专题围绕 C++ 在高性能网络服务开发中的应用展开,深入讲解 Socket 编程、多路复用机制、Reactor 模型设计原理以及线程池协作策略。内容涵盖 epoll 实现机制、内存管理优化、连接管理策略与高并发场景下的性能调优方法。通过构建高并发网络服务器实战案例,帮助开发者掌握 C++ 在底层系统与网络通信领域的核心技术。

34

2026.03.03

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号