Files
signal-platform/app/providers/openai_compatible_sentiment.py
T
dennisthiessen ffb609d38f
Deploy / lint (push) Successful in 5s
Deploy / test (push) Successful in 31s
Deploy / deploy (push) Successful in 23s
Fix xAI sentiment: use Agent Tools web_search (Live Search deprecated)
xAI returned 410 — search_parameters/Live Search is retired. Route xAI
through the Responses API web_search tool instead (same path as OpenAI):
- OpenAISentimentProvider parametrized with base_url / tool_type / source
- xAI builds it against https://api.x.ai/v1 with the web_search tool
- Drop the dead Live Search code from the generic compatible provider
- Frontend label: "xAI Grok — web search"

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-13 14:30:45 +02:00

132 lines
4.9 KiB
Python

"""Sentiment provider for any OpenAI-compatible Chat Completions endpoint.
Covers DeepSeek, OpenRouter, Together, Groq, Mistral, local Ollama, etc. — any
service exposing the OpenAI Chat Completions API at a custom base_url.
NOTE: Unlike the OpenAI Responses provider and Gemini, this path has NO web
search grounding. Sentiment reflects the model's training knowledge, not live
news. Cheap, but not real-time.
"""
from __future__ import annotations
import json
import logging
import os
from datetime import datetime, timezone
from pathlib import Path
import httpx
from openai import AsyncOpenAI
from app.exceptions import ProviderError, RateLimitError
from app.providers.protocol import SentimentData
logger = logging.getLogger(__name__)
_CA_BUNDLE = os.environ.get("SSL_CERT_FILE", "")
_SENTIMENT_PROMPT = """\
Assess the CURRENT market sentiment for the stock ticker {ticker} based on your \
knowledge of the company, its sector, and recent developments you are aware of.
Respond ONLY with a JSON object in this exact format (no markdown, no extra text):
{{"classification": "<bullish|bearish|neutral>", "confidence": <0-100>, "reasoning": "<brief explanation>"}}
Rules:
- classification must be exactly one of: bullish, bearish, neutral
- confidence must be an integer from 0 to 100
- reasoning should be a brief one-sentence explanation
"""
VALID_CLASSIFICATIONS = {"bullish", "bearish", "neutral"}
def _clean_json_text(raw: str) -> str:
clean = raw.strip()
if clean.startswith("```"):
clean = clean.split("\n", 1)[1] if "\n" in clean else clean[3:]
if clean.endswith("```"):
clean = clean[:-3]
return clean.strip()
class OpenAICompatibleSentimentProvider:
"""Sentiment via the OpenAI Chat Completions API at a configurable base_url."""
def __init__(
self,
api_key: str,
model: str,
base_url: str,
source: str = "openai_compatible",
) -> None:
if not api_key:
raise ProviderError("API key is required")
if not base_url:
raise ProviderError("base_url is required for an OpenAI-compatible provider")
if not model:
raise ProviderError("model is required")
http_kwargs: dict = {}
if _CA_BUNDLE and Path(_CA_BUNDLE).exists():
http_kwargs["verify"] = _CA_BUNDLE
http_client = httpx.AsyncClient(**http_kwargs)
self._client = AsyncOpenAI(api_key=api_key, base_url=base_url, http_client=http_client)
self._model = model
self._source = source
async def fetch_sentiment(self, ticker: str) -> SentimentData:
try:
response = await self._client.chat.completions.create(
model=self._model,
messages=[
{
"role": "system",
"content": "You are a financial sentiment analyst. Always respond with valid JSON only, no markdown fences.",
},
{"role": "user", "content": _SENTIMENT_PROMPT.format(ticker=ticker)},
],
temperature=0.3,
)
raw_text = (response.choices[0].message.content or "").strip()
if not raw_text:
raise ProviderError(f"Empty response from {self._source} for {ticker}")
parsed = json.loads(_clean_json_text(raw_text))
classification = str(parsed.get("classification", "")).lower()
if classification not in VALID_CLASSIFICATIONS:
raise ProviderError(
f"Invalid classification '{classification}' from {self._source} for {ticker}"
)
confidence = max(0, min(100, int(parsed.get("confidence", 50))))
reasoning = str(parsed.get("reasoning", ""))
if reasoning:
logger.info(
"%s sentiment for %s: %s (confidence=%d) — %s",
self._source, ticker, classification, confidence, reasoning,
)
return SentimentData(
ticker=ticker,
classification=classification,
confidence=confidence,
source=self._source,
timestamp=datetime.now(timezone.utc),
reasoning=reasoning,
)
except json.JSONDecodeError as exc:
logger.error("Failed to parse %s JSON for %s: %s", self._source, ticker, exc)
raise ProviderError(f"Invalid JSON from {self._source} for {ticker}") from exc
except ProviderError:
raise
except Exception as exc:
msg = str(exc).lower()
if "429" in msg or "rate" in msg or "quota" in msg or "insufficient" in msg:
raise RateLimitError(f"{self._source} rate limit hit for {ticker}") from exc
logger.error("%s provider error for %s: %s", self._source, ticker, exc)
raise ProviderError(f"{self._source} provider error for {ticker}: {exc}") from exc