diff --git a/langchain_linkup/search_retriever.py b/langchain_linkup/search_retriever.py index e4a79bf..9ea9605 100644 --- a/langchain_linkup/search_retriever.py +++ b/langchain_linkup/search_retriever.py @@ -10,12 +10,106 @@ class LinkupSearchRetriever(BaseRetriever): - """A retriever using the Linkup API search to retrieve documents using natural language. + """LinkupSearchRetriever retriever. - This retriever is a wrapper around the Linkup API search entrypoint, making possible to - retrieve documents from the Linkup API sources, that is the web and the Linkup Premium Partner - sources, using natural language. - """ + The LinkupSearchRetriever uses the Linkup API search entrypoint, making possible to retrieve + documents from the Linkup API sources, that is the web and the Linkup Premium Partner sources, + using natural language. + + Setup: + Install ``langchain_linkup`` and set environment variable ``LINKUP_API_KEY``. + + .. code-block:: bash + + pip install -U langchain_linkup + export LINKUP_API_KEY="your-api-key" + + Key init args: + depth: Literal["standard", "deep"] + The depth of the Linkup search. Can be either "standard", for a straighforward and fast + search, or "deep" for a more powerful agentic workflow. + linkup_api_key: Optional[str] = None + The API key for the Linkup API. If None (the default), the API key will be read from + the environment variable `LINKUP_API_KEY`. + + + Instantiate: + .. code-block:: python + + from langchain_linkup import LinkupSearchRetriever + + retriever = LinkupSearchRetriever( + depth="deep", # "standard" or "deep" + linkup_api_key=None, + ) + + Usage: + .. code-block:: python + + query = "Who won the latest US presidential elections?" + + retriever.invoke(query) + + .. code-block:: python + + [Document(metadata={'name': 'US presidential election results 2024: Harris vs. Trump | Live maps ...', 'url': 'https://www.reuters.com/graphics/USA-ELECTION/R + ESULTS/zjpqnemxwvx/'}, page_content='Updated results from the 2024 election for the US president. Reuters live coverage of the 2024 US President, Senate, Hous + e and state governors races.'), Document(metadata={'name': 'Election 2024: Presidential results - CNN', 'url': 'https://www.cnn.com/election/2024/results/pres + ident'}, page_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 ...'), Document(metadata={'name': 'Presidential Election 2024 Live Results: Donald Trump wins - NBC News', 'url': 'https://www.nbcnews + .com/politics/2024-elections/president-results'}, page_content='View live election results from the 2024 presidential race as Kamala Harris and Donald Trump f + ace off. See the map of votes by state as results are tallied.'), Document(metadata={'name': '2024 President Election - Live Results | RealClearPolitics', 'ur + l': 'https://www.realclearpolitics.com/elections/live_results/2024/president/'}, page_content='Latest Election 2024 Results • President • United States • Tues + day November 3rd • Presidential Election Details'), Document(metadata={'name': 'US Presidential Election Results 2024 - BBC News', 'url': 'https://www.bbc.com + /news/election/2024/us/results'}, page_content='Kamala Harris of the Democrat party has 74,498,303 votes (48.3%) Donald Trump of the Republican party has 76,9 + 89,499 votes (49.9%) This map of the US states was filled in as presidential results ...'), Document(metadata={'name': '2024 US Presidential Election Results: + Live Map - Bloomberg.com', 'url': 'https://www.bloomberg.com/graphics/2024-us-election-results/'}, page_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 ...'), Do + cument(metadata={'name': 'Presidential Election Results 2024: Electoral Votes & Map by State ...', 'url': 'https://www.politico.com/2024-election/results/pres + ident/'}, page_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.'), Document(metadata={'name': '2024 U.S. Election: Live Results and Maps - USA TODAY', 'url': 'https://www.usatoday.com/elections + /results/2024-11-05'}, page_content='See who is winning races in the Nov. 5, 2024 U.S. Election with real-time results and state-by-state maps.'), Document(me + tadata={'name': 'US Presidential Election Results 2024 - BBC News', 'url': 'https://www.bbc.co.uk/news/election/2024/us/results'}, page_content='Follow the 20 + 24 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.'), Documen + t(metadata={'name': '2024 US Presidential Election Results: Live Map - ABC News', 'url': 'https://abcnews.go.com/Elections/2024-us-presidential-election-resul + ts-live-map/'}, page_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')] + + Use within a chain: + .. code-block:: python + + from langchain_core.output_parsers import StrOutputParser + from langchain_core.prompts import ChatPromptTemplate + from langchain_core.runnables import RunnablePassthrough + from langchain_openai import ChatOpenAI + + prompt = ChatPromptTemplate.from_template( + \"\"\"Answer the question based only on the context provided. + + Context: {context} + + Question: {question}\"\"\" + ) + + llm = ChatOpenAI(model="gpt-3.5-turbo-0125") + + def format_docs(docs): + return "\n\n".join(doc.page_content for doc in docs) + + chain = ( + {"context": retriever | format_docs, "question": RunnablePassthrough()} + | prompt + | llm + | StrOutputParser() + ) + + chain.invoke("Who won the latest US presidential elections?") + + .. code-block:: python + + 'Donald Trump won the latest US presidential elections.' + + """ # noqa: E501 depth: Literal["standard", "deep"] """The depth of the search. Can be either "standard", for a straighforward and fast search, or diff --git a/langchain_linkup/search_tool.py b/langchain_linkup/search_tool.py index f64cdbd..d1571fc 100644 --- a/langchain_linkup/search_tool.py +++ b/langchain_linkup/search_tool.py @@ -14,12 +14,96 @@ class LinkupSearchInput(BaseModel): class LinkupSearchTool(BaseTool): - """A tool to query the Linkup API search in natural language. + """LinkupSearchTool tool. - This tool is a wrapper around the Linkup API search entrypoint, making possible to perform + The LinkupSearchTool uses the Linkup API search entrypoint, making possible to perform search queries based on the Linkup API sources, that is the web and the Linkup Premium Partner sources, using natural language. - """ + + Setup: + Install ``langchain_linkup`` and set environment variable ``LINKUP_API_KEY``. + + .. code-block:: bash + + pip install -U langchain_linkup + export LINKUP_API_KEY="your-api-key" + + Key init args: + depth: Literal["standard", "deep"] + The depth of the Linkup search. Can be either "standard", for a straighforward and fast + search, or "deep" for a more powerful agentic workflow. + output_type: Literal["searchResults", "sourcedAnswer", "structured"] + The type of output which is expected from the Linkup API search: "searchResults" will + output raw search results, "sourcedAnswer" will output the answer to the query and + sources supporting it, and "structured" will base the output on the format provided in + structured_output_schema. + linkup_api_key: Optional[str] = None + The API key for the Linkup API. If None (the default), the API key will be read from + the environment variable `LINKUP_API_KEY`. + structured_output_schema: Union[Type[BaseModel], str, None] = None + If output_type is "structured", specify the schema of the output. Supported formats are + a pydantic.BaseModel or a string representing a valid object JSON schema. + + Instantiate: + .. code-block:: python + + from langchain_linkup import LinkupSearchTool + + tool = LinkupSearchTool( + depth="deep", # "standard" or "deep" + output_type="sourcedAnswer", # "searchResults", "sourcedAnswer" or "structured" + linkup_api_key=None, + structured_output_schema=None, + ) + + Usage: + .. code-block:: python + + query = "Who won the latest US presidential elections?" + + tool.invoke(query) + + .. code-block:: python + + LinkupSourcedAnswer(answer='Donald Trump has won the 2024 presidential election by securing more than the 270 Electoral College votes needed for the presidency.', sources=[LinkupSource(name='NBC News', url='https://www.nbcnews.com/politics/2024-elections + + Use within an agent: + .. code-block:: python + + from langchain_core.messages import HumanMessage + from langchain_openai import ChatOpenAI + from langgraph.prebuilt import create_react_agent + + model = ChatOpenAI(model="gpt-4o-mini") + agent_executor = create_react_agent(model=model, tools=[tool]) + + # Use the agent + for chunk in agent_executor.stream(input=dict(messages=[HumanMessage(content=query)])): + print(chunk) + + .. code-block:: python + + {'agent': {'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_9q6zsP8hRyGHyOsf0FYLLYJQ', 'function': {'arguments': '{"query":"latest US presidential elections winner 2024"}', 'name': 'linkup'}, 'type': 'function'}], 'refusa + l': None}, response_metadata={'token_usage': {'completion_tokens': 21, 'prompt_tokens': 85, 'total_tokens': 106, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'p + rompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_0705bf87c0', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-f61f4081-30e4-4130-8823-c161c25d22af-0', tool_calls= + [{'name': 'linkup', 'args': {'query': 'latest US presidential elections winner 2024'}, 'id': 'call_9q6zsP8hRyGHyOsf0FYLLYJQ', 'type': 'tool_call'}], usage_metadata={'input_tokens': 85, 'output_tokens': 21, 'total_tokens': 106, 'input_token_details': {'au + dio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})]}} + {'tools': {'messages': [ToolMessage(content="answer='The latest results from the 2024 US presidential election indicate that Donald Trump has won against Kamala Harris. Trump secured approximately 49.9% of the vote, while Harris received around 48.3%.' s + ources=[LinkupSource(name='Election 2024: Presidential results - CNN', url='https://www.cnn.com/election/2024/results/president', snippet='View maps and real-time results for the 2024 US presidential election matchup between former President Donald Trump + and Vice President Kamala Harris.'), LinkupSource(name='NBC News - Presidential Election 2024 Live Results', url='https://www.nbcnews.com/politics/2024-elections/president-results', snippet='View live election results from the 2024 presidential race as + Kamala Harris and Donald Trump face off.'), LinkupSource(name='Los Angeles Times - Trump wins 2024 U.S. presidential election, defeats Harris', url='https://www.latimes.com/politics/story/2024-11-06/trump-defeats-harris-47th-president-election-2024', sni + ppet='2024 U.S. elections results See how the latest national vote counts for the President, Senate, Congress and Governors races change the balance of power.'), LinkupSource(name='The New York Times - Presidential Election Results: Trump Wins', url='htt + ps://www.nytimes.com/interactive/2024/11/05/us/elections/results-president.html', snippet='Donald J. Trump has won the presidency, improving upon his 2020 performance in both red and blue states.'), LinkupSource(name='BBC News - US Presidential Election + Results 2024', url='https://www.bbc.com/news/election/2024/us/results', snippet='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%).')]", name='linkup', id='c9a53419-b6fe-486 + 9-b57d-ac26083e5342', tool_call_id='call_9q6zsP8hRyGHyOsf0FYLLYJQ')]}} + {'agent': {'messages': [AIMessage(content='The latest results from the 2024 US presidential election indicate that Donald Trump has won against Kamala Harris. Trump secured approximately 49.9% of the vote, while Harris received around 48.3%.\n\nHere are + some sources for more details:\n- [CNN - Election 2024: Presidential results](https://www.cnn.com/election/2024/results/president)\n- [NBC News - Presidential Election 2024 Live Results](https://www.nbcnews.com/politics/2024-elections/president-results)\ + n- [Los Angeles Times - Trump wins 2024 U.S. presidential election, defeats Harris](https://www.latimes.com/politics/story/2024-11-06/trump-defeats-harris-47th-president-election-2024)\n- [The New York Times - Presidential Election Results: Trump Wins](h + ttps://www.nytimes.com/interactive/2024/11/05/us/elections/results-president.html)\n- [BBC News - US Presidential Election Results 2024](https://www.bbc.com/news/election/2024/us/results)', additional_kwargs={'refusal': None}, response_metadata={'token_u + sage': {'completion_tokens': 229, 'prompt_tokens': 519, 'total_tokens': 748, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_token + s': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_3de1288069', 'finish_reason': 'stop', 'logprobs': None}, id='run-3c2962e2-bae7-47e3-92c5-b7725314254a-0', usage_metadata={'input_tokens': 519, 'output_tokens': + 229, 'total_tokens': 748, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})]}} + """ # noqa: E501 depth: Literal["standard", "deep"] """The depth of the search. Can be either "standard", for a straighforward and