| import logging |
| import time |
| import requests |
| import json |
| import os |
|
|
| from src.api.finnhub.financial_news_requester import fetch_comp_financial_news |
| from src.api.openrouter.prompt_generator import PromptGenerator |
|
|
|
|
| class OpenRouterClient: |
| def __init__(self, model: str = "tngtech/deepseek-r1t2-chimera:free", api_key: str | None = None): |
| self._api_key = api_key or os.getenv("OPENROUTER_API_TOKEN") |
| if not self._api_key: |
| raise ValueError("OpenRouter API key is required") |
| self._api_url = "https://openrouter.ai/api/v1/chat/completions" |
| self.model = model |
|
|
| def chat(self, user_message: str, role: str = "user") -> str: |
| """ |
| Sends a message to the OpenRouter API and returns the response. |
| Raises RuntimeError for HTTP errors and ValueError for unexpected response formats. |
| |
| Args: |
| user_message (str): The message to send to the model. |
| Returns: |
| str: The response from the model. |
| Raises: |
| RuntimeError: If the API request fails. |
| ValueError: If the response format is unexpected. |
| """ |
| headers = { |
| "Authorization": f"Bearer {self._api_key}", |
| "Content-Type": "application/json" |
| } |
| payload = { |
| "model": self.model, |
| "messages": [ |
| { |
| "role": role, |
| "content": user_message |
| } |
| ] |
| } |
| try: |
| response = requests.post( |
| url=self._api_url, |
| headers=headers, |
| data=json.dumps(payload), |
| timeout=10 |
| ) |
| response.raise_for_status() |
| except requests.exceptions.RequestException as e: |
| logging.error(f"OpenRouter request error: {e}") |
| raise RuntimeError(f"Request error: {e}") |
| response_json = response.json() |
| try: |
| return response_json["choices"][0]["message"]["content"] |
| except (KeyError, IndexError): |
| logging.error(f"Unexpected response format: {response_json}") |
| raise ValueError(f"Unexpected response format: {response_json}") |
|
|
|
|
| if __name__ == "__main__": |
| sample_news = fetch_comp_financial_news(ticker='NVDA', date_from='2025-08-04', date_to='2025-08-05') |
| print(sample_news) |
| print(len(sample_news)) |
| |
| client = OpenRouterClient() |
| try: |
| for news in sample_news: |
| start_time = time.perf_counter() |
| prompt = PromptGenerator.format_prompt(news) |
| print(f"Prompt: {prompt}") |
| response = client.chat(prompt) |
| print(f"Response: {response}") |
| elapsed = time.perf_counter() - start_time |
| print(f"Processing time: {elapsed:.2f} seconds") |
| except (RuntimeError, ValueError) as e: |
| print(f"Error: {e}") |
|
|