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

本文涉及的产品
阿里云百炼推荐规格 ADB PostgreSQL,4核16GB 100GB 1个月
简介: LangChain-24 Agengts 通过TavilySearch Agent实现检索内容并回答 AgentExecutor转换Search 借助Prompt Tools工具

安装依赖

pip install -qU langchain-core langchain-openai
• 1

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.'}


相关实践学习
阿里云百炼xAnalyticDB PostgreSQL构建AIGC应用
通过该实验体验在阿里云百炼中构建企业专属知识库构建及应用全流程。同时体验使用ADB-PG向量检索引擎提供专属安全存储,保障企业数据隐私安全。
AnalyticDB PostgreSQL 企业智能数据中台:一站式管理数据服务资产
企业在数据仓库之上可构建丰富的数据服务用以支持数据应用及业务场景;ADB PG推出全新企业智能数据平台,用以帮助用户一站式的管理企业数据服务资产,包括创建, 管理,探索, 监控等; 助力企业在现有平台之上快速构建起数据服务资产体系
相关文章
|
2天前
LangChain-26 Custom Agent 自定义一个Agent并通过@tool绑定对应的工具 同时让大模型自己调用编写的@tools函数
LangChain-26 Custom Agent 自定义一个Agent并通过@tool绑定对应的工具 同时让大模型自己调用编写的@tools函数
11 1
LangChain-26 Custom Agent 自定义一个Agent并通过@tool绑定对应的工具 同时让大模型自己调用编写的@tools函数
|
3天前
|
搜索推荐 API
LangChain-16 Using Tools LangChain封装好的工具集tools
LangChain-16 Using Tools LangChain封装好的工具集tools
19 5
|
3天前
|
JSON 数据格式
LangChain-20 Document Loader 文件加载 加载MD DOCX EXCEL PPT PDF HTML JSON 等多种文件格式 后续可通过FAISS向量化 增强检索
LangChain-20 Document Loader 文件加载 加载MD DOCX EXCEL PPT PDF HTML JSON 等多种文件格式 后续可通过FAISS向量化 增强检索
14 2
|
3天前
LangChain-15 Manage Prompt Size 管理上下文大小,用Agent的方式询问问题,并去百科检索内容,总结后返回
LangChain-15 Manage Prompt Size 管理上下文大小,用Agent的方式询问问题,并去百科检索内容,总结后返回
16 2
|
2天前
|
机器学习/深度学习 存储 自然语言处理
LangChain-22 Text Embedding 续接21节 文本切分后 对文本进行embedding向量化处理 后续可保存到向量数据库后进行检索 从而扩展大模型的能力
LangChain-22 Text Embedding 续接21节 文本切分后 对文本进行embedding向量化处理 后续可保存到向量数据库后进行检索 从而扩展大模型的能力
7 0
|
2天前
|
机器学习/深度学习 JSON JavaScript
LangChain-21 Text Splitters 内容切分器 支持多种格式 HTML JSON md Code(JS/Py/TS/etc) 进行切分并输出 方便将数据进行结构化后检索
LangChain-21 Text Splitters 内容切分器 支持多种格式 HTML JSON md Code(JS/Py/TS/etc) 进行切分并输出 方便将数据进行结构化后检索
7 0
|
2月前
|
存储 人工智能
|
4天前
|
Python 机器学习/深度学习 人工智能
手把手教你从零开始构建并训练你的第一个强化学习智能体:深入浅出Agent项目实战,带你体验编程与AI结合的乐趣
【10月更文挑战第1天】本文通过构建一个简单的强化学习环境,演示了如何创建和训练智能体以完成特定任务。我们使用Python、OpenAI Gym和PyTorch搭建了一个基础的智能体,使其学会在CartPole-v1环境中保持杆子不倒。文中详细介绍了环境设置、神经网络构建及训练过程。此实战案例有助于理解智能体的工作原理及基本训练方法,为更复杂应用奠定基础。首先需安装必要库: ```bash pip install gym torch ``` 接着定义环境并与之交互,实现智能体的训练。通过多个回合的试错学习,智能体逐步优化其策略。这一过程虽从基础做起,但为后续研究提供了良好起点。
21 4
手把手教你从零开始构建并训练你的第一个强化学习智能体:深入浅出Agent项目实战,带你体验编程与AI结合的乐趣
|
24天前
|
人工智能 JSON 数据格式
RAG+Agent人工智能平台:RAGflow实现GraphRA知识库问答,打造极致多模态问答与AI编排流体验
【9月更文挑战第6天】RAG+Agent人工智能平台:RAGflow实现GraphRA知识库问答,打造极致多模态问答与AI编排流体验
RAG+Agent人工智能平台:RAGflow实现GraphRA知识库问答,打造极致多模态问答与AI编排流体验
|
27天前
|
人工智能 算法 自动驾驶
用AI自动设计智能体,数学提分25.9%,远超手工设计
【9月更文挑战第18天】《智能体自动设计(ADAS)》是由不列颠哥伦比亚大学等机构的研究者们发布的一篇关于自动化设计智能体系统的最新论文。研究中提出了一种创新算法——“Meta Agent Search”,此算法通过迭代生成并优化智能体设计,从而实现更高效的智能体系统构建。实验表明,相比人工设计的智能体,Meta Agent Search生成的智能体在多个领域均有显著的性能提升。然而,该方法也面临着实际应用中的有效性与鲁棒性等挑战。论文详细内容及实验结果可于以下链接查阅:https://arxiv.org/pdf/2408.08435。
74 12