LinkupSearchTool
Linkup 提供 API,將 LLM 連接到網路和 Linkup Premium Partner 來源。
本筆記本快速概述 LinkupSearchTool 工具 的入門方法。如需 LinkupSearchTool 所有功能和配置的詳細文件,請前往API 參考。
總覽
整合詳細資訊
類別 | 套件 | 可序列化 | JS 支援 | 最新套件 |
---|---|---|---|---|
LinkupSearchTool | langchain-linkup | ❌ | ❌ |
設定
若要使用 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["LANGSMITH_TRACING"] = "true"
# os.environ["LANGSMITH_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.chat_models import init_chat_model
llm = init_chat_model("gpt-4o-mini", model_provider="openai")
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 參考。