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

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

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

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

1. 理解链

1.1 浪链中什么是链?

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

1.2 链条的类型

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

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

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

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

1.3 创建自定义链

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

from langchain.chains import llmchainfrom langchain.llms import openaifrom langchain.prompts import prompttemplateclass 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 chainllm = openai(temperature=0.7)chain = customchain(llm)# add steps to the chainchain.add_step("summarize the following text in one sentence: {input}")chain.add_step("translate the following english text to french: {input}")# execute the chainresult = chain.execute("langchain is a powerful framework for building ai applications.")print(result)

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

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

2.1 将链与提示和 llm 集成

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

from langchain import prompttemplate, llmchainfrom langchain.llms import openaifrom langchain.chains import simplesequentialchainllm = openai(temperature=0.7)# first chain: generate a topicfirst_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 topicsecond_prompt = prompttemplate(    input_variables=["topic"],    template="write a short paragraph about {topic}:")second_chain = llmchain(llm=llm, prompt=second_prompt)# combine the chainsoverall_chain = simplesequentialchain(chains=[first_chain, second_chain], verbose=true)# run the chainresult = overall_chain.run("science")print(result)

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

2.2 调试和优化链-llm 交互

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

from langchain.callbacks import stdoutcallbackhandlerfrom langchain.chains import llmchainfrom langchain.llms import openaifrom langchain.prompts import prompttemplateclass 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, agenttypefrom langchain.llms import openaillm = 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, LLMSingleActionAgentfrom langchain.prompts import StringPromptTemplatefrom langchain import OpenAI, SerpAPIWrapper, LLMChainfrom typing import List, Unionfrom langchain.schema import AgentAction, AgentFinishimport re# Define custom toolssearch = SerpAPIWrapper()tools = [    Tool(        name="Search",        func=search.run,        description="Useful for answering questions about current events"    )]# Define a custom prompt templatetemplate = """Answer the following questions as best you can:{input}Use the following format:Question: the input question you must answerThought: you should always think about what to doAction: the action to take, should be one of [{tool_names}]Action Input: the input to the actionObservation: the result of the action... (this Thought/Action/Action Input/Observation can repeat N times)Thought: I now know the final answerFinal Answer: the final answer to the original input questionBegin!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 parserclass 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 parseroutput_parser = CustomOutputParser()# Define the LLM chainllm = OpenAI(temperature=0)llm_chain = LLMChain(llm=llm, prompt=prompt)# Define the custom agentagent = LLMSingleActionAgent(    llm_chain=llm_chain,    output_parser=output_parser,    stop=["nObservation:"],    allowed_tools=[tool.name for tool in tools])# Create an agent executoragent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, , verbose=True)# Run the agentresult = agent_executor.run(“What’s the latest news about AI?”)print(result)

结论

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

以上就是浪链部分构建强大的链和代理的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1348446.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月13日 12:02:54
下一篇 2025年12月13日 12:02:59

