LangChain(6)构建用户自己的Agent

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

LangChain 中有一些可用的Agent内置工具,但在实际应用中我们可能需要编写自己的Agent。

编写简单的计算工具

!pip install -qU langchain openai transformers
from langchain.tools import BaseTool
from math import pi
from typing import Union
class CircumferenceTool(BaseTool):
	# tool名称
    name = "Circumference calculator"
    # 描述此工具能做什么,当LLM语义匹配到该description时,就会执行此tool
    description = "use this tool when you need to calculate a circumference using the radius of a circle"
	# 调用run 时执行此函数
    def _run(self, radius: Union[int, float]):
        return float(radius)*2.0*pi
    # 异步用
    def _arun(self, radius: Union[int, float]):
        raise NotImplementedError("This tool does not support async")


import os
from langchain.chat_models import ChatOpenAI
from langchain.chains.conversation.memory import ConversationBufferWindowMemory
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY') or 'OPENAI_API_KEY'
# initialize LLM (we use ChatOpenAI because we'll later define a `chat` agent)
llm = ChatOpenAI(
    openai_api_key=OPENAI_API_KEY,
    temperature=0,
    model_name='gpt-3.5-turbo'
)
# 缓存 initialize conversational memory
conversational_memory = ConversationBufferWindowMemory(
    memory_key='chat_history',
    k=5,
    return_messages=True
)

from langchain.agents import initialize_agent
tools = [CircumferenceTool()]
# initialize agent with tools
agent = initialize_agent(
	'''
	chat-conversational-react-description名称解释
	chat:使用chat模型,如 gpt-4 and gpt-3.5-turbo
	conversational:含缓存conversation memory
	react:模型自推理
	description:LLM模型决定使用哪个工具
	'''
    agent='chat-conversational-react-description',
    tools=tools,
    llm=llm,
    verbose=True,
    max_iterations=3,
    early_stopping_method='generate',
    memory=conversational_memory
)
agent("can you calculate the circumference of a circle that has a radius of 7.81mm")

>>>  {'input': 'can you calculate the circumference of a circle that has a radius of 7.81mm',
 'chat_history': [],
 'output': 'The circumference of a circle with a radius of 7.81mm is approximately 49.03mm.'}

输出的答案为 49.03,是个错误答案,实际上为 49.07=(7.81 * 2) * pi
可见模型并没有使用我们定义的 Circumference calculator 进行计算,而是LLM模型自己进行了推理,但LLM不善于数据计算,所以最后的结果虽然接近但是是错误的。

# 打印提示词 existing prompt
print(agent.agent.llm_chain.prompt.messages[0].prompt.template)

>>> '''Assistant is a large language model trained by OpenAI.

Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.

Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.

Overall, Assistant is a powerful system that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.'''

可以修改提示词,当让模型清楚自己不善于数学计算,当碰到数学问题时,需要调用工具得到结果

sys_msg = """Assistant is a large language model trained by OpenAI.

Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.

Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.

Unfortunately, Assistant is terrible at maths. When provided with math questions, no matter how simple, assistant always refers to it's trusty tools and absolutely does NOT try to answer math questions by itself

Overall, Assistant is a powerful system that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.
"""
# 更新提示词 prompt
new_prompt = agent.agent.create_prompt(
    system_message=sys_msg,
    tools=tools
)
agent.agent.llm_chain.prompt = new_prompt

agent("can you calculate the circumference of a circle that has a radius of 7.81mm")

# 现在能得到正确答案
>>>{'input': 'can you calculate the circumference of a circle that has a radius of 7.81mm',
 'chat_history': [HumanMessage(content='can you calculate the circumference of a circle that has a radius of 7.81mm', additional_kwargs={}),
  AIMessage(content='The circumference of a circle with a radius of 7.81mm is approximately 49.03mm.', additional_kwargs={})],
 'output': 'The circumference of a circle with a radius of 7.81mm is approximately 49.07mm.'}

编写有多个参数的工具

一个用于计算三角形斜边的工具

from typing import Optional
from math import sqrt, cos, sin

desc = (
    "use this tool when you need to calculate the length of an hypotenuse "
    "given one or two sides of a triangle and/or an angle (in degrees). "
    "To use the tool you must provide at least two of the following parameters "
    "['adjacent_side', 'opposite_side', 'angle']."
)

class PythagorasTool(BaseTool):
    name = "Hypotenuse calculator"
    description = desc

    def _run(
        self,
        adjacent_side: Optional[Union[int, float]] = None,
        opposite_side: Optional[Union[int, float]] = None,
        angle: Optional[Union[int, float]] = None
    ):
        # check for the values we have been given
        if adjacent_side and opposite_side:
            return sqrt(float(adjacent_side)**2 + float(opposite_side)**2)
        elif adjacent_side and angle:
            return adjacent_side / cos(float(angle))
        elif opposite_side and angle:
            return opposite_side / sin(float(angle))
        else:
            return "Could not calculate the hypotenuse of the triangle. Need two or more of `adjacent_side`, `opposite_side`, or `angle`."
    
    def _arun(self, query: str):
        raise NotImplementedError("This tool does not support async")

tools = [PythagorasTool()]

new_prompt = agent.agent.create_prompt(
    system_message=sys_msg,
    tools=tools
)

agent.agent.llm_chain.prompt = new_prompt
# 更新计算工具 update the agent tools
agent.tools = tools

agent("If I have a triangle with two sides of length 51cm and 34cm, what is the length of the hypotenuse?")

其它更高级的工具

一个描述图像的工具

import torch
from transformers import BlipProcessor, BlipForConditionalGeneration
# 描述图像的模型名称
hf_model = "Salesforce/blip-image-captioning-large"
device = 'cuda' if torch.cuda.is_available() else 'cpu'

processor = BlipProcessor.from_pretrained(hf_model)
model = BlipForConditionalGeneration.from_pretrained(hf_model).to(device)

# 下载图片
import requests
from PIL import Image
img_url = 'https://images.unsplash.com/photo-1616128417859-3a984dd35f02?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2372&q=80' 
image = Image.open(requests.get(img_url, stream=True).raw).convert('RGB')
image.show() # image

# unconditional image captioning
inputs = processor(image, return_tensors="pt").to(device)

out = model.generate(**inputs, max_new_tokens=20)
print(processor.decode(out[0], skip_special_tokens=True))

>>>there is a monkey that is sitting in a tree

LangChain(6)构建用户自己的Agent,Python,LLM,langchain,python,agent,多参数
构建 agent 工具

desc = (
    "use this tool when given the URL of an image that you'd like to be "
    "described. It will return a simple caption describing the image."
)

class ImageCaptionTool(BaseTool):
    name = "Image captioner"
    description = desc

    def _run(self, url: str):
        # download the image and convert to PIL object
        image = Image.open(requests.get(img_url, stream=True).raw).convert('RGB')
        # preprocess the image
        inputs = processor(image, return_tensors="pt").to(device)
        # generate the caption
        out = model.generate(**inputs, max_new_tokens=20)
        # get the caption
        caption = processor.decode(out[0], skip_special_tokens=True)
        return caption
    
    def _arun(self, query: str):
        raise NotImplementedError("This tool does not support async")

tools = [ImageCaptionTool()]

# 新的提示词
sys_msg = """Assistant is a large language model trained by OpenAI.

Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.

Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.

Overall, Assistant is a powerful system that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.
"""

new_prompt = agent.agent.create_prompt(
    system_message=sys_msg,
    tools=tools
)

agent.agent.llm_chain.prompt = new_prompt
# update the agent tools
agent.tools = tools

agent(f"What does this image show?\n{img_url}")

参考
Building Tools
Building Custom Tools for LLM Agents文章来源地址https://www.toymoban.com/news/detail-575942.html

到了这里,关于LangChain(6)构建用户自己的Agent的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • LangChain:打造自己的LLM应用 | 京东云技术团队

    LangChain是一个框架,用于开发由LLM驱动的应用程序。可以简单认为是LLM领域的Spring,以及开源版的ChatGPT插件系统。核心的2个功能为: 1)可以将 LLM 模型与外部数据源进行连接。 2)允许与 LLM 模型与环境进行交互,通过Agent使用工具。 [外链图片转存失败,源站可能有防盗链机

    2024年02月14日
    浏览(42)
  • LangChain入门:构建LLM驱动的应用程序的初学者指南

    LangChain DemoGPT         你有没有想过如何使用大型语言模型(LLM)构建强大的应用程序?或者,也许您正在寻找一种简化的方式来开发这些应用程序?那么你来对地方了!本指南将向您介绍LangChain,这是一个简化构建LLM驱动的应用程序的过程的工具。我们还将深入研究 

    2024年02月12日
    浏览(42)
  • LLM之RAG实战(一):使用Mistral-7b, LangChain, ChromaDB搭建自己的WEB聊天界面

          如何使用没有被LLM训练过的数据来提高LLM性能?检索增强生成(RAG)是未来的发展方向,下面将解释一下它的含义和实际工作原理。 ​       假设您有自己的数据集,例如来自公司的文本文档。如何让ChatGPT和其他LLM了解它并回答问题?         这可以通过四个步骤

    2024年01月18日
    浏览(49)
  • 【ChatGPT】使用 LangChain 和 Ray 实现 100 行代码构建 LLM 开源搜索引擎【1】

    目录 Introduction Building the index 构建索引 Accelerating indexing using Ray 使用 Ray 加速索引编制 Serving

    2024年02月08日
    浏览(46)
  • 把通过autogen构建的AI agent接入到自己的应用程序中

    同志们,我很高兴的告诉大家我们有了一个比langchain更好用的构建AI agent的工具。众所周知,langchain主要就是一堆字符串提示模板构成的,这导致,当我们的模型性能不够强大(比如说gpt3.5)时会因为上下文的干扰而产生幻觉,从而无法完成我们所需要让其完成的任务(之前想让

    2024年02月04日
    浏览(59)
  • Java-langchain:在Java环境中构建强大的基于LLM的应用程序

    Java-langchain : 一个Java 8+的LangChain实现。在(企业)Java环境中构建强大的基于LLM的应用程序。 这里持续连载详细的Java入门的LLM学习课程。课程分四个部分: 面向开发者的提示工程 (promptdevelopment) 搭建基于 ChatGPT 的问答系统 (chagptapi) 使用 LangChain 开发应用程序 (langchain) 使用 Lang

    2024年02月21日
    浏览(48)
  • Elasticsearch:使用在本地计算机上运行的 LLM 以及 Ollama 和 Langchain 构建 RAG 应用程序

    无需 GPU 的隐私保护 LLM。在本博客中,我将演示使用不同的工具 Ollama 构建的 RAG 应用程序。 与本文相关的所有源代码均已发布在 github上。 请克隆存储库以跟随文章操作。我们可以通过如下的方式来克隆: Ollama 是一个轻量级且灵活的框架,专为在个人计算机上本地部署 LL

    2024年04月16日
    浏览(55)
  • LLM本地知识库问答系统(一):使用LangChain和LlamaIndex从零构建PDF聊天机器人指南

           随着大型语言模型(LLM)(如ChatGPT和GPT-4)的兴起,现在比以往任何时候都更容易构建比普通熊更智能的智能聊天机器人,并且可以浏览堆积如山的文档,为您的输入提供准确的响应。        在本系列中,我们将探索如何使用pre-trained的LLM创建一个聊天机器人,该聊

    2024年02月11日
    浏览(65)
  • 【LangChain】如何本地部署基于chatGPT的实时文档和表格数据的助手,在自己的数据上构建chatGPT?

    (1) LangChain 是一个用于自然语言处理的 Python 库,它的目标是尝试简化自然语言处理任务,提高处理效率和准确性。 该库提供了一组易于使用的函数和工具,可以帮助你实现各种自然语言处理任务,例如语句分割、分词、词性标注、命名实体识别、情感分析等。与其它自然

    2024年02月08日
    浏览(47)
  • langchain agent

    每一步action,可以是另外一个chain, 核心思想:工具如果需要多种输入,也需要将参数一起构建进prompt当中 prompt

    2024年02月10日
    浏览(31)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包