menikev commited on
Commit
165f4bd
·
verified ·
1 Parent(s): 74851dc

Update news_tools.py

Browse files
Files changed (1) hide show
  1. news_tools.py +53 -52
news_tools.py CHANGED
@@ -1,58 +1,59 @@
 
1
  import os
2
- from langchain.tools import tool
3
  import requests
 
 
 
4
 
5
- @tool("Search Crypto News")
6
- def search_crypto_news(query: str) -> str:
7
- """Searches for cryptocurrency news articles based on a given query."""
8
- try:
9
- # Since you might not have the CryptoNews API key, let's use a free alternative
10
- # Using NewsAPI (free tier) or fall back to mock data
11
-
12
- api_key = os.getenv("NEWS_API_KEY") # You can get this free from newsapi.org
13
-
14
- if api_key:
15
- url = "https://newsapi.org/v2/everything"
16
- params = {
17
- 'q': f"{query} cryptocurrency",
18
- 'sortBy': 'publishedAt',
19
- 'pageSize': 3,
20
- 'apiKey': api_key,
21
- 'language': 'en'
22
- }
23
-
24
- response = requests.get(url, params=params, timeout=10)
25
- response.raise_for_status()
26
-
27
- data = response.json()
28
- articles = data.get('articles', [])
29
 
30
- if articles:
31
- news_summary = []
32
- for article in articles[:3]:
33
- title = article.get('title', 'No title')
34
- source = article.get('source', {}).get('name', 'Unknown source')
35
- news_summary.append(f"• {title} - {source}")
 
 
 
 
 
 
 
 
 
36
 
37
- return f"Recent news for {query}:\n" + "\n".join(news_summary)
 
 
 
 
 
 
 
 
 
38
  else:
39
- return f"No recent news found for {query}"
40
- else:
41
- # Mock news data when API key is not available
42
- mock_headlines = [
43
- f"{query.title()} shows strong technical indicators amid market volatility",
44
- f"Institutional adoption of {query.title()} continues to grow",
45
- f"Market analysts remain optimistic about {query.title()}'s long-term prospects"
46
- ]
47
-
48
- return f"Recent news for {query}:\n" + "\n".join([f"• {headline}" for headline in mock_headlines])
49
-
50
- except requests.exceptions.RequestException as e:
51
- return f"Error fetching news: {str(e)}"
52
- except Exception as e:
53
- return f"News search error: {str(e)}"
54
-
55
- class NewsTools:
56
- """Container class for news tools - for backward compatibility"""
57
- def __init__(self):
58
- self.search_crypto_news = search_crypto_news
 
1
+ # news_tools.py - CrewAI Native Version
2
  import os
 
3
  import requests
4
+ from crewai.tools import BaseTool
5
+ from typing import Type
6
+ from pydantic import BaseModel, Field
7
 
8
+ class NewsSearchInput(BaseModel):
9
+ """Input schema for NewsSearchTool."""
10
+ query: str = Field(..., description="Query string to search for cryptocurrency news")
11
+
12
+ class NewsSearchTool(BaseTool):
13
+ name: str = "Search Crypto News"
14
+ description: str = "Searches for cryptocurrency news articles based on a given query"
15
+ args_schema: Type[NewsSearchInput] = NewsSearchInput
16
+
17
+ def _run(self, query: str) -> str:
18
+ try:
19
+ # Using NewsAPI (free tier) or fall back to mock data
20
+ api_key = os.getenv("NEWS_API_KEY")
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ if api_key:
23
+ url = "https://newsapi.org/v2/everything"
24
+ params = {
25
+ 'q': f"{query} cryptocurrency",
26
+ 'sortBy': 'publishedAt',
27
+ 'pageSize': 3,
28
+ 'apiKey': api_key,
29
+ 'language': 'en'
30
+ }
31
+
32
+ response = requests.get(url, params=params, timeout=10)
33
+ response.raise_for_status()
34
+
35
+ data = response.json()
36
+ articles = data.get('articles', [])
37
 
38
+ if articles:
39
+ news_summary = []
40
+ for article in articles[:3]:
41
+ title = article.get('title', 'No title')
42
+ source = article.get('source', {}).get('name', 'Unknown source')
43
+ news_summary.append(f"• {title} - {source}")
44
+
45
+ return f"Recent news for {query}:\n" + "\n".join(news_summary)
46
+ else:
47
+ return f"No recent news found for {query}"
48
  else:
49
+ # Mock news data when API key is not available
50
+ mock_headlines = [
51
+ f"{query.title()} shows strong technical indicators amid market volatility",
52
+ f"Institutional adoption of {query.title()} continues to grow",
53
+ f"Market analysts remain optimistic about {query.title()}'s long-term prospects"
54
+ ]
55
+
56
+ return f"Recent news for {query}:\n" + "\n".join([f"• {headline}" for headline in mock_headlines])
57
+
58
+ except Exception as e:
59
+ return f"Error fetching news: {str(e)}"