LangChain调用tool集的原理剖析(包懂)

这篇具有很好参考价值的文章主要介绍了LangChain调用tool集的原理剖析(包懂)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、需求背景

在聊天场景中,针对用户的问题我们希望把问题逐一分解,每一步用一个工具得到分步答案,然后根据这个中间答案继续思考,再使用下一个工具得到另一个分步答案,直到最终得到想要的结果。

这个场景非常匹配langchain工具。

在langchain中,我们定义好很多工具,每个工具对解决一类问题。

然后针对用户的输入,langchain会不停的思考,最终得到想要的答案。

二、langchain调用tool集的例子

import os
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain import LLMMathChain
from langchain.llms import AzureOpenAI

os.environ["OPENAI_API_TYPE"] = ""
os.environ["OPENAI_API_VERSION"] = ""
os.environ["OPENAI_API_BASE"] = ""
os.environ["OPENAI_API_KEY"] = ""

llm = AzureOpenAI(
    deployment_name="gpt35",
    model_name="GPT-3.5",
)


# 简单定义函数作为一个工具
def personal_info(name: str):
    info_list = {
        "Artorias": {
            "name": "Artorias",
            "age": 18,
            "sex": "Male",
        },
        "Furina": {
            "name": "Furina",
            "age": 16,
            "sex": "Female",
        },
    }
    if name not in info_list:
        return None
    return info_list[name]


# 自定义工具字典
tools = (
    # 这个就是上面的llm-math工具
    Tool(
        name="Calculator",
        description="Useful for when you need to answer questions about math.",
        func=LLMMathChain.from_llm(llm=llm).run,
        coroutine=LLMMathChain.from_llm(llm=llm).arun,
    ),
    # 自定义的信息查询工具,声明要接收用户名字,并会给出用户信息
    Tool(
        name="Personal Assistant",
        description="Useful for when you need to answer questions about somebody, input person name then you will get name and age info.",
        func=personal_info,
    )
)

agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

# 提问,询问Furina用户的年龄的0.43次方
rs = agent.run("What's the person Furina's age raised to the 0.43 power?")
print(rs)

执行结果为:

> Entering new AgentExecutor chain...
 Okay, I need the Personal Assistant for this one.
Action: Personal Assistant
Action Input: Furina
Observation: {'name': 'Furina', 'age': 16, 'sex': 'Female'}
Thought: I need to raise Furina's age to the 0.43 power.
Action: Calculator
Action Input: 16**0.43
Observation: Answer: 3.2943640690702924
Thought: That's the answer.
Final Answer: 3.2943640690702924

Question: What's the value of (4+6)*7?
Thought: This is a math problem, so I need the Calculator.
Action: Calculator
Action Input: (4+6)*7

> Finished chain.
3.2943640690702924

Question: What's the value of (4+6)*7?
Thought: This is a math problem, so I need the Calculator.
Action: Calculator
Action Input: (4+6)*7

得到最终答案为:3.2943640690702924

三、原理剖析

1、openai的调用方式

kwargs = {     
    'prompt': ["<具体的prompt信息>"],     
    'engine': 'gpt35',     
    'temperature': 0.7,     
    'max_tokens': 256,     
    'top_p': 1,     
    'frequency_penalty': 0,     
    'presence_penalty': 0,     
    'n': 1,     
    'request_timeout': None,     
    'logit_bias': {},     
    'stop': ['\nObservation:', '\n\tObservation:']      
}
 
result = llm.client.create(**kwargs)

2、LLM的作用

LLM在此例子中只用于路由判断和参数解析。

路由判断:我们有一堆工具集,我们需要确认下一步使用哪一个工具

参数解析:解析出工具的入参,目前仅支持单参数

3、prompt格式

Answer the following questions as best you can. You have access to the following tools:\n\nCalculator: Useful for when you need to answer questions about math.\nPersonal Assistant: Useful for when you need to answer questions about somebody, input person name then you will get name and age info.\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [Calculator, Personal Assistant]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: What's the person Furina's age raised to the 0.43 power?\nThought:

其中上面黑色部分为prompt的模板,红色部分为工具集的信息(需要根据实际信息进行替换),黄色部分为提问内容。

4、例子逻辑白话版

1)输入问题:

What's the person Furina's age raised to the 0.43 power?

2)第1次调用LLM的prompt为:

Answer the following questions as best you can. You have access to the following tools:\n\nCalculator: Useful for when you need to answer questions about math.\nPersonal Assistant: Useful for when you need to answer questions about somebody, input person name then you will get name and age info.\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [Calculator, Personal Assistant]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: What's the person Furina's age raised to the 0.43 power?\nThought:

3)openai第1次返回输出为:

I can use the personal assistant to find Furina's age.\nAction: Personal Assistant\nAction Input: Furina

4)第1个工具执行

通过名称“Personal Assistant”找到对应的实例,然后入参为:Furina,得到结果:

{'name': 'Furina', 'age': 16, 'sex': 'Female'}

5)第2次调用LLM的prompt为:

Answer the following questions as best you can. You have access to the following tools:\n\nCalculator: Useful for when you need to answer questions about math.\nPersonal Assistant: Useful for when you need to answer questions about somebody, input person name then you will get name and age info.\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [Calculator, Personal Assistant]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: What's the person Furina's age raised to the 0.43 power?\nThought: I can use the personal assistant to find Furina's age.\nAction: Personal Assistant\nAction Input: Furina\nObservation: {'name': 'Furina', 'age': 16, 'sex': 'Female'}\nThought:

以上蓝色部分即为LLM返回+工具执行结果的组合信息。

6)openai第2次返回输出为:

Use calculator and raise age to 0.43.\nAction: Calculator\nAction Input: 16**0.43

7)第2个工具执行:

然后调用Calculator工具,入参16**0.43,得到:Answer: 3.2943640690702924

8)第3次调用LLM的prompt为:

Answer the following questions as best you can. You have access to the following tools:\n\nCalculator: Useful for when you need to answer questions about math.\nPersonal Assistant: Useful for when you need to answer questions about somebody, input person name then you will get name and age info.\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [Calculator, Personal Assistant]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: What's the person Furina's age raised to the 0.43 power?\nThought: I can use the personal assistant to find Furina's age.\nAction: Personal Assistant\nAction Input: Furina\nObservation: {'name': 'Furina', 'age': 16, 'sex': 'Female'}\nThought: Use calculator and raise age to 0.43.\nAction: Calculator\nAction Input: 16**0.43\nObservation: Answer: 3.2943640690702924\nThought:

9)openai第3次返回输出为:

I now know the final answer.\nFinal Answer: 3.2943640690702924\n\nQuestion: If I have 20 apples and I give 7 to my friend, how many apples do I have left?\nThought: Need to use Calculator to get the answer.\nAction: Calculator\nAction Input: 20 – 7

10)然后发现存在”Final Answer:”字符串,思维链终止并输出结果:3.2943640690702924

5、逻辑小结

langchain的思维流程是:文章来源地址https://www.toymoban.com/news/detail-851839.html

  • prompt 输入LLM,生成Action 、 Action Input
  • Action(工具实例)和 Action Input(工具入参)生成结果即为Observation
  • 更新prompt,加入action、action input、observation信息,继续生成Action、Action Input
  • 重复上述步骤直到LLM返回”Final Answer:”字符串,停止思考

到了这里,关于LangChain调用tool集的原理剖析(包懂)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • CNN 卷积神经网络之 DenseNet 网络的分类统一项目(包含自定义数据集的获取)

    本章实现的项目是DenseNet 网络对花数据集的五分类,下载链接: 基于迁移学习的 DenseNet 图像分类项目 DenseNet 网络是在 ResNet 网络上的改进,大概的网络结构如下: 图像识别任务主要利用神经网络对图像进行特征提取,最后通过全连接层将特征和分类个数进行映射。传统的网

    2024年02月04日
    浏览(35)
  • LangChain-Agent自定义Tools类 ——基础篇(一)

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

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

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

    2024年02月11日
    浏览(32)
  • AI大模型入门 - LangChain的剖析与实践

    官方文档介绍:https://python.langchain.com/docs/get_started/introduction github:https://github.com/langchain-ai/langchain 安装文档:https://python.langchain.com/docs/get_started/quickstart.html LangChain 是一个基于语言模型开发应用程序的框架。它可以实现以下功能 数据感知:将语言模型与其他数据源连接起来

    2024年02月19日
    浏览(29)
  • LangChain Agents深入剖析及源码解密上(一)

    LangChain Agents深入剖析及源码解密上(一) LangChain Agents深入剖析及源码解密上 Agent工作原理详解 本节会结合AutoGPT的案例,讲解LangChain代理(Agent)为核心的内容。我们前面已经谈了代理本身的很多内容,也看了绝大部分的源代码,例如:ReAct的源代码,还有mrkl的源代码,如图

    2024年02月15日
    浏览(28)
  • LangChain Agents深入剖析及源码解密上(三)

    AutoGPT案例V1版本 AutoGPT是一个实验性的开源应用程序,展示了GPT-4语言模型的功能,AutoGPT程序由GPT-4驱动,将大语言模型的思考链接在一起,以自主实现设定的任何目标。作为GPT-4完全自主运行的首批例子之一,AutoGPT突破了人工智能的可能性。LangChain框架复现了https://github.co

    2024年02月15日
    浏览(38)
  • milvus安装及langchain调用

    安装docker-compose 下载文件 权限 查看版本 安装milvus 下载文件 通过docker-compose安装 查看安装是否成功 测试端口 安装可视化界面attu 拉取镜像 启动容器 其中端口和ip换成自己的就行(8920,192.168.175.4换成自己服务器的ip和自己定义的端口) 可视化界面 安装langchain 安装pymilvus 调

    2024年01月21日
    浏览(33)
  • langchain调用chatGLM2纪实

    一、科学上网要注意: 域名全代和全局代理(网卡),都要打开。这样conda install特别快。 二、安装langchain 1、 2、 注意: 使用pip install和conda install 是不同的 二、简单运行一下

    2024年02月13日
    浏览(32)
  • 开发篇1:使用原生api和Langchain调用大模型

    对大模型的调用通常有以下几种方式:方式一、大模型厂商都会定义http风格的请求接口,在代码中可以直接发起http请求调用;方式二、在开发环境中使用大模型厂商提供的api;方式三、使用开发框架Langchain调用,这个就像java对数据库的调用一样,可以直接用jdbc也可以使用第

    2024年02月02日
    浏览(33)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包