LangChain-24 Agengts 通过TavilySearch Agent实现检索内容并回答 AgentExecutor转换Search 借助Prompt Tools工具

本文介绍了如何在Python中使用Langchain库进行文档检索,加载Web内容,配置OpenAIEmbeddings,并集成GPT-3.5-turbo模型进行问答。展示了如何创建代理执行器来处理用户查询并获取相关信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

请添加图片描述

安装依赖

pip install -qU langchain-core langchain-openai

Prompt

# 从Hub加载Prompt,自己写加载进来也一样
# SYSTEM
#
# You are a helpful assistant
#
# PLACEHOLDER
#
# chat_history
# HUMAN
#
# {input}
#
# PLACEHOLDER
#

编写代码

from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_community.document_loaders import WebBaseLoader
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain.tools.retriever import create_retriever_tool
from langchain_openai import ChatOpenAI
from langchain.agents import create_openai_functions_agent
from langchain.agents import AgentExecutor
from langchain import hub


# 这里需要配置KEY 免费
search = TavilySearchResults()
# message1 = search.invoke("what is the weather in SF")
# print(f"message1: {message1}")

loader = 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()
result1 = retriever.get_relevant_documents("how to upload a dataset")[0]
print(f"result1: {result1}")

# 转换为工具
retriever_tool = create_retriever_tool(
    retriever,
    "langsmith_search",
    "Search for information about LangSmith. For any questions about LangSmith, you must use this tool!",
)

# 定义工具
tools = [search, retriever_tool]
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)

# 从Hub加载Prompt,自己写加载进来也一样
# SYSTEM
#
# You are a helpful assistant
#
# PLACEHOLDER
#
# chat_history
# HUMAN
#
# {input}
#
# PLACEHOLDER
#
# agent_scratchpad
prompt = hub.pull("hwchase17/openai-functions-agent")
print(f"prompt message: {prompt.messages}")

# 新建Agent
agent = create_openai_functions_agent(llm, tools, prompt)
# Agent执行器
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# 尝试执行
message2 = agent_executor.invoke({"input": "hi!"})
print(f"message2: {message2}")

# 执行任务
message3 = agent_executor.invoke({"input": "how can langsmith help with testing?"})
print(f"message3: {message3}")


运行结果

➜ python3 test24.py
result1: page_content="about LangSmith:User Guide: Learn about the workflows LangSmith supports at each stage of the LLM application lifecycle.Setup: Learn how to create an account, obtain an API key, and configure your environment.Pricing: Learn about the pricing model for LangSmith.Self-Hosting: Learn about self-hosting options for LangSmith.Proxy: Learn about the proxy capabilities of LangSmith.Tracing: Learn about the tracing capabilities of LangSmith.Evaluation: Learn about the evaluation capabilities of LangSmith.Prompt Hub Learn about the Prompt Hub, a prompt management tool built into LangSmith.Additional Resources\u200bLangSmith Cookbook: A collection of tutorials and end-to-end walkthroughs using LangSmith.LangChain Python: Docs for the Python LangChain library.LangChain Python API Reference: documentation to review the core APIs of LangChain.LangChain JS: Docs for the TypeScript LangChain libraryDiscord: Join us on our Discord to discuss all things LangChain!Contact SalesIf you're interested in" metadata={'source': 'https://docs.smith.langchain.com/overview', 'title': 'LangSmith | 🦜️🛠️ LangSmith', 'description': 'Introduction', 'language': 'en'}
prompt message: [SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], template='You are a helpful assistant')), MessagesPlaceholder(variable_name='chat_history', optional=True), HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input'], template='{input}')), MessagesPlaceholder(variable_name='agent_scratchpad')]


> Entering new AgentExecutor chain...
Hello! How can I assist you today?

> Finished chain.
message2: {'input': 'hi!', 'output': 'Hello! How can I assist you today?'}


> Entering new AgentExecutor chain...
LangSmith is a search engine that can help you find information about testing. You can use it to search for best practices, testing frameworks, testing tools, and other resources related to testing. Additionally, LangSmith can help you find answers to specific questions you may have about testing. For example, you can search for information on how to write effective test cases, how to automate testing, or how to perform load testing. By using LangSmith, you can save time and effort in your testing efforts by quickly finding the information you need.

> Finished chain.
message3: {'input': 'how can langsmith help with testing?', 'output': 'LangSmith is a search engine that can help you find information about testing. You can use it to search for best practices, testing frameworks, testing tools, and other resources related to testing. Additionally, LangSmith can help you find answers to specific questions you may have about testing. For example, you can search for information on how to write effective test cases, how to automate testing, or how to perform load testing. By using LangSmith, you can save time and effort in your testing efforts by quickly finding the information you need.'}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

武子康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值