-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create tool to get news using NewsAPI
- Loading branch information
Showing
4 changed files
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
from typing import Optional | ||
|
||
from langchain.callbacks.manager import ( | ||
AsyncCallbackManagerForToolRun, | ||
CallbackManagerForToolRun, | ||
) | ||
from langchain_core.tools import BaseTool | ||
from newsapi import NewsApiClient | ||
from config.settings import settings | ||
|
||
|
||
newsapi = NewsApiClient(api_key=settings.NEWS_API) | ||
|
||
|
||
def get_top_headlines_formatted() -> str: | ||
# Get top headlines | ||
result = "" | ||
|
||
top_headlines = newsapi.get_top_headlines() | ||
|
||
articles = top_headlines["articles"] | ||
for idx, article in enumerate(articles): | ||
title = f"{idx} + {article['title']} + '\n' " | ||
result += title | ||
result += f"Description: {article["description"]} + '\n'" | ||
|
||
return result | ||
|
||
|
||
class NewsTool(BaseTool): | ||
name = "news_tool" | ||
description = "Useful for when you need to answer questions about current news" | ||
|
||
def _run( | ||
self, run_manager: Optional[CallbackManagerForToolRun] = None | ||
) -> str: | ||
return get_top_headlines_formatted() | ||
|
||
async def _arun( | ||
self, run_manager: Optional[AsyncCallbackManagerForToolRun] = None | ||
) -> str: | ||
"""Use the tool asynchronously.""" | ||
raise NotImplementedError("custom_search does not support async") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file not shown.