跳转到主要内容

LinkupSearchTool

Linkup 提供了一个 API,用于将 LLM 连接到 Web 和 Linkup Premium Partner 资源。

本笔记本提供了使用 LinkupSearchTool 工具的快速入门概述。 有关 LinkupSearchTool 所有特性和配置的详细文档,请访问API 参考

概述

集成细节

可序列化JS 支持最新包
LinkupSearchToollangchain-linkupPyPI - Version

设置

要使用 Linkup 提供程序,您需要一个有效的 API 密钥,您可以通过在此处注册 注册 来找到它。 要运行以下示例,您还需要一个 OpenAI API 密钥。

安装

此工具位于 langchain-linkup 包中

%pip install -qU langchain-linkup

凭据

import getpass
import os

# if not os.environ.get("LINKUP_API_KEY"):
# os.environ["LINKUP_API_KEY"] = getpass.getpass("LINKUP API key:\n")

设置 LangSmith 以获得一流的可观察性也很有帮助(但不是必需的)

# os.environ["LANGCHAIN_TRACING_V2"] = "true"
# os.environ["LANGCHAIN_API_KEY"] = getpass.getpass()

实例化

这里我们展示了如何实例化 LinkupSearchTool 工具的一个实例,其中

from langchain_linkup import LinkupSearchTool

tool = LinkupSearchTool(
depth="deep", # "standard" or "deep"
output_type="searchResults", # "searchResults", "sourcedAnswer" or "structured"
linkup_api_key=None, # API key can be passed here or set as the LINKUP_API_KEY environment variable
)

调用

使用 args 直接调用

该工具仅接受一个 query,它是一个字符串。

