2. 添加工具
https://langchain-ai.github.io/langgraph/tutorials/introduction/#part-2-enhancing-the-chatbot-with-tools
前面实现第一步,在LangGraph中跑起Deepseek大语言模型,并进行多轮对话以后呢,让我们再添加点其他东西,这就是官网教程的第二小节——使用工具加强聊天机器人
Tavily工具
from langchain_community.tools.tavily_search import TavilySearchResults
tool = TavilySearchResults(max_results=2)
tools = [tool]
tool.invoke("What's a 'node' in LangGraph?")
示例中(别忘了跟前面小节一样,为API_KEY设置环境变量),使用了TavilySearch这个工具,https://tavily.com/是一个搜索引擎AI工具,简单的说,就是根据你的提示词,在线帮你搜索理想的内容(无广告且精准),它会像百度或者谷歌一样,给以列出相关的结果,你可以在代码中打印出来。返回的结果是这样:
[{
'url': 'https://medium.com/@cplog/introduction-to-langgraph-a-beginners-guide-14f9be027141',
'content': 'Nodes: Nodes are the building blocks of your LangGraph. Each node represents a function or a computation step. You define nodes to perform specific tasks, such as processing input, making ...'},
{
'url': 'https://saksheepatil05.medium.com/demystifying-langgraph-a-beginner-friendly-dive-into-langgraph-concepts-5ffe890ddac0',
'content': 'Nodes (Tasks): Nodes are like the workstations on the assembly line. Each node performs a specific task on the product. In LangGraph, nodes are Python functions that take the current state, do some work, and return an updated state. Next, we define the nodes, each representing a task in our sandwich-making process.'}]
可以看出,它就跟搜索引擎一样,只不过更智能,且不需要打开浏览器,只需要去官网拿个API_KEY就可以用了,免费1000次,够你玩的了。LangGraph官方代码如下:
from langchain_community.tools.tavily_search import TavilySearchResults
tool = TavilySearchResults(max_results=2)
tools = [tool]
tool.invoke("What's a 'node' in LangGraph?")
运行python文件的小伙伴看着命令行,以为会打印一堆什么东西。这个工具的调用(invoke方法)可什么都不会吐。所以,把结果打出来看看,就知道它在干嘛了:
import getpass
import os
def _set_env(var: str):
print(f"Checking if {
var} is set...")
if not os.environ.get(var):
print(f"{
var} is not set, prompting user for input.")
os.environ[var] = getpass.getpass(f"{
var}: ")
print(f"{
var} has been set.{
os.environ.get(var)}")
else:
print(f"{
var} is already set to: {
os.environ[var]}")
# 命令行中需要你输入你的tavily api-key: tvly-dev-xxxxxxxxxxxxxxxxx
_set_env("TAVILY_API_KEY")
from langchain_community.tools.tavily_search import TavilySearchResults
tool = TavilySearchResults(max_results=2)
tools = [tool]
print(tools)
# tool.invoke("What's a 'node' in LangGraph?")
# 执行搜索并打印结果
question = "What's a 'node' in LangGraph?"
print(f"\nQuestion: {
question}")
try:
result = tool.invoke(question)
# 格式化输出结果
print("\nSearch Results:")
for i, item in enumerate(result, 1):
print(f"Result {
i}:")
print(f"Title: {
item.get('title', 'N/A')}")
print(f"URL: {
item.get('url', 'N/A')}")
print(f"Content: {
item.get('content', 'N/A')[:200]}...") # 截断内容前200字符
print("-" * 50)
except Exception as e:
print(f"Error occurred: {
str(e)}")
跑起来看到结果:
Question: What's a 'node' in LangGraph?
Search Results:
Result 1:
Title: N/A
URL: https://medium.com/@kbdhunga/beginners-guide-to-langgraph-understanding-state-nodes-and-edges-part-1-897e6114fa48
Content: Beginner’s Guide to LangGraph: Understanding State, Nodes, and Edges — Part 1 | by Kamal Dhungana | Medium Beginner’s Guide to LangGraph: Understanding State, Nodes, and Edges — Part 1 LangGraph — Sta...
--------------------------------------------------
Result 2:
Title: N/A
URL: https://blog.langchain.dev/langgraph/
Content: TL;DR: LangGraph is module built on top of LangChain to better enable creation of cyclical graphs, often needed for agent runtimes. This state is updated by nodes in the graph, which return operations...
--------------------------------------------------
看,这就跟你使用百度等搜索引擎一样,返回结果和链接,只不过这些结果是经过AI筛选的,直接从页面中抽取的内容,觉得比搜索引擎还要智能一些。不过,Tavily的服务还是要科学上网的。。。
其实看引入包就知道langchain_community.tools非常重要。这里面的工具(很多工具都是谷歌微软这种大厂定制开发的)基本构建了整个LangGraph的生态,里面有啥可以用,基本就决定了LangGraph的格局,只是对国内开发者不是很友好。
开始吧,官方demo
import getpass
import os
# 1. 命令行中输入Tavily的API key
def _set_env(var: str):
print(f"Checking if {
var} is set...")
if not os.environ.get(var):
print(f"{
var} is not set, prompting user for input.")
os.environ[var] = getpass.getpass(f"{
var}: ")
print(f"{
var} has been set.{
os.environ.get(var)}


1297

被折叠的 条评论
为什么被折叠?



