Spaces:
Runtime error
Runtime error
File size: 2,889 Bytes
bba1099 |
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 |
import logging
import time
import requests
import json
import os
from api.finnhub.financial_news_requester import fetch_comp_financial_news
from 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_KEY")
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))
# Example usage
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}")
|