tool.invoke({"query": "Who won the latest US presidential elections?"})
LinkupSearchResults(results=[LinkupSearchResult(name='US presidential election results 2024: Harris vs. Trump | Live maps ...', url='https://www.reuters.com/graphics/USA-ELECTION/RESULTS/zjpqnemxwvx/', content='Updated results from the 2024 election for the US president. Reuters live coverage of the 2024 US President, Senate, House and state governors races.'), LinkupSearchResult(name='Election 2024: Presidential results - CNN', url='https://www.cnn.com/election/2024/results/president', content='View maps and real-time results for the 2024 US presidential election matchup between former President Donald Trump and Vice President Kamala Harris. For more ...'), LinkupSearchResult(name='Presidential Election 2024 Live Results: Donald Trump wins - NBC News', url='https://www.nbcnews.com/politics/2024-elections/president-results', content='View live election results from the 2024 presidential race as Kamala Harris and Donald Trump face off. See the map of votes by state as results are tallied.'), LinkupSearchResult(name='Live: Presidential Election Results 2024 : NPR', url='https://apps.npr.org/2024-election-results/', content='Presidential race ratings are based on NPR analysis. Maps do not shade in until 50% of the estimated vote is in for a given state, to mitigate flutuations in early returns . 2024 General Election Results'), LinkupSearchResult(name='2024 US Presidential Election Results: Live Map - Bloomberg.com', url='https://www.bloomberg.com/graphics/2024-us-election-results/', content='US Presidential Election Results November 5, 2024. Bloomberg News is reporting live election results in the presidential race between Democratic Vice President Kamala Harris and her Republican ...'), LinkupSearchResult(name='US Presidential Election Results 2024 - BBC News', url='https://www.bbc.com/news/election/2024/us/results', content='Kamala Harris of the Democrat party has 74,470,899 votes (48.3%) Donald Trump of the Republican party has 76,971,602 votes (49.9%) This map of the US states was filled in as presidential results ...'), LinkupSearchResult(name='Election Results 2024: Live Map - Races by State - POLITICO', url='https://www.politico.com/2024-election/results/', content='Live 2024 election results and maps by state. POLITICO’s real-time coverage of 2024 races for President, Senate, House and Governor.'), LinkupSearchResult(name='Presidential Election Results 2024: Electoral Votes & Map by State ...', url='https://www.politico.com/2024-election/results/president/', content='Live 2024 Presidential election results, maps and electoral votes by state. POLITICO’s real-time coverage of 2024 races for President, Senate, House and Governor.'), LinkupSearchResult(name='2024 US Presidential Election Results: Live Map - ABC News', url='https://abcnews.go.com/Elections/2024-us-presidential-election-results-live-map/', content='View live updates on electoral votes by state for presidential candidates Joe Biden and Donald Trump on ABC News. Senate, House, and Governor Election results also available at ABCNews.com'), LinkupSearchResult(name='US Presidential Election Results 2024 - BBC News', url='https://www.bbc.co.uk/news/election/2024/us/results', content='Follow the 2024 US presidential election results as they come in with BBC News. Find out if Trump or Harris is ahead as well as detailed state-by-state results.'), LinkupSearchResult(name='Presidential Election 2024 Live Results: Donald Trump winsNBC News LogoSearchSearchNBC News LogoMSNBC LogoToday Logo', url='https://www.nbcnews.com/politics/2024-elections/president-results', content="Profile\n\nSections\n\nLocal\n\ntv\n\nFeatured\n\nMore From NBC\n\nFollow NBC News\n\nnews Alerts\n\nThere are no new alerts at this time\n\n2024 President Results: Trump wins\n==================================\n\nDonald Trump has secured more than the 270 Electoral College votes needed to secure the presidency, NBC News projects.\n\nRaces to watch\n--------------\n\nAll Presidential races\n----------------------\n\nElection Night Coverage\n-----------------------\n\n### China competition should be top priority for Trump, Sullivan says, as Biden and Xi prepare for final meeting\n\n### Jim Himes says 'truth and analysis are not what drive’ Gabbard and Gaetz\n\n### Trump praises RFK Jr. in Mar-a-Lago remarks\n\n### Trump announces North Dakota Gov. Doug Burgum as his pick for interior secretary\n\n### House Ethics Committee cancels meeting at which Gaetz probe was on the agenda\n\n### Trump picks former Rep. Doug Collins for veterans affairs secretary\n\n### Trump to nominate his criminal defense lawyer for deputy attorney general\n\n### From ‘brilliant’ to ‘dangerous’: Mixed reactions roll in after Trump picks RFK Jr. for top health post\n\n### Donald Trump Jr. says he played key role in RFK Jr., Tulsi Gabbard picks\n\n### Jared Polis offers surprising words of support for RFK Jr. pick for HHS secretary\n\nNational early voting\n---------------------\n\n### 88,233,886 mail-in and early in-person votes cast nationally\n\n### 65,676,748 mail-in and early in-person votes requested nationally\n\nPast Presidential Elections\n---------------------------\n\n### Vote Margin by State in the 2020 Presidential Election\n\nCircle size represents the number electoral votes in that state.\n\nThe expected vote is the total number of votes that are expected in a given race once all votes are counted. This number is an estimate and is based on several different factors, including information on the number of votes cast early as well as information provided to our vote reporters on Election Day from county election officials. The figure can change as NBC News gathers new information.\n\n**Source**: [National Election Pool (NEP)](https://www.nbcnews.com/politics/2024-elections/how-election-data-is-collected )\n\n2024 election results\n---------------------\n\nElection Night Coverage\n-----------------------\n\n### China competition should be top priority for Trump, Sullivan says, as Biden and Xi prepare for final meeting\n\n### Jim Himes says 'truth and analysis are not what drive’ Gabbard and Gaetz\n\n### Trump praises RFK Jr. in Mar-a-Lago remarks\n\n©\xa02024 NBCUniversal Media, LLC")])

使用 ToolCall 调用

我们还可以使用模型生成的 ToolCall 调用该工具,在这种情况下,将返回一个 ToolMessage

