最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python?langchain?ReAct?使用范例詳解

 更新時(shí)間:2024年12月21日 16:12:12   作者:愛(ài)學(xué)習(xí)的小道長(zhǎng)  
這篇文章主要介紹了Python?langchain?ReAct?使用范例,本文給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧

0. 介紹

ReAct: Reasoning + Acting ,ReAct Prompt 由 few-shot task-solving trajectories 組成,包括人工編寫(xiě)的文本推理過(guò)程和動(dòng)作,以及對(duì)動(dòng)作的環(huán)境觀察。

1. 范例

langchain version 0.3.7

$ pip show langchain
Name: langchain
Version: 0.3.7
Summary: Building applications with LLMs through composability
Home-page: https://github.com/langchain-ai/langchain
Author: 
Author-email: 
License: MIT
Location: /home/xjg/.conda/envs/langchain/lib/python3.10/site-packages
Requires: aiohttp, async-timeout, langchain-core, langchain-text-splitters, langsmith, numpy, pydantic, PyYAML, requests, SQLAlchemy, tenacity
Required-by: langchain-community

1.1 使用第三方工具

Google 搜索對(duì)接
第三方平臺(tái):https://serpapi.com
LangChain API 封裝:SerpAPI

1.1.1 簡(jiǎn)單使用工具

from langchain_community.utilities import SerpAPIWrapper
import os
# 刪除all_proxy環(huán)境變量
if 'all_proxy' in os.environ:
    del os.environ['all_proxy']
# 刪除ALL_PROXY環(huán)境變量
if 'ALL_PROXY' in os.environ:
    del os.environ['ALL_PROXY']
os.environ["SERPAPI_API_KEY"] = "xxx"
params = {
    "engine": "bing",
    "gl": "us",
    "hl": "en",
}
search = SerpAPIWrapper(params=params)
result = search.run("Obama's first name?")
print(result)

輸出結(jié)果:

['In 1975, when Obama started high school in Hawaii, teacher Eric Kusunoki read the roll call and stumbled on Obama\'s first name. "Is Barack here?" he asked, pronouncing it BAR-rack .', "Barack Obama, the 44th president of the United States, was born on August 4, 1961, in Honolulu, Hawaii to Barack Obama, Sr. (1936–1982) (born in Oriang' Kogelo of Rachuonyo North District, Kenya) and Stanley Ann Dunham, known as Ann (1942–1995) (born in Wichita, Kansas, United States). Obama spent most of his childhood years in Honolulu, where his mother attended the University of Hawai?i at Mānoa", 'Barack Obama is named after his father, who was a Kenyan economist (called under the same name). He’s first real given name is “Barak”, also spelled Baraq (Not to be confused with Barack which is is a building or group of buildings …', 'Nevertheless, he was proud enough of his formal name that after he and Ann Dunham married in 1961, they named their son, Barack Hussein Obama II. As a youngster, the former president likely never...', 'https://www.britannica.com/biography/Barack-Obama', 'The name Barack means "one who is blessed" in Swahili. Obama was the first African-American U.S. president. Obama was the first president born outside of the contiguous United States. Obama was the eighth left-handed …', 'Barack Obama is the first Black president of the United States. Learn facts about him: his age, height, leadership legacy, quotes, family, and more.', 'Barack and Ann’s son, Barack Hussein Obama Jr., was born in Honolulu on August 4, 1961. Did you know? Not only was Obama the first African American president, he was also the first to be...', "President Obama's full name is Barack Hussein Obama. His full, birth name is Barack Hussein Obama, II. He was named after his father, Barack Hussein Obama, Sr., who …", 'When Barack Obama was elected president in 2008, he became the first African American to hold the office. The framers of the Constitution always hoped that our leadership would not be limited...']

1.1.2 使用第三方工具時(shí)ReAct

提示詞 hwchase17/self-ask-with-search

from langchain_community.utilities import SerpAPIWrapper
from langchain.agents import create_self_ask_with_search_agent, AgentType,Tool,AgentExecutor
from langchain import hub
from langchain_openai import ChatOpenAI
import os
from dotenv import load_dotenv, find_dotenv
# 刪除all_proxy環(huán)境變量
if 'all_proxy' in os.environ:
    del os.environ['all_proxy']
# 刪除ALL_PROXY環(huán)境變量
if 'ALL_PROXY' in os.environ:
    del os.environ['ALL_PROXY']