相关推荐

  • 性能追求第二部分:Perl 与 Python

    运行了一个玩具性能示例后,我们现在将稍微偏离主题并将性能与 进行对比一些 python 实现。首先让我们设置计算阶段,并提供命令行python 脚本的功能。 import argparseimport timeimport mathimport numpy as npimport osfrom nu…

    好文分享 2025年12月13日
    000
  • python如何计算销售额

    通过使用 Python 编程语言,您可以自动化电子商务销售额计算,获取准确的数据。导入库:import pandas as pd加载销售数据到 DataFrame 中。计算总销售额:使用 df.sum() 方法计算 DataFrame 中所有销售值的总和。按产品类别计算销售额:使用 df.group…

    2025年12月13日
    000
  • python如何定义一个函数?

    Python 函数的定义方法有三种:使用 def 关键字和函数参数定义。使用匿名 lambda 表达式在一行中定义。使用 functools.partial 函数预绑定参数。 如何定义一个 Python 函数 在 Python 中定义函数有多种方法。最常见的方法是使用 def 关键字,后跟函数名称和…

    2025年12月13日
    000
  • python如何获取当前日期

    在 Python 中获取当前日期有两种方法:使用 datetime.date.today() 直接获取当前日期(不含时间部分);使用 datetime.datetime.now().date() 获取当前日期和时间,然后提取日期部分。 如何用 Python 获取当前日期 获取当前日期的两种方法: 1…

    2025年12月13日
    000
  • python如何建立新文件夹

    对于使用 Python 创建新文件夹,步骤如下:导入 os 模块。使用 os.makedirs() 函数传递文件夹路径。处理错误,使用 try 和 except 语句捕获 OSError 异常。检查文件夹是否存在,使用 os.path.exists() 函数避免 FileExistsError 异常…

    2025年12月13日
    000
  • python如何换行继续编写

    Python 换行有三种方法:1)使用反斜杠();2)使用括号(());3)使用分号(;)。单行代码用反斜杠最简便,多行代码用括号更清晰,分号不推荐用于换行。 如何使用 Python 换行继续编写 在编写 Python 代码时,有时需要暂时断开一行,并在下一行继续编写。这通常是为了增强代码的可读性或…

    2025年12月13日
    000
  • python如何换行写代码

    Python 中可使用以下三种方法换行写代码:1. 在行末使用反斜杠 ();2. 使用括号 ();3. 使用分号 (;)。三重引号 (“””或”’) 可定义多行字符串。 Python 中换行写代码 在 Python 中,使用反斜杠()字符可…

    2025年12月13日
    000
  • python如何换行输入代码

    Python中换行输入代码的方法有:使用’n’符号使用多行字符串使用re.compile()使用第三方库(如line-by-line) Python中换行输入代码的方法 在Python中,可以使用input()函数从用户获取输入。默认情况下,input()函数会将所有输入视为…

    2025年12月13日
    000
  • python如何下载pip库

    使用 Pip 库可通过 pip install 命令下载 Python 库。额外选项包括:升级包(–U)、安装特定版本(== 标识符)、从特定源安装(–index-url)、离线安装(-r 标识符)和验证安装(pip freeze)。 如何使用 Python 下载 Pip 库…

    2025年12月13日
    000
  • python如何编写函数

    函数是可重复使用的代码块,可执行特定任务,需要输入,执行处理,并返回输出。编写 Python 函数的步骤包括:1. 定义函数;2. 添加参数;3. 编写函数体;4. 返回值;5. 调用函数。 如何编写 Python 函数 什么是函数? 函数是一组可重复使用的代码块,用于执行特定的任务。它们可以接受输…

    2025年12月13日
    000
  • 写python如何另起一行

    在 Python 中可使用不同的方法另起一行,包括:使用换行符(适用于不同的操作系统)使用 print() 方法,指定 “n” 作为结尾使用 write() 方法,写入 “n”使用特殊字符序列 “x0a”,等价于换行符 如何用 …

    2025年12月13日
    000
  • if __name__ =&#__main__&# 在 Python 中做什么?

    你可能在 python 脚本中经常看到这行代码 if __name__==”__main__”: ,但不知道它的实际用途是什么。别担心,因为在这个简短的博客中我们将讨论这个 当您直接运行程序或脚本时,python 会自动将“main”分配给特殊的name变量。这样做基本上是为…

    2025年12月13日
    000
  • 高知 D Soft Technologies 的 Python 学生取得的令人瞩目的成就

    在高知的 D Soft Technologies,我们的 Python 课程一直是周围许多最优秀学生的起点。这些学生每天都在挑战 Python 所能完成的极限。他们在这里期间接触过各种项目,从开发网络应用程序到构建机器学习模型。这些学生所做的很多工作都解决了实际问题,不仅展示了他们在技术上学到的知识…

    2025年12月13日
    000
  • python需要插件才能运行吗

    否,Python 无需插件即可运行。它附带了一个标准库,提供了各种功能,而无需安装任何额外的插件。但是,在某些情况下您可能需要插件,例如:① 安装特定库或模块 ② 增强 IDE 集成 ③ 集成第三方软件。 Python 需要插件才能运行吗? 回答:否,Python 无需插件即可运行。 详细解答: P…

    2025年12月13日
    000
  • python如何新建一个文件夹

    Python 中创建文件夹的方法:导入 os 模块。指定文件夹路径。使用 os.makedirs() 函数创建文件夹。处理潜在的异常。验证文件夹是否已创建。 如何使用 Python 创建文件夹 在 Python 中,可以使用 os 模块来创建文件夹。以下步骤演示如何创建文件夹: 导入 os 模块 i…

    2025年12月13日
    000
  • python如何安装pip工具

    Pip 是 Python 包管理器,用于安装、管理和卸载 Python 包。安装 Pip 的步骤包括:检查现有 pip 版本。如果未安装,下载 get-pip.py 脚本并使用 Python 运行它。验证 pip 安装。 如何安装 Python 的 Pip 工具 Pip 是 Python 包管理器,…

    2025年12月13日
    000
  • 使用 React 语音用户界面增强用户体验

    简介 数字时代,提升用户体验是关键。凭借人工智能语音助手和语音用户界面的强大功能,sista ai 正在引领这场革命。他们的技术无缝集成在任何应用程序或网站中,改变了交互方式,使它们更具吸引力和可访问性。 重新构想客户支持 客户支持至关重要,Sista AI 的人工智能语音助手彻底改变了这一流程。支…

    2025年12月13日
    000
  • Intonight Mod APK 高级版已解锁) 下载适用于 Android 的

    Intonight Mod APK 是一款娱乐应用程序,旨在通过免费提供各种高级功能来增强用户体验。该应用程序允许用户以最佳质量享受各种多媒体内容,例如视频和音乐,并且没有广告中断。通过 Mod APK 版本,用户可以完全访问通常需要付费订阅的高级功能。 免费下载:Intonight Mod APK…

    2025年12月13日
    000
  • 使用 Python3 构建 Web 应用程序

    要使用 python 3 构建 web 应用程序,您可以使用 flask 框架。 flask 轻量、灵活,非常适合快速创建 web 应用程序。以下是开始的步骤: 安装 flask: 首先,激活你的python环境并使用pip安装flask: source env/bin/activate # act…

    2025年12月13日
    000
  • FP和BF有什么区别这里给你很好的解释

    浮点表示: fp16(半精度):在 fp16 中,浮点数使用 16 位表示。它由 1 个符号位、5 位指数和 10 位分数(尾数)组成。这种格式为表示其范围内的小数值提供了更高的精度。 bf16 (bfloat16):bf16 也使用 16 位,但分布不同。它有 1 个符号位、8 位指数、7 位尾数…

    2025年12月13日
    000

发表回复

登录后才能评论
关注微信