# This is usually generated by a model, but we'll create a tool call directly for demo purposes.
model_generated_tool_call = {
"args": {"query": "Who won the latest US presidential elections?"},
"id": "1",
"name": tool.name,
"type": "tool_call",
}
tool.invoke(model_generated_tool_call)
ToolMessage(content='results=[LinkupSearchResult(name=\'US presidential election results 2024: Harris vs. Trump | Live maps ...\', url=\'https://www.reuters.com/graphics/USA-ELECTION/RESULTS/zjpqnemxwvx/\', content=\'Updated results from the 2024 election for the US president. Reuters live coverage of the 2024 US President, Senate, House and state governors races.\'), LinkupSearchResult(name=\'Election 2024: Presidential results - CNN\', url=\'https://www.cnn.com/election/2024/results/president\', content=\'View maps and real-time results for the 2024 US presidential election matchup between former President Donald Trump and Vice President Kamala Harris. For more ...\'), LinkupSearchResult(name=\'Presidential Election 2024 Live Results: Donald Trump wins - NBC News\', url=\'https://www.nbcnews.com/politics/2024-elections/president-results\', content=\'View live election results from the 2024 presidential race as Kamala Harris and Donald Trump face off. See the map of votes by state as results are tallied.\'), LinkupSearchResult(name=\'2024 US Presidential Election Results: Live Map - Bloomberg.com\', url=\'https://www.bloomberg.com/graphics/2024-us-election-results/\', content=\'US Presidential Election Results November 5, 2024. Bloomberg News is reporting live election results in the presidential race between Democratic Vice President Kamala Harris and her Republican ...\'), LinkupSearchResult(name=\'US Presidential Election Results 2024 - BBC News\', url=\'https://www.bbc.com/news/election/2024/us/results\', content=\'Kamala Harris of the Democrat party has 74,498,303 votes (48.3%) Donald Trump of the Republican party has 76,989,499 votes (49.9%) This map of the US states was filled in as presidential results ...\'), LinkupSearchResult(name=\'Presidential Election Results 2024: Electoral Votes & Map by State ...\', url=\'https://www.politico.com/2024-election/results/president/\', content=\'Live 2024 Presidential election results, maps and electoral votes by state. POLITICO’s real-time coverage of 2024 races for President, Senate, House and Governor.\'), LinkupSearchResult(name=\'2024 U.S. Election: Live Results and Maps - USA TODAY\', url=\'https://www.usatoday.com/elections/results/2024-11-05\', content=\'See who is winning races in the Nov. 5, 2024 U.S. Election with real-time results and state-by-state maps.\'), LinkupSearchResult(name=\'Donald Trump wins US presidency - US election 2024 complete results map\', url=\'https://www.aljazeera.com/us-election-2024/results/\', content=\'Complete, state-by-state breakdown of the 2024 US presidential, Senate, House and Governor results\'), LinkupSearchResult(name=\'US Presidential Election Results 2024 - BBC News\', url=\'https://www.bbc.co.uk/news/election/2024/us/results\', content=\'Follow the 2024 US presidential election results as they come in with BBC News. Find out if Trump or Harris is ahead as well as detailed state-by-state results.\'), LinkupSearchResult(name=\'Election Results 2024: Live Map - Races by State - POLITICO\', url=\'https://www.politico.com/2024-election/results/\', content=\'Live 2024 election results and maps by state. POLITICO’s real-time coverage of 2024 races for President, Senate, House and Governor.\'), LinkupSearchResult(name=\'Presidential Election 2024 Live Results: Donald Trump winsNBC News LogoSearchSearchNBC News LogoMSNBC LogoToday Logo\', url=\'https://www.nbcnews.com/politics/2024-elections/president-results\', content="Profile\\n\\nSections\\n\\nLocal\\n\\ntv\\n\\nFeatured\\n\\nMore From NBC\\n\\nFollow NBC News\\n\\nnews Alerts\\n\\nThere are no new alerts at this time\\n\\n2024 President Results: Trump wins\\n==================================\\n\\nDonald Trump has secured more than the 270 Electoral College votes needed to secure the presidency, NBC News projects.\\n\\nRaces to watch\\n--------------\\n\\nAll Presidential races\\n----------------------\\n\\nElection Night Coverage\\n-----------------------\\n\\n### China competition should be top priority for Trump, Sullivan says, as Biden and Xi prepare for final meeting\\n\\n### Jim Himes says \'truth and analysis are not what drive’ Gabbard and Gaetz\\n\\n### Trump praises RFK Jr. in Mar-a-Lago remarks\\n\\n### Trump announces North Dakota Gov. Doug Burgum as his pick for interior secretary\\n\\n### House Ethics Committee cancels meeting at which Gaetz probe was on the agenda\\n\\n### Trump picks former Rep. Doug Collins for veterans affairs secretary\\n\\n### Trump to nominate his criminal defense lawyer for deputy attorney general\\n\\n### From ‘brilliant’ to ‘dangerous’: Mixed reactions roll in after Trump picks RFK Jr. for top health post\\n\\n### Donald Trump Jr. says he played key role in RFK Jr., Tulsi Gabbard picks\\n\\n### Jared Polis offers surprising words of support for RFK Jr. pick for HHS secretary\\n\\nNational early voting\\n---------------------\\n\\n### 88,233,886 mail-in and early in-person votes cast nationally\\n\\n### 65,676,748 mail-in and early in-person votes requested nationally\\n\\nPast Presidential Elections\\n---------------------------\\n\\n### Vote Margin by State in the 2020 Presidential Election\\n\\nCircle size represents the number electoral votes in that state.\\n\\nThe expected vote is the total number of votes that are expected in a given race once all votes are counted. This number is an estimate and is based on several different factors, including information on the number of votes cast early as well as information provided to our vote reporters on Election Day from county election officials. The figure can change as NBC News gathers new information.\\n\\n**Source**: [National Election Pool (NEP)](https://www.nbcnews.com/politics/2024-elections/how-election-data-is-collected )\\n\\n2024 election results\\n---------------------\\n\\nElection Night Coverage\\n-----------------------\\n\\n### China competition should be top priority for Trump, Sullivan says, as Biden and Xi prepare for final meeting\\n\\n### Jim Himes says \'truth and analysis are not what drive’ Gabbard and Gaetz\\n\\n### Trump praises RFK Jr. in Mar-a-Lago remarks\\n\\n©\\xa02024 NBCUniversal Media, LLC")]', name='linkup', tool_call_id='1')