_ = load_dotenv(find_dotenv())
os.environ["SERPAPI_API_KEY"] = "xxx"
chat_model = ChatOpenAI(model="gpt-4o-mini", temperature=0)
# 實(shí)例化查詢工具
search = SerpAPIWrapper()
tools = [
    Tool(
        name="Intermediate Answer",
        func=search.run,
        description="useful for when you need to ask with search",
    )
]
prompt = hub.pull("hwchase17/self-ask-with-search")
self_ask_with_search = create_self_ask_with_search_agent(
     chat_model,tools,prompt
)
agent_executor = AgentExecutor(agent=self_ask_with_search, tools=tools,verbose=True,handle_parsing_errors=True)
reponse = agent_executor.invoke({"input": "成都舉辦的大運(yùn)會(huì)是第幾屆大運(yùn)會(huì)?2023年大運(yùn)會(huì)舉辦地在哪里?"})
print(reponse)
print(chat_model.invoke("成都舉辦的大運(yùn)會(huì)是第幾屆大運(yùn)會(huì)?").content)
print(chat_model.invoke("2023年大運(yùn)會(huì)舉辦地在哪里?").content)

輸出:

> Entering new AgentExecutor chain...
Could not parse output: Yes.  
Follow up: 成都舉辦的大運(yùn)會(huì)是由哪個(gè)組織舉辦的?  

1. **成都舉辦的大運(yùn)會(huì)是第幾屆大運(yùn)會(huì)?**
   - The 2023 Chengdu Universiade was the 31st Summer Universiade.

2. **2023年大運(yùn)會(huì)舉辦地在哪里?**
   - The 2023 Summer Universiade was held in Chengdu, China.

So the final answers are:
- 成都舉辦的大運(yùn)會(huì)是第31屆大運(yùn)會(huì)。
- 2023年大運(yùn)會(huì)舉辦地是成都,China。

如果你還有其他問(wèn)題或需要進(jìn)一步的澄清,請(qǐng)隨時(shí)問(wèn)我!
For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILUREInvalid or incomplete response

> Finished chain.
{'input': '成都舉辦的大運(yùn)會(huì)是第幾屆大運(yùn)會(huì)?2023年大運(yùn)會(huì)舉辦地在哪里?', 'output': '31屆,成都,China'}
成都舉辦的世界大學(xué)生運(yùn)動(dòng)會(huì)是第31屆大運(yùn)會(huì)。該屆大運(yùn)會(huì)于2023年在中國(guó)成都舉行。
2023年大運(yùn)會(huì)(世界大學(xué)生運(yùn)動(dòng)會(huì))將于2023年在中國(guó)成都舉辦。

1.2 使用langchain內(nèi)置的工具

hwchase17/react

from langchain.agents import create_react_agent, AgentType,Tool,AgentExecutor
from langchain import hub
from langchain_community.agent_toolkits.load_tools import load_tools
from langchain.prompts import PromptTemplate
from dotenv import load_dotenv, find_dotenv
from langchain_openai import ChatOpenAI
import os
# 刪除all_proxy環(huán)境變量
if 'all_proxy' in os.environ:
    del os.environ['all_proxy']
# 刪除ALL_PROXY環(huán)境變量
if 'ALL_PROXY' in os.environ:
    del os.environ['ALL_PROXY']
_ = load_dotenv(find_dotenv())
os.environ["SERPAPI_API_KEY"] = "xxx"
chat_model = ChatOpenAI(model="gpt-4o-mini", temperature=0)
prompt = hub.pull("hwchase17/react")
tools = load_tools(["serpapi", "llm-math"], llm=chat_model)
agent = create_react_agent(chat_model, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools,verbose=True)
reponse =agent_executor.invoke({"input": "誰(shuí)是萊昂納多·迪卡普里奧的女朋友?她現(xiàn)在年齡的0.43次方是多少?"})
print(reponse)

輸出:

> Entering new AgentExecutor chain...
我需要先找到萊昂納多·迪卡普里奧目前的女朋友是誰(shuí),然后獲取她的年齡以計(jì)算年齡的0.43次方。  
Action: Search  
Action Input: "Leonardo DiCaprio girlfriend 2023"  
Vittoria Ceretti我找到萊昂納多·迪卡普里奧的女朋友是維多利亞·切雷提(Vittoria Ceretti)。接下來(lái),我需要找到她的年齡以計(jì)算0.43次方。  
Action: Search  
Action Input: "Vittoria Ceretti age 2023"  

About 25 years維多利亞·切雷提(Vittoria Ceretti)大約25歲。接下來(lái),我將計(jì)算25的0.43次方。  
Action: Calculator  
Action Input: 25 ** 0.43  

