大模型架构记录12【Agent实例-tool】

运行根目录下几个ipynb文件- Learn-Agent.ipynb- 学习《Custom agent 自定义代理》部分- v1-Create-Custom-Agent.ipynb- v2-Create-Custom-Agent.ipynb- 基于v1,新增一些职位描述(JD)信息- v3-Create-Custom-Agent.ipynb- 基于v2,新增一些简历(CV)信息- Learn-Function calling.ipynb- 理解Function calling理念- 补充-路由链.ipynb- 与本课、与Agent无关,是前面课程遗留的知识点

一 Learn-Agent

1.1 Define tools 定义工具

  • LangChain Decorators ✨ | 🦜️🔗 LangChain
from dotenv import load_dotenv, find_dotenvload_dotenv(find_dotenv())from langchain_community.document_loaders import WebBaseLoader
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitterloader = WebBaseLoader("https://docs.smith.langchain.com/overview")
docs = loader.load()
documents = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200
).split_documents(docs)
vector = FAISS.from_documents(documents, OpenAIEmbeddings())
retriever = vector.as_retriever()retriever.get_relevant_documents("how to upload a dataset")[0]

from langchain.tools.retriever import create_retriever_toolretriever_tool = create_retriever_tool(retriever,"langsmith_search","Search for information about LangSmith. For any questions about LangSmith, you must use this tool!",
)tools = [retriever_tool]

1.2 Create the agent 创建代理

from langchain_openai import ChatOpenAIllm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)from langchain import hub# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/openai-functions-agent")
prompt.messagesfrom langchain.agents import create_openai_functions_agentagent = create_openai_functions_agent(llm, tools, prompt)from langchain.agents import AgentExecutoragent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

1.3 Run the agent 运行代理

agent_executor.invoke({"input": "hi!"})agent_executor.invoke({"input": "how can langsmith help with testing?"})

1.4 Adding in memory 添加内存

# Here we pass in an empty list of messages for chat_history because it is the first message in the chat
agent_executor.invoke({"input": "hi! my name is bob", "chat_history": []})

from langchain_core.messages import AIMessage, HumanMessageagent_executor.invoke({"chat_history": [HumanMessage(content="hi! my name is bob"),AIMessage(content="Hello Bob! How can I assist you today?"),],"input": "what's my name?",}
)

1.5 keep track of these messages automatically 自动跟踪这些消息

from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistorymessage_history = ChatMessageHistory()agent_with_chat_history = RunnableWithMessageHistory(agent_executor,# This is needed because in most real world scenarios, a session id is needed# It isn't really used here because we are using a simple in memory ChatMessageHistorylambda session_id: message_history,input_messages_key="input",history_messages_key="chat_history",
)agent_with_chat_history.invoke({"input": "hi! I'm bob"},# This is needed because in most real world scenarios, a session id is needed# It isn't really used here because we are using a simple in memory ChatMessageHistoryconfig={"configurable": {"session_id": "<foo>"}},
)

agent_with_chat_history.invoke({"input": "what's my name?"},# This is needed because in most real world scenarios, a session id is needed# It isn't really used here because we are using a simple in memory ChatMessageHistoryconfig={"configurable": {"session_id": "<foo>"}},
)

二 Concepts 概念

  • Schema 图式
  • Agent 代理
  • AgentExecutor 代理执行器
  • Tools 工具
  • Toolkits 工具包

2.1 OpenAI tools

# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/openai-tools-agent")prompt.messages

2.2 JSON Chat Agent

# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/react-chat-json")prompt.messages

# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/structured-chat-agent")prompt.messagesprint(prompt.messages[0].prompt.template)

2.3 Structured chat

# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/structured-chat-agent")print(prompt.messages[0].prompt.template)

2.4 ReAct

# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/react")
promptprint(prompt.template)

# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/self-ask-with-search")
promptprint(prompt.template)

三 Custom agent 自定义代理

3.1 Load the LLM 加载LLM

from langchain_openai import ChatOpenAIllm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)

3.2 Define Tools 定义工具

from langchain.agents import tool@tool
def get_word_length(word: str) -> int:"""Returns the length of a word."""return len(word)get_word_length.invoke("abc")tools = [get_word_length]tools

3.3 Create Prompt 创建提示

由于 OpenAI 函数调用针对工具使用进行了微调,因此我们几乎不需要任何关于如何推理或如何输出格式的说明。

我们将只有两个输入变量: input 和 agent_scratchpad

input 应为包含用户目标的字符串。

agent_scratchpad 应该是包含先前代理工具调用和相应工具输出的消息序列。

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholderprompt = ChatPromptTemplate.from_messages([("system","You are very powerful assistant, but don't know word's lens",),("user", "{input}"),MessagesPlaceholder(variable_name="agent_scratchpad"),]
)prompt.messages[0].prompt.template
# "You are very powerful assistant, but don't know current events"

3.4 Bind tools to LLM 将工具绑定到LLM

要将我们的工具传递给代理,我们只需将它们格式化为 OpenAI 工具格式,然后传递给我们的模型即可。(通过绑定函数,我们可以确保每次调用模型时都能将它们传入)。

llm_with_tools = llm.bind_tools(tools)llm_with_tools.kwargs['tools']

3.5 Create the Agent 创建代理

from langchain.agents.format_scratchpad.openai_tools import (format_to_openai_tool_messages,
)
from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParseragent = ({"input": lambda x: x["input"],"agent_scratchpad": lambda x: format_to_openai_tool_messages(x["intermediate_steps"]),}| prompt| llm_with_tools| OpenAIToolsAgentOutputParser()
)

3.6 Run the agent 运行代理

from langchain.agents import AgentExecutoragent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)agent_executor.invoke({"input": "How many letters in the word eudca"})

llm.invoke("How many letters in the word educa")
# AIMessage(content='5')

3.7 Adding memory 添加内存

from langchain.prompts import MessagesPlaceholderMEMORY_KEY = "chat_history"
prompt = ChatPromptTemplate.from_messages([("system","You are very powerful assistant, but bad at calculating lengths of words.",),MessagesPlaceholder(variable_name=MEMORY_KEY),("user", "{input}"),MessagesPlaceholder(variable_name="agent_scratchpad"),]
)from langchain_core.messages import AIMessage, HumanMessagechat_history = []agent = ({"input": lambda x: x["input"],"agent_scratchpad": lambda x: format_to_openai_tool_messages(x["intermediate_steps"]),"chat_history": lambda x: x["chat_history"],}| prompt| llm_with_tools| OpenAIToolsAgentOutputParser()
)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)input1 = "how many letters in the word educa?"
result = agent_executor.invoke({"input": input1, "chat_history": chat_history})
chat_history.extend([HumanMessage(content=input1),AIMessage(content=result["output"]),]
)
agent_executor.invoke({"input": "is that a real word?", "chat_history": chat_history})

四 Tools 工具

from langchain_community.tools import WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapperapi_wrapper = WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=100)
tool = WikipediaQueryRun(api_wrapper=api_wrapper)tool.name   # 'wikipedia'

4.1 Defining Custom Tools 定义自定义工具

# Import things that are needed generically
from langchain.pydantic_v1 import BaseModel, Field
from langchain.tools import BaseTool, StructuredTool, tool@tool
def search(query: str) -> str:"""Look up things online."""return "LangChain"print(search.name)
print(search.description)
print(search.args)"""search
search(query: str) -> str - Look up things online.
{'query': {'title': 'Query', 'type': 'string'}}"""@tool
def multiply(a: int, b: int) -> int:"""Multiply two numbers."""return a * bprint(multiply.name)
print(multiply.description)
print(multiply.args)"""multiply
multiply(a: int, b: int) -> int - Multiply two numbers.
{'a': {'title': 'A', 'type': 'integer'}, 'b': {'title': 'B', 'type': 'integer'}}"""from langchain_openai import ChatOpenAI# 参数temperature设置为0.0,从而减少生成答案的随机性。
llm = ChatOpenAI(temperature=0)from langchain.agents import load_tools# llm-math 工具结合语言模型和计算器用以进行数学计算
# wikipedia工具通过API连接到wikipedia进行搜索查询。
tools = load_tools(["llm-math","wikipedia"], llm=llm #第一步初始化的模型
)from langchain.agents import initialize_agent
from langchain.agents import AgentType# 初始化代理
agent= initialize_agent(tools, #第二步加载的工具llm, #第一步初始化的模型agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,  #代理类型handle_parsing_errors=True, #处理解析错误verbose = True #输出中间步骤
)agent("计算300的25%") 

question = "Tom M. Mitchell是一位美国计算机科学家,\
也是卡内基梅隆大学(CMU)的创始人大学教授。\
他写了哪本书呢?"agent(question) 

from langchain import hub
base_prompt = hub.pull("langchain-ai/openai-functions-template")
base_promptbase_prompt.messagesfrom langchain_experimental.tools import PythonREPLTooltools = [PythonREPLTool()]instructions = """You are an agent designed to write and execute python code to answer questions.
You have access to a python REPL, which you can use to execute python code.
If you get an error, debug your code and try again.
Only use the output of your code to answer the question. 
You might know the answer without running any code, but you should still run the code to get the answer.
If it does not seem like you can write code to answer the question, just return "I don't know" as the answer.
"""instructions = """您是一个设计用于编写和执行python代码以回答问题的代理。
您可以访问python REPL,可以使用它来执行python代码。
如果出现错误,请调试代码,然后重试。
只使用代码的输出来回答问题。
您可能在不运行任何代码的情况下就知道了答案,但您仍然应该运行代码来获得答案。
如果你似乎无法编写代码来回答这个问题,只需返回“我不知道”作为答案。
"""prompt = base_prompt.partial(instructions=instructions)
prompt

from langchain_openai import ChatOpenAI
from langchain.agents import create_openai_functions_agentagent = create_openai_functions_agent(ChatOpenAI(temperature=0), tools, prompt)
agent

from langchain.agents import AgentExecutor
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executorcustomer_list = ["小明","小黄","小红","小蓝","小橘","小绿",]agent_executor.invoke({"input": f"将使用pinyin拼音库这些客户名字转换为拼音,并打印输出列表: {customer_list}。"})

# !pip install pypinyinagent_executor.invoke({"input": f"将使用pinyin拼音库这些客户名字转换为拼音,并打印输出列表: {customer_list}。"})

import langchain
langchain.debug=True
agent_executor.invoke({"input": f"将使用pinyin拼音库这些客户名字转换为拼音,并打印输出列表: {customer_list}。"})
langchain.debug=False

import langchain
langchain.debug=True
agent_executor.invoke({"input": "第 10 个斐波那契数是多少?"})
langchain.debug=False
from langchain_openai import ChatOpenAIllm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)from langchain.agents import tool@tool
def get_word_length(word: str) -> int:"""Returns the length of a word."""return len(word)get_word_length.invoke("abc")  # 3tools = [get_word_length]from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholderprompt = ChatPromptTemplate.from_messages([("system","You are very powerful assistant, but don't know current events",),("user", "{input}"),MessagesPlaceholder(variable_name="agent_scratchpad"),]
)llm_with_tools = llm.bind_tools(tools)

4.2 关联工具

from langchain.agents.format_scratchpad.openai_tools import (format_to_openai_tool_messages,
)
from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParseragent = ({"input": lambda x: x["input"],"agent_scratchpad": lambda x: format_to_openai_tool_messages(x["intermediate_steps"]),}| prompt| llm_with_tools| OpenAIToolsAgentOutputParser()
)from langchain.agents import AgentExecutoragent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)list(agent_executor.stream({"input": "How many letters in the word eudca"}))

# 导入tool函数装饰器
from langchain.agents import tool
from datetime import date@tool
def time(text: str) -> str:"""返回今天的日期,用于任何需要知道今天日期的问题。\输入应该总是一个空字符串,\这个函数将总是返回今天的日期,任何日期计算应该在这个函数之外进行。"""return str(date.today())# 初始化代理
agent= initialize_agent(tools=[time], #将刚刚创建的时间工具加入代理llm=llm, #初始化的模型agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,  #代理类型handle_parsing_errors=True, #处理解析错误verbose = True #输出中间步骤
)# 使用代理询问今天的日期. 
# 注: 代理有时候可能会出错(该功能正在开发中)。如果出现错误,请尝试再次运行它。
agent("今天的日期是?") 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/899598.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

在MCU工程中优化CPU工作效率的几种方法

在嵌入式系统开发中&#xff0c;优化 CPU 工作效率对于提升系统性能、降低功耗、提高实时性至关重要。Keil 作为主流的嵌入式开发工具&#xff0c;提供了多种优化策略&#xff0c;包括 关键字使用、内存管理、字节对齐、算法优化 等。本文将从多个方面介绍如何在 Keil 工程中优…

Linux系统下C语言fork函数使用案例

一、fork函数的作用 生成一个子进程&#xff0c;异步执行某个任务&#xff1b; 二、子进程的作用 1、子进程能复制一份父进程的变量、函数&#xff1b; 2、子进程可以和父进程同时并发执行&#xff1b; 函数语法&#xff1a; pid_t fork() 说明&#xff1a;调用后返回一个进程…

MySQL中的CREATE TABLE LIKE和CREATE TABLE SELECT

MySQL中的CREATE TABLE LIKE和CREATE TABLE SELECT CREATE TABLE LIKECREATE TABLE SELECT CREATE TABLE LIKE CREATE TABLE ... LIKE可以用来复制表结构&#xff0c;源表上的索引和约束也会复制。CREATE TABLE ... LIKE不能复制表数据。CREATE TABLE ... LIKE只能复制基表&…

Java开发者指南:深入理解HotStuff新型共识算法

&#x1f9d1; 博主简介&#xff1a;CSDN博客专家、全栈领域优质创作者、高级开发工程师、高级信息系统项目管理师、系统架构师&#xff0c;数学与应用数学专业&#xff0c;10年以上多种混合语言开发经验&#xff0c;从事DICOM医学影像开发领域多年&#xff0c;熟悉DICOM协议及…

opencv图像处理之指纹验证

一、简介 在当今数字化时代&#xff0c;生物识别技术作为一种安全、便捷的身份验证方式&#xff0c;正广泛应用于各个领域。指纹识别作为生物识别技术中的佼佼者&#xff0c;因其独特性和稳定性&#xff0c;成为了众多应用场景的首选。今天&#xff0c;我们就来深入探讨如何利…

wfs.js之h264转码mp4分析

准备源文件 下载源文件 git clone https://github.com/ChihChengYang/wfs.js.git编译后得到wfs.js这个文件 调用 在demo/index.html中&#xff0c;前端对wfs.js进行了调用 var video1 document.getElementById("video1"), wfs new Wfs(); wfs.attachMedia…

协程 Coroutine

协程是 C20 引入的新特性。 文章目录 基本概念std::coroutine_handlepromise 类型co_yield 基本用法 优势异步 TCPco_await 基本概念 协程&#xff08;Coroutine&#xff09;是一种比线程更加轻量级的并发编程模型。协程的调度由程序员手动控制。 异步不是并行&#xff0c;但…

uniapp中的流式输出

一、完整代码展示 目前大多数的ai对话都是流式输出&#xff0c;也就是对话是一个字或者多个字逐一进行显示的下面是一个完整的流式显示程序&#xff0c;包含的用户的消息发出和ai的消息回复 <template><view class"chat-container"><view class&quo…

洛谷题单1-P5703 【深基2.例5】苹果采购-python-流程图重构

题目描述 现在需要采购一些苹果&#xff0c;每名同学都可以分到固定数量的苹果&#xff0c;并且已经知道了同学的数量&#xff0c;请问需要采购多少个苹果&#xff1f; 输入格式 输入两个不超过 1 0 9 10^9 109 正整数&#xff0c;分别表示每人分到的数量和同学的人数。 输…

JS 手撕题高频考点

前端面试中&#xff0c;JS 手撕题是高频考点&#xff0c;主要考察 编程能力、算法思维、JS 核心知识。以下是最常见的手撕题分类 代码示例&#xff1a; 目录 &#x1f4cc; 1. 手写函数柯里化&#x1f4cc; 2. 手写 debounce&#xff08;防抖&#xff09;&#x1f4cc; 3. 手写…

【STM32】知识点介绍一:硬件知识

文章目录 一、电源引脚简介二、电平信号三、电路分析 一、电源引脚简介 VCC、GND、VDD和VSS是电子电路中常见的术语&#xff0c;代表着不同的电源引脚或电压。 VCC&#xff08;Voltage at the Common Collector&#xff09;&#xff1a;VCC是指集电极&#xff08;Collector&am…

3. 列表元素替换

【问题描述】给定一个列表&#xff0c;将列表中所有的偶数替换为0 【输入形式】输入一行&#xff0c;包含若干个整数&#xff0c;用空格分隔 【输出形式】输出替换后的列表&#xff0c;每个元素用空格分隔 【样例输入】1 2 3 4 5 6 7 8 9 10 【样例输出】1 0 3 0 5 0 7 0 9…

问题的根源还是解题的方案

周末的早上照例是要早醒 debug 代码的&#xff0c;仿佛又回到了 2014 年… 古人几天甚至几个月不洗澡&#xff0c;不会臭吗&#xff1f;有没有可能古人没有化纤类衣服&#xff0c;且古人的纯天然生活环境其身体菌群和现代人不同&#xff0c;古人就像健康的野生动物一样即使不洗…

虚拟机安装linux系统无法上网的解决方法

在虚拟环境中运行Linux系统时&#xff0c;有时会遇到网络连接问题&#xff0c;特别是在使用虚拟机软件如VMware或VirtualBox时。本文将详细介绍一种针对“虚拟机安装Linux系统无法上网”问题的解决方案&#xff0c;以CentOS 6.5为例&#xff0c;适用于其他基于NAT模式的虚拟机环…

子网划分浅度解析

文章目录 ip地址的组成不同类型ip地址的范围子网掩码默认子网掩码子网掩码如何作用的&#xff1f;默认子网掩码怎么作用&#xff1f; ip地址的组成 ip地址一般写作4位点分十进制&#xff08;x.x.x.x&#xff09;&#xff0c;他们由32位二进制组成&#xff0c;每个x由8位二进制…

什么是 SEO(搜索引擎优化)?

您有网站吗&#xff0c;或者您正在考虑创建一个网站&#xff1f;您想吸引更多人加入您的业务吗&#xff1f;如果答案是肯定的&#xff0c;那么毫无疑问&#xff1a;SEO 应该是您营销工作的一部分。这是建立品牌和吸引用户访问您的网站的好方法。但它实际上意味着什么呢&#xf…

鸿蒙HarmonyOS NEXT设备升级应用数据迁移流程

数据迁移是什么 什么是数据迁移&#xff0c;对用户来讲就是本地数据的迁移&#xff0c;终端设备从HarmonyOS 3.1 Release API 9及之前版本&#xff08;单框架&#xff09;迁移到HarmonyOS NEXT&#xff08;双框架&#xff09;后保证本地数据不丢失。例如&#xff0c;我在某APP…

【现代深度学习技术】现代卷积神经网络04:含并行连接的网络(GoogLeNet)

【作者主页】Francek Chen 【专栏介绍】 ⌈ ⌈ ⌈PyTorch深度学习 ⌋ ⌋ ⌋ 深度学习 (DL, Deep Learning) 特指基于深层神经网络模型和方法的机器学习。它是在统计机器学习、人工神经网络等算法模型基础上&#xff0c;结合当代大数据和大算力的发展而发展出来的。深度学习最重…

【ESP32】ESP32与MQTT通信:实现传感器数据监测与设备控制

ESP32与MQTT通信 1 项目概览2 硬件组成3 MQTT协议解析MQTT协议简介MQTT核心概念本项目中的MQTT应用 4 MQTT Broker选择EMQX Broker其他常用MQTT Broker 5 代码解析初始化与配置MQTT消息处理发布传感器数据 6 MQTT话题TOPIC设计7 EMQX的优势在IoT项目中的体现8 MQTT通信流程9 应…

[特殊字符]《Curve DAO 系统学习目录》

本教程旨在系统学习 Curve DAO 项目的整体架构、核心机制、合约设计、治理逻辑与代币经济等内容&#xff0c;帮助开发者全面理解其设计理念及运作方式。 目录总览&#xff1a; 1. Curve 项目概览 • 1.1 Curve 是什么&#xff1f;主要解决什么问题&#xff1f; • 1.2 与其他…