大模型架構記錄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.pswp.cn/news/899598.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/899598.shtml
英文地址,請注明出處:http://en.pswp.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 與其他…