### Example: Iterating Through Search Stories Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/response-types.md Demonstrates how to process the search stories response, iterating through stories and their updates. ```python response = sdk.stories.search_stories( query="technology", limit=10 ) for story in response.stories: print(f"{story.topic} ({story.n_updates} updates)") for update in story.updates[:3]: print(f" - {update.headline}") ``` -------------------------------- ### Async SDK Initialization and Ping Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/sdk-initialization.md Demonstrates how to initialize the asynchronous SDK using a context manager and ping the API to get version information. ```APIDOC ## Async SDK Initialization and Ping ### Description Initializes the asynchronous SDK using an API key and a context manager. It then calls the `ping` method to retrieve the API version. ### Method `AsyncAskNewsSDK` (constructor) and `ping()` ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from asknews_sdk import AsyncAskNewsSDK import asyncio async def main(): async with AsyncAskNewsSDK(api_key="your-api-key") as sdk: response = await sdk.ping() print(f"API Version: {response.version}") asyncio.run(main()) ``` ### Response #### Success Response (PingResponse) - **app** (str) - Application name - **version** (str) - Version string #### Response Example ```json { "app": "asknews-api", "version": "1.0.0" } ``` ``` -------------------------------- ### Quick Start with API Key Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/authentication.md Initialize the SDK with a single API key for straightforward authentication. This is suitable for single-application use where simplicity is prioritized. ```python from asknews_sdk import AskNewsSDK sdk = AskNewsSDK(api_key="sk-asknews-...") response = sdk.news.search_news("query") ``` -------------------------------- ### Search News Example Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/types.md Demonstrates how to perform a news search and access the results in different formats. ```python response = sdk.news.search_news(return_type="both") print(response.as_string) # LLM-ready text for article in response.as_dicts: print(article.title) ``` -------------------------------- ### Get Streaming Chat Completions Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/chat-api.md This example demonstrates how to receive chat completions in a streaming fashion. It iterates over the response chunks and prints the content as it arrives. ```python response_stream = sdk.chat.get_chat_completions( messages=messages, model="gpt-4o", stream=True ) for chunk in response_stream: if chunk.choices: print(chunk.choices[0].delta.content, end="", flush=True) ``` -------------------------------- ### Install AskNews Python SDK Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/README.md Install the AskNews Python SDK using pip. Ensure you have Python 3.8 or higher. ```bash pip install asknews ``` -------------------------------- ### Initialize SDK and Ping API Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/sdk-initialization.md Demonstrates how to initialize the AsyncAskNewsSDK and ping the API to get version information. Uses an async context manager for proper resource handling. ```python from asknews_sdk import AsyncAskNewsSDK import asyncio async def main(): async with AsyncAskNewsSDK(api_key="your-api-key") as sdk: response = await sdk.ping() print(f"API Version: {response.version}") asyncio.run(main()) ``` -------------------------------- ### Example: Getting and Processing Asset Sentiment Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/response-types.md Demonstrates how to retrieve asset sentiment data and iterate through the data points to print the date, value, and mention count. ```python response = sdk.analytics.get_asset_sentiment( asset="bitcoin", metric="news_positive_weighted", date_from="2024-01-01", date_to="2024-12-31" ) for point in response.data: print(f"{point.date.date()}: {point.value} ({point.count} mentions)") ``` -------------------------------- ### Example: Getting and Processing Chat Completion Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/response-types.md Shows how to request a chat completion and extract details like the model used, token count, and the response content. ```python response = sdk.chat.get_chat_completions( messages=[{"role": "user", "content": "Summarize AI trends"}], model="gpt-4o" ) print(f"Model: {response.model}") print(f"Tokens: {response.usage.total_tokens}") print(f"Response: {response.choices[0].message.content}") ``` -------------------------------- ### Migrate from API Key to OAuth2 Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/authentication.md Example of migrating from using an API key to using OAuth2 client credentials for SDK initialization. ```python # Old - API key sdk_old = AskNewsSDK(api_key="sk-asknews-...") # New - OAuth2 sdk_new = AskNewsSDK( client_id="your-client-id", client_secret="your-client-secret" ) # Both work identically from user perspective response = sdk_new.news.search_news("query") ``` -------------------------------- ### Example: Performing and Processing a Wiki Search Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/response-types.md Demonstrates how to search Wikipedia for a query and iterate through the returned documents to print their details. ```python response = sdk.wiki.search_wiki( query="quantum computing", n_documents=5 ) for doc in response.documents: print(f"Title: {doc.title}") print(f"URL: {doc.url}") print(f"Categories: {', '.join(doc.categories)}") print(f"Content: {doc.content[:200]}...") ``` -------------------------------- ### Key Rotation Example Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/wiki-byok-apis.md Illustrates the process of rotating an API key by first deleting the old key and then storing the new one. ```python # Delete old key sdk.byok.delete_byok_key(provider="anthropic") # Store new key sdk.byok.set_byok_key( provider="anthropic", api_key="sk-ant-new..." ) ``` -------------------------------- ### Date Format Examples Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/analytics-api.md Demonstrates how to specify date ranges using either datetime objects or ISO format strings for API requests. ```python # Using datetime objects from datetime import datetime date_from = datetime(2024, 1, 1) # Using ISO format strings date_from = "2024-01-01T00:00:00Z" ``` -------------------------------- ### OAuth2 Token Response Example Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/authentication.md An example of a successful JSON response from the OAuth2 server containing the access token, token type, expiration time, and granted scopes. ```json { "access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...", "token_type": "Bearer", "expires_in": 3600, "scope": "news stories chat analytics" } ``` -------------------------------- ### Example Usage of AsyncAPIResponse Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/response-types.md Illustrates how to use the AsyncAPIResponse within an asynchronous function, including SDK initialization and accessing response status. ```python import asyncio from asknews_sdk import AsyncAskNewsSDK async def main(): async with AsyncAskNewsSDK(api_key="key") as sdk: response = await sdk.news.search_news("query") print(f"Status: {response.status_code}") asyncio.run(main()) ``` -------------------------------- ### Bitcoin Sentiment Tracking Example Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/analytics-api.md Example of tracking the total news sentiment for Bitcoin over a specific date range. This snippet demonstrates a common use case for monitoring asset sentiment. ```python response = sdk.analytics.get_asset_sentiment( asset="bitcoin", metric="news_total", date_from="2024-06-01", date_to="2024-12-31" ) ``` -------------------------------- ### Example: Streaming Chat Response Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/response-types.md Demonstrates how to stream chat completions and process each received chunk, printing the content as it arrives. ```python # Stream chat response response = sdk.chat.get_chat_completions( messages=[{"role": "user", "content": "Hello"}], stream=True ) for chunk in response: if chunk.choices: token = chunk.choices[0].delta.content print(token, end="", flush=True) ``` -------------------------------- ### Weighted Sentiment Analysis Example Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/analytics-api.md Example of retrieving weighted positive sentiment for Ethereum, which accounts for source credibility. This snippet shows how to use weighted metrics for a more nuanced analysis. ```python response = sdk.analytics.get_asset_sentiment( asset="ethereum", metric="news_positive_weighted", date_from="2024-06-01" ) ``` -------------------------------- ### Example Usage of APIResponse Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/response-types.md Demonstrates how to access common attributes of an APIResponse object after making a synchronous SDK call. ```python response = sdk.news.search_news("query") print(f"Status: {response.status_code}") print(f"Content type: {response.content_type}") print(f"Headers: {response.headers}") ``` -------------------------------- ### Configure SDK for Development vs. Production Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/configuration.md Set up the SDK differently for development and production environments. For development, enable debug logging and disable SSL verification for local testing. Production setup includes API key, SSL verification, and retry count. ```python import os import logging # Development setup with debug if os.getenv("ENV") == "dev": logging.basicConfig(level=logging.DEBUG) sdk = AskNewsSDK( api_key=os.getenv("ASKNEWS_API_KEY_DEV"), verify_ssl=False # For local testing ) else: # Production setup sdk = AskNewsSDK( api_key=os.getenv("ASKNEWS_API_KEY"), verify_ssl=True, retries=5 ) ``` -------------------------------- ### Async Chat Completion Example Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/chat-api.md Demonstrates how to perform asynchronous chat completions using the AsyncAskNewsSDK. Ensure you have an API key and have imported asyncio. ```python import asyncio from asknews_sdk import AsyncAskNewsSDK async def main(): async with AsyncAskNewsSDK(api_key="key") as sdk: messages = [{"role": "user", "content": "Latest AI news?"}] response = await sdk.chat.get_chat_completions( messages=messages, model="gpt-4o" ) print(response.choices[0].message.content) asyncio.run(main()) ``` -------------------------------- ### Get Headline Questions Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/chat-api.md Generates relevant questions from a given news headline. Requires the headline string as input. ```python def get_headline_questions( headline: str, *, http_headers: Optional[Dict] = None ) -> HeadlineQuestionsResponse ``` -------------------------------- ### Example: Estimating Chat Completion Cost Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/response-types.md Shows how to access token usage details from a chat completion response and estimate the cost based on a given price per token. ```python response = sdk.chat.get_chat_completions(messages=...) print(f"Prompt tokens: {response.usage.prompt_tokens}") print(f"Completion tokens: {response.usage.completion_tokens}") print(f"Total: {response.usage.total_tokens}") # Estimate cost if $0.01 per 1000 tokens cost = response.usage.total_tokens * 0.01 / 1000 print(f"Estimated cost: ${cost:.4f}") ``` -------------------------------- ### Example: Processing Streaming Chat Completions Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/response-types.md Demonstrates how to handle a streaming chat completion response, printing content chunks as they arrive and adding a newline at the end. ```python stream = sdk.chat.get_chat_completions( messages=[{"role": "user", "content": "What is AI?"}], stream=True ) for chunk in stream: if chunk.choices: delta = chunk.choices[0].delta if delta.content: print(delta.content, end="", flush=True) if chunk.choices[0].finish_reason: print() # New line at end ``` -------------------------------- ### Store Multiple Provider Keys Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/wiki-byok-apis.md Example of storing API keys for multiple providers sequentially using the BYOK API. ```python # Store Anthropic key sdk.byok.set_byok_key( provider="anthropic", api_key="sk-ant-..." ) # Store Google key sdk.byok.set_byok_key( provider="google", api_key="AIza..." ) ``` -------------------------------- ### Example Usage of SearchResponse Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/response-types.md Shows how to retrieve news search results in different formats (string and dictionaries) and access specific article details. ```python response = sdk.news.search_news( query="artificial intelligence", return_type="both" # Get both formats ) # Use LLM-ready text print(response.as_string) # Or parse structured data for article in response.as_dicts: print(f"{article.title} ({article.pub_date})") print(f"Sentiment: {article.sentiment}") ``` -------------------------------- ### Initialize AskNews SDK and Search News Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/README.md Initialize the AskNews SDK with your API key and desired scopes. Then, use the search_news method to find relevant articles and get a prompt-optimized string. ```python from asknews_sdk import AskNewsSDK ask = AskNewsSDK( api_key="" scopes=["news", "chat", "stories", "analytics"] ) query = "Effect of fed policy on tech sector" # prompt-optimized string ready to go for any LLM: news_context = ask.news.search_news(query).as_string ``` -------------------------------- ### WikiAPI Module Usage Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Provides an example of searching Wikipedia content using the WikiAPI. This functionality is accessible via the 'wiki' property of the SDK. ```python sdk.wiki.search_wiki(query="", n_documents=10, ...) ``` -------------------------------- ### API Key Response Structure Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/wiki-byok-apis.md Example JSON structure for the response from key operations, including the provider and a hint of the stored key. ```json { "provider": "anthropic", "key_hint": "sk-ant-***...7Xyz" } ``` -------------------------------- ### NewsAPI Module Usage Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Provides examples of common operations available through the NewsAPI module, such as searching news, retrieving articles by ID, and indexing URLs. These methods are accessed via the 'news' property of an initialized SDK instance. ```python sdk.news.search_news(query, n_articles=10, ...) sdk.news.get_article(article_id) sdk.news.get_articles(article_ids) sdk.news.get_index_counts(start_datetime, end_datetime, ...) sdk.news.search_reddit(keywords, ...) sdk.news.build_graph(query, ...) sdk.news.index_urls(request) ``` -------------------------------- ### SDK Initialization with Custom HTTP Client Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/sdk-initialization.md Demonstrates initializing the SDK with a pre-configured httpx Client for advanced customization. ```APIDOC ## SDK Initialization with Custom HTTP Client ### Description Initializes the SDK by providing a custom `httpx.Client` instance, enabling advanced configurations like connection limits and timeouts. ### Method `AskNewsSDK` (constructor) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from asknews_sdk import AskNewsSDK from httpx import Client custom_client = Client( limits=httpx.Limits(max_connections=100), timeout=30.0, verify=False ) sdk = AskNewsSDK(api_key="key", client=custom_client) ``` ### Response None (Initialization does not return a response) ``` -------------------------------- ### ChatAPI Module Usage Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Shows examples of using the ChatAPI module for LLM completions, DeepNews research, forecasting, and web search. These functionalities are available via the 'chat' property of the SDK. ```python sdk.chat.get_chat_completions(messages, model="gpt-4o-mini", ...) sdk.chat.get_deepnews(messages, model=None, ...) sdk.chat.get_forecasts(query, ...) sdk.chat.get_charts(query, ...) sdk.chat.get_web_search(query, ...) sdk.chat.get_headline_questions(headline, ...) sdk.chat.list_models() ``` -------------------------------- ### Get Stock Sentiment Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/analytics-api.md Retrieve the sentiment metric for a specific asset within a date range. Use this to get a particular sentiment score for a stock. ```python response = sdk.analytics.get_asset_sentiment( asset="tesla", metric="news_negative", date_from="2024-09-01", date_to="2024-12-31" ) ``` -------------------------------- ### Asynchronous SDK Initialization and Usage Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Demonstrates how to initialize the asynchronous `AsyncAskNewsSDK` using API key authentication and perform a basic news search. ```APIDOC ## Asynchronous SDK ### Description Initialize the asynchronous `AsyncAskNewsSDK` and perform a news search. ### Initialization ```python import asyncio from asknews_sdk import AsyncAskNewsSDK async def main(): async with AsyncAskNewsSDK(api_key="sk-asknews-...") as sdk: response = await sdk.news.search_news("query") asyncio.run(main()) ``` ### Import Path `asknews_sdk.AsyncAskNewsSDK` ### Source File `asknews_sdk/sdk.py:148` ``` -------------------------------- ### SDK Initialization with Custom Authentication Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/sdk-initialization.md Shows how to initialize the SDK with a custom authentication handler. ```APIDOC ## SDK Initialization with Custom Authentication ### Description Initializes the SDK by providing a custom authentication handler, allowing for flexible authentication mechanisms. ### Method `AskNewsSDK` (constructor) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from asknews_sdk import AskNewsSDK from httpx import Auth class CustomAuth(Auth): def auth_flow(self, request): request.headers["X-Custom-Auth"] = "value" yield request sdk = AskNewsSDK(auth=CustomAuth()) ``` ### Response None (Initialization does not return a response) ``` -------------------------------- ### SDK Initialization with OAuth2 Client Credentials Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/sdk-initialization.md Demonstrates initializing the SDK using OAuth2 client credentials. ```APIDOC ## SDK Initialization with OAuth2 Client Credentials ### Description Initializes the SDK using OAuth2 client ID, client secret, and scopes. The SDK handles token management automatically. ### Method `AskNewsSDK` (constructor) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from asknews_sdk import AskNewsSDK sdk = AskNewsSDK( client_id="your-client-id", client_secret="your-client-secret", scopes={"news", "stories", "chat", "analytics"} ) ``` ### Response None (Initialization does not return a response) ``` -------------------------------- ### SDK Initialization with API Key Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/sdk-initialization.md Shows the basic initialization of the SDK using an API key. ```APIDOC ## SDK Initialization with API Key ### Description Initializes the SDK using a simple API key for authentication. ### Method `AskNewsSDK` (constructor) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from asknews_sdk import AskNewsSDK sdk = AskNewsSDK(api_key="your-api-key") ``` ### Response None (Initialization does not return a response) ``` -------------------------------- ### Get Chat Completions Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/chat-api.md Use this method to get chat completions from LLM models with built-in news context. Configure parameters like model, streaming, citation format, and journalist mode for tailored responses. ```python from asknews_sdk import AskNewsSDK with AskNewsSDK(api_key="key") as sdk: messages = [ { "role": "user", "content": "What are the latest developments in AI regulation?" } ] response = sdk.chat.get_chat_completions( messages=messages, model="gpt-4o", inline_citations="markdown_link", journalist_mode=True ) print(response.choices[0].message.content) ``` -------------------------------- ### Async SDK Usage Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Demonstrates initializing and using the asynchronous SDK with await for API calls. Requires asyncio to run. ```python import asyncio from asknews_sdk import AsyncAskNewsSDK async def main(): async with AsyncAskNewsSDK(api_key="key") as sdk: # All method names are identical, just add await response = await sdk.news.search_news("query") stories = await sdk.stories.search_stories() completion = await sdk.chat.get_chat_completions(messages) asyncio.run(main()) ``` -------------------------------- ### Async SDK with API Key Authentication Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/authentication.md Demonstrates initializing the asynchronous SDK with an API key and performing an asynchronous search request. Ensure to use `async with` for proper resource management. ```python from asknews_sdk import AsyncAskNewsSDK import asyncio async def main(): async with AsyncAskNewsSDK(api_key="key") as sdk: response = await sdk.news.search_news("query") print(response.as_string) asyncio.run(main()) ``` -------------------------------- ### Handle UnauthorizedError Exception Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/errors.md Example of catching an UnauthorizedError, prompting the user to check their API key. ```python try: sdk = AskNewsSDK(api_key="invalid-key") response = sdk.news.search_news("query") except UnauthorizedError: print("Check your API key") ``` -------------------------------- ### Initialize SDK with Manual Resource Management Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Manually initialize the SDK and ensure resources are closed using a try-finally block. This is an alternative to using the context manager. ```python sdk = AskNewsSDK(api_key="key") try: response = sdk.news.search_news("query") finally: sdk.close() ``` -------------------------------- ### Initialize SDK with Mock Client Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/configuration.md Initialize the SDK with a mock client for testing purposes without making actual API calls. Configure mock responses for the client's request method. ```python # For testing without real API calls mock_client = Mock() sdk = AskNewsSDK(api_key="test", client=mock_client) # Configure mock responses sdk.client.request = Mock(return_value=Mock(content={"test": "data"})) ``` -------------------------------- ### Initialize SDK with API Key Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/sdk-initialization.md Initializes the AskNewsSDK using a simple API key for authentication. This is the most straightforward authentication method. ```python sdk = AskNewsSDK(api_key="your-api-key") ``` -------------------------------- ### Chat with Context and Inline Citations Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Get chat completions with a user message and specify inline citation format. ```python messages = [ { "role": "user", "content": "Summarize the latest tech industry trends" } ] response = sdk.chat.get_chat_completions( messages=messages, model="gpt-4o", inline_citations="markdown_link" ) print(response.choices[0].message.content) ``` -------------------------------- ### Search News with API Key Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Initialize the SDK with an API key and search for news articles. Use the 'as_string' attribute for LLM-ready output. ```python from asknews_sdk import AskNewsSDK with AskNewsSDK(api_key="sk-asknews-...") as sdk: response = sdk.news.search_news( query="federal reserve interest rates", n_articles=10, return_type="string", # LLM-ready text sentiment="positive" ) # Use with LLM print(response.as_string) ``` -------------------------------- ### get_web_search() Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/chat-api.md Search the web and get LLM-processed summaries. This method takes a query and an optional number of results to return. ```APIDOC ## get_web_search() ### Description Search the web and get LLM-processed summaries. This method takes a query and an optional number of results to return. ### Method `get_web_search` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **query** (str) - Required - Search query * **n_results** (int) - Optional - Number of results * **http_headers** (Optional[Dict]) - Optional - Additional HTTP headers ### Response #### Success Response Returns `WebSearchResponse` - Web search results with summaries. #### Response Example (Response content varies based on query and number of results) ``` -------------------------------- ### Custom Deserialization Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/response-types.md Provides an example of custom deserialization using Pydantic's `TypeAdapter` for advanced use cases. ```APIDOC ### Custom Deserialization For advanced use cases: ```python from pydantic import TypeAdapter # Custom deserialization adapter = TypeAdapter(List[ArticleResponse]) articles = adapter.validate_python(raw_data) ``` ``` -------------------------------- ### Initialize SDK with Retries and Timeout Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Initialize the SDK with custom retry count and timeout settings. This is useful for handling transient network issues. ```python sdk = AskNewsSDK( api_key="key", retries=5, # Retry up to 5 times timeout=30.0 # 30 second timeout ) ``` -------------------------------- ### Synchronous SDK Initialization and Usage Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Demonstrates how to initialize the synchronous AskNewsSDK using API key or OAuth2 authentication and perform a basic news search. ```APIDOC ## Synchronous SDK ### Description Initialize the synchronous `AskNewsSDK` and perform a news search. ### Initialization ```python from asknews_sdk import AskNewsSDK # API key authentication with AskNewsSDK(api_key="sk-asknews-...") as sdk: response = sdk.news.search_news("query") # OAuth2 authentication sdk = AskNewsSDK( client_id="your-client-id", client_secret="your-client-secret" ) ``` ### Import Path `asknews_sdk.AskNewsSDK` ### Source File `asknews_sdk/sdk.py:37` ``` -------------------------------- ### get_forecasts() Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/chat-api.md Get forecasts on real-time events. This method takes a query string and optional filter parameters to retrieve predictions. ```APIDOC ## get_forecasts() ### Description Get forecasts on real-time events. This method takes a query string and optional filter parameters to retrieve predictions. ### Method `get_forecasts` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **query** (str) - Required - Event or topic to forecast * **filter_params** (Optional[Dict]) - Optional - News filters for context * **http_headers** (Optional[Dict]) - Optional - Additional HTTP headers ### Response #### Success Response Returns `ForecastResponse` - Forecast data and predictions. #### Response Example (Response content varies based on query) ``` -------------------------------- ### Initialize SDK with Custom HTTP Client Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/sdk-initialization.md Initializes the AskNewsSDK by providing a custom httpx Client for advanced configuration, such as connection limits, timeouts, or SSL verification. ```python from httpx import Client custom_client = Client( limits=httpx.Limits(max_connections=100), timeout=30.0, verify=False ) sdk = AskNewsSDK(api_key="key", client=custom_client) ``` -------------------------------- ### Handle ConcurrencyLimitExceededError Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/errors.md Example of catching a ConcurrencyLimitExceededError and informing the user to try again later. This error indicates too many simultaneous requests. ```python try: response = sdk.chat.get_chat_completions(messages) except ConcurrencyLimitExceededError: print("Too many concurrent requests, try again later") ``` -------------------------------- ### Load SDK Configuration from Environment Variables Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/configuration.md Configure the SDK using standard environment variables for API key and base URL. The SDK defaults to 'https://api.asknews.app' if ASKNEWS_BASE_URL is not set. ```python import os from asknews_sdk import AskNewsSDK # Load from environment api_key = os.getenv("ASKNEWS_API_KEY") base_url = os.getenv("ASKNEWS_BASE_URL", "https://api.asknews.app") sdk = AskNewsSDK( api_key=api_key, base_url=base_url ) ``` -------------------------------- ### Get News Stories Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Retrieves complete news stories with updates and metadata. Supports filtering by categories and limiting the number of results. ```APIDOC ## Get News Stories ### Description Retrieves complete news stories with updates and metadata. Supports filtering by categories and limiting the number of results. ### Method POST (assumed from SDK usage) ### Endpoint /v1/stories/search (assumed from SDK usage) ### Parameters #### Query Parameters - **query** (string) - Required - The search query for stories. - **categories** (list[string]) - Optional - Filters stories by specified categories. - **limit** (integer) - Optional - The maximum number of stories to return. - **expand_updates** (boolean) - Optional - Whether to include detailed updates for each story. ### Request Example ```python response = sdk.stories.search_stories( query="artificial intelligence", categories=["Technology", "Science"], limit=5, expand_updates=True ) for story in response.stories: print(f"{story.topic} ({story.n_updates} updates)") for update in story.updates: print(f" {update.headline}") ``` ### Response #### Success Response - **stories** (list[StoryResponse]) - A list of news stories, each containing topic, updates, sentiment, countries, languages, people, locations, and categories. #### Response Example ```json { "stories": [ { "topic": "AI Advancements", "updates": [ { "headline": "New AI Model Achieves Human-Level Performance", "timestamp": "..." } ], "sentiment": 0.8, "countries": ["USA"], "languages": ["en"], "people": ["Dr. Smith"], "locations": ["Silicon Valley"], "categories": ["Technology"] } ] } ``` ``` -------------------------------- ### Initialize AskNewsSDK with Standard Configuration Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/configuration.md Initialize the AskNewsSDK with various authentication, OAuth, and connection settings. Authentication can be done via API key, client ID/secret, or OAuth. ```python from asknews_sdk import AskNewsSDK sdk = AskNewsSDK( # Authentication (one required) api_key: Optional[str] = None, client_id: Optional[str] = None, client_secret: Optional[str] = None, # OAuth Configuration scopes: Optional[Set[str]] = {"news", "stories", "chat", "analytics"}, token_url: str = "https://auth.asknews.app/oauth2/token", # Connection Settings base_url: str = "https://api.asknews.app", verify_ssl: bool = True, timeout: Optional[float] = None, retries: int = 3, follow_redirects: bool = True, # HTTP Client client: Union[Type[Client], Client] = Client, auth: Optional[Union[RequestAuth, Sentinel]] = CLIENT_DEFAULT, # Additional kwargs passed to httpx Client **kwargs ) ``` -------------------------------- ### Initialize AskNewsSDK with Custom HTTPX Client Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/configuration.md Configure connection pooling for the underlying HTTPX client and pass it during SDK initialization. This allows for fine-grained control over connection management. ```python from httpx import Limits, Client from asknews_sdk import AskNewsSDK # Configure connection pooling client = Client( limits=Limits( max_connections=100, max_keepalive_connections=50 ) ) sdk = AskNewsSDK(api_key="key", client=client) ``` -------------------------------- ### Basic Authentication Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/authentication.md Initialize the SDK with basic authentication credentials (username and password). This is a common and simple authentication method for many services. ```python sdk = AskNewsSDK( auth=("username", "password") ) ``` -------------------------------- ### Handle ValidationError Exception Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/errors.md Example of catching a ValidationError and printing the validation error details. This is useful for debugging issues with request data. ```python try: request = URLIndexingRequest( start_time="invalid", # Should be datetime end_time=datetime.now(), urls=[] ) except ValidationError as e: print(f"Validation errors: {e.detail}") ``` -------------------------------- ### IndexCountsResponse Data Structure Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/types.md Represents time-series article counts, including the start and end times of the period and the count within that period. ```python class IndexCountsResponse(BaseSchema, RootModel[List[IndexCountItem]]): root: List[IndexCountItem] class IndexCountItem(BaseModel): start: datetime end: datetime count: int ``` -------------------------------- ### Verify Stored Keys with Error Handling Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/wiki-byok-apis.md Demonstrates how to retrieve a stored key hint and handle potential exceptions if no key is stored for the provider. ```python try: response = sdk.byok.get_byok_key(provider="anthropic") print(f"Anthropic key stored: {response.key_hint}") except Exception as e: print(f"No Anthropic key stored: {e}") ``` -------------------------------- ### Search News Stories with Filters Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Search for news stories using keywords and categories. Expand updates to get more details per story. ```python response = sdk.stories.search_stories( query="artificial intelligence", categories=["Technology", "Science"], limit=5, expand_updates=True ) for story in response.stories: print(f"{story.topic} ({story.n_updates} updates)") for update in story.updates: print(f" {update.headline}") ``` -------------------------------- ### SDK Initialization with OAuth2 Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Initialize the AskNewsSDK using OAuth2 client credentials and specified scopes. ```python sdk = AskNewsSDK( client_id="your-id", client_secret="your-secret", scopes={"news", "chat"} ) ``` -------------------------------- ### Configure Proxy for Requests Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/configuration.md Set up a proxy for SDK requests, either by reading from environment variables or by explicitly defining the proxy URL. This is essential for routing traffic through a proxy server. ```python import os # From environment proxy = os.getenv("HTTPS_PROXY") # Or explicit from httpx import Client client = Client(proxy="https://proxy.company.com:8080") sdk = AskNewsSDK(api_key="key", client=client) ``` -------------------------------- ### Initialize Synchronous SDK with API Key Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/sdk-initialization.md Instantiate the synchronous AskNewsSDK client using an API key for authentication. This client can be used within a context manager for automatic resource cleanup. ```python from asknews_sdk import AskNewsSDK with AskNewsSDK(api_key="your-api-key") as sdk: response = sdk.ping() print(f"API Version: {response.version}") ``` -------------------------------- ### Handle APIError Exception Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/errors.md Example of how to catch and process a general APIError. It prints the error code, detail, and the HTTP status code from the response. ```python try: article = sdk.news.get_article(invalid_id) except APIError as e: print(f"Error {e.code}: {e.detail}") print(f"Status: {e.response.status_code}") ``` -------------------------------- ### Initialize SDK with Custom Authentication Handler Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/sdk-initialization.md Initializes the AskNewsSDK with a custom authentication handler. This allows for advanced or non-standard authentication mechanisms. ```python from httpx import Auth class CustomAuth(Auth): def auth_flow(self, request): request.headers["X-Custom-Auth"] = "value" yield request sdk = AskNewsSDK(auth=CustomAuth()) ``` -------------------------------- ### Initialize Synchronous SDK with OAuth2 Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Shows how to initialize the synchronous AskNewsSDK using OAuth2 client credentials. This method is suitable for server-to-server authentication flows. ```python sdk = AskNewsSDK( client_id="your-client-id", client_secret="your-client-secret" ) ``` -------------------------------- ### Get Asset Sentiment Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/analytics-api.md Retrieves sentiment analysis for a specific asset. This can be used for individual stock sentiment or as a building block for custom sentiment indices. ```APIDOC ## Get Asset Sentiment ### Description Retrieves sentiment analysis for a specific asset. This can be used for individual stock sentiment or as a building block for custom sentiment indices. ### Method `sdk.analytics.get_asset_sentiment` ### Parameters #### Path Parameters None #### Query Parameters - **asset** (string) - Required - The asset symbol (e.g., "tesla", "bitcoin"). - **metric** (string) - Required - The sentiment metric to retrieve (e.g., "news_negative", "news_positive_weighted"). - **date_from** (string) - Optional - The start date for the sentiment data in YYYY-MM-DD format. - **date_to** (string) - Optional - The end date for the sentiment data in YYYY-MM-DD format. ### Request Example ```python response = sdk.analytics.get_asset_sentiment( asset="tesla", metric="news_negative", date_from="2024-09-01", date_to="2024-12-31" ) ``` ### Response #### Success Response (200) - **data** (list) - A list of sentiment data points, each containing a value and timestamp. #### Response Example ```json { "data": [ { "timestamp": "2024-09-01T00:00:00Z", "value": 0.15 }, { "timestamp": "2024-09-02T00:00:00Z", "value": 0.12 } ] } ``` ``` -------------------------------- ### Get News Sources Report Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/news-api.md Retrieve an analytics report on news sources and their diversity. This function is useful for understanding the landscape of news coverage over a specified period. ```python def get_sources_report( n_points: int = 100, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None, metric: str = "countries_diversity", sampling: str = "1h", *, http_headers: Optional[Dict] = None ) -> SourceReportResponse ``` -------------------------------- ### Get Asset Sentiment (Asynchronous) Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/analytics-api.md Asynchronously retrieves time-series sentiment data for a specified financial asset and metric. Use this in async applications for non-blocking operations. ```python import asyncio from asknews_sdk import AsyncAskNewsSDK from datetime import datetime, timedelta async def main(): async with AsyncAskNewsSDK(api_key="key") as sdk: response = await sdk.analytics.get_asset_sentiment( asset="ethereum", metric="news_negative_weighted", date_from=datetime(2024, 1, 1), date_to=datetime(2024, 12, 31) ) print(response) asyncio.run(main()) ``` -------------------------------- ### Initialize SDK using Context Manager Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Use the SDK as a context manager for automatic resource management. The connection pool is automatically closed upon exiting the 'with' block. ```python with AskNewsSDK(api_key="key") as sdk: response = sdk.news.search_news("query") # Connection pool automatically closed ``` -------------------------------- ### list_models Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/chat-api.md Get a list of available Large Language Models (LLMs) that can be used with the API. This method accepts optional HTTP headers and returns a list of model identifiers. ```APIDOC ## list_models() ### Description Get available LLM models. ### Method GET ### Endpoint /v1/models ### Parameters #### Query Parameters - **http_headers** (Optional[Dict]) - Optional - Additional HTTP headers ### Response #### Success Response (200) - **models** (ListModelResponse) - List of available models ``` -------------------------------- ### Use Synchronous SDK as Context Manager Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/sdk-initialization.md Demonstrates using the synchronous AskNewsSDK within a Python 'with' statement, ensuring proper initialization and cleanup. This pattern is recommended for managing SDK resources. ```python with AskNewsSDK(api_key="your-api-key") as sdk: result = sdk.news.search_news("query") ``` -------------------------------- ### Custom Pydantic Deserialization with TypeAdapter Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/response-types.md Provides an example of using Pydantic's TypeAdapter for custom deserialization scenarios, such as validating a list of ArticleResponse objects from raw data. ```python from pydantic import TypeAdapter # Custom deserialization adapter = TypeAdapter(List[ArticleResponse]) articles = adapter.validate_python(raw_data) ``` -------------------------------- ### Initialize Asynchronous SDK with API Key Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Illustrates initializing the asynchronous AsyncAskNewsSDK using an API key. This is the asynchronous equivalent for API key authentication, suitable for non-blocking operations. ```python import asyncio from asknews_sdk import AsyncAskNewsSDK async def main(): async with AsyncAskNewsSDK(api_key="sk-asknews-...") as sdk: response = await sdk.news.search_news("query") asyncio.run(main()) ``` -------------------------------- ### Get Index Counts Over Time Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/news-api.md Retrieve time-series article index counts within a specified date range. Useful for tracking trends in news volume for specific categories. ```python def get_index_counts( start_datetime: datetime, end_datetime: datetime, sampling: Literal["5m", "1h", "12h", "1d", "1w", "1m"] = "1d", time_filter: Literal["crawl_date", "pub_date"] = "pub_date", categories: Optional[List[str]] = None, provocative: Optional[str] = "all", reporting_voice: Optional[Union[List[str], str]] = None, domains: Optional[Union[List[str], str]] = None, bad_domain_url: Optional[Union[List[str], str]] = None, page_rank: Optional[int] = None, string_guarantee: Optional[List[str]] = None, string_guarantee_op: Optional[str] = "OR", reverse_string_guarantee: Optional[List[str]] = None, entity_guarantee: Optional[List[str]] = None, entity_guarantee_op: Optional[str] = "OR", countries: Optional[List[str]] = None, countries_blacklist: Optional[List[str]] = None, languages: Optional[List[str]] = None, continents: Optional[List[str]] = None, sentiment: Optional[Literal["negative", "neutral", "positive"]] = None, *, http_headers: Optional[Dict] = None ) -> IndexCountsResponse ``` ```python from datetime import datetime, timedelta end = datetime.now() start = end - timedelta(days=7) response = sdk.news.get_index_counts( start_datetime=start, end_datetime=end, sampling="1d", categories=["Technology"] ) ``` -------------------------------- ### Get Forecasts on Events with get_forecasts() Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/chat-api.md Retrieve forecasts on real-time events or topics. This function requires a query string and optionally accepts news filters and custom HTTP headers. ```python def get_forecasts( query: str, filter_params: Optional[Dict] = None, *, http_headers: Optional[Dict] = None ) -> ForecastResponse ``` -------------------------------- ### Async SDK Configuration Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/configuration.md Configure the asynchronous version of the SDK with similar parameters to the synchronous SDK. Use 'async with' for automatic resource management. ```python import asyncio from asknews_sdk import AsyncAskNewsSDK async def main(): # Same configuration as sync SDK async with AsyncAskNewsSDK( api_key="key", timeout=30.0, retries=3 ) as sdk: response = await sdk.news.search_news("query") return response result = asyncio.run(main()) ``` -------------------------------- ### Initialize SDK with OAuth2 Client Credentials Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/sdk-initialization.md Initializes the AskNewsSDK using OAuth2 client credentials. The SDK automatically manages token refresh and expiration. ```python sdk = AskNewsSDK( client_id="your-client-id", client_secret="your-client-secret", scopes={"news", "stories", "chat", "analytics"} ) ``` -------------------------------- ### get_asset_sentiment() Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/analytics-api.md Get time-series sentiment data for a financial asset based on news mentions. Supports various cryptocurrencies and stocks, with options to specify sentiment metrics and date ranges. ```APIDOC ## GET /analytics/asset/sentiment ### Description Retrieves time-series sentiment data for a specified financial asset based on news mentions. Allows filtering by asset, sentiment metric, and date range. ### Method GET ### Endpoint /analytics/asset/sentiment ### Parameters #### Query Parameters - **asset** (Literal["bitcoin", "ethereum", "cardano", "uniswap", "ripple", "solana", "polkadot", "polygon", "chainlink", "tether", "dogecoin", "monero", "tron", "binance", "aave", "tesla", "microsoft", "amazon"]) - Required - Asset to analyze. - **metric** (Literal["news_positive", "news_negative", "news_total", "news_positive_weighted", "news_negative_weighted", "news_total_weighted"]) - Optional - Sentiment metric to return. Defaults to "news_positive". - **date_from** (Optional[Union[datetime, str]]) - Optional - Start date (ISO format or datetime). - **date_to** (Optional[Union[datetime, str]]) - Optional - End date (ISO format or datetime). ### Request Example ```python # Using the synchronous SDK client from datetime import datetime, timedelta from asknews_sdk import AskNewsSDK with AskNewsSDK(api_key="key") as sdk: end_date = datetime.now() start_date = end_date - timedelta(days=30) response = sdk.analytics.get_asset_sentiment( asset="bitcoin", metric="news_positive_weighted", date_from=start_date, date_to=end_date ) for data_point in response.data: print(f"{data_point.date}: {data_point.value}") ``` ### Response #### Success Response (200) - **data** (List[SentimentDataPoint]) - Time series data points. - **asset** (str) - Asset analyzed. - **metric** (str) - Metric returned. - **date_from** (datetime) - Start of date range. - **date_to** (datetime) - End of date range. #### Response Example ```json { "data": [ { "date": "2024-01-01T00:00:00Z", "value": 0.75, "count": 150 }, { "date": "2024-01-02T00:00:00Z", "value": 0.82, "count": 165 } ], "asset": "bitcoin", "metric": "news_positive_weighted", "date_from": "2023-12-03T00:00:00Z", "date_to": "2024-01-01T00:00:00Z" } ``` ``` -------------------------------- ### ByokAPI Methods Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/README.md Provides methods for managing Bring Your Own Key (BYOK) configurations. ```APIDOC ## ByokAPI / AsyncByokAPI ### Description Manage Bring Your Own Key (BYOK) settings for external providers. ### Methods - `sdk.byok.set_byok_key(provider, api_key)`: Set a BYOK key for a provider. - `sdk.byok.get_byok_key(provider)`: Retrieve the BYOK key for a provider. - `sdk.byok.delete_byok_key(provider)`: Delete the BYOK key for a provider. ### Import Paths - `asknews_sdk.api.ByokAPI` - `asknews_sdk.api.AsyncByokAPI` ### Documentation [Wiki & BYOK APIs](wiki-byok-apis.md) ``` -------------------------------- ### Chat Message Format Source: https://github.com/emergentmethods/asknews-python-sdk/blob/main/_autodocs/chat-api.md Illustrates the standard message format for chat interactions, following the OpenAI Chat Completions specification. Includes examples for system, user, and assistant roles. ```python messages = [ { "role": "system", "content": "You are a financial analyst." }, { "role": "user", "content": "What happened to the stock market today?" }, { "role": "assistant", "content": "Based on the latest news..." }, { "role": "user", "content": "Any impact on tech stocks?" } ] ```