File size: 23,156 Bytes
62da328 |
1 2 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 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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 |
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
import os
from datetime import datetime
from typing import List, Literal, Optional, Tuple, Union
from camel.toolkits import FunctionTool
from camel.toolkits.base import BaseToolkit
def _process_response(
response, return_type: str
) -> Union[str, dict, Tuple[str, dict]]:
r"""Process the response based on the specified return type.
This helper method processes the API response and returns the content
in the specified format, which could be a string, a dictionary, or
both.
Args:
response: The response object returned by the API call.
return_type (str): Specifies the format of the return value. It
can be "string" to return the response as a string, "dicts" to
return it as a dictionary, or "both" to return both formats as
a tuple.
Returns:
Union[str, dict, Tuple[str, dict]]: The processed response,
formatted according to the return_type argument. If "string",
returns the response as a string. If "dicts", returns the
response as a dictionary. If "both", returns a tuple
containing both formats.
Raises:
ValueError: If the return_type provided is invalid.
"""
if return_type == "string":
return response.as_string
elif return_type == "dicts":
return response.as_dicts
elif return_type == "both":
return (response.as_string, response.as_dicts)
else:
raise ValueError(f"Invalid return_type: {return_type}")
class AskNewsToolkit(BaseToolkit):
r"""A class representing a toolkit for interacting with the AskNews API.
This class provides methods for fetching news, stories, and other content
based on user queries using the AskNews API.
"""
def __init__(self):
r"""Initialize the AskNewsToolkit with API clients.The API keys and
credentials are retrieved from environment variables.
"""
from asknews_sdk import AskNewsSDK
client_id = os.environ.get("ASKNEWS_CLIENT_ID")
client_secret = os.environ.get("ASKNEWS_CLIENT_SECRET")
self.asknews_client = AskNewsSDK(client_id, client_secret)
def get_news(
self,
query: str,
n_articles: int = 10,
return_type: Literal["string", "dicts", "both"] = "string",
method: Literal["nl", "kw"] = "kw",
) -> Union[str, dict, Tuple[str, dict]]:
r"""Fetch news or stories based on a user query.
Args:
query (str): The search query for fetching relevant news.
n_articles (int): Number of articles to include in the response.
(default: :obj:`10`)
return_type (Literal["string", "dicts", "both"]): The format of the
return value. (default: :obj:`"string"`)
method (Literal["nl", "kw"]): The search method, either "nl" for
natural language or "kw" for keyword search. (default:
:obj:`"kw"`)
Returns:
Union[str, dict, Tuple[str, dict]]: A string, dictionary,
or both containing the news or story content, or error message
if the process fails.
"""
try:
response = self.asknews_client.news.search_news(
query=query,
n_articles=n_articles,
return_type=return_type,
method=method,
)
return _process_response(response, return_type)
except Exception as e:
return f"Got error: {e}"
def get_stories(
self,
query: str,
categories: List[
Literal[
'Politics',
'Economy',
'Finance',
'Science',
'Technology',
'Sports',
'Climate',
'Environment',
'Culture',
'Entertainment',
'Business',
'Health',
'International',
]
],
reddit: int = 3,
expand_updates: bool = True,
max_updates: int = 2,
max_articles: int = 10,
) -> Union[dict, str]:
r"""Fetch stories based on the provided parameters.
Args:
query (str): The search query for fetching relevant stories.
categories (list): The categories to filter stories by.
reddit (int): Number of Reddit threads to include.
(default: :obj:`3`)
expand_updates (bool): Whether to include detailed updates.
(default: :obj:`True`)
max_updates (int): Maximum number of recent updates per story.
(default: :obj:`2`)
max_articles (int): Maximum number of articles associated with
each update. (default: :obj:`10`)
Returns:
Unio[dict, str]: A dictionary containing the stories and their
associated data, or error message if the process fails.
"""
try:
response = self.asknews_client.stories.search_stories(
query=query,
categories=categories,
reddit=reddit,
expand_updates=expand_updates,
max_updates=max_updates,
max_articles=max_articles,
)
# Collect only the headline and story content from the updates
stories_data = {
"stories": [
{
"headline": story.updates[0].headline,
"updates": [
{
"headline": update.headline,
"story": update.story,
}
for update in story.updates[:max_updates]
],
}
for story in response.stories
]
}
return stories_data
except Exception as e:
return f"Got error: {e}"
def get_web_search(
self,
queries: List[str],
return_type: Literal["string", "dicts", "both"] = "string",
) -> Union[str, dict, Tuple[str, dict]]:
r"""Perform a live web search based on the given queries.
Args:
queries (List[str]): A list of search queries.
return_type (Literal["string", "dicts", "both"]): The format of the
return value. (default: :obj:`"string"`)
Returns:
Union[str, dict, Tuple[str, dict]]: A string,
dictionary, or both containing the search results, or
error message if the process fails.
"""
try:
response = self.asknews_client.chat.live_web_search(
queries=queries
)
return _process_response(response, return_type)
except Exception as e:
return f"Got error: {e}"
def search_reddit(
self,
keywords: List[str],
n_threads: int = 5,
return_type: Literal["string", "dicts", "both"] = "string",
method: Literal["nl", "kw"] = "kw",
) -> Union[str, dict, Tuple[str, dict]]:
r"""Search Reddit based on the provided keywords.
Args:
keywords (List[str]): The keywords to search for on Reddit.
n_threads (int): Number of Reddit threads to summarize and return.
(default: :obj:`5`)
return_type (Literal["string", "dicts", "both"]): The format of the
return value. (default: :obj:`"string"`)
method (Literal["nl", "kw"]): The search method, either "nl" for
natural language or "kw" for keyword search.
(default::obj:`"kw"`)
Returns:
Union[str, dict, Tuple[str, dict]]: The Reddit search
results as a string, dictionary, or both, or error message if
the process fails.
"""
try:
response = self.asknews_client.news.search_reddit(
keywords=keywords, n_threads=n_threads, method=method
)
return _process_response(response, return_type)
except Exception as e:
return f"Got error: {e}"
def query_finance(
self,
asset: Literal[
'bitcoin',
'ethereum',
'cardano',
'uniswap',
'ripple',
'solana',
'polkadot',
'polygon',
'chainlink',
'tether',
'dogecoin',
'monero',
'tron',
'binance',
'aave',
'tesla',
'microsoft',
'amazon',
],
metric: Literal[
'news_positive',
'news_negative',
'news_total',
'news_positive_weighted',
'news_negative_weighted',
'news_total_weighted',
] = "news_positive",
return_type: Literal["list", "string"] = "string",
date_from: Optional[datetime] = None,
date_to: Optional[datetime] = None,
) -> Union[list, str]:
r"""Fetch asset sentiment data for a given asset, metric, and date
range.
Args:
asset (Literal): The asset for which to fetch sentiment data.
metric (Literal): The sentiment metric to analyze.
return_type (Literal["list", "string"]): The format of the return
value. (default: :obj:`"string"`)
date_from (datetime, optional): The start date and time for the
data in ISO 8601 format.
date_to (datetime, optional): The end date and time for the data
in ISO 8601 format.
Returns:
Union[list, str]: A list of dictionaries containing the datetime
and value or a string describing all datetime and value pairs
for providing quantified time-series data for news sentiment
on topics of interest, or an error message if the process
fails.
"""
try:
response = self.asknews_client.analytics.get_asset_sentiment(
asset=asset,
metric=metric,
date_from=date_from,
date_to=date_to,
)
time_series_data = response.data.timeseries
if return_type == "list":
return time_series_data
elif return_type == "string":
header = (
f"This is the sentiment analysis for '{asset}' based "
+ f"on the '{metric}' metric from {date_from} to {date_to}"
+ ". The values reflect the aggregated sentiment from news"
+ " sources for each given time period.\n"
)
descriptive_text = "\n".join(
[
f"On {entry.datetime}, the sentiment value was "
f"{entry.value}."
for entry in time_series_data
]
)
return header + descriptive_text
except Exception as e:
return f"Got error: {e}"
def get_tools(self) -> List[FunctionTool]:
r"""Returns a list of FunctionTool objects representing the functions
in the toolkit.
Returns:
List[FunctionTool]: A list of FunctionTool objects representing
the functions in the toolkit.
"""
return [
FunctionTool(self.get_news),
FunctionTool(self.get_stories),
FunctionTool(self.get_web_search),
FunctionTool(self.search_reddit),
FunctionTool(self.query_finance),
]
class AsyncAskNewsToolkit(BaseToolkit):
r"""A class representing a toolkit for interacting with the AskNews API
asynchronously.
This class provides methods for fetching news, stories, and other
content based on user queries using the AskNews API.
"""
def __init__(self):
r"""Initialize the AsyncAskNewsToolkit with API clients.The API keys
and credentials are retrieved from environment variables.
"""
from asknews_sdk import AsyncAskNewsSDK # type: ignore[import]
client_id = os.environ.get("ASKNEWS_CLIENT_ID")
client_secret = os.environ.get("ASKNEWS_CLIENT_SECRET")
self.asknews_client = AsyncAskNewsSDK(client_id, client_secret)
async def get_news(
self,
query: str,
n_articles: int = 10,
return_type: Literal["string", "dicts", "both"] = "string",
method: Literal["nl", "kw"] = "kw",
) -> Union[str, dict, Tuple[str, dict]]:
r"""Fetch news or stories based on a user query.
Args:
query (str): The search query for fetching relevant news or
stories.
n_articles (int): Number of articles to include in the response.
(default: :obj:10)
return_type (Literal["string", "dicts", "both"]): The format of the
return value. (default: :obj:"string")
method (Literal["nl", "kw"]): The search method, either "nl" for
natural language or "kw" for keyword search. (default:
:obj:"kw")
Returns:
Union[str, dict, Tuple[str, dict]]: A string,
dictionary, or both containing the news or story content, or
error message if the process fails.
"""
try:
response = await self.asknews_client.news.search_news(
query=query,
n_articles=n_articles,
return_type=return_type,
method=method,
)
return _process_response(response, return_type)
except Exception as e:
return f"Got error: {e}"
async def get_stories(
self,
query: str,
categories: List[
Literal[
'Politics',
'Economy',
'Finance',
'Science',
'Technology',
'Sports',
'Climate',
'Environment',
'Culture',
'Entertainment',
'Business',
'Health',
'International',
]
],
reddit: int = 3,
expand_updates: bool = True,
max_updates: int = 2,
max_articles: int = 10,
) -> Union[dict, str]:
r"""Fetch stories based on the provided parameters.
Args:
query (str): The search query for fetching relevant stories.
categories (list): The categories to filter stories by.
reddit (int): Number of Reddit threads to include.
(default: :obj:`3`)
expand_updates (bool): Whether to include detailed updates.
(default: :obj:`True`)
max_updates (int): Maximum number of recent updates per story.
(default: :obj:`2`)
max_articles (int): Maximum number of articles associated with
each update. (default: :obj:`10`)
Returns:
Unio[dict, str]: A dictionary containing the stories and their
associated data, or error message if the process fails.
"""
try:
response = await self.asknews_client.stories.search_stories(
query=query,
categories=categories,
reddit=reddit,
expand_updates=expand_updates,
max_updates=max_updates,
max_articles=max_articles,
)
# Collect only the headline and story content from the updates
stories_data = {
"stories": [
{
"headline": story.updates[0].headline,
"updates": [
{
"headline": update.headline,
"story": update.story,
}
for update in story.updates[:max_updates]
],
}
for story in response.stories
]
}
return stories_data
except Exception as e:
return f"Got error: {e}"
async def get_web_search(
self,
queries: List[str],
return_type: Literal["string", "dicts", "both"] = "string",
) -> Union[str, dict, Tuple[str, dict]]:
r"""Perform a live web search based on the given queries.
Args:
queries (List[str]): A list of search queries.
return_type (Literal["string", "dicts", "both"]): The format of the
return value. (default: :obj:`"string"`)
Returns:
Union[str, dict, Tuple[str, dict]]: A string,
dictionary, or both containing the search results, or
error message if the process fails.
"""
try:
response = await self.asknews_client.chat.live_web_search(
queries=queries
)
return _process_response(response, return_type)
except Exception as e:
return f"Got error: {e}"
async def search_reddit(
self,
keywords: List[str],
n_threads: int = 5,
return_type: Literal["string", "dicts", "both"] = "string",
method: Literal["nl", "kw"] = "kw",
) -> Union[str, dict, Tuple[str, dict]]:
r"""Search Reddit based on the provided keywords.
Args:
keywords (list): The keywords to search for on Reddit.
n_threads (int): Number of Reddit threads to summarize and return.
(default: :obj:5)
return_type (Literal["string", "dicts", "both"]): The format of the
return value. (default: :obj:"string")
method (Literal["nl", "kw"]): The search method, either "nl" for
natural language or "kw" for keyword search.
(default::obj:"kw")
Returns:
Union[str, dict, Tuple[str, dict]]: The Reddit search
results as a string, dictionary, or both, or error message if
the process fails.
"""
try:
response = await self.asknews_client.news.search_reddit(
keywords=keywords, n_threads=n_threads, method=method
)
return _process_response(response, return_type)
except Exception as e:
return f"Got error: {e}"
async def query_finance(
self,
asset: Literal[
'bitcoin',
'ethereum',
'cardano',
'uniswap',
'ripple',
'solana',
'polkadot',
'polygon',
'chainlink',
'tether',
'dogecoin',
'monero',
'tron',
'binance',
'aave',
'tesla',
'microsoft',
'amazon',
],
metric: Literal[
'news_positive',
'news_negative',
'news_total',
'news_positive_weighted',
'news_negative_weighted',
'news_total_weighted',
] = "news_positive",
return_type: Literal["list", "string"] = "string",
date_from: Optional[datetime] = None,
date_to: Optional[datetime] = None,
) -> Union[list, str]:
r"""Fetch asset sentiment data for a given asset, metric, and date
range.
Args:
asset (Literal): The asset for which to fetch sentiment data.
metric (Literal): The sentiment metric to analyze.
return_type (Literal["list", "string"]): The format of the return
value. (default: :obj:`"string"`)
date_from (datetime, optional): The start date and time for the
data in ISO 8601 format.
date_to (datetime, optional): The end date and time for the data
in ISO 8601 format.
Returns:
Union[list, str]: A list of dictionaries containing the datetime
and value or a string describing all datetime and value pairs
for providing quantified time-series data for news sentiment
on topics of interest, or an error message if the process
fails.
"""
try:
response = await self.asknews_client.analytics.get_asset_sentiment(
asset=asset,
metric=metric,
date_from=date_from,
date_to=date_to,
)
time_series_data = response.data.timeseries
if return_type == "list":
return time_series_data
elif return_type == "string":
header = (
f"This is the sentiment analysis for '{asset}' based "
+ f"on the '{metric}' metric from {date_from} to {date_to}"
+ ". The values reflect the aggregated sentiment from news"
+ " sources for each given time period.\n"
)
descriptive_text = "\n".join(
[
f"On {entry.datetime}, the sentiment value was "
f"{entry.value}."
for entry in time_series_data
]
)
return header + descriptive_text
except Exception as e:
return f"Got error: {e}"
def get_tools(self) -> List[FunctionTool]:
r"""Returns a list of FunctionTool objects representing the functions
in the toolkit.
Returns:
List[FunctionTool]: A list of FunctionTool objects representing
the functions in the toolkit.
"""
return [
FunctionTool(self.get_news),
FunctionTool(self.get_stories),
FunctionTool(self.get_web_search),
FunctionTool(self.search_reddit),
FunctionTool(self.query_finance),
]
|