链式调用

我们可以在链中使用我们的工具,首先将其绑定到工具调用模型,然后再调用它

pip install -qU langchain-openai
import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o-mini")
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableConfig, chain

prompt = ChatPromptTemplate(
[
("system", "You are a helpful assistant."),
("human", "{user_input}"),
("placeholder", "{messages}"),
]
)

# specifying tool_choice will force the model to call this tool.
llm_with_tools = llm.bind_tools([tool], tool_choice=tool.name)

llm_chain = prompt | llm_with_tools


@chain
def tool_chain(user_input: str, config: RunnableConfig):
input_ = {"user_input": user_input}
ai_msg = llm_chain.invoke(input_, config=config)
tool_msgs = tool.batch(ai_msg.tool_calls, config=config)
return llm_chain.invoke({**input_, "messages": [ai_msg, *tool_msgs]}, config=config)


tool_chain.invoke("Who won the 2016 US presidential elections?")
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_JcHj0XLARWRnwrrLhUoBjOV1', 'function': {'arguments': '{"query":"2016 US presidential election winner"}', 'name': 'linkup'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 10, 'prompt_tokens': 1037, 'total_tokens': 1047, 'completion_tokens_details': {'audio_tokens': 0, 'reasoning_tokens': 0, 'accepted_prediction_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_831e067d82', 'finish_reason': 'stop', 'logprobs': None}, id='run-cd7642ed-4509-4c96-8934-20bd0b986c3f-0', tool_calls=[{'name': 'linkup', 'args': {'query': '2016 US presidential election winner'}, 'id': 'call_JcHj0XLARWRnwrrLhUoBjOV1', 'type': 'tool_call'}], usage_metadata={'input_tokens': 1037, 'output_tokens': 10, 'total_tokens': 1047, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})

API 参考

有关 LinkupSearchTool 所有特性和配置的详细文档,请访问API 参考


此页内容是否对您有帮助?