Spaces:
Sleeping
Sleeping
Update src/langgraphagenticai/nodes/ai_news_node.py
Browse files
src/langgraphagenticai/nodes/ai_news_node.py
CHANGED
|
@@ -1,131 +1,133 @@
|
|
| 1 |
-
from tavily import TavilyClient
|
| 2 |
-
from langchain_core.prompts import ChatPromptTemplate
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
frequency
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
-
|
| 81 |
-
-
|
| 82 |
-
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
("
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
frequency
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
from tavily import TavilyClient
|
| 2 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class AINewsNode:
|
| 7 |
+
def __init__(self, llm):
|
| 8 |
+
"""
|
| 9 |
+
Initializes the AI News Node.
|
| 10 |
+
|
| 11 |
+
This class handles fetching and summarizing recent AI-related news
|
| 12 |
+
using Tavily (a web search API) and an LLM (language model such as Groq).
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
llm: The language model used for generating summaries.
|
| 16 |
+
"""
|
| 17 |
+
# Create an instance of Tavily client to perform news searches
|
| 18 |
+
self.tavily = TavilyClient()
|
| 19 |
+
# Store the LLM (used later for summarization)
|
| 20 |
+
self.llm = llm
|
| 21 |
+
# A dictionary to store intermediate data such as frequency, fetched news, and summaries
|
| 22 |
+
self.state = {}
|
| 23 |
+
|
| 24 |
+
# ----------------------------------------------------------------------
|
| 25 |
+
def fetch_news(self, state: dict) -> dict:
|
| 26 |
+
"""
|
| 27 |
+
Fetch AI-related news articles using the Tavily API.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
state (dict): The current graph state, expected to include
|
| 31 |
+
'messages' containing the news frequency (e.g., daily, weekly, monthly).
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
dict: Updated state with 'news_data' containing the fetched news articles.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
# Extract frequency from user input (e.g., "daily", "weekly", etc.)
|
| 38 |
+
frequency = state['messages'][0].content.lower()
|
| 39 |
+
self.state['frequency'] = frequency
|
| 40 |
+
|
| 41 |
+
# Mapping for Tavily's time range codes and days
|
| 42 |
+
time_range_map = {'daily': 'd', 'weekly': 'w', 'monthly': 'm', 'year': 'y'}
|
| 43 |
+
days_map = {'daily': 1, 'weekly': 7, 'monthly': 30, 'year': 366}
|
| 44 |
+
|
| 45 |
+
# Perform a Tavily API search for the latest AI news
|
| 46 |
+
response = self.tavily.search(
|
| 47 |
+
query="Top Artificial Intelligence (AI) technology news globally",
|
| 48 |
+
topic="news",
|
| 49 |
+
time_range=time_range_map[frequency], # How far back to look
|
| 50 |
+
include_answer="advanced", # Request detailed information
|
| 51 |
+
max_results=20, # Limit number of news items
|
| 52 |
+
days=days_map[frequency], # Number of days to consider
|
| 53 |
+
# include_domains=["techcrunch.com", "venturebeat.com/ai", ...] # (Optional) restrict sources
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# Store the fetched results in the state dictionary
|
| 57 |
+
state['news_data'] = response.get('results', [])
|
| 58 |
+
self.state['news_data'] = state['news_data']
|
| 59 |
+
|
| 60 |
+
return state
|
| 61 |
+
|
| 62 |
+
# ----------------------------------------------------------------------
|
| 63 |
+
def summarize_news(self, state: dict) -> dict:
|
| 64 |
+
"""
|
| 65 |
+
Summarize the fetched AI news articles using the provided LLM.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
state (dict): The current graph state containing 'news_data'.
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
dict: Updated state with 'summary' containing the summarized news in markdown format.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
# Get the list of fetched news articles
|
| 75 |
+
news_items = self.state['news_data']
|
| 76 |
+
|
| 77 |
+
# Define how the summary should be formatted (markdown structure)
|
| 78 |
+
prompt_template = ChatPromptTemplate.from_messages([
|
| 79 |
+
("system", """Summarize AI news articles into markdown format. For each item include:
|
| 80 |
+
- Date in **YYYY-MM-DD** format (IST timezone)
|
| 81 |
+
- A concise summary of the news
|
| 82 |
+
- Sorted by latest date first
|
| 83 |
+
- Include the source URL as a hyperlink
|
| 84 |
+
Use this format:
|
| 85 |
+
### [Date]
|
| 86 |
+
- [Summary](URL)"""),
|
| 87 |
+
("user", "Articles:\n{articles}")
|
| 88 |
+
])
|
| 89 |
+
|
| 90 |
+
# Convert each article into a formatted string with content, URL, and publication date
|
| 91 |
+
articles_str = "\n\n".join([
|
| 92 |
+
f"Content: {item.get('content', '')}\nURL: {item.get('url', '')}\nDate: {item.get('published_date', '')}"
|
| 93 |
+
for item in news_items
|
| 94 |
+
])
|
| 95 |
+
|
| 96 |
+
# Ask the LLM to generate a markdown summary from the provided articles
|
| 97 |
+
response = self.llm.invoke(prompt_template.format(articles=articles_str))
|
| 98 |
+
|
| 99 |
+
# Save the summary to the state
|
| 100 |
+
state['summary'] = response.content
|
| 101 |
+
self.state['summary'] = state['summary']
|
| 102 |
+
|
| 103 |
+
return self.state
|
| 104 |
+
|
| 105 |
+
# ----------------------------------------------------------------------
|
| 106 |
+
def save_result(self, state):
|
| 107 |
+
"""
|
| 108 |
+
Save the summarized AI news to a markdown (.md) file.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
state (dict): The current graph state (contains 'frequency' and 'summary').
|
| 112 |
+
|
| 113 |
+
Returns:
|
| 114 |
+
dict: Updated state with 'filename' indicating where the summary file was saved.
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
# Retrieve frequency and summary content from the state
|
| 118 |
+
frequency = self.state['frequency']
|
| 119 |
+
summary = self.state['summary']
|
| 120 |
+
|
| 121 |
+
# Define output file path (e.g., ./AINews/daily_summary.md)
|
| 122 |
+
filename = f"./AINews/{frequency}_summary.md"
|
| 123 |
+
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
| 124 |
+
|
| 125 |
+
# Write the summary content to a markdown file
|
| 126 |
+
with open(filename, 'w') as f:
|
| 127 |
+
f.write(f"# {frequency.capitalize()} AI News Summary\n\n")
|
| 128 |
+
f.write(summary)
|
| 129 |
+
|
| 130 |
+
# Save filename in the state for reference
|
| 131 |
+
self.state['filename'] = filename
|
| 132 |
+
|
| 133 |
+
return self.state
|