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)

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

MVM mall 网上购物系统
MVM mall 网上购物系统

采用 php+mysql 数据库方式运行的强大网上商店系统,执行效率高速度快,支持多语言,模板和代码分离,轻松创建属于自己的个性化用户界面 v3.5更新: 1).进一步静态化了活动商品. 2).提供了一些重要UFT-8转换文件 3).修复了除了网银在线支付其它支付显示错误的问题. 4).修改了LOGO广告管理,增加LOGO链接后主页LOGO路径错误的问题 5).修改了公告无法发布的问题,可能是打压

下载

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

相关专题

更多
人工智能在生活中的应用
人工智能在生活中的应用

人工智能在生活中的应用有语音助手、无人驾驶、金融服务、医疗诊断、智能家居、智能推荐、自然语言处理和游戏设计等。本专题为大家提供人工智能相关的文章、下载、课程内容,供大家免费下载体验。

405

2023.08.17

人工智能的基本概念是什么
人工智能的基本概念是什么

人工智能的英文缩写为AI,是研究、开发用于模拟、延伸和扩展人的智能的理论、方法、技术及应用系统的一门新的技术科学;该领域的研究包括机器人、语言识别、图像识别、自然语言处理和专家系统等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

291

2024.01.09

人工智能不能取代人类的原因是什么
人工智能不能取代人类的原因是什么

人工智能不能取代人类的原因包括情感与意识、创造力与想象力、伦理与道德、社会交往与沟通能力、灵活性与适应性、持续学习和自我提升等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

622

2024.09.10

Python 人工智能
Python 人工智能

本专题聚焦 Python 在人工智能与机器学习领域的核心应用,系统讲解数据预处理、特征工程、监督与无监督学习、模型训练与评估、超参数调优等关键知识。通过实战案例(如房价预测、图像分类、文本情感分析),帮助学习者全面掌握 Python 机器学习模型的构建与实战能力。

32

2025.10.21

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

138

2025.12.31

php网站源码教程大全
php网站源码教程大全

本专题整合了php网站源码相关教程,阅读专题下面的文章了解更多详细内容。

80

2025.12.31

视频文件格式
视频文件格式

本专题整合了视频文件格式相关内容,阅读专题下面的文章了解更多详细内容。

82

2025.12.31

不受国内限制的浏览器大全
不受国内限制的浏览器大全

想找真正自由、无限制的上网体验?本合集精选2025年最开放、隐私强、访问无阻的浏览器App,涵盖Tor、Brave、Via、X浏览器、Mullvad等高自由度工具。支持自定义搜索引擎、广告拦截、隐身模式及全球网站无障碍访问,部分更具备防追踪、去谷歌化、双内核切换等高级功能。无论日常浏览、隐私保护还是突破地域限制,总有一款适合你!

61

2025.12.31

出现404解决方法大全
出现404解决方法大全

本专题整合了404错误解决方法大全,阅读专题下面的文章了解更多详细内容。

458

2025.12.31

热门下载

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

精品课程

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

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