当前位置: 代码网 > it编程>游戏开发>游戏引擎 > LangChain(八)构建多Agent的AI系统-实战!

LangChain(八)构建多Agent的AI系统-实战!

2024年08月03日 游戏引擎 我要评论
好久没有更新LangChian系列的文章了,最近一直在给我们的项目进行集成工作。代码集成、系统优化、多线程操作等等……交给一个算法工程师真的好吗……不得已恶补了一下这方面的知识,写了很多有关于系统集成、代码规范、多线程编程方面的文章。时至今日终于告一段落……针对项目中实际编写的有关多链路由多Agent的模块,总结后也有了一些心得体悟,遂有此文。本篇对于多链路由、工具调用、大模型构建方式进行了复习,并给出实战代码!最合适的函数,不是官网现成的函数,而是你自己搭建的啊。

系列文章目录

langchain(二)基础问答大模型,纯新手向-csdn博客

langchain(三)基础问答大模型,从llmchain开始了解chain!纯新手向-csdn博客

langchain(四)工具调用的底层原理!给大模型按上双手吧!(新手向)-csdn博客

langchain(五)工具调用的底层原理进阶!依旧纯新手向~-csdn博客

langchain(六)llmroutechain的基本原理和构建方式-新手向-csdn博客

langchain(七)让大模型拥有记忆!新手向_chatprompttemplate是什么-csdn博客


前言

好久没有更新langchian系列的文章了,最近一直在给我们的项目进行集成工作。代码集成、系统优化、多线程操作等等……交给一个算法工程师真的好吗……不得已恶补了一下这方面的知识,写了很多有关于系统集成、代码规范、多线程编程方面的文章。时至今日终于告一段落……

针对项目中实际编写的有关多链路由多agent的模块,总结后也有了一些心得体悟,遂有此文。

预备知识

在阅读本文之前,需要有一些预备知识,如下:

  • 基础问答大模型的开发(基础的聊天机器人构建能力) 

langchain(二)基础问答大模型,纯新手向-csdn博客

  • 大模型工具调用的方法(大模型如何调用函数工具的能力)

langchain(四)工具调用的底层原理!给大模型按上双手吧!(新手向)-csdn博客

langchain(五)工具调用的底层原理进阶!依旧纯新手向~-csdn博客

  • 路由链的构建原理(多agent的选择路由模块的构建能力)

 langchain(六)llmroutechain的基本原理和构建方式-新手向-csdn博客

实战详解!

项目背景与需求

本项目是旨在实现某个垂直领域专业操作的同时满足水平领域横展聊天问答的功能……

用人话说就是,既要大模型有工具调用能力,还要大模型和你聊天……

思考过程

显然,这需要三个agent来完成任务,

  • 一个agent用于工具调用,
  • 一个agent用于聊天。
  • 以及最后一个agent用以把问题具体路由到上面的哪一个agent

step1:大模型的构建

当然,第一步,也是最基础的一部,就是先构建llm聊天大模型,此处没啥好说的。亮出代码即可

from langchain_community.llms import qianfanllmendpoint
import os

# 设定百度千帆大模型的ak和sk
os.environ["qianfan_ak"] = "your_ak"
os.environ["qianfan_sk"] = "your_sk"

# 创建千帆llm模型
llm = qianfanllmendpoint()

step2:工具函数的编写

此处,基于我实际的项目经验,所有相关的调用函数,最好统一构建为一个python文件。

此处我构建了一个新的python文件:“ai_tools.py”。由于项目的保密性,我在此虚构几个函数。

from langchain.tools.render import render_text_description
from langchain_core.tools import tool

'''
step1: 构建工具调用的工具函数
'''

@tool
def kick_your_ass(power: int = 1):
    '''
    踢用户的屁股

    参数:
        power->int:用以描述踢的力气
    '''
    # some funtion……
    return true
        
@tool
def kiss_your_ass(power: int = 1):
    '''
    亲用户的屁股

    参数:
        power->int:用以描述亲的力气
    '''
    # some funtion……
    return true

@tool
def kick_your_face(power: int = 1):
    '''
    踢用户的脸

    参数:
        power->int:用以描述踢的力气
    '''
    # some funtion……
    return true

@tool
def kiss_your_face(power: int = 1):
    '''
    亲用户的脸

    参数:
        power->int:用以描述亲的力气
    '''
    # some funtion……
    return true

'''
step2:构建工具集合和工具描述
'''
tools =[
    kick_your_ass,
    kiss_your_ass,
    kiss_your_face, 
    kick_your_face
]

tool_map = {tool.name: tool for tool in tools}

# 构建工具条件和调用描述
rendered_tools = render_text_description(tools)


'''
step3:构建工具调用路由函数
'''
def tools_call(model_output):
    chosen_tool = tool_map[model_output["name"]]
    return chosen_tool.invoke(model_output["arguments"])
   

注意:所有有关于工具相关的函数都应该写在此处,保持良好的代码习惯……

step3:工具调用agent和聊天agent的撰写!

链的构建!

chat_chain = prompttemplate.from_template(
    """你是一个聊天陪聊机器人,你的名字叫:小黑。
你的编写者是***,你需要使用中文并以谦卑尊敬的态度对用户的输入进行回复。
always answer questions starting with "阿巴阿巴". \
respond to the following question:

question: {question}
answer:"""
) | llm

tools_call_chain = (
    chatprompttemplate.from_messages(
        [
            ("system", f"""you are an assistant that has access to the following set of tools. here are the names and descriptions for each tool:

{ai_tools.rendered_tools}

given the user input, return the name and input of the tool to use. 
用户若没有给你具体的参数,则使用默认参数。
return your response as a json blob with 'name' and 'arguments' keys."""), 
            ("user", "{question}")
        ]
    ) 
    | llm
    | jsonoutputparser()
    | ai_tools.tools_call
)

各位可以看到,两个chain中的系统人设prompt我使用了两种构建方式,一个是使用prompttemplate,一个是使用chatprompttemplate。这里没什么特别的理由,仅仅是复习一下过去的知识。但是对我个人而言,我更喜欢chatprompttemplate,更正规,可操作性更大。

注意:第二个tools_call_chain,由于我们返回的是一个json的str格式文本,所以需要jsonoutputparser函数对于返回值进行处理成真正的json格式数据,最后再调用tools_call函数。该函数在上面的工具调用文件中有。

step4:路由agent的构建

路由agent最好不要使用langchain官网给的现成链,非常麻烦不说,可扩展性也很差,也很有些莫名其妙的操作方式。

chain = (
    prompttemplate.from_template("""
根据下面提供的问题输入,将其分类为:`test`或`chat`.
当输入的文本有关于车载仪表符号灯测试的时候,分类为:test
否则,分类为:chat

return your response as a json blob with 'classification' keys.

<question>
{question}
</question>
"""
    )
    | llm
    | jsonoutputparser()
)

def route(info):
    print("info = ", info)
    try:
        if info["topic"]["classification"] == "chat":
            print("chat")
            return chat_chain
        elif info["topic"]["classification"] == "test":
            print("test")
            return tools_call_chain
        else:
            return chat_chain
    except exception as e:
        print("e = ", e)
        return chat_chain
        
from langchain_core.runnables import runnablelambda

full_chain = {"topic": chain, "question": lambda x: x["question"]} | runnablelambda(
    route
)

if __name__ == "__main__":
    print(full_chain.invoke({"question": "你好呀,你叫什么?"}))

详细内容可以移步 langchain(六)llmroutechain的基本原理和构建方式-新手向_langchain llmrouterchain-csdn博客

有非常详尽的操作思路。

总结

本篇对于多链路由、工具调用、大模型构建方式进行了复习,并给出实战代码!

最合适的函数,不是官网现成的函数,而是你自己搭建的啊

(0)

相关文章:

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

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com