mirror of
				https://github.com/hwchase17/langchain.git
				synced 2025-11-04 10:10:09 +00:00 
			
		
		
		
	Signed-off-by: ChengZi <chen.zhang@zilliz.com> Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com> Co-authored-by: Bagatur <22008038+baskaryan@users.noreply.github.com> Co-authored-by: Dan O'Donovan <dan.odonovan@gmail.com> Co-authored-by: Tom Daniel Grande <tomdgrande@gmail.com> Co-authored-by: Grande <Tom.Daniel.Grande@statsbygg.no> Co-authored-by: Bagatur <baskaryan@gmail.com> Co-authored-by: ccurme <chester.curme@gmail.com> Co-authored-by: Harrison Chase <hw.chase.17@gmail.com> Co-authored-by: Tomaz Bratanic <bratanic.tomaz@gmail.com> Co-authored-by: ZhangShenao <15201440436@163.com> Co-authored-by: Friso H. Kingma <fhkingma@gmail.com> Co-authored-by: ChengZi <chen.zhang@zilliz.com> Co-authored-by: Nuno Campos <nuno@langchain.dev> Co-authored-by: Morgante Pell <morgantep@google.com>
		
			
				
	
	
		
			116 lines
		
	
	
		
			3.5 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			116 lines
		
	
	
		
			3.5 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
"""Util that calls AskNews api."""
 | 
						|
 | 
						|
from __future__ import annotations
 | 
						|
 | 
						|
from datetime import datetime, timedelta
 | 
						|
from typing import Any, Dict, Optional
 | 
						|
 | 
						|
from langchain_core.utils import get_from_dict_or_env
 | 
						|
from pydantic import BaseModel, ConfigDict, model_validator
 | 
						|
 | 
						|
 | 
						|
class AskNewsAPIWrapper(BaseModel):
 | 
						|
    """Wrapper for AskNews API."""
 | 
						|
 | 
						|
    asknews_sync: Any = None  #: :meta private:
 | 
						|
    asknews_async: Any = None  #: :meta private:
 | 
						|
    asknews_client_id: Optional[str] = None
 | 
						|
    """Client ID for the AskNews API."""
 | 
						|
    asknews_client_secret: Optional[str] = None
 | 
						|
    """Client Secret for the AskNews API."""
 | 
						|
 | 
						|
    model_config = ConfigDict(
 | 
						|
        extra="forbid",
 | 
						|
    )
 | 
						|
 | 
						|
    @model_validator(mode="before")
 | 
						|
    @classmethod
 | 
						|
    def validate_environment(cls, values: Dict) -> Any:
 | 
						|
        """Validate that api credentials and python package exists in environment."""
 | 
						|
 | 
						|
        asknews_client_id = get_from_dict_or_env(
 | 
						|
            values, "asknews_client_id", "ASKNEWS_CLIENT_ID"
 | 
						|
        )
 | 
						|
        asknews_client_secret = get_from_dict_or_env(
 | 
						|
            values, "asknews_client_secret", "ASKNEWS_CLIENT_SECRET"
 | 
						|
        )
 | 
						|
 | 
						|
        try:
 | 
						|
            import asknews_sdk
 | 
						|
 | 
						|
        except ImportError:
 | 
						|
            raise ImportError(
 | 
						|
                "AskNews python package not found. "
 | 
						|
                "Please install it with `pip install asknews`."
 | 
						|
            )
 | 
						|
 | 
						|
        an_sync = asknews_sdk.AskNewsSDK(
 | 
						|
            client_id=asknews_client_id,
 | 
						|
            client_secret=asknews_client_secret,
 | 
						|
            scopes=["news"],
 | 
						|
        )
 | 
						|
        an_async = asknews_sdk.AsyncAskNewsSDK(
 | 
						|
            client_id=asknews_client_id,
 | 
						|
            client_secret=asknews_client_secret,
 | 
						|
            scopes=["news"],
 | 
						|
        )
 | 
						|
 | 
						|
        values["asknews_sync"] = an_sync
 | 
						|
        values["asknews_async"] = an_async
 | 
						|
        values["asknews_client_id"] = asknews_client_id
 | 
						|
        values["asknews_client_secret"] = asknews_client_secret
 | 
						|
 | 
						|
        return values
 | 
						|
 | 
						|
    def search_news(
 | 
						|
        self, query: str, max_results: int = 10, hours_back: int = 0
 | 
						|
    ) -> str:
 | 
						|
        """Search news in AskNews API synchronously."""
 | 
						|
        if hours_back > 48:
 | 
						|
            method = "kw"
 | 
						|
            historical = True
 | 
						|
            start = int((datetime.now() - timedelta(hours=hours_back)).timestamp())
 | 
						|
            stop = int(datetime.now().timestamp())
 | 
						|
        else:
 | 
						|
            historical = False
 | 
						|
            method = "nl"
 | 
						|
            start = None
 | 
						|
            stop = None
 | 
						|
 | 
						|
        response = self.asknews_sync.news.search_news(
 | 
						|
            query=query,
 | 
						|
            n_articles=max_results,
 | 
						|
            method=method,
 | 
						|
            historical=historical,
 | 
						|
            start_timestamp=start,
 | 
						|
            end_timestamp=stop,
 | 
						|
            return_type="string",
 | 
						|
        )
 | 
						|
        return response.as_string
 | 
						|
 | 
						|
    async def asearch_news(
 | 
						|
        self, query: str, max_results: int = 10, hours_back: int = 0
 | 
						|
    ) -> str:
 | 
						|
        """Search news in AskNews API asynchronously."""
 | 
						|
        if hours_back > 48:
 | 
						|
            method = "kw"
 | 
						|
            historical = True
 | 
						|
            start = int((datetime.now() - timedelta(hours=hours_back)).timestamp())
 | 
						|
            stop = int(datetime.now().timestamp())
 | 
						|
        else:
 | 
						|
            historical = False
 | 
						|
            method = "nl"
 | 
						|
            start = None
 | 
						|
            stop = None
 | 
						|
 | 
						|
        response = await self.asknews_async.news.search_news(
 | 
						|
            query=query,
 | 
						|
            n_articles=max_results,
 | 
						|
            method=method,
 | 
						|
            historical=historical,
 | 
						|
            start_timestamp=start,
 | 
						|
            end_timestamp=stop,
 | 
						|
            return_type="string",
 | 
						|
        )
 | 
						|
        return response.as_string
 |