Skip to content

Commit

Permalink
___init__
Browse files Browse the repository at this point in the history
  • Loading branch information
Your Name committed Sep 24, 2024
1 parent ff1215c commit 555ea1a
Show file tree
Hide file tree
Showing 17 changed files with 401 additions and 44 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ model = OpenAIChat(
)

# Initialize the agent
agent = Agent(
base_agent = Agent(
agent_name="News-Agent-V1",
# system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
llm=model,
Expand All @@ -70,7 +70,7 @@ agent = Agent(
# Agent
agent = NewsAgent(
agent_name="news-agent-v1",
agent=agent,
agent=base_agent,
newsapi_api_key=os.getenv("NEWSAPI_API_KEY"),
system_prompt=None,
return_json=True,
Expand All @@ -80,8 +80,8 @@ agent = NewsAgent(


# Run the agent
# agent.run(["multi-agent collaboration"])
agent.run_concurrently(["Swarm Multi-Agent", "AGI"])
print(agent.run("multi-agent collaboration"))
print(agent.run_concurrently(["OpenAI", "Anthropic"]))


```
Expand Down
3 changes: 2 additions & 1 deletion example.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,6 @@


# Run the agent
print(agent.run("multi-agent collaboration"))
# print(agent.run("multi-agent collaboration"))
print(agent.run_concurrently(["OpenAI", "Anthropic"]))
# print(agent.return_sources("Science"))

Large diffs are not rendered by default.

Large diffs are not rendered by default.

15 changes: 15 additions & 0 deletions news_swarm/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from news_swarm.main import NewsAgent
from news_swarm.tool import (
fetch_stock_news,
return_headlines,
return_sources,
)
from news_swarm.prompts import NEWS_SYS_PROMPT

__all__ = [
"NewsAgent",
"fetch_stock_news",
"return_headlines",
"return_sources",
"NEWS_SYS_PROMPT",
]
78 changes: 41 additions & 37 deletions news_swarm/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
from pydantic import BaseModel, Field
from swarms import Agent, create_file_in_folder

from news_swarm.tool import fetch_stock_news
from news_swarm.tool import fetch_stock_news, return_sources
from loguru import logger


class InputLog(BaseModel):
id: Optional[str] = Field(
default=str(uuid.uuid4()),
Expand Down Expand Up @@ -66,6 +67,17 @@ class NewsAgent(Agent):
"""
A specialized agent for fetching and processing news articles based on given tasks.
It utilizes the News API to fetch articles and a language model to generate summaries.
Args:
agent_name (str): The name of the agent.
newsapi_api_key (str, optional): The API key for News API. Defaults to None.
system_prompt (str, optional): The system prompt for the language model. Defaults to None.
llm (BaseLLM, optional): The language model to use for summarization. Defaults to None.
agent (Agent, optional): The base agent to inherit from. Defaults to None.
start_date (Optional[str], optional): The start date for the news query in 'YYYY-MM-DD' format. Defaults to None.
end_date (Optional[str], optional): The end date for the news query in 'YYYY-MM-DD' format. Defaults to None.
return_json (bool, optional): If True, return the result as a JSON object, otherwise return a formatted string. Defaults to False.
max_articles (int, optional): The maximum number of articles to fetch. Defaults to 5.
"""

def __init__(
Expand All @@ -80,20 +92,7 @@ def __init__(
max_articles: int = 5,
autosave: bool = True,
):
"""
Initializes the NewsAgent with the necessary parameters.

Args:
agent_name (str): The name of the agent.
newsapi_api_key (str, optional): The API key for News API. Defaults to None.
system_prompt (str, optional): The system prompt for the language model. Defaults to None.
llm (BaseLLM, optional): The language model to use for summarization. Defaults to None.
agent (Agent, optional): The base agent to inherit from. Defaults to None.
start_date (Optional[str], optional): The start date for the news query in 'YYYY-MM-DD' format. Defaults to None.
end_date (Optional[str], optional): The end date for the news query in 'YYYY-MM-DD' format. Defaults to None.
return_json (bool, optional): If True, return the result as a JSON object, otherwise return a formatted string. Defaults to False.
max_articles (int, optional): The maximum number of articles to fetch. Defaults to 5.
"""
self.agent_name = agent_name
self.system_prompt = system_prompt
self.newsapi_api_key = newsapi_api_key
Expand All @@ -120,15 +119,17 @@ def __init__(

def run(self, task: str, *args, **kwargs):
"""
Runs the news fetching and summarization process sequentially for each task.
Executes the news retrieval and summarization process sequentially for a given task.
This method fetches news articles related to the specified task, summarizes the content, and logs the process. It supports both string and JSON output formats based on the `return_json` parameter.
Args:
tasks (List[str]): A list of tasks or queries to process.
task (str): The task or query to process.
Returns:
Union[str, dict]: The output of the process, either a formatted string or a JSON object depending on the return_json parameter.
Union[str, dict]: The output of the process, either a formatted string or a JSON object depending on the `return_json` parameter.
"""
logger.info("Running task Now")
logger.info("Initiating task execution")
self.output_log.input_log.query = task

string_query, *data_dict = fetch_stock_news(
Expand All @@ -138,8 +139,8 @@ def run(self, task: str, *args, **kwargs):
self.end_date,
max_articles=self.max_articles,
)
logger.info(f"Fetched the articles now")

logger.info(f"Completed fetching articles for task {task}")

summary = self.agent.run(string_query)

Expand All @@ -149,29 +150,19 @@ def run(self, task: str, *args, **kwargs):
)

self.output_log.output_logs.append(output_log_indi)

logger.info(f"Finished summarizing this query {task}")

# # Save the log
# create_file_in_folder(
# "news_agent_runs",
# f"news_agent_run_id:{self.output_log.id}.json",
# self.output_log.model_dump_json(indent=4),
# )
logger.info(f"Summarization completed for task {task}")

# if self.return_json is True:
# return self.output_log.model_dump_json(indent=4)

# else:
# return summary
return summary

def run_concurrently(self, tasks: List[str]) -> str:
"""
Runs the news fetching and summarization process concurrently for each task.
Executes the news retrieval and summarization process concurrently for a list of tasks.
This method leverages multithreading to process multiple tasks simultaneously, ensuring efficient handling of multiple queries. The output is always in JSON format.
Args:
tasks (List[str]): A list of tasks or queries to process.
tasks (List[str]): A list of tasks or queries to process concurrently.
Returns:
str: The output of the process as a JSON object.
Expand All @@ -183,8 +174,7 @@ def run_concurrently(self, tasks: List[str]) -> str:
}
for future in futures:
future.result() # Wait for all tasks to complete



# Save the log
create_file_in_folder(
"news_agent_runs",
Expand All @@ -193,3 +183,17 @@ def run_concurrently(self, tasks: List[str]) -> str:
)

return self.output_log.model_dump_json(indent=4)

def return_sources(self, source: Any, *args, **kwargs):
"""
Returns sources related to a given source or query.
This method is a wrapper for fetching sources based on a provided source or query. It utilizes the `newsapi_api_key` for authentication.
Args:
source (Any): The source or query to fetch related sources for.
Returns:
Any: The fetched sources based on the provided source or query.
"""
return return_sources(source, self.newsapi_api_key)
59 changes: 58 additions & 1 deletion news_swarm/tool.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from newsapi import NewsApiClient
from typing import Optional, Dict, Union, List
from typing import Optional, Dict, Union, List, Literal


def fetch_stock_news(
Expand Down Expand Up @@ -103,3 +103,60 @@ def process_article(article: Dict[str, str]) -> Dict[str, str]:

# # Example
# out = fetch_stock_news("Swarms")


def return_sources(
source: Literal[
"business",
"entertainment",
"general",
"health",
"science",
"sports",
"technology",
],
newsapi_api_key: str = None,
*args,
**kwargs,
):
"""
Fetches stock news for a query within a specified date range using NewsApiClient.
Args:
query (str): The query name or stock symbol to query news for.
newsapi_api_key (str): Your API key for News API.
start_date (Optional[str]): The start date for the news query in 'YYYY-MM-DD' format (default: None).
end_date (Optional[str]): The end date for the news query in 'YYYY-MM-DD' format (default: None).
max_articles (int): The maximum number of articles to retrieve (default: 5).
return_json (bool): If True, return the result as a JSON object, otherwise return a formatted string (default: False).
Returns:
Union[Dict[str, Union[str, List[Dict[str, str]]]], str]:
A JSON object (if return_json=True) containing articles and metadata, or a formatted string of the news articles.
"""

# Initialize the NewsApiClient with the provided API key
newsapi = NewsApiClient(api_key=newsapi_api_key)

data = newsapi.get_sources(category=source, *args, **kwargs)

return data


def return_headlines(
source: str = None, newsapi_api_key: str = None, *args, **kwargs
):
"""
Fetches stock news for a query within a specified date range using NewsApiClient.
Args:
query (str): The query name or stock symbol to query news for.
newsapi_api_key (str): Your API key for News API.
"""

# Initialize the NewsApiClient with the provided API key
newsapi = NewsApiClient(api_key=newsapi_api_key)

data = newsapi.get_top_headlines(sources=source, *args, **kwargs)

return data
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"

[tool.poetry]
name = "news-swarm"
version = "0.0.5"
version = "0.0.6"
description = "NewsAgent - TGSC"
license = "MIT"
authors = ["Kye Gomez <kye@apac.ai>"]
Expand Down

0 comments on commit 555ea1a

Please sign in to comment.