Answer: 3.991298452658078我現(xiàn)在知道最終答案  
Final Answer: 萊昂納多·迪卡普里奧的女朋友是維多利亞·切雷提,她的年齡0.43次方約為3.99。

> Finished chain.
{'input': '誰(shuí)是萊昂納多·迪卡普里奧的女朋友?她現(xiàn)在年齡的0.43次方是多少?', 'output': '萊昂納多·迪卡普里奧的女朋友是維多利亞·切雷提,她的年齡0.43次方約為3.99。'}

1.3 使用自定義的工具

hwchase17/openai-functions-agent

1.3.1 簡(jiǎn)單使用

from langchain_openai import ChatOpenAI
from  langchain.agents import tool,AgentExecutor,create_openai_functions_agent
from langchain import hub
import os
from dotenv import load_dotenv, find_dotenv
# 刪除all_proxy環(huán)境變量
if 'all_proxy' in os.environ:
    del os.environ['all_proxy']
# 刪除ALL_PROXY環(huán)境變量
if 'ALL_PROXY' in os.environ:
    del os.environ['ALL_PROXY']
_ = load_dotenv(find_dotenv())
chat_model = ChatOpenAI(model="gpt-4o-mini",temperature=0)
@tool
def get_word_length(word: str) -> int:
    """Returns the length of a word."""
    return len(word)
tools = [get_word_length]
prompt = hub.pull("hwchase17/openai-functions-agent")
agent = create_openai_functions_agent(llm=chat_model, tools=tools, prompt=prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True,handle_parsing_errors=True)
agent_executor.invoke({"input": "單詞“educati”中有多少個(gè)字母?"})

輸出:

> Entering new AgentExecutor chain...

Invoking: `get_word_length` with `{'word': 'educati'}`

7單詞“educati”中有7個(gè)字母。

> Finished chain.

1.3.1 帶有記憶功能

from langchain_openai import ChatOpenAI
from  langchain.agents import tool,AgentExecutor,create_openai_functions_agent
from langchain_core.prompts.chat import ChatPromptTemplate
from langchain.prompts import MessagesPlaceholder
from langchain.memory import ConversationBufferMemory
from langchain import hub
import os
from dotenv import load_dotenv, find_dotenv
# 刪除all_proxy環(huán)境變量
if 'all_proxy' in os.environ:
    del os.environ['all_proxy']
# 刪除ALL_PROXY環(huán)境變量
if 'ALL_PROXY' in os.environ:
    del os.environ['ALL_PROXY']
_ = load_dotenv(find_dotenv())
chat_model = ChatOpenAI(model="gpt-4o-mini",temperature=0)
@tool
def get_word_length(word: str) -> int:
    """Returns the length of a word."""
    return len(word)
tools = [get_word_length]
prompt = ChatPromptTemplate.from_messages(
    [
        ("placeholder", "{chat_history}"),
        ("human", "{input}"),
        ("placeholder", "{agent_scratchpad}"),
    ]
)
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
agent = create_openai_functions_agent(llm=chat_model, tools=tools, prompt=prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, memory=memory, verbose=True)
agent_executor.invoke({"input":"單詞“educati”中有多少個(gè)字母?"})
agent_executor.invoke({"input":"那是一個(gè)真實(shí)的單詞嗎?"})

輸出:

> Entering new AgentExecutor chain...

Invoking: `get_word_length` with `{'word': 'educati'}`

7

單詞“educati”中有7個(gè)字母。

> Finished chain.

> Entering new AgentExecutor chain...
“educati”并不是一個(gè)標(biāo)準(zhǔn)的英語(yǔ)單詞。它可能是“education”的一個(gè)變形或拼寫(xiě)錯(cuò)誤。標(biāo)準(zhǔn)英語(yǔ)中的相關(guān)詞是“education”,意為“教育”。

> Finished chain.

2. 參考

LangChain Hub https://smith.langchain.com/hub/
LangChain https://python.langchain.com/docs/introduction/
DevAGI開(kāi)放平臺(tái) https://devcto.com/

到此這篇關(guān)于Python langchain ReAct 使用范例的文章就介紹到這了,更多相關(guān)Python langchain ReAct 使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 利用?Python?開(kāi)發(fā)一個(gè)?Python?解釋器

    利用?Python?開(kāi)發(fā)一個(gè)?Python?解釋器

    這篇文章主要介紹了利用?Python?開(kāi)發(fā)一個(gè)?Python?解釋器,在本文中,我們將設(shè)計(jì)一個(gè)可以執(zhí)行算術(shù)運(yùn)算的解釋器。下面我們大家一起來(lái)看看吧</P><P>
    2022-01-01
  • Python+OpenCV實(shí)現(xiàn)邊緣檢測(cè)與角點(diǎn)檢測(cè)詳解

    Python+OpenCV實(shí)現(xiàn)邊緣檢測(cè)與角點(diǎn)檢測(cè)詳解

    這篇文章主要為大家詳細(xì)介紹了如何通過(guò)Python+OpenCV實(shí)現(xiàn)邊緣檢測(cè)與角點(diǎn)檢測(cè),文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Python與OpenCV有一定的幫助,需要的可以參考一下
    2023-02-02
  • 全面理解Python中self的用法

    全面理解Python中self的用法

    Python中看到或使用self時(shí)一定要弄明白self的指代,這里就帶大家來(lái)全面理解Python中self的用法,需要的朋友可以參考下
    2016-06-06
  • Pandas遍歷DataFrame每一行的多種方法

    Pandas遍歷DataFrame每一行的多種方法

    Pandas遍歷DataFrame有多種方法:iterrows(返回Series,適合需索引)、itertuples(命名元組,高性能)、apply(向量化計(jì)算)、df.values(最快但無(wú)列名),最佳實(shí)踐是優(yōu)先使用向量化操作,避免逐行遍歷,大數(shù)據(jù)推薦dask或swifter加速,下面由小編給大家詳細(xì)說(shuō)說(shuō)
    2025-09-09
  • PyPy?如何讓Python代碼運(yùn)行得和C一樣快

    PyPy?如何讓Python代碼運(yùn)行得和C一樣快

    這篇文章主要介紹了如何讓Python代碼運(yùn)行得和C一樣快,由于?PyPy?只是?Python?的一種替代實(shí)現(xiàn),大多數(shù)時(shí)候它都是開(kāi)箱即用,無(wú)需對(duì)?Python?項(xiàng)目進(jìn)行任何更改。它與?Web?框架?Django、科學(xué)計(jì)算包?Numpy?和許多其他包完全兼容,推薦大家多多使用
    2022-01-01
  • 解決pyecharts運(yùn)行后產(chǎn)生的html文件用瀏覽器打開(kāi)空白

    解決pyecharts運(yùn)行后產(chǎn)生的html文件用瀏覽器打開(kāi)空白

    這篇文章主要介紹了解決pyecharts運(yùn)行后產(chǎn)生的html文件用瀏覽器打開(kāi)空白,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-03-03
  • python命令行參數(shù)解析OptionParser類(lèi)用法實(shí)例

    python命令行參數(shù)解析OptionParser類(lèi)用法實(shí)例

    這篇文章主要介紹了python命令行參數(shù)解析OptionParser類(lèi)用法實(shí)例,需要的朋友可以參考下
    2014-10-10
  • 詳解Python中httptools模塊的使用

    詳解Python中httptools模塊的使用

    httptools?是一個(gè)?HTTP?解析器,它首先提供了一個(gè)?parse_url?函數(shù),用來(lái)解析?URL。這篇文章就來(lái)和大家聊聊它的用法吧,感興趣的可以了解一下
    2023-03-03
  • 基于Python編寫(xiě)簡(jiǎn)單實(shí)用的日志裝飾器

    基于Python編寫(xiě)簡(jiǎn)單實(shí)用的日志裝飾器

    在寫(xiě)代碼的時(shí)候,往往會(huì)漏掉日志這個(gè)關(guān)鍵因素,導(dǎo)致功能在使用的時(shí)候出錯(cuò)卻無(wú)法溯源。這個(gè)時(shí)候只要利用日志裝飾器就能解決,本文將用Python自制一個(gè)簡(jiǎn)單實(shí)用的日志裝飾器,需要的可以參考一下
    2022-05-05
  • Django在Model保存前記錄日志實(shí)例

    Django在Model保存前記錄日志實(shí)例

    這篇文章主要介紹了Django在Model保存前記錄日志實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-05-05

最新評(píng)論

阳原县| 米林县| 新宾| 昂仁县| 屯留县| 集贤县| 全南县| 确山县| 平南县| 万宁市| 柳州市| 保定市| 安达市| 中阳县| 张掖市| 富宁县| 靖江市| 南通市| 涡阳县| 南投市| 喜德县| 金坛市| 昔阳县| 仁寿县| 金阳县| 来安县| 台东县| 会东县| 信丰县| 炉霍县| 固阳县| 谢通门县| 黑山县| 西贡区| 诸城市| 民乐县| 宣城市| 北安市| 伊川县| 西充县| 凤庆县|