当前位置:首页 > 文章列表 > 文章 > python教程 > 浪链部分构建强大的链和代理

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

来源:dev.to 2024-07-31 10:13:01 0浏览 收藏

本篇文章给大家分享《浪链部分构建强大的链和代理》,覆盖了文章的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

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

在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)

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

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 之旅中不断进步时,请随意尝试不同的链类型、代理设置和自定义模块,以充分利用该框架的潜力。

今天关于《浪链部分构建强大的链和代理》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

版本声明
本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
golang框架中间件在金融系统中的实践golang框架中间件在金融系统中的实践
上一篇
golang框架中间件在金融系统中的实践
鸭子类型遇到类型提示:在 Python 中使用协议
下一篇
鸭子类型遇到类型提示:在 Python 中使用协议
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    508次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    497次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • 毕业宝AIGC检测:AI生成内容检测工具,助力学术诚信
    毕业宝AIGC检测
    毕业宝AIGC检测是“毕业宝”平台的AI生成内容检测工具,专为学术场景设计,帮助用户初步判断文本的原创性和AI参与度。通过与知网、维普数据库联动,提供全面检测结果,适用于学生、研究者、教育工作者及内容创作者。
    23次使用
  • AI Make Song:零门槛AI音乐创作平台,助你轻松制作个性化音乐
    AI Make Song
    AI Make Song是一款革命性的AI音乐生成平台,提供文本和歌词转音乐的双模式输入,支持多语言及商业友好版权体系。无论你是音乐爱好者、内容创作者还是广告从业者,都能在这里实现“用文字创造音乐”的梦想。平台已生成超百万首原创音乐,覆盖全球20个国家,用户满意度高达95%。
    33次使用
  • SongGenerator.io:零门槛AI音乐生成器,快速创作高质量音乐
    SongGenerator
    探索SongGenerator.io,零门槛、全免费的AI音乐生成器。无需注册,通过简单文本输入即可生成多风格音乐,适用于内容创作者、音乐爱好者和教育工作者。日均生成量超10万次,全球50国家用户信赖。
    30次使用
  •  BeArt AI换脸:免费在线工具,轻松实现照片、视频、GIF换脸
    BeArt AI换脸
    探索BeArt AI换脸工具,免费在线使用,无需下载软件,即可对照片、视频和GIF进行高质量换脸。体验快速、流畅、无水印的换脸效果,适用于娱乐创作、影视制作、广告营销等多种场景。
    33次使用
  • SEO标题协启动:AI驱动的智能对话与内容生成平台 - 提升创作效率
    协启动
    SEO摘要协启动(XieQiDong Chatbot)是由深圳协启动传媒有限公司运营的AI智能服务平台,提供多模型支持的对话服务、文档处理和图像生成工具,旨在提升用户内容创作与信息处理效率。平台支持订阅制付费,适合个人及企业用户,满足日常聊天、文案生成、学习辅助等需求。
    36次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码