【Langchain Agent研究】SalesGPT项目介绍(五)

这篇具有很好参考价值的文章主要介绍了【Langchain Agent研究】SalesGPT项目介绍(五)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

【Langchain Agent研究】SalesGPT项目介绍(四)-CSDN博客        

        上节课,我们分析了一下salesGPT项目里源代码的一些问题,重新写了一个运行方法,换了一个模型并修改了一些源代码开始把项目跑起来了,我们已经可以通过console和模型进行对话了。

        我们之前选的模式是不使用工具的模式,所以我们启用的是sales_conversation_utterance_chain,这节课我们尝试使用工具,也就是之前我们介绍过的sales_agent_executor和用setup_knowledge_base()方法构造的knowledge_base。

1. 运行使用工具的Agent

        我们重新写一个my_test_with_tools.py的方法,其他的地方一样,注意在构造sales_agent的时候,use_tools=True,product_catalog要改一下,用你项目本地的地址:

sales_agent = SalesGPT.from_llm(
            llm,
            verbose=True,
            use_tools=True,
            product_catalog=r"C:\Users\Administrator\SalesGPT\examples\sample_product_catalog.txt",
            salesperson_name="Ted Lasso",
            salesperson_role="Sales Representative",
            company_name="Sleep Haven",
            company_business="""Sleep Haven 
                                    is a premium mattress company that provides
                                    customers with the most comfortable and
                                    supportive sleeping experience possible. 
                                    We offer a range of high-quality mattresses,
                                    pillows, and bedding accessories 
                                    that are designed to meet the unique 
                                    needs of our customers.""",
        )

        我们运行一下这块代码,发现在我们询问产品价格后,Agent开始思考是否要使用工具(就是我们之前构造的另外一个Agent——knowledge_base,它是一个RetrievalQA类型的Chain,也可以认为是一个Agent),下面是它的思考过程,我直接用prompt模板里面的内容了:

Previous conversation history:
Ted Lasso: Hello there! This is Ted Lasso from Sleep Haven. How are you doing today? <END_OF_TURN>
User: 我挺好的 <END_OF_TURN>
Ted Lasso: That's great to hear! I hope you're having a wonderful day. How can I assist you today? <END_OF_TURN>
User: 能介绍一下你们的产品么? <END_OF_TURN>
Ted Lasso:
Thought: Do I need to use a tool? Yes
Action: ProductSearch
Action Input: Sleep Haven mattresses
Observation: Sleep Haven offers a range of mattresses, including the Luxury Cloud-Comfort Memory Foam Mattress, the Classic Harmony Spring Mattress, the Plush Serenity Bamboo Mattress, and the EcoGreen Hybrid Latex Mattress. Each mattress has its own unique features and benefits, catering to different preferences and needs. The prices and sizes available for each mattress are as follows:
1. Luxury Cloud-Comfort Memory Foam Mattress:
- Price: $999
- Sizes available: Twin, Queen, King
2. Classic Harmony Spring Mattress:
- Price: $1,299
- Sizes available: Queen, King
3. Plush Serenity Bamboo Mattress:
- Price: $2,599
- Sizes available: King
4. EcoGreen Hybrid Latex Mattress:
- Price: $1,599
- Sizes available: Twin, Full
These mattresses are designed to provide comfort, support, and a restful night's sleep.
Thought: 

        这里能看到我和机器人对话的聊天记录(我使用的是中文询问),也能看到当我询问产品和价格后,我们启用了 sales_agent_executor,它开始思考是否使用它的工具——另外一个Agent进行QA查询。它的决定是YES,启用knowledge_base去查询价格。

        我们在【Langchain Agent研究】SalesGPT项目介绍(三)-CSDN博客中留下了两个遗留问题,我们在能运行项目之后再来看一下这里面的东西就清晰了:

2. CustomPromptTemplateForTools

        首先在调用CustomPromptTemplateForTools时,有三个地方需要注意,第一个是tools_getter=lambda x: tools。

prompt = CustomPromptTemplateForTools(
                template=SALES_AGENT_TOOLS_PROMPT,
                tools_getter=lambda x: tools,
                # This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically
                # This includes the `intermediate_steps` variable because that is needed
                input_variables=[
                    "input",
                    "intermediate_steps",  #这是在调用tools时,会产生的中间变量,是一个list里面的一个tuple,一个是action,一个是observation
                    "salesperson_name",
                    "salesperson_role",
                    "company_name",
                    "company_business",
                    "company_values",
                    "conversation_purpose",
                    "conversation_type",
                    "conversation_history",
                ],
            )

        这一行的意思是,tools_getter这个lambda函数接收任意一个参数,返回tools。所以在后面的代码里,我改变了原来代码的输入,这完全不影响后续的结果:

  # tools = self.tools_getter(kwargs["input"])
  tools = self.tools_getter([])

         第二个是input_variables里的input是没有值的,这一点困惑了我很久,后来我才发现其实这里根本不需要input应该也是不影响代码调用的,大家可以自己试试。

         第三个是intermediate_steps,这是一个只有在代码运行中并调用了tools时才会产生的中间变量,我把它找了出来贴一下:

[(AgentAction(tool='ProductSearch', tool_input='mattress prices', log='Thought: Do I need to use a tool? Yes\nAction: ProductSearch\nAction Input: mattress prices'), 'The prices for the Sleep Haven mattresses are as follows:\n\n1. Luxury Cloud-Comfort Memory Foam Mattress: $999\n2. Classic Harmony Spring Mattress: $1,299\n3. EcoGreen Hybrid Latex Mattress: $1,599\n4. Plush Serenity Bamboo Mattress: $2,599\n\nPlease note that these prices are subject to change and may vary depending on the size of the mattress.')]

        这个是一个LIST,里面有一个tuple,tuple里面又是两个tuple ,一个是action,一个是observation,我们就用action的log和observation去构造agent_scratchpad,agent_scratchpad是构造有memory的agent必要的一个组件。至此,我们就基本搞明白了CustomPromptTemplateForTools,用它的format方法把输入的参数进行一些调整、拼接,获得一个新的prompt。但是有一点我有点不太明白的是,CustomPromptTemplateForTools这个类的format方法我并没有调用过,为啥就生效呢?这个确实不太明白,可能涉及到langchain对于prompt这块的底层设计原理,我现在还接触不到。

3. SalesConvoOutputParser

        我们来看一下这个输出解析器。这块也是之前遗留的一个难点,因为这个Parser处理的是sales_agent_executor执行后的结果,不看到具体的输出我们确实很难理解这块代码在干什么。

        我们启动代码,然后输入查询价格的指令:

Ted Lasso: Hello there! This is Ted Lasso from Sleep Haven. How are you doing today? 
say something FINE , I WANT TO KNOW YOUR PRODUCT PRICE

        首先,stage_analyzer_chain进行阶段判断,判定到了第三个阶段:

Conversation Stage ID: 3
Conversation Stage: Value proposition: Briefly explain how your product/service can benefit the prospect. Focus on the unique selling points and value proposition of your product/service that sets it apart from competitors.

        然后,AgentExecutor开始执行,AgentExecutor在读取了历史聊天记录后开始进行分析,这个是它的输出:

TEXT
Thought: Do I need to use a tool? Yes
Action: ProductSearch
Action Input: Mattress price
-------

        到这里,我们就理解了SalesConvoOutputParser代码中:

        regex = r"Action: (.*?)[\n]*Action Input: (.*)"
        match = re.search(regex, text)
        if not match:
            ## TODO - this is not entirely reliable, sometimes results in an error.
            return AgentFinish(
                {
                    "output": "I apologize, I was unable to find the answer to your question. Is there anything else I can help with?"
                },
                text,
            )
            # raise OutputParserException(f"Could not parse LLM output: `{text}`")
        action = match.group(1)
        action_input = match.group(2)
        return AgentAction(action.strip(), action_input.strip(" ").strip('"'), text)

        regex = r"Action: (.*?)[\n]*Action Input: (.*)" 是一个正则表达式,这个正则表达式可以用来匹配文本中以"Action:"开头,接着是动作内容,然后是零个或多个换行符,最后以"Action Input:"开头,接着是动作输入内容的部分。后面做的事情就是要用这个正则表达式去查询TEXT内容,去把"Action:"和"Action Input:"后面的东西提取出来,并赋值给action和action_input。

        这是AgentExecutor第一轮的输出,然后到第二轮的输出:

TEXT
Ted Lasso: The prices for our Sleep Haven mattresses range from $999 to $2,599, depending on the model you choose. We have the Classic Harmony Spring Mattress for $1,299, the Luxury Cloud-Comfort Memory Foam Mattress for $999, the EcoGreen Hybrid Latex Mattress for $1,599, and the Plush Serenity Bamboo Mattress for $2,599. These prices reflect the high-quality materials and craftsmanship that go into creating our mattresses. Is there a specific model you are interested in?
-------

        这个时候,已经通过调用工具进行了知识库查询,获得了这段TEXT,然后我们就理解了这段代码的作用:

        if f"{self.ai_prefix}:" in text:
            return AgentFinish(
                {"output": text.split(f"{self.ai_prefix}:")[-1].strip()}, text
            )

         就是如果发现了Ted Lasso:为开头的输出,那就表明AgentExecutor已经获得了执行结果,代表可以返回AgentFinish,代表这个流程结束了。

 4.结束语

        至此,我们就基本掌握了SalesGPT的基本原理,也了解了它的核心代码逻辑和一些有难点的地方,这对于我们理解多Agent系统,对话阶段判断和prompt与parser的内容组装调整有巨大的好处。

        下一步,我们将尝试把我们之前构造的聊天机器人加入多Agent系统,让他可以根据用户对话的情况进行分析,给用户推销适配的旅游产品。文章来源地址https://www.toymoban.com/news/detail-827103.html

到了这里,关于【Langchain Agent研究】SalesGPT项目介绍(五)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 让AI做决策,学会langChain的Agent

    今天内容涉及如下: 1.initialize_agent,:执行gent工作,并把工具Tool传入 2.Tool:选取行为函数工具类 之前我们学习的都是把问题给AI,让AI模型给出答案,那么这种情况下应该怎么处理呢,我需要根据不同的问题选择不同的答案,比如我问AI我想选择一件衣服就去调用挑选衣服的

    2024年01月18日
    浏览(33)
  • 怎么和Bing一样使用ChatGPT?如何让ChapGPT与外界世界交互结合?LangChain Agent模块帮你解决问题。LangChain Agent模块的使用案例和源码详解

    ChatGPT很火,但是对于这个模型我们怎么用呢?只是和他聊聊天,回答回答问题? 如何基于这个模型进行二次开发呢?是否可以和new bing一样,可以搜索资料然后进行回复?甚至可以按照你的指令帮你操作机器人? LangChain的 Agent模块就可以帮大家做到这些,而Agent是如何使用

    2023年04月14日
    浏览(49)
  • LangChain-Agent自定义Tools类 ——基础篇(一)

    其他友情链接: 为 LLM 代理构建自定义工具 |松果 (pinecone.io) Create Custom Tools for Chatbots in LangChain — LangChain #8 - YouTube //油管这个小哥讲的比较好  Tools怎么使用?可以定义自己的tool么? - General - LangChain中文社区

    2024年02月11日
    浏览(29)
  • Langchain+ElasticSearch+文心千帆 构建检索增强LLM Agent

    很早就开始做检索增强的大语言模型Agent了,通过外接知识库为LLM提供外部知识能增强它回答的准确性。这里我们使用ElasticSearch作为数据库存储相关知识,使用百度文心千帆的embedding API提供向量嵌入;借助langchain搭建LLM Agent. 需要安装的环境有: Python, ElasticSearch, langchain, q

    2024年02月04日
    浏览(33)
  • LangChain与大型语言模型(LLMs)应用基础教程:神奇的Agent

      LangChain是大型语言模型(LLM)的应用框架,LangChain可以直接与 OpenAI 的 text-davinci-003、gpt-3.5-turbo 模型以及 Hugging Face 的各种开源语言模如 Google 的 flan-t5等模型集成。通过使用LangChain可以开发出更为强大和高效的LLM的各种应用。 今天我们就来实现一个神奇的功能,如何你是一个不

    2024年02月03日
    浏览(33)
  • LangChain-Agent自定义Tools类 ——输入参数篇(二)

    给自定义函数传入输入参数,分别有single-input 参数函数案例和multi-input 参数函数案例:  运行结果  后期关注结构化输出,方便作为借口提供给其他下游应用  相关友情链接: 为 LLM 代理构建自定义工具 |松果 (pinecone.io)

    2024年02月11日
    浏览(33)
  • 从API到Agent:万字长文洞悉LangChain工程化设计

    我想做一个尝试,看看能不能用尽量清晰的逻辑,给“AI外行人士”(当然,我也是……)引入一下LangChain,试着从工程角度去理解LangChain的设计和使用。同时大家也可以将此文档作为LangChain的“10分钟快速上手”手册,本意是希望帮助需要的同学实现AI工程的Bootstrap。 文中所

    2024年03月15日
    浏览(24)
  • LlamaIndex的使用 | LangChain的研究 | pdfgpt安装使用

    项目来源https://juejin.cn/post/7206950454097690680 先把项目clone下来了,在项目当前目录运行npm install 出报错,查了一下资料问了一下chatgpt觉得应该是nodejieba的安装问题,会涉及系统内使用的编译器等等一些问题,比较不好解决,于是采取使用另一个jieba分词的库来替代参考https://z

    2024年02月09日
    浏览(23)
  • 人力资源智能化管理项目(day01:基础架构拆解)

    git clone GitHub - PanJiaChen/vue-admin-template: a vue2.0 minimal admin template 项目名 项目模版中的core-js的版本号有些滞后,需要将其版本号改为“3.25.5”(package.json里面18行) 再安装依赖(npm i) 登录界面 首页 ESLint Vetur 提升开发效率 main.js: ①new Vue({})实例化 路由 store(Vuex) 根组件 ②全局注

    2024年01月16日
    浏览(31)
  • YoloV8改进策略:Agent Attention|Softmax与线性注意力的融合研究|有效涨点|代码注释与改进|全网首发(唯一)

    涨点效果:在我自己的数据集上,mAP50 由0.986涨到了0.991,mAP50-95由0.737涨到0.753,涨点明显! 本文提出了一种新型的注意力机制——Agent Attention,旨在平衡计算效率和表示能力。该机制在传统的注意力模块中引入了额外的agent tokens A,这些agent tokens首先为query tokens Q聚合信息,

    2024年01月18日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包