Spaces:
Sleeping
Sleeping
Charan S commited on
Commit ·
3e964dd
0
Parent(s):
fix: deployment ready commit
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .dockerignoreAdded+26
- .env.exampleAdded+81
- .gitignoreAdded+22
- DockerfileAdded+25
- README.mdAdded+17
- backend/__init__.pyAdded
- backend/api/__init__.pyAdded
- backend/api/middleware/__init__.pyAdded
- backend/api/middleware/guardrails.pyAdded+38
- backend/api/middleware/rate_limit.pyAdded+12
- backend/api/routes/__init__.pyAdded
- backend/api/routes/chat.pyAdded+330
- backend/api/routes/health.pyAdded+116
- backend/api/routes/stocks.pyAdded+382
- backend/finora_mcp/__init__.pyAdded
- backend/finora_mcp/server.pyAdded+43
- backend/finora_mcp/tools/__init__.pyAdded
- backend/finora_mcp/tools/fundamentals.pyAdded+9
- backend/finora_mcp/tools/historical.pyAdded+26
- backend/finora_mcp/tools/news.pyAdded+27
- backend/finora_mcp/tools/quote.pyAdded+9
- backend/finora_mcp/tools/screener.pyAdded+63
- backend/graph/__init__.pyAdded
- backend/graph/finora_graph.pyAdded+96
- backend/graph/nodes/__init__.pyAdded
- backend/graph/nodes/fundamentals_node.pyAdded+131
- backend/graph/nodes/fusion_node.pyAdded+595
- backend/graph/nodes/historical_rag_node.pyAdded+41
- backend/graph/nodes/intent_classifier.pyAdded+102
- backend/graph/nodes/news_rag_node.pyAdded+72
- backend/graph/nodes/realtime_node.pyAdded+118
- backend/graph/nodes/response_cache.pyAdded+45
- backend/graph/nodes/response_node.pyAdded+193
- backend/graph/state.pyAdded+43
- backend/guardrails/__init__.pyAdded
- backend/guardrails/classifier.pyAdded+108
- backend/guardrails/disclaimers.pyAdded+20
- backend/guardrails/output_filter.pyAdded+86
- backend/main.pyAdded+93
- backend/observability/__init__.pyAdded
- backend/observability/langsmith_client.pyAdded+66
- backend/observability/langsmith_url.pyAdded+64
- backend/observability/metrics.pyAdded+23
- backend/rag/__init__.pyAdded
- backend/rag/chunking/__init__.pyAdded
- backend/rag/chunking/financial.pyAdded+125
- backend/rag/chunking/strategies.pyAdded+124
- backend/rag/embedder.pyAdded+22
- backend/rag/evaluation/__init__.pyAdded
- backend/rag/evaluation/ragas_eval.pyAdded+147
1234567891011121314151617181920212223242526__pycache__/*.pyc*.pyo*.pyd
.venv/venv/env/
data/hf_cache/data/qdrant/data/bm25_index/
.git/.gitignore
*.loglogs/
.env.venv
finora-frontend/node_modules/
.DS_Store123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081# =============================================================================# FINORA BACKEND — Environment Variables Template# Copy this file to .env and fill in your values: cp .env.example .env# Production: set all these in HuggingFace Secrets instead of this file# =============================================================================
# ── LLM: Groq ────────────────────────────────────────────────────────────────# https://console.groq.com → Create API KeyGROQ_API_KEY=your_groq_api_key_hereGROQ_MODEL_PRIMARY=llama-3.3-70b-versatileGROQ_MODEL_FAST=llama-3.1-8b-instantGROQ_MAX_TOKENS=2048GROQ_TEMPERATURE=0.1
# ── Observability: LangSmith ──────────────────────────────────────────────────# https://smith.langchain.com → Settings → API KeysLANGCHAIN_API_KEY=your_langsmith_api_key_hereLANGCHAIN_PROJECT=finora-prodLANGCHAIN_TRACING_V2=trueLANGCHAIN_ENDPOINT=https://api.smith.langchain.com
# ── Vector Store: Qdrant Cloud ────────────────────────────────────────────────# https://cloud.qdrant.io → Create free cluster → copy URL and API keyQDRANT_URL=https://your-cluster-id.us-east-1-1.aws.cloud.qdrant.ioQDRANT_API_KEY=your_qdrant_api_key_hereQDRANT_COLLECTION_NEWS=finora_newsQDRANT_COLLECTION_HISTORICAL=finora_historicalQDRANT_COLLECTION_FILINGS=finora_filings
# ── Reranker: Cohere ──────────────────────────────────────────────────────────# https://dashboard.cohere.com → API Keys (free tier available)# Falls back to local BAAI/bge-reranker-base if Cohere fails or rate-limitsCOHERE_API_KEY=your_cohere_api_key_hereRERANKER_PROVIDER=cohere
# ── Market Data ───────────────────────────────────────────────────────────────# Polygon.io: https://polygon.io/dashboard (free: 5 calls/min)POLYGON_API_KEY=your_polygon_api_key_here# NewsAPI: https://newsapi.org/register (free: 100 req/day)NEWSAPI_KEY=your_newsapi_key_here
# ── Embeddings: HuggingFace (local, no API key needed) ───────────────────────EMBEDDING_MODEL=sentence-transformers/all-MiniLM-L6-v2RERANKER_MODEL=BAAI/bge-reranker-baseHF_HOME=./data/hf_cache
# ── SEC EDGAR (no key — fair use requires a user agent) ──────────────────────SEC_EDGAR_USER_AGENT=YourName contact@youremail.com
# ── RAG Configuration ─────────────────────────────────────────────────────────RAG_TOP_K=8RAG_OVER_RETRIEVE_FACTOR=2RAG_HYDE_ENABLED=trueRAG_RERANKER_ENABLED=trueRAG_HYBRID_ALPHA=0.6RAG_MMR_LAMBDA=0.6RAG_DEDUP_THRESHOLD=0.92
# ── Guardrails ────────────────────────────────────────────────────────────────GUARDRAILS_ENABLED=trueGUARDRAILS_MODE=strictDISCLAIMER_LOCALE=INGUARDRAILS_LOG_BLOCKED=true
# ── Application ───────────────────────────────────────────────────────────────BACKEND_PORT=7860BACKEND_HOST=0.0.0.0ENV=developmentLOG_LEVEL=INFOCORS_ORIGINS=http://localhost:3000,https://your-app.vercel.appSCHEDULER_ENABLED=false
# ── Rate Limiting ─────────────────────────────────────────────────────────────RATE_LIMIT_PER_MINUTE=20RATE_LIMIT_PER_HOUR=200MAX_QUERY_LENGTH=500MAX_CONVERSATION_TURNS=50
# ── Ingestion Scheduler ───────────────────────────────────────────────────────NEWS_INGEST_INTERVAL_MINUTES=15HISTORICAL_UPDATE_INTERVAL_HOURS=2412345678910111213141516171819202122# virtual environment.venv/venv/.env/
# Python cache__pycache__/*.pyc
# HF / ML cachesdata/data/hf_cache/data/qdrant/data/bm25_index/
# logs*.loglogs/
# env files (IMPORTANT).envfinora-backend/.env12345678910111213141516171819202122232425FROM python:3.11-slim
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends \ curl \ build-essential \ git \ && rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
ENV HF_HOME=/tmp/hf_cacheENV TRANSFORMERS_CACHE=/tmp/hf_cacheENV SENTENCE_TRANSFORMERS_HOME=/tmp/hf_cache
ENV PYTHONPATH=/app/backend
COPY . .
EXPOSE 7860
CMD ["uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "7860"]1234567891011121314151617---title: Finora Backendemoji: 🐳colorFrom: purplecolorTo: graysdk: dockerapp_port: 7860---
# Finora Backend (FastAPI + RAG + ML Stack)
Production-grade financial AI backend with:- Intent classification (LLM + rules)- RAG (news, historical, filings)- Qdrant vector search- Groq LLM inference- HuggingFace embeddings1234567891011121314151617181920212223242526272829303132333435363738"""Financial guardrails FastAPI middleware — request-level content policy enforcement.
Runs before the route handler to reject clearly non-financial querieswithout spending Groq tokens on the graph-level classifier."""from __future__ import annotations
import re
from fastapi import Request, Responsefrom fastapi.responses import JSONResponsefrom starlette.middleware.base import BaseHTTPMiddleware
_HARD_BLOCK_PATTERNS = [ re.compile(r"\b(hack|exploit|malware|phishing|ransomware)\b", re.I), re.compile(r"\b(credit card number|cvv|ssn|social security)\b", re.I),]
_CHAT_PATH = "/api/chat"
class FinancialGuardrailMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): if request.method == "POST" and request.url.path == _CHAT_PATH: try: body = await request.json() query = body.get("query", "") for pattern in _HARD_BLOCK_PATTERNS: if pattern.search(query): return JSONResponse( status_code=400, content={"detail": "Query violates content policy."}, ) except Exception: pass # malformed JSON handled downstream
return await call_next(request)123456789101112import os
from slowapi import Limiterfrom slowapi.util import get_remote_address
limiter = Limiter( key_func=get_remote_address, default_limits=[ f"{os.getenv('RATE_LIMIT_PER_MINUTE', '20')}/minute", f"{os.getenv('RATE_LIMIT_PER_HOUR', '200')}/hour", ],)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330import jsonimport osimport reimport uuidfrom typing import AsyncIterator
import structlogfrom fastapi import APIRouter, Requestfrom fastapi.responses import StreamingResponsefrom pydantic import BaseModel, Field
from backend.api.middleware.rate_limit import limiterfrom backend.graph.nodes.response_cache import cache_key as _resp_cache_key, get_cached as _resp_get_cached, is_volatile_query as _resp_is_volatilefrom backend.rag.ingestion.universe import universe
log = structlog.get_logger()router = APIRouter(tags=["chat"])
def _parse_chart_timeframe(query: str) -> tuple[str, str, str]: """ Returns (range_str, interval, label) for fetch_ohlcv based on query text. Handles standard timeframes, custom day counts, and date ranges. """ q = query.lower()
# Custom date range: "from 2025-01-01 to 2025-03-31" or "from jan 1 to mar 31" date_range = re.search( r"from\s+(\d{4}-\d{2}-\d{2})\s+to\s+(\d{4}-\d{2}-\d{2})", q ) if date_range: # Yahoo doesn't support arbitrary date ranges via range_str easily; # fall back to period calculation from datetime import date try: start = date.fromisoformat(date_range.group(1)) end = date.fromisoformat(date_range.group(2)) days = (end - start).days if days <= 7: return (f"{days}d", "5m", f"{days}D") elif days <= 90: return (f"{days}d", "1d", f"{days}D") else: return (f"{days}d", "1wk", f"{days}D") except ValueError: pass
# Custom N days: "20 days", "45 days", "past 10 days" n_days = re.search(r"(\d+)\s*day", q) if n_days: d = int(n_days.group(1)) d = max(1, min(d, 365)) interval = "5m" if d == 1 else "1d" if d <= 90 else "1wk" return (f"{d}d", interval, f"{d}D")
# N weeks n_weeks = re.search(r"(\d+)\s*week", q) if n_weeks: w = int(n_weeks.group(1)) w = max(1, min(w, 52)) days = w * 7 interval = "30m" if w == 1 else "1d" return (f"{days}d", interval, f"{w}W")
# N months n_months = re.search(r"(\d+)\s*month", q) if n_months: m = int(n_months.group(1)) m = max(1, min(m, 60)) interval = "1d" if m <= 6 else "1wk" return (f"{m}mo", interval, f"{m}M")
# N years n_years = re.search(r"(\d+)\s*year", q) if n_years: y = int(n_years.group(1)) y = max(1, min(y, 20)) interval = "1wk" if y <= 5 else "1mo" return (f"{y}y", interval, f"{y}Y")
# Named timeframes if any(x in q for x in ("intraday", "today", "1d", "1 day", "one day", "suddenly", "crashing", "crashed", "surging", "surged", "dropped", "spiked", "right now", "happening now")): return ("1d", "5m", "1D") if any(x in q for x in ("this week", "1w", "1 week", "one week", "past week", "7 day")): return ("5d", "30m", "1W") if any(x in q for x in ("3m", "3 month", "three month", "quarter", "quarterly")): return ("3mo", "1d", "3M") if any(x in q for x in ("6m", "6 month", "six month", "half year")): return ("6mo", "1d", "6M") if any(x in q for x in ("1y", "1 year", "one year", "past year", "this year", "ytd", "annual")): return ("1y", "1wk", "1Y") if any(x in q for x in ("3y", "3 year", "three year")): return ("3y", "1wk", "3Y") if any(x in q for x in ("5y", "5 year", "five year")): return ("5y", "1wk", "5Y") if any(x in q for x in ("all time", "all-time", "max", "20 year", "full history")): return ("20y", "1mo", "ALL")
# Default: 1 month return ("1mo", "1d", "1M")
MAX_CONVERSATION_TURNS = int(os.getenv("MAX_CONVERSATION_TURNS", "50"))
class ConversationTurn(BaseModel): role: str content: str
class ChatRequest(BaseModel): query: str = Field(..., max_length=500) ticker: str = Field(default="") conversation_history: list[ConversationTurn] = Field(default_factory=list) session_id: str = Field(default_factory=lambda: str(uuid.uuid4())) user_mode: str = Field(default="insight", pattern="^(insight|trader)$")
def _sse(event: dict) -> str: return f"data: {json.dumps(event)}\n\n"
async def _stream_graph(req: ChatRequest) -> AsyncIterator[str]: from backend.graph.finora_graph import graph
# Resolve yf_ticker from universe (e.g. TCS → TCS.NS, RELIANCE → RELIANCE.NS) entry = universe.get_by_ticker(req.ticker) if req.ticker else None yf_ticker = entry.get("yf_ticker", req.ticker) if entry else req.ticker
initial_state = { "query": req.query, "ticker": req.ticker, "yf_ticker": yf_ticker, "company_name": entry.get("name", req.ticker) if entry else req.ticker, "currency": entry.get("currency", "USD") if entry else "USD", "user_mode": req.user_mode, "session_id": req.session_id, "conversation_history": [t.model_dump() for t in req.conversation_history], "intents": [], "guardrail_flags": [], "guardrail_blocked": False, "realtime_context": None, "news_chunks": [], "historical_chunks": [], "fundamental_data": None, "sector_context": None, "fused_context": "", "response": "", "citations": [], "confidence_score": 0.0, "disclaimer_text": "", "trace_id": str(uuid.uuid4())[:8], "retrieval_scores": {}, }
# Per-request unique thread_id — prevents MemorySaver from accumulating # operator.add fields (news_chunks, historical_chunks) across invocations. # Conversation history is passed explicitly in initial_state, so nothing is lost. trace_id = initial_state["trace_id"] config = {"configurable": {"thread_id": f"{req.session_id}:{req.ticker}:{trace_id}"}}
try: yield _sse({"type": "status", "message": "Analyzing query..."})
# Early cache bypass — skip entire graph if response is cached # Uses TTL-only check (no price data yet); price-based invalidation runs in response_node if req.ticker and not _resp_is_volatile(req.query): _key = _resp_cache_key(req.ticker, req.query, req.user_mode) _cached_text = _resp_get_cached(_key, current_pct=None) if _cached_text: log.info("early_cache_hit", ticker=req.ticker, session=req.session_id) yield _sse({"type": "guardrail", "status": "allowed"}) yield _sse({"type": "intent", "intents": []}) sentences = _cached_text.split(". ") for i, sent in enumerate(sentences): content = sent + (". " if i < len(sentences) - 1 else "") yield _sse({"type": "token", "content": content}) yield _sse({"type": "done", "trace_id": trace_id, "confidence": 0.0, "cached": True}) return
# Stream graph events node-by-node async for event in graph.astream(initial_state, config=config): node_name = next(iter(event)) node_output = event[node_name]
if node_name == "guardrail_check": blocked = node_output.get("guardrail_blocked", False) yield _sse({"type": "guardrail", "status": "blocked" if blocked else "allowed"}) if blocked: response = node_output.get("response", "") disclaimer = node_output.get("disclaimer_text", "") yield _sse({"type": "token", "content": response}) if disclaimer: yield _sse({"type": "disclaimer", "text": disclaimer}) yield _sse({"type": "done", "trace_id": req.session_id[:8], "confidence": 0.0}) return
elif node_name == "intent_classifier": intents = node_output.get("intents", []) yield _sse({"type": "intent", "intents": intents})
elif node_name == "parallel_retrieval": news_n = len(node_output.get("news_chunks") or []) hist_n = len(node_output.get("historical_chunks") or []) has_rt = node_output.get("realtime_context") is not None yield _sse({ "type": "retrieving", "status": "done", "news_chunks": news_n, "historical_chunks": hist_n, "realtime": has_rt, })
elif node_name == "response_node": response = node_output.get("response", "") # Stream sentence-by-sentence for smooth rendering sentences = response.split(". ") for i, sent in enumerate(sentences): content = sent + (". " if i < len(sentences) - 1 else "") yield _sse({"type": "token", "content": content})
# Final state — emit citations, disclaimer, done final = await graph.aget_state(config) final_vals = final.values if final else {}
# Shared intent + keyword context for gating visual/news output _active_intents = set(final_vals.get("intents") or []) _query_words = set(req.query.lower().split())
_news_intents = {"news"} _news_keywords = {"news", "why", "drop", "rise", "fell", "rally", "crash", "surge", "spike", "decline", "moved", "sliding", "today", "week", "recent", "latest", "reported", "announced", "earnings", "results", "catalyst"} _should_cite = bool( _active_intents & _news_intents or _query_words & _news_keywords )
citations = final_vals.get("citations", []) if citations and _should_cite: yield _sse({"type": "citation", "sources": citations})
disclaimer = final_vals.get("disclaimer_text", "") if disclaimer: yield _sse({"type": "disclaimer", "text": disclaimer})
# Emit 30-day price chart only when visually meaningful _chart_intents = {"real_time", "historical"} _chart_keywords = {"chart", "price", "movement", "trend", "performance", "summarize", "visualize", "graph", "history", "drop", "rise", "fell", "rally", "crash", "surge", "spike", "decline", "week", "month", "year", "today", "yesterday", "52", "high", "low", "range"} _should_chart = bool( _active_intents & _chart_intents or _query_words & _chart_keywords ) if yf_ticker and _should_chart: try: import asyncio as _asyncio from backend.rag.yahoo_client import fetch_ohlcv as _fetch_ohlcv currency = initial_state.get("currency", "USD")
range_str, interval, label = _parse_chart_timeframe(req.query)
def _get_bars(): df = _fetch_ohlcv(yf_ticker, range_str=range_str, interval=interval) if df.empty: return [] bars = [] for dt, row in df.iterrows(): try: date_str = str(dt) if interval in ("5m", "30m") else str(dt.date()) bars.append({ "date": date_str, "open": round(float(row["Open"]), 4), "high": round(float(row["High"]), 4), "low": round(float(row["Low"]), 4), "close": round(float(row["Close"]), 4), }) except Exception: continue return bars
loop = _asyncio.get_event_loop() bars = await loop.run_in_executor(None, _get_bars) if bars: yield _sse({ "type": "chart_data", "ticker": req.ticker, "currency": currency, "label": label, "bars": bars, }) except Exception as chart_exc: log.debug("chart_data_fetch_failed", error=str(chart_exc))
confidence = final_vals.get("confidence_score", 0.0) trace_id = final_vals.get("trace_id", req.session_id[:8]) from backend.observability.langsmith_url import get_project_url langsmith_url = get_project_url() yield _sse({ "type": "done", "trace_id": trace_id, "confidence": confidence, "langsmith_url": langsmith_url, })
except Exception as exc: log.error("graph_stream_failed", session=req.session_id, error=str(exc)) yield _sse({"type": "error", "message": "An error occurred processing your query."}) yield _sse({"type": "done", "trace_id": req.session_id[:8], "confidence": 0.0})
@router.post("/chat")@limiter.limit("20/minute")async def chat(request: Request, body: ChatRequest) -> StreamingResponse: if len(body.conversation_history) > MAX_CONVERSATION_TURNS: body.conversation_history = body.conversation_history[-MAX_CONVERSATION_TURNS:]
log.info("chat_request", session=body.session_id, ticker=body.ticker, query_len=len(body.query))
return StreamingResponse( _stream_graph(body), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "X-Accel-Buffering": "no", }, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116import jsonimport osfrom pathlib import Path
import structlogfrom fastapi import APIRouterfrom pydantic import BaseModel
from backend.rag.ingestion.universe import universe
log = structlog.get_logger()router = APIRouter(tags=["health"])
_LANGSMITH_PROJECT = os.getenv("LANGCHAIN_PROJECT", "finora-prod")_EVAL_PATH = Path(__file__).parent.parent.parent / "data" / "eval_results" / "latest.json"
class HealthResponse(BaseModel): status: str qdrant: str groq: str langsmith: str langsmith_url: str universe_size: int
class EvalMetric(BaseModel): score: float target: float passed: bool delta: float | None = None
class EvalResponse(BaseModel): overall_pass: bool scores: dict[str, float] results: dict[str, EvalMetric] run_at: str | None = None tickers: list[str] = [] n_pairs: int | None = None
@router.get("/health", response_model=HealthResponse)async def health() -> HealthResponse: qdrant_status = "unconfigured" groq_status = "unconfigured" langsmith_status = "unconfigured" langsmith_url = f"https://smith.langchain.com/projects/{_LANGSMITH_PROJECT}"
if os.getenv("QDRANT_URL") and os.getenv("QDRANT_API_KEY"): try: from qdrant_client import QdrantClient client = QdrantClient( url=os.getenv("QDRANT_URL"), api_key=os.getenv("QDRANT_API_KEY"), timeout=3, ) client.get_collections() qdrant_status = "connected" except Exception as exc: log.warning("qdrant_health_failed", error=str(exc)) qdrant_status = "error"
if os.getenv("GROQ_API_KEY"): try: from groq import Groq groq_client = Groq(api_key=os.getenv("GROQ_API_KEY")) groq_client.chat.completions.create( model="llama-3.1-8b-instant", messages=[{"role": "user", "content": "ping"}], max_tokens=1, ) groq_status = "connected" except Exception as exc: log.warning("groq_health_failed", error=str(exc)) groq_status = "error"
if os.getenv("LANGCHAIN_API_KEY"): langsmith_status = "configured"
return HealthResponse( status="ok", qdrant=qdrant_status, groq=groq_status, langsmith=langsmith_status, langsmith_url=langsmith_url, universe_size=len(universe.stocks), )
@router.get("/eval/latest", response_model=EvalResponse)async def eval_latest() -> EvalResponse: """Return most recent RAGAS evaluation results from disk.""" if not _EVAL_PATH.exists(): return EvalResponse( overall_pass=False, scores={}, results={}, run_at=None, ) try: data = json.loads(_EVAL_PATH.read_text()) return EvalResponse( overall_pass=data.get("overall_pass", False), scores=data.get("scores", {}), results={ k: EvalMetric(**v) for k, v in data.get("results", {}).items() }, tickers=data.get("tickers", []), n_pairs=data.get("n_pairs"), run_at=data.get("run_at"), ) except Exception as exc: log.warning("eval_read_failed", error=str(exc)) return EvalResponse(overall_pass=False, scores={}, results={}, run_at=None)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382import asyncioimport timefrom typing import Any
import structlogfrom fastapi import APIRouter, HTTPException, Query, Requestfrom pydantic import BaseModel
from backend.api.middleware.rate_limit import limiterfrom backend.rag.ingestion.universe import universefrom backend.rag.yahoo_client import fetch_company_info, fetch_fundamentals, fetch_news, fetch_ohlcv, fetch_quote, fetch_sector_etfs
log = structlog.get_logger()router = APIRouter(tags=["stocks"])
class StockSearchResult(BaseModel): ticker: str name: str exchange: str sector: str country: str currency: str yf_ticker: str
class AnalystConsensus(BaseModel): buy: int hold: int sell: int avg_target: float | None
class OHLCVBar(BaseModel): date: str open: float high: float low: float close: float volume: int
class NewsItem(BaseModel): text: str title: str source: str published_at: str url: str
class HistoricalSignal(BaseModel): text: str event_type: str date_range: str return_pct: float | None
class SimilarStock(BaseModel): ticker: str name: str sector: str exchange: str currency: str
class SectorData(BaseModel): sector: str etf: str return_pct: float price: float | None = None
class StockDetail(BaseModel): ticker: str name: str exchange: str currency: str sector: str | None industry: str | None country: str | None city: str | None website: str | None full_time_employees: int | None business_summary: str | None beta: float | None dividend_yield: float | None price: float | None change: float | None pct_change: float | None volume: int | None avg_volume_30d: int | None market_cap: int | None pe: float | None forward_pe: float | None eps: float | None week_52_high: float | None week_52_low: float | None analyst_consensus: AnalystConsensus | None ohlcv_7d: list[OHLCVBar] news_rag: list[NewsItem] historical_signals: list[HistoricalSignal] similar_stocks: list[SimilarStock] = []
_SECTORS_CACHE: tuple[list[dict], float] | None = None_SECTORS_TTL = 300.0 # 5 minutes
def _get_similar_stocks(current_ticker: str, sector: str | None, limit: int = 5) -> list[SimilarStock]: if not sector: return [] all_stocks = universe.search("", limit=10000) similar = [ SimilarStock( ticker=s["ticker"], name=s["name"], sector=s.get("sector", ""), exchange=s.get("exchange", ""), currency=s.get("currency", "USD"), ) for s in all_stocks if s.get("sector", "").lower() == sector.lower() and s["ticker"] != current_ticker ] return similar[:limit]
def _safe_float(val: Any) -> float | None: try: v = float(val) return None if v != v else v except (TypeError, ValueError): return None
def _safe_int(val: Any) -> int | None: try: v = float(val) return None if v != v else int(v) except (TypeError, ValueError): return None
async def _fetch_detail(yf_ticker: str, display_ticker: str) -> dict[str, Any]: def _blocking() -> dict[str, Any]: try: quote = fetch_quote(yf_ticker) except Exception: quote = {} try: fund = fetch_fundamentals(yf_ticker) except Exception: fund = {} try: company = fetch_company_info(yf_ticker) except Exception: company = {}
# 7-day daily OHLCV ohlcv_7d: list[OHLCVBar] = [] try: df = fetch_ohlcv(yf_ticker, days=7, interval="1d") if not df.empty: for dt, row in df.tail(7).iterrows(): ohlcv_7d.append(OHLCVBar( date=str(dt.date()), open=round(float(row["Open"]), 4), high=round(float(row["High"]), 4), low=round(float(row["Low"]), 4), close=round(float(row["Close"]), 4), volume=int(row["Volume"]), )) except Exception: pass
# Live news via Google News RSS news_rag: list[NewsItem] = [] try: raw_news = fetch_news(yf_ticker, count=5) for n in raw_news: news_rag.append(NewsItem( text=n.get("text", n.get("title", "")), title=n.get("title", ""), source=n.get("source", ""), published_at=n.get("published_at", ""), url=n.get("url", ""), )) except Exception as exc: log.warning("news_fetch_failed", ticker=yf_ticker, error=str(exc))
# Historical signals from Qdrant (best-effort, silent fail) historical_signals: list[HistoricalSignal] = [] try: from backend.rag.retrieval.hybrid import hybrid_search from backend.rag.ingestion.collections import collection_name chunks = hybrid_search( query=f"{display_ticker} historical price patterns", ticker=display_ticker, collection=collection_name("historical"), limit=4, allow_global_fallback=False, ) for ch in chunks: meta = ch.metadata historical_signals.append(HistoricalSignal( text=ch.text, event_type=meta.get("event_type", "price_event"), date_range=meta.get("date_range", meta.get("start_date", "")), return_pct=_safe_float(meta.get("return_pct")), )) except Exception: pass # Qdrant unavailable or ticker not in historical corpus
ac = fund.get("analyst_consensus", {}) or {} consensus = AnalystConsensus( buy=int(ac.get("buy") or 0), hold=int(ac.get("hold") or 0), sell=int(ac.get("sell") or 0), avg_target=_safe_float(ac.get("avg_target")), )
return { "price": _safe_float(quote.get("price")), "change": _safe_float(quote.get("change")), "pct_change": _safe_float(quote.get("pct_change")), "volume": _safe_int(quote.get("volume")), "avg_volume_30d": _safe_int(quote.get("avg_volume_3m")) or _safe_int(fund.get("avg_volume_3m")), "market_cap": _safe_int(fund.get("market_cap")) or _safe_int(quote.get("market_cap")), "pe": _safe_float(fund.get("pe")), "forward_pe": _safe_float(fund.get("forward_pe")), "eps": _safe_float(fund.get("eps")), "week_52_high": _safe_float(fund.get("week_52_high")), "week_52_low": _safe_float(fund.get("week_52_low")), "beta": _safe_float(fund.get("beta")), "dividend_yield": _safe_float(fund.get("dividend_yield")), "industry": company.get("industry") or fund.get("industry"), "country": company.get("country") or fund.get("country"), "city": company.get("city") or fund.get("city"), "website": company.get("website") or fund.get("website"), "full_time_employees": _safe_int(company.get("full_time_employees") or fund.get("full_time_employees")), "business_summary": company.get("business_summary") or fund.get("business_summary"), "analyst_consensus": consensus, "ohlcv_7d": ohlcv_7d, "news_rag": news_rag, "historical_signals": historical_signals, }
loop = asyncio.get_running_loop() return await loop.run_in_executor(None, _blocking)
@router.get("/sectors", response_model=list[SectorData])@limiter.limit("30/minute")async def get_sectors(request: Request) -> list[SectorData]: global _SECTORS_CACHE now = time.monotonic() if _SECTORS_CACHE and (now - _SECTORS_CACHE[1]) < _SECTORS_TTL: return [SectorData(**s) for s in _SECTORS_CACHE[0]]
loop = asyncio.get_running_loop() raw = await loop.run_in_executor(None, fetch_sector_etfs) _SECTORS_CACHE = (raw, now) return [SectorData(**s) for s in raw]
@router.get("/search", response_model=list[StockSearchResult])@limiter.limit("60/minute")async def search_stocks( request: Request, q: str = Query("", max_length=100), limit: int = Query(10, ge=1, le=50),) -> list[StockSearchResult]: results = universe.search(q, limit=limit) return [ StockSearchResult( ticker=s["ticker"], name=s["name"], exchange=s.get("exchange", ""), sector=s.get("sector", ""), country=s.get("country", ""), currency=s.get("currency", "USD"), yf_ticker=s.get("yf_ticker", s["ticker"]), ) for s in results ]
@router.get("/{ticker}", response_model=StockDetail)@limiter.limit("30/minute")async def get_stock(request: Request, ticker: str) -> StockDetail: entry = universe.get_by_ticker(ticker) if not entry: raise HTTPException(status_code=404, detail=f"Ticker '{ticker}' not in universe")
yf_ticker = entry.get("yf_ticker", ticker) data: dict[str, Any] = { "price": None, "change": None, "pct_change": None, "volume": None, "avg_volume_30d": None, "market_cap": None, "pe": None, "forward_pe": None, "eps": None, "week_52_high": None, "week_52_low": None, "beta": None, "dividend_yield": None, "industry": None, "country": None, "city": None, "website": None, "full_time_employees": None, "business_summary": None, "analyst_consensus": AnalystConsensus(buy=0, hold=0, sell=0, avg_target=None), "ohlcv_7d": [], "news_rag": [], "historical_signals": [], } try: data = await _fetch_detail(yf_ticker, entry["ticker"]) except Exception as exc: log.warning("yahoo_fetch_failed", ticker=yf_ticker, error=str(exc))
sector = entry.get("sector") similar = _get_similar_stocks(entry["ticker"], sector)
return StockDetail( ticker=entry["ticker"], name=entry["name"], exchange=entry.get("exchange", ""), currency=entry.get("currency", "USD"), sector=sector, similar_stocks=similar, **data, )
# Timeframe → (yahoo_range, yahoo_interval)_TIMEFRAME_MAP: dict[str, tuple[str, str]] = { "1D": ("1d", "5m"), "1W": ("5d", "30m"), "1M": ("1mo", "1d"), "3M": ("3mo", "1d"), "6M": ("6mo", "1d"), "1Y": ("1y", "1wk"), "3Y": ("3y", "1wk"), "5Y": ("5y", "1wk"), "ALL": ("20y", "1mo"),}
class OHLCVResponse(BaseModel): ticker: str range: str interval: str bars: list[OHLCVBar]
@router.get("/{ticker}/ohlcv", response_model=OHLCVResponse)@limiter.limit("60/minute")async def get_ohlcv( request: Request, ticker: str, range: str = Query("1M", pattern="^(1D|1W|1M|3M|6M|1Y|3Y|5Y|ALL)$"),) -> OHLCVResponse: entry = universe.get_by_ticker(ticker) if not entry: raise HTTPException(status_code=404, detail=f"Ticker '{ticker}' not in universe")
yf_ticker = entry.get("yf_ticker", ticker) yahoo_range, interval = _TIMEFRAME_MAP.get(range, ("1mo", "1d"))
def _blocking() -> list[OHLCVBar]: df = fetch_ohlcv(yf_ticker, interval=interval, range_str=yahoo_range) bars: list[OHLCVBar] = [] if df.empty: return bars for dt, row in df.iterrows(): try: bars.append(OHLCVBar( date=str(dt) if range == "1D" else str(dt.date()), open=round(float(row["Open"]), 4), high=round(float(row["High"]), 4), low=round(float(row["Low"]), 4), close=round(float(row["Close"]), 4), volume=int(row["Volume"]), )) except Exception: continue return bars
loop = asyncio.get_running_loop() bars = await loop.run_in_executor(None, _blocking) return OHLCVResponse(ticker=ticker, range=range, interval=interval, bars=bars)12345678910111213141516171819202122232425262728293031323334353637383940414243"""Finora FastMCP server — stdio transport.
Run from repo root: cd backend && python -m finora_mcp.server
Tools exposed: get_realtime_quote, search_historical_rag, search_news_rag, get_fundamentals, screen_stocks, get_stock_universe"""from __future__ import annotations
import sysfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[2]BACKEND = ROOT / "backend"
sys.path.insert(0, str(BACKEND))
from dotenv import load_dotenvload_dotenv(ROOT / ".env")
from fastmcp import FastMCP
from finora_mcp.tools.fundamentals import get_fundamentalsfrom finora_mcp.tools.historical import search_historical_ragfrom finora_mcp.tools.news import search_news_ragfrom finora_mcp.tools.quote import get_realtime_quotefrom finora_mcp.tools.screener import get_stock_universe, screen_stocks
mcp = FastMCP("finora-mcp")
mcp.tool()(get_realtime_quote)mcp.tool()(search_historical_rag)mcp.tool()(search_news_rag)mcp.tool()(get_fundamentals)mcp.tool()(screen_stocks)mcp.tool()(get_stock_universe)
if __name__ == "__main__": mcp.run(transport="stdio")123456789"""MCP tool: get_fundamentals — PE, EPS, revenue, margins, analyst consensus."""from __future__ import annotations
from backend.rag.yahoo_client import fetch_fundamentals
def get_fundamentals(ticker: str) -> dict: """PE, EPS, revenue, margins, debt, analyst consensus, price targets.""" return fetch_fundamentals(ticker)1234567891011121314151617181920212223242526"""MCP tool: search_historical_rag — semantic + BM25 hybrid over 20yr OHLCV event chunks."""from __future__ import annotations
def search_historical_rag(ticker: str, query: str, years: int = 20, top_k: int = 5) -> list[dict]: """Semantic + BM25 hybrid search over 20yr OHLCV event chunks. Reranked results.""" from backend.rag.pipeline import run_rag_branch
results = run_rag_branch( query=query, ticker=ticker, collection_key="historical", use_hyde=True, top_k=top_k, ) return [ { "text": r.text, "ticker": r.metadata.get("ticker"), "date_range": r.metadata.get("date_range"), "event_type": r.metadata.get("event_type"), "return_pct": r.metadata.get("return_pct"), "score": round(r.score, 4) if r.score else None, } for r in results ]123456789101112131415161718192021222324252627"""MCP tool: search_news_rag — hybrid search over news + SEC filings."""from __future__ import annotations
def search_news_rag(ticker: str, query: str, days: int = 30, top_k: int = 8) -> list[dict]: """Hybrid search over news + SEC filings. Reranked, deduplicated.""" from backend.rag.pipeline import run_rag_branch
results = run_rag_branch( query=query, ticker=ticker, collection_key="news", use_hyde=True, top_k=top_k, ) return [ { "text": r.text, "ticker": r.metadata.get("ticker"), "source": r.metadata.get("source"), "published_at": r.metadata.get("published_at"), "url": r.metadata.get("url"), "sentiment_score": r.metadata.get("sentiment_score"), "score": round(r.score, 4) if r.score else None, } for r in results ]123456789"""MCP tool: get_realtime_quote — live price, volume, intraday OHLC."""from __future__ import annotations
from backend.rag.yahoo_client import fetch_quote
def get_realtime_quote(ticker: str) -> dict: """Live price, volume, intraday OHLC, market status. Works for US + Indian stocks.""" return fetch_quote(ticker)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263"""MCP tool: screen_stocks + get_stock_universe."""from __future__ import annotations
from typing import Optional
def screen_stocks( sector: Optional[str] = None, min_pe: Optional[float] = None, max_pe: Optional[float] = None, country: Optional[str] = None, limit: int = 20,) -> list[dict]: """Screen S&P 500 + NIFTY 50 universe by criteria.""" from backend.rag.ingestion.universe import StockUniverse from backend.rag.yahoo_client import fetch_fundamentals
u = StockUniverse() stocks = u.stocks
if sector: stocks = [s for s in stocks if (s.get("sector") or "").lower() == sector.lower()] if country: stocks = [s for s in stocks if (s.get("country") or "").lower() == country.lower()]
if (min_pe is not None or max_pe is not None) and stocks: filtered = [] for s in stocks[:50]: try: fund = fetch_fundamentals(s.get("yf_ticker", s["ticker"])) pe = fund.get("pe") if pe is None: continue if min_pe is not None and pe < min_pe: continue if max_pe is not None and pe > max_pe: continue filtered.append({**s, "pe": round(pe, 2)}) if len(filtered) >= limit: break except Exception: continue return filtered
return [ {"ticker": s["ticker"], "name": s.get("name"), "sector": s.get("sector"), "country": s.get("country"), "exchange": s.get("exchange")} for s in stocks[:limit] ]
def get_stock_universe(query: Optional[str] = None, limit: int = 10) -> list[dict]: """Fuzzy search ~555 stocks by name or ticker.""" from backend.rag.ingestion.universe import StockUniverse
u = StockUniverse() results = u.search(query, limit=limit) if query else u.stocks[:limit] return [ {"ticker": s["ticker"], "name": s.get("name"), "sector": s.get("sector"), "country": s.get("country"), "exchange": s.get("exchange"), "yf_ticker": s.get("yf_ticker", s["ticker"])} for s in results ]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Finora LangGraph StateGraph.
Topology: guardrail_check → [blocked → END | allowed → intent_classifier] intent_classifier → parallel_retrieval (asyncio.gather over all needed branches) parallel_retrieval → fusion_node → response_node → END
Note: parallel_retrieval is a single async node that fans out internally viaasyncio.gather — simpler and more reliable than graph-level fan-out for this use case."""from __future__ import annotations
import asyncio
import structlogfrom langgraph.checkpoint.memory import MemorySaverfrom langgraph.graph import END, StateGraph
from backend.graph.nodes.fusion_node import fusion_nodefrom backend.graph.nodes.fundamentals_node import fundamentals_nodefrom backend.graph.nodes.historical_rag_node import historical_rag_nodefrom backend.graph.nodes.intent_classifier import intent_classifier_nodefrom backend.graph.nodes.news_rag_node import news_rag_nodefrom backend.graph.nodes.realtime_node import realtime_nodefrom backend.graph.nodes.response_node import response_nodefrom backend.graph.state import FiNoraStatefrom backend.guardrails.classifier import guardrail_check_node, route_after_guardrail
log = structlog.get_logger()
async def parallel_retrieval_node(state: FiNoraState) -> dict: """ Fan-out: runs all applicable retrieval branches concurrently via asyncio.gather. Merges results back into state. """ tasks = [ realtime_node(state), news_rag_node(state), historical_rag_node(state), fundamentals_node(state), ] results = await asyncio.gather(*tasks, return_exceptions=True)
merged: dict = { "realtime_context": None, "news_chunks": [], "historical_chunks": [], "fundamental_data": None, "sector_context": None, "retrieval_scores": {}, } for r in results: if isinstance(r, Exception): log.error("parallel_retrieval_branch_failed", error=str(r)) continue for key, val in r.items(): if key in ("news_chunks", "historical_chunks"): merged[key] = merged.get(key, []) + (val or []) elif key == "retrieval_scores": merged["retrieval_scores"].update(val or {}) elif val is not None: merged[key] = val
return merged
def _build_graph() -> StateGraph: builder = StateGraph(FiNoraState)
builder.add_node("guardrail_check", guardrail_check_node) builder.add_node("intent_classifier", intent_classifier_node) builder.add_node("parallel_retrieval", parallel_retrieval_node) builder.add_node("fusion_node", fusion_node) builder.add_node("response_node", response_node)
builder.set_entry_point("guardrail_check")
builder.add_conditional_edges( "guardrail_check", route_after_guardrail, {"blocked": END, "allowed": "intent_classifier"}, )
builder.add_edge("intent_classifier", "parallel_retrieval") builder.add_edge("parallel_retrieval", "fusion_node") builder.add_edge("fusion_node", "response_node") builder.add_edge("response_node", END)
return builder
# Compiled graph — shared across all requests_checkpointer = MemorySaver()graph = _build_graph().compile(checkpointer=_checkpointer)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131"""Fundamentals node — Yahoo Finance quoteSummary via curl_cffi."""from __future__ import annotations
import asyncioimport time
import structlog
from backend.graph.state import FiNoraStatefrom backend.rag.yahoo_client import fetch_fundamentals, fetch_sector_etfs
log = structlog.get_logger()
_FUNDAMENTALS_CACHE: dict[str, tuple[dict, float]] = {}_SECTOR_CACHE: tuple[list[dict], float] | None = None_CACHE_TTL = 300.0 # 5 minutes
def _get_cached_fundamentals(yf_ticker: str) -> dict | None: entry = _FUNDAMENTALS_CACHE.get(yf_ticker) if entry and (time.monotonic() - entry[1]) < _CACHE_TTL: return entry[0] return None
def _set_cached_fundamentals(yf_ticker: str, data: dict) -> None: _FUNDAMENTALS_CACHE[yf_ticker] = (data, time.monotonic())
def _get_similar_stocks(ticker: str, sector: str | None) -> list[dict]: if not sector: return [] try: from backend.rag.ingestion.universe import universe all_stocks = universe.search("", limit=10000) similar = [ {"ticker": s["ticker"], "name": s["name"], "sector": s.get("sector", ""), "exchange": s.get("exchange", ""), "currency": s.get("currency", "USD")} for s in all_stocks if s.get("sector", "").lower() == sector.lower() and s["ticker"] != ticker ] return similar[:8] except Exception: return []
def _fetch_sector_context(ticker: str, sector: str | None) -> dict: global _SECTOR_CACHE now = time.monotonic()
etfs: list[dict] = [] if _SECTOR_CACHE and (now - _SECTOR_CACHE[1]) < _CACHE_TTL: etfs = _SECTOR_CACHE[0] else: try: etfs = fetch_sector_etfs() _SECTOR_CACHE = (etfs, now) except Exception: etfs = []
similar = _get_similar_stocks(ticker, sector)
# Find the ETF for this stock's sector sector_etf: dict | None = None if sector: for etf in etfs: if etf.get("sector", "").lower() == sector.lower(): sector_etf = etf break
return { "sector": sector, "sector_etf": sector_etf, "all_sector_etfs": etfs, "similar_stocks": similar, }
async def fundamentals_node(state: FiNoraState) -> dict: intents = state.get("intents", []) has_fundamental = "fundamental" in intents has_comparative = "comparative" in intents
if not has_fundamental and not has_comparative: return {"fundamental_data": None, "sector_context": None}
ticker = state.get("ticker", "") yf_ticker = state.get("yf_ticker", ticker) if not ticker: return {"fundamental_data": None, "sector_context": None}
result: dict = {"fundamental_data": None, "sector_context": None}
# Fetch fundamentals if needed if has_fundamental: cached = _get_cached_fundamentals(yf_ticker) if cached: log.debug("fundamentals_cache_hit", ticker=ticker) result["fundamental_data"] = cached else: loop = asyncio.get_running_loop() data = await loop.run_in_executor(None, fetch_fundamentals, yf_ticker) data["ticker"] = ticker _set_cached_fundamentals(yf_ticker, data) log.info("fundamentals_node_done", ticker=ticker, yf_ticker=yf_ticker, pe=data.get("pe")) result["fundamental_data"] = data
# Fetch sector context if comparative intent present if has_comparative: # Get sector from fundamentals data or state fd = result.get("fundamental_data") or {} sector = fd.get("sector") or state.get("sector")
# If no fundamentals fetched yet, get sector from universe if not sector: try: from backend.rag.ingestion.universe import universe entry = universe.get_by_ticker(ticker) sector = (entry or {}).get("sector") except Exception: sector = None
loop = asyncio.get_running_loop() sector_ctx = await loop.run_in_executor(None, _fetch_sector_context, ticker, sector) result["sector_context"] = sector_ctx log.info("sector_context_fetched", ticker=ticker, sector=sector, similar_count=len(sector_ctx.get("similar_stocks", [])), etfs_count=len(sector_ctx.get("all_sector_etfs", [])))
return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595"""Fusion node — assembles structured data context for the response LLM."""from __future__ import annotations
import os
import structlog
from backend.graph.state import FiNoraStatefrom backend.guardrails.disclaimers import get_disclaimer
log = structlog.get_logger()
_SUMMARY_TRIGGERS = { "summarize", "summary", "explain", "overview", "what's happening", "whats happening", "tell me about", "breakdown", "analyse", "analyze", "give me a", "what do you think", "how is", "how's",}
def _is_summary_query(query: str) -> bool: q = query.lower().strip() return any(trigger in q for trigger in _SUMMARY_TRIGGERS)
def _currency_sym(currency: str) -> str: return "₹" if currency == "INR" else "$"
def _fmt_realtime(rt: dict | None, currency: str = "USD") -> str: if not rt or not rt.get("price"): return "[REAL-TIME DATA UNAVAILABLE]" sym = _currency_sym(currency) ticker = rt.get("ticker", "") price = rt.get("price") change = rt.get("change") pct = rt.get("pct_change") vol = rt.get("volume") avg_vol = rt.get("avg_volume_30d") vol_ratio = round(vol / avg_vol, 1) if vol and avg_vol else None
lines = [f"{ticker}: {sym}{price:.2f} ({pct:+.2f}%)" if price and pct else f"{ticker}: {sym}{price}"] if change: lines.append(f"Change: {sym}{change:+.4f}") if vol_ratio is not None: lines.append(f"Volume: {vol:,} ({vol_ratio}x 30d avg)") w52h = rt.get("week_52_high") w52l = rt.get("week_52_low") if w52h and w52l: lines.append(f"52W Range: {sym}{w52l:.2f} - {sym}{w52h:.2f}")
return "\n".join(lines)
def _fmt_historical_patterns(patterns: list[dict]) -> str: """Format always-available historical patterns fetched alongside realtime data.""" if not patterns: return "" top = patterns[:2] lines = [f"[HISTORICAL PATTERNS — {len(top)} events]"] for i, p in enumerate(top, 1): parts = [f"[{i}]"] if p.get("event_type"): parts.append(p["event_type"].replace("_", " ").title()) if p.get("date_range"): parts.append(f"({p['date_range']})") if p.get("return_pct") is not None: parts.append(f"fwd return: {p['return_pct']:+.1f}%") if p.get("text"): parts.append(f"— {p['text'][:120]}") lines.append(" ".join(parts)) return "\n".join(lines)
_CHUNK_TEXT_LIMIT = int(os.getenv("RAG_CHUNK_TEXT_LIMIT", "400"))_MAX_NEWS_CHUNKS = int(os.getenv("RAG_MAX_NEWS_CHUNKS", "4"))_MAX_HIST_CHUNKS = int(os.getenv("RAG_MAX_HIST_CHUNKS", "3"))
def _fmt_chunks(chunks: list[dict], label: str, max_chunks: int = _MAX_NEWS_CHUNKS) -> str: if not chunks: return f"[NO {label.upper()} DATA]" lines = [f"[{label.upper()} - {min(len(chunks), max_chunks)} sources]"] for i, ch in enumerate(chunks[:max_chunks], 1): source = ch.get("source", ch.get("url", "unknown")) date = ch.get("published_at", ch.get("start_date", ch.get("date_range", ""))) text = ch.get("text", "")[:_CHUNK_TEXT_LIMIT] lines.append(f"[{i}] {source} ({date}): {text}") return "\n".join(lines)
def _fmt_sector_context(sc: dict | None, currency: str = "USD") -> str: if not sc: return "" sym = _currency_sym(currency) lines = []
sector = sc.get("sector") etf = sc.get("sector_etf") if sector: header = f"[SECTOR CONTEXT — {sector}]" if etf: pct = etf.get("return_pct", 0) price = etf.get("price") etf_name = etf.get("etf", "") price_str = f" ({sym}{price:.2f})" if price else "" header += f"\nSector ETF ({etf_name}){price_str}: {pct:+.2f}% today" lines.append(header)
all_etfs = sc.get("all_sector_etfs", []) if all_etfs: sorted_etfs = sorted(all_etfs, key=lambda x: x.get("return_pct", 0), reverse=True) etf_parts = [ f"{e['sector']} ({e['etf']}): {e.get('return_pct', 0):+.2f}%" for e in sorted_etfs[:6] ] lines.append("Sector performance today:\n" + "\n".join(etf_parts))
similar = sc.get("similar_stocks", []) if similar: sim_parts = [ f"- {s['ticker']} ({s['exchange']}): {s['name']}" for s in similar[:6] ] lines.append(f"Similar stocks in {sector or 'sector'}:\n" + "\n".join(sim_parts))
return "\n".join(lines)
def _fmt_fundamentals(fd: dict | None, currency: str = "USD") -> str: if not fd: return "[FUNDAMENTAL DATA UNAVAILABLE]" sym = _currency_sym(currency) parts: list[str] = [] if fd.get("pe"): parts.append(f"PE: {fd['pe']:.1f}") if fd.get("forward_pe"): parts.append(f"Forward PE: {fd['forward_pe']:.1f}") if fd.get("eps"): parts.append(f"EPS: {sym}{fd['eps']:.2f}") if fd.get("analyst_target"): parts.append(f"Analyst target: {sym}{fd['analyst_target']:.2f}") if fd.get("recommendation"): parts.append(f"Consensus: {fd['recommendation'].upper()}") if fd.get("profit_margins"): parts.append(f"Net margin: {fd['profit_margins']*100:.1f}%") if fd.get("beta"): parts.append(f"Beta: {fd['beta']:.2f}") if fd.get("revenue"): parts.append(f"Revenue: {sym}{fd['revenue']/1e9:.1f}B") if fd.get("market_cap"): mc = fd["market_cap"] mc_str = f"{sym}{mc/1e12:.2f}T" if mc >= 1e12 else f"{sym}{mc/1e9:.1f}B" parts.append(f"Mkt Cap: {mc_str}")
consensus = fd.get("analyst_consensus") or {} buy = consensus.get("buy", 0) or 0 hold = consensus.get("hold", 0) or 0 sell = consensus.get("sell", 0) or 0 if buy or hold or sell: total = buy + hold + sell buy_pct = round(buy / total * 100) if total else 0 parts.append(f"Analysts: {buy} Buy / {hold} Hold / {sell} Sell ({buy_pct}% bullish)")
return " | ".join(parts) if parts else "[LIMITED FUNDAMENTAL DATA]"
def _compute_insight_flags(state: FiNoraState) -> list[str]: """Pre-compute interpretive signals grounded in data — no hallucination possible.""" flags: list[str] = [] rt = state.get("realtime_context") or {} fd = state.get("fundamental_data") or {} sym = _currency_sym(state.get("currency", "USD"))
# Volume anomaly vol = rt.get("volume") avg_vol = rt.get("avg_volume_30d") if vol and avg_vol and avg_vol > 0: vol_z = vol / avg_vol if vol_z >= 2.5: flags.append(f"Volume spike: {vol_z:.1f}x 30-day average — unusual institutional activity likely") elif vol_z <= 0.4: flags.append("Volume well below average — low conviction move, may not be sustained")
# PE interpretation pe = fd.get("pe") fpe = fd.get("forward_pe") if pe and pe > 0: if pe > 40: flags.append(f"PE of {pe:.1f} — premium valuation, priced for high earnings growth expectations") elif pe < 12: flags.append(f"PE of {pe:.1f} — below typical market average, may signal undervaluation or elevated risk") if fpe and fpe > 0: ratio = fpe / pe if ratio < 0.80: flags.append( f"Forward PE ({fpe:.1f}) significantly below trailing ({pe:.1f}) — " "earnings growth expected ahead" ) elif ratio > 1.20: flags.append( f"Forward PE ({fpe:.1f}) above trailing ({pe:.1f}) — " "earnings expected to slow or decline" )
# 52W range position price = rt.get("price") w52h = rt.get("week_52_high") or fd.get("week_52_high") w52l = rt.get("week_52_low") or fd.get("week_52_low") if price and w52h and w52l and w52h > w52l: pos_pct = ((price - w52l) / (w52h - w52l)) * 100 if pos_pct >= 95: flags.append(f"Near 52-week high ({sym}{w52h:.2f}) — potential resistance zone") elif pos_pct <= 5: flags.append(f"Near 52-week low ({sym}{w52l:.2f}) — potential support zone") elif pos_pct >= 75: flags.append(f"Upper quartile of 52-week range ({pos_pct:.0f}% from low) — relative strength") elif pos_pct <= 25: flags.append(f"Lower quartile of 52-week range ({pos_pct:.0f}% from low) — relative weakness")
# Analyst consensus consensus = fd.get("analyst_consensus") or {} buy = consensus.get("buy", 0) or 0 hold = consensus.get("hold", 0) or 0 sell = consensus.get("sell", 0) or 0 total = buy + hold + sell if total >= 3: buy_pct = buy / total if buy_pct >= 0.75: flags.append(f"Strong buy consensus: {round(buy_pct*100)}% of {total} analysts rate Buy") elif buy_pct <= 0.25: flags.append(f"Weak buy consensus: only {round(buy_pct*100)}% of {total} analysts rate Buy")
# Price vs analyst target target = fd.get("analyst_target") or (consensus.get("avg_target") if consensus else None) if price and target and target > 0: upside = ((target - price) / price) * 100 if upside >= 15: flags.append(f"Analyst target ({sym}{target:.2f}) implies {upside:.0f}% upside from current price") elif upside <= -10: flags.append(f"Current price {abs(upside):.0f}% above consensus analyst target ({sym}{target:.2f})")
# Profit margin margin = fd.get("profit_margins") if margin is not None: if margin >= 0.25: flags.append(f"High net margin of {margin*100:.1f}% — strong pricing power or operational efficiency") elif margin < 0.05: flags.append(f"Thin net margin of {margin*100:.1f}% — highly sensitive to cost pressures")
# Beta beta = fd.get("beta") if beta is not None: if beta >= 1.5: flags.append(f"High beta ({beta:.2f}) — moves significantly more than the broader market") elif beta <= 0.5: flags.append(f"Low beta ({beta:.2f}) — defensive stock with low market correlation")
return flags
def _compute_narrative_hint(state: FiNoraState) -> str: """Single most important signal — used to anchor the opening narrative sentence.""" rt = state.get("realtime_context") or {} fd = state.get("fundamental_data") or {}
pct = rt.get("pct_change") vol = rt.get("volume") avg_vol = rt.get("avg_volume_30d") price = rt.get("price") w52h = rt.get("week_52_high") w52l = rt.get("week_52_low") consensus = (fd.get("analyst_consensus") or {}) buy = consensus.get("buy", 0) or 0 hold = consensus.get("hold", 0) or 0 sell = consensus.get("sell", 0) or 0 total = buy + hold + sell
# Priority order: large price move > volume spike > 52W extreme > consensus if pct is not None and abs(pct) >= 3.0: direction = "sharp_upward_move" if pct > 0 else "sharp_downward_move" return direction
if vol and avg_vol and avg_vol > 0 and (vol / avg_vol) >= 2.5: return "high_volume_move"
if price and w52h and w52l and w52h > w52l: pos = (price - w52l) / (w52h - w52l) if pos >= 0.95: return "near_52w_high" if pos <= 0.05: return "near_52w_low"
if total >= 3: if buy / total >= 0.75: return "analyst_strongly_bullish" if buy / total <= 0.25: return "analyst_bearish"
if pct is not None: if pct >= 1.0: return "mild_upward_move" if pct <= -1.0: return "mild_downward_move"
return "consolidating"
def _compute_confidence_level(state: FiNoraState) -> str: """Derived confidence: how strongly do signals agree?""" rt = state.get("realtime_context") or {} fd = state.get("fundamental_data") or {}
strong_signals = 0
pct = rt.get("pct_change") if pct is not None and abs(pct) >= 2.0: strong_signals += 1
vol = rt.get("volume") avg_vol = rt.get("avg_volume_30d") if vol and avg_vol and avg_vol > 0 and (vol / avg_vol) >= 2.0: strong_signals += 1
price = rt.get("price") w52h = rt.get("week_52_high") w52l = rt.get("week_52_low") if price and w52h and w52l and w52h > w52l: pos = (price - w52l) / (w52h - w52l) if pos >= 0.85 or pos <= 0.15: strong_signals += 1
consensus = (fd.get("analyst_consensus") or {}) buy = consensus.get("buy", 0) or 0 hold = consensus.get("hold", 0) or 0 sell = consensus.get("sell", 0) or 0 total = buy + hold + sell if total >= 3 and (buy / total >= 0.70 or buy / total <= 0.30): strong_signals += 1
has_news = bool(state.get("news_chunks")) has_historical = bool(state.get("historical_chunks")) has_fundamentals = bool(fd) data_sources = sum([bool(rt), has_news, has_historical, has_fundamentals])
if strong_signals >= 3 and data_sources >= 3: return "high" if strong_signals >= 1 and data_sources >= 2: return "medium" return "low"
def _compute_conflict(state: FiNoraState) -> tuple[bool, str]: """Detect meaningful signal conflicts — price vs analyst, short vs long-term.""" rt = state.get("realtime_context") or {} fd = state.get("fundamental_data") or {}
pct = rt.get("pct_change") consensus = (fd.get("analyst_consensus") or {}) buy = consensus.get("buy", 0) or 0 hold = consensus.get("hold", 0) or 0 sell = consensus.get("sell", 0) or 0 total = buy + hold + sell
price = rt.get("price") w52h = rt.get("week_52_high") w52l = rt.get("week_52_low")
# Price falling but analysts strongly bullish if pct is not None and pct <= -2.0 and total >= 3 and buy / total >= 0.65: return True, "price_down_but_analyst_bullish"
# Price rising sharply but analysts mostly bearish/hold if pct is not None and pct >= 2.0 and total >= 3 and (hold + sell) / total >= 0.65: return True, "price_up_but_analyst_cautious"
# Near 52W low but strong buy consensus if price and w52h and w52l and w52h > w52l and total >= 3: pos = (price - w52l) / (w52h - w52l) if pos <= 0.15 and buy / total >= 0.65: return True, "near_52w_low_but_analyst_bullish"
# Near 52W high but analyst target below current price target = fd.get("analyst_target") or (consensus.get("avg_target") if consensus else None) if price and target and w52h and w52l and w52h > w52l: pos = (price - w52l) / (w52h - w52l) if pos >= 0.85 and target < price: return True, "near_52w_high_but_target_below_price"
return False, ""
def _compute_price_trend(rt: dict | None, fd: dict | None) -> dict[str, str]: signals: dict[str, str] = {} if not rt: return signals
pct = rt.get("pct_change") if pct is not None: if pct >= 2.0: signals["short_term"] = f"Upward (+{pct:.1f}% today)" elif pct <= -2.0: signals["short_term"] = f"Downward ({pct:.1f}% today)" else: signals["short_term"] = f"Flat ({pct:+.1f}% today)"
price = rt.get("price") w52h = rt.get("week_52_high") w52l = rt.get("week_52_low") if price and w52h and w52l and w52h > w52l: pos = (price - w52l) / (w52h - w52l) if pos >= 0.7: signals["long_term"] = "Near 52-week high — longer-term uptrend" elif pos <= 0.3: signals["long_term"] = "Near 52-week low — longer-term downtrend or consolidation" else: signals["long_term"] = "Mid-range of 52-week band"
beta = (fd or {}).get("beta") if beta is not None: if beta >= 1.3: signals["volatility"] = f"High ({beta:.2f} beta) — amplified market moves" elif beta <= 0.7: signals["volatility"] = f"Low ({beta:.2f} beta) — defensive, dampened moves" else: signals["volatility"] = f"Moderate ({beta:.2f} beta)"
return signals
def _compute_confidence(state: FiNoraState) -> float: score = 0.0 if state.get("realtime_context") and state["realtime_context"].get("price"): score += 0.3 if state.get("news_chunks"): score += 0.3 if state.get("historical_chunks"): score += 0.25 if state.get("fundamental_data"): score += 0.15 return min(round(score, 2), 1.0)
def _build_data_context(state: FiNoraState) -> str: """Pure data context — no behavioral instructions. Used as the user message.""" ticker = state.get("ticker", "") company_name = state.get("company_name") or ticker currency = state.get("currency") or "USD" history = state.get("conversation_history", [])
rt = state.get("realtime_context") fd = state.get("fundamental_data") insight_flags = _compute_insight_flags(state) trend = _compute_price_trend(rt, fd) narrative_hint = _compute_narrative_hint(state) confidence_level = _compute_confidence_level(state) has_conflict, conflict_reason = _compute_conflict(state) uncertainty_flag = confidence_level == "low" or (has_conflict and confidence_level != "high")
rt_section = _fmt_realtime(rt, currency) news_section = _fmt_chunks(state.get("news_chunks", []), "NEWS")
# Historical: prefer deep RAG chunks (historical_rag_node) when intent fired, # otherwise use always-available patterns fetched alongside realtime data rag_hist = state.get("historical_chunks", []) if rag_hist: hist_section = _fmt_chunks(rag_hist, "HISTORICAL PATTERN", max_chunks=_MAX_HIST_CHUNKS) else: # Always-available fallback: fetched in realtime_node concurrently rt_patterns = (rt or {}).get("historical_patterns", []) hist_section = _fmt_historical_patterns(rt_patterns)
fund_section = _fmt_fundamentals(fd, currency) sector_section = _fmt_sector_context(state.get("sector_context"), currency)
flags_text = "\n".join(f"- {f}" for f in insight_flags[:4]) if insight_flags else "No significant flags." trend_text = "\n".join( f"- {k.replace('_', ' ').title()}: {v}" for k, v in trend.items() ) if trend else "Trend data unavailable."
conv_section = "" if history: recent = history[-4:] conv_lines = [f"{m['role'].upper()}: {m['content'][:200]}" for m in recent] conv_section = "[CONVERSATION HISTORY]\n" + "\n".join(conv_lines) + "\n\n"
# Translate internal labels → natural language before sending to LLM # This prevents label leakage ("dominant signal suggests", "uncertainty flag") _HINT_TO_NL = { "sharp_downward_move": "The stock is experiencing a sharp decline today.", "sharp_upward_move": "The stock is surging sharply today.", "high_volume_move": "Unusually high trading volume is the dominant signal today.", "near_52w_high": "The stock is trading near its 52-week high.", "near_52w_low": "The stock is trading near its 52-week low.", "analyst_strongly_bullish": "Analyst consensus is strongly bullish.", "analyst_bearish": "Analyst consensus is leaning bearish.", "mild_upward_move": "The stock is seeing a mild upward move today.", "mild_downward_move": "The stock is seeing a mild decline today.", "consolidating": "No strong directional signal is present — the stock is consolidating.", } market_context = _HINT_TO_NL.get(narrative_hint, "Market context is unclear.")
_CONFIDENCE_TO_POSTURE = { "high": "Be direct. State conclusions without hedging.", "medium": "Be measured. Use 'data shows' or 'current price action shows' — not 'suggests' or 'indicates'.", "low": "Be cautious. Avoid directional conclusions. Acknowledge limited signal clearly.", } response_posture = _CONFIDENCE_TO_POSTURE.get(confidence_level, "Be cautious. Avoid strong conclusions.")
if uncertainty_flag: response_posture += " No strong signal — do not construct a directional narrative."
if has_conflict: _CONFLICT_NL = { "price_down_but_analyst_bullish": "Price is declining but analyst consensus is bullish — name this divergence explicitly.", "price_up_but_analyst_cautious": "Price is rising but analysts are cautious — name this divergence explicitly.", "near_52w_low_but_analyst_bullish": "Stock is near 52-week lows but analysts rate it bullish — name this divergence explicitly.", "near_52w_high_but_target_below_price":"Stock is near 52-week highs but analyst target is below current price — name this divergence explicitly.", } conflict_text = _CONFLICT_NL.get(conflict_reason, f"Signal divergence detected: {conflict_reason.replace('_', ' ')}.") else: conflict_text = ""
return f"""{conv_section}STOCK: {company_name} ({ticker}) | Currency: {currency}
[MARKET CONTEXT — anchor your opening sentence here]{market_context}{f"[SIGNAL DIVERGENCE — acknowledge this in your narrative]{chr(10)}{conflict_text}" if conflict_text else ""}[RESPONSE POSTURE]{response_posture}
[REAL-TIME DATA]{rt_section}
[INSIGHT FLAGS]{flags_text}
[TREND SIGNALS]{trend_text}
[FUNDAMENTALS]{fund_section}
{news_section}
{hist_section}{chr(10) + sector_section if sector_section else ""}"""
def fusion_node(state: FiNoraState) -> dict: query = state["query"] ticker = state.get("ticker", "") is_summary = _is_summary_query(query)
data_context = _build_data_context(state)
if is_summary: task = ( "TASK: Explain what is happening with this stock right now, " "as if the user just opened the stock dashboard. " "Use the structured output format from your instructions." ) else: task = f"QUESTION: {query}"
fused = f"{data_context}\n\n{task}"
confidence = _compute_confidence(state) disclaimer = get_disclaimer(os.getenv("DISCLAIMER_LOCALE", "IN"))
citations: list[dict] = [] for ch in (state.get("news_chunks") or [])[:5]: if ch.get("url"): citations.append({ "url": ch["url"], "title": ch.get("title", ""), "source": ch.get("source", ""), "time": ch.get("published_at", ""), })
log.info( "fusion_done", ticker=ticker, mode="summary" if is_summary else "focused", user_mode=state.get("user_mode", "insight"), confidence=confidence, news=len(state.get("news_chunks") or []), historical=len(state.get("historical_chunks") or []), )
return { "fused_context": fused, "confidence_score": confidence, "disclaimer_text": disclaimer, "citations": citations, }1234567891011121314151617181920212223242526272829303132333435363738394041"""Historical RAG node — HyDE → hybrid retrieval → rerank → dedup → append to historical_chunks."""from __future__ import annotations
import structlog
from backend.graph.state import FiNoraStatefrom backend.rag.pipeline import run_rag_branchfrom backend.rag.retrieval.router import RetrievalBranch
log = structlog.get_logger()
_BRANCH = RetrievalBranch( intent="historical", collection="historical", use_hyde=True, description="20yr OHLCV event patterns, earnings history, technicals", allow_global_fallback=True,)
async def historical_rag_node(state: FiNoraState) -> dict: if "historical" not in state.get("intents", []): return {"historical_chunks": []}
query = state["query"] ticker = state.get("ticker", "")
import asyncio loop = asyncio.get_running_loop() result = await loop.run_in_executor(None, run_rag_branch, query, ticker, _BRANCH)
chunks = [ {"text": ch.text, "score": ch.score, **ch.metadata} for ch in result.chunks ] scores = result.retrieval_scores log.info("historical_rag_done", ticker=ticker, chunks=len(chunks), scores=scores) return { "historical_chunks": chunks, "retrieval_scores": {**state.get("retrieval_scores", {}), "historical": scores}, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Intent classification node — llama-3.1-8b-instant (~200ms).Classifies query into one or more intents that drive graph fan-out."""from __future__ import annotations
import jsonimport osimport uuid
import structlogfrom groq import Groq
from backend.graph.state import FiNoraState, Intent
log = structlog.get_logger()
_MODEL = os.getenv("GROQ_MODEL_FAST", "llama-3.1-8b-instant")
_SYSTEM = """\You are a financial query intent classifier. Classify the user query into one or more intents.
Intents:- real_time: live price, today's movement, current volume, intraday- news: recent news, announcements, catalysts, analyst notes, press releases- historical: past patterns, earnings history, 20yr comparison, technical patterns- fundamental: PE, EPS, revenue, margins, balance sheet, valuation- comparative: compare two stocks or sectors, sector performance, peers, similar stocks, competitors- screener: find stocks matching criteria
INCLUDE news for: "why", "what's driving", "catalyst", "reason", "what happened", "latest", "moving", "dropped", "surged", "crashed", "rally", explicit news requestsDO NOT include news for: pure fundamental queries (PE, EPS, revenue, valuation, margins), pure technical queries (RSI, MACD, support, resistance, moving average), basic price or volume lookupsINCLUDE comparative for: "sector", "peers", "similar stocks", "competitors", "how does it compare", "vs", "against", "sector performance", "industry peers", "sector heatmap"
Examples:- "Why did Apple drop today?" → ["real_time", "news", "historical"]- "What is the PE ratio?" → ["fundamental"]- "What's the RSI?" → ["real_time", "historical"]- "Latest news on NVDA" → ["news"]- "What's AAPL trading at?" → ["real_time"]- "Compare AAPL and MSFT earnings" → ["fundamental", "historical", "comparative"]- "How is the tech sector doing?" → ["real_time", "comparative"]- "Show me similar stocks to AAPL" → ["comparative"]- "Who are Apple's peers?" → ["comparative"]- "How does AAPL compare to its sector?" → ["real_time", "fundamental", "comparative"]
Return ONLY the JSON array, no explanation."""
_SUMMARY_TRIGGERS = { "summarize", "summary", "explain", "overview", "what's happening", "whats happening", "tell me about", "breakdown", "analyse", "analyze", "give me a", "what do you think", "how is", "how's",}
_ALL_INTENTS: list[Intent] = ["real_time", "fundamental", "news", "historical"]
def _is_summary_query(query: str) -> bool: q = query.lower().strip() return any(trigger in q for trigger in _SUMMARY_TRIGGERS)
def intent_classifier_node(state: FiNoraState) -> dict: query = state["query"] ticker = state.get("ticker", "") trace_id = state.get("trace_id") or str(uuid.uuid4())[:8]
# Summary queries always fire all 4 branches — need full data for narrative if _is_summary_query(query): log.info("intents_classified", query=query[:60], intents=_ALL_INTENTS, trace_id=trace_id, reason="summary_shortcut") return {"intents": _ALL_INTENTS, "trace_id": trace_id}
try: client = Groq(api_key=os.getenv("GROQ_API_KEY")) prompt = f'Ticker context: {ticker}\nQuery: "{query}"'
resp = client.chat.completions.create( model=_MODEL, messages=[ {"role": "system", "content": _SYSTEM}, {"role": "user", "content": prompt}, ], max_tokens=60, temperature=0.0, ) raw = resp.choices[0].message.content or "[]"
start = raw.find("[") end = raw.rfind("]") + 1 intents = json.loads(raw[start:end]) if start >= 0 else ["real_time"]
valid = {"real_time", "news", "historical", "fundamental", "comparative", "screener"} intents = [i for i in intents if i in valid] or ["real_time"]
except Exception as exc: log.warning("intent_classifier_failed", error=str(exc)) intents = ["real_time"]
log.info("intents_classified", query=query[:60], intents=intents, trace_id=trace_id) return {"intents": intents, "trace_id": trace_id}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""News RAG node — live Google RSS (dashboard-parity) + Qdrant supplementary context."""from __future__ import annotations
import asyncio
import structlog
from backend.graph.state import FiNoraStatefrom backend.rag.pipeline import run_rag_branchfrom backend.rag.retrieval.router import RetrievalBranch
log = structlog.get_logger()
_BRANCH = RetrievalBranch( intent="news", collection="news", use_hyde=False, description="News articles, analyst reports, press releases", allow_global_fallback=False,)
_TOP_K = 4 # Qdrant supplementary chunks (already capped in fusion)_LIVE_COUNT = 5 # Google RSS headlines — same source as dashboard
async def news_rag_node(state: FiNoraState) -> dict: if "news" not in state.get("intents", []) and "comparative" not in state.get("intents", []): return {"news_chunks": []}
query = state["query"] ticker = state.get("ticker", "") yf_ticker = state.get("yf_ticker", ticker)
loop = asyncio.get_running_loop() from backend.rag.yahoo_client import fetch_news
# Always fetch live Google RSS first — same source the dashboard displays. # This guarantees LLM sees the same headlines the user is looking at. live_task = loop.run_in_executor(None, fetch_news, yf_ticker or ticker, _LIVE_COUNT) rag_task = loop.run_in_executor(None, run_rag_branch, query, ticker, _BRANCH)
live_news, result = await asyncio.gather(live_task, rag_task)
# Qdrant chunks — supplementary historical/older context qdrant_chunks = [ {"text": ch.text, "score": ch.score, **ch.metadata} for ch in result.chunks ]
# Deduplicate: drop Qdrant chunks whose title appears in live headlines live_titles = {n.get("title", "").lower()[:60] for n in live_news} qdrant_chunks = [ ch for ch in qdrant_chunks if ch.get("title", ch.get("text", ""))[:60].lower() not in live_titles ]
# Live RSS headlines first (highest priority = same as dashboard) # Qdrant supplementary second chunks = list(live_news) + qdrant_chunks
scores = result.retrieval_scores log.info( "news_rag_done", ticker=ticker, live=len(live_news), qdrant=len(qdrant_chunks), total=len(chunks), ) return { "news_chunks": chunks, "retrieval_scores": {**state.get("retrieval_scores", {}), "news": scores}, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""Real-time data node — Yahoo Finance v8 via curl_cffi Chrome TLS impersonation."""from __future__ import annotations
import asyncioimport time
import structlog
from backend.graph.state import FiNoraStatefrom backend.rag.yahoo_client import fetch_ohlcv, fetch_quote
log = structlog.get_logger()
_PATTERNS_CACHE: dict[str, tuple[list[dict], float]] = {}_PATTERNS_TTL = 300.0 # 5 minutes
def _fetch_historical_patterns(ticker: str) -> list[dict]: """ Fetch historical context from Qdrant — same query the dashboard uses — so chat has historical data regardless of intent routing. Returns up to 2 pattern chunks, empty list on any failure. Cached 5 min. """ cached = _PATTERNS_CACHE.get(ticker) if cached and (time.monotonic() - cached[1]) < _PATTERNS_TTL: log.debug("historical_patterns_cache_hit", ticker=ticker) return cached[0]
try: from backend.rag.retrieval.hybrid import hybrid_search from backend.rag.ingestion.collections import collection_name chunks = hybrid_search( query=f"{ticker} historical price patterns earnings volatility", ticker=ticker, collection=collection_name("historical"), limit=2, allow_global_fallback=False, ) results = [] for ch in chunks: meta = ch.metadata if hasattr(ch, "metadata") else {} results.append({ "text": ch.text if hasattr(ch, "text") else str(ch), "event_type": meta.get("event_type", "price_event"), "date_range": meta.get("date_range", meta.get("start_date", "")), "return_pct": meta.get("return_pct"), }) _PATTERNS_CACHE[ticker] = (results, time.monotonic()) return results except Exception as exc: log.debug("historical_patterns_fetch_skipped", ticker=ticker, error=str(exc)) return []
def _fetch_realtime(ticker: str) -> dict: quote = fetch_quote(ticker)
# 1d intraday bars (5m interval, last 12 bars for streaming chart) df_intraday = fetch_ohlcv(ticker, days=1, interval="5m") intraday: list[dict] = [] if not df_intraday.empty: for dt, row in df_intraday.tail(12).iterrows(): intraday.append({ "time": str(dt), "close": round(float(row["Close"]), 4), "volume": int(row["Volume"]), })
# 30d daily bars for monthly price chart df_30d = fetch_ohlcv(ticker, range_str="1mo", interval="1d") monthly: list[dict] = [] if not df_30d.empty: for dt, row in df_30d.iterrows(): monthly.append({ "date": str(dt)[:10], "close": round(float(row["Close"]), 4), })
return { "price": quote.get("price"), "change": quote.get("change"), "pct_change": quote.get("pct_change"), "volume": quote.get("volume"), "avg_volume_30d": quote.get("avg_volume_3m"), "market_cap": quote.get("market_cap"), "week_52_high": None, "week_52_low": None, "open": quote.get("open"), "intraday": intraday, "monthly": monthly, }
async def realtime_node(state: FiNoraState) -> dict: ticker = state.get("ticker", "") yf_ticker = state.get("yf_ticker", ticker) if not ticker: return {"realtime_context": None}
loop = asyncio.get_running_loop()
# Fetch realtime + historical patterns concurrently realtime_task = loop.run_in_executor(None, _fetch_realtime, yf_ticker) historical_task = loop.run_in_executor(None, _fetch_historical_patterns, ticker)
data, historical_patterns = await asyncio.gather(realtime_task, historical_task)
data["ticker"] = ticker # Always inject historical patterns — chat has parity with dashboard regardless of intent data["historical_patterns"] = historical_patterns
log.info( "realtime_node_done", ticker=ticker, price=data.get("price"), historical_patterns=len(historical_patterns), ) return {"realtime_context": data}123456789101112131415161718192021222324252627282930313233343536373839404142434445"""Shared response cache — imported by response_node and chat route for early bypass."""from __future__ import annotations
import hashlibimport osimport time
_RESPONSE_CACHE: dict[str, tuple[str, float | None, float]] = {}_CACHE_TTL = float(os.getenv("RESPONSE_CACHE_TTL", "300"))_CACHE_PRICE_THRESHOLD = float(os.getenv("RESPONSE_CACHE_PRICE_THRESHOLD", "2.0"))
_VOLATILE_TERMS = frozenset({ "right now", "just now", "breaking", "latest news", "happening now", "this second", "live", "real time", "realtime", "right this moment",})
def cache_key(ticker: str, query: str, user_mode: str) -> str: fingerprint = hashlib.sha256(query.lower().strip().encode()).hexdigest()[:12] return f"{ticker}:{fingerprint}:{user_mode}"
def is_volatile_query(query: str) -> bool: q = query.lower() return any(term in q for term in _VOLATILE_TERMS)
def get_cached(key: str, current_pct: float | None = None) -> str | None: """Return cached response if valid. current_pct=None skips price-based invalidation.""" entry = _RESPONSE_CACHE.get(key) if not entry: return None text, cached_pct, ts = entry if (time.monotonic() - ts) > _CACHE_TTL: del _RESPONSE_CACHE[key] return None if current_pct is not None and cached_pct is not None: if abs(current_pct - cached_pct) >= _CACHE_PRICE_THRESHOLD: del _RESPONSE_CACHE[key] return None return text
def set_cached(key: str, text: str, pct: float | None) -> None: _RESPONSE_CACHE[key] = (text, pct, time.monotonic())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193"""Response node — Groq llama-3.3-70b with mode-aware output, response cache, and 8B fallback."""from __future__ import annotations
import os
import structlogfrom groq import Groq
from backend.graph.nodes.response_cache import cache_key, get_cached, is_volatile_query, set_cachedfrom backend.graph.state import FiNoraStatefrom backend.guardrails.output_filter import apply_output_guardrail
log = structlog.get_logger()
_GROQ_MODEL_PRIMARY = os.getenv("GROQ_MODEL_PRIMARY", "openai/gpt-oss-120b")_GROQ_MODEL_FALLBACK = os.getenv("GROQ_MODEL_FAST", "llama-3.1-8b-instant")_MAX_TOKENS = int(os.getenv("GROQ_MAX_TOKENS", "1200"))_TEMPERATURE = float(os.getenv("GROQ_TEMPERATURE", "0.15"))
_SYSTEM_INSIGHT = """You are Finora AI — a financial intelligence system. Behave like an analyst reading a dashboard, not a chatbot.
STRICT RULES:- Never hallucinate numbers. Ground every statement in provided data.- Interpret metrics, don't restate them. High PE = premium valuation — say why it matters.- Correct currency: INR for Indian stocks, USD for US stocks. Use company name, not ticker.- No emojis.
OPENING — NON-NEGOTIABLE:- First sentence states what the stock is doing, grounded in [MARKET CONTEXT].- Never start with: "Based on", "According to", "The data shows".- Good: "Apple is down 0.9% today with no strong momentum — markets appear to be waiting ahead of earnings."
RESPONSE POSTURE: Follow [RESPONSE POSTURE] exactly — it controls certainty level.
SIGNAL DIVERGENCE: If [SIGNAL DIVERGENCE] present, name it in one sentence.- Good: "Price is down 2% but 78% of analysts rate Buy — the market may be discounting near-term noise."
INTENSITY AWARENESS:- Query uses strong language but data shows mild move → use contrast phrases: "no signs of heavy selling", "price action remains orderly", "no panic-driven volume"- Data confirms sharp move → match intensity, be direct.- Never reference the user's wording. Let data speak.
BANNED WORDS: suggesting, indicating, implying, appears to, seems to, would suggest, dominant signal, uncertainty flag, MARKET CONTEXT, RESPONSE POSTURE, SIGNAL DIVERGENCE, "not X% as stated", "discrepancy", "does not match", "despite the", "as you mentioned", mixed signals, it depends
HISTORICAL PATTERNS: If [HISTORICAL PATTERNS] present → reference at least one. Integrate naturally: "This mirrors [date] when the stock [outcome]."
STYLE: 1-2 tight sentences per section. Each section adds new info. Expand where data is strong; omit where weak.- [UNAVAILABLE] / [NO DATA] / [LIMITED] → skip that section entirely, no explanation.- Low signal fallback: "No strong directional signal is present — the stock is consolidating."
OUTPUT — summary queries:## What's Happening## Fundamentals## Technical Trend## Analyst Sentiment## Recent Drivers## Key Risks
OUTPUT — focused queries: Answer directly. No headers. Max 100 words.
For buy/sell queries: price action + analyst sentiment + top risk, then end with EXACTLY:Consider consulting a financial advisor before making investment decisions."""
_SYSTEM_TRADER = """You are Finora AI — financial intelligence for active traders. Behave like a quant analyst at a trading desk — data-first, directional, precise.
STRICT RULES:- Never hallucinate numbers. Ground every statement in provided data.- Be specific and directional. Correct currency: INR Indian, USD US. Company name, not ticker.- No emojis.
OPENING — NON-NEGOTIABLE:- First sentence: stock action + explicit directional bias (bullish / bearish / neutral).- Never start with: "Based on", "According to", "The data shows".- Good: "Momentum is neutral — Apple is down 0.9% on below-average volume, consolidating ahead of earnings."
RESPONSE POSTURE: Follow [RESPONSE POSTURE] exactly — controls certainty and directional strength.
SIGNAL DIVERGENCE: If [SIGNAL DIVERGENCE] present, name it — most actionable signal for a trader.- Good: "Price is down 2.4% but 78% of analysts rate Buy — this divergence may signal opportunity or analyst lag."
INTENSITY AWARENESS:- Query uses strong language but data shows mild move → contrast phrases: "no signs of heavy selling", "price action remains orderly", "no panic-driven volume"- Data confirms sharp move → match intensity, be urgent.- Never reference the user's wording.
BANNED WORDS: suggesting, indicating, implying, appears to, seems to, would suggest, dominant signal, uncertainty flag, MARKET CONTEXT, RESPONSE POSTURE, SIGNAL DIVERGENCE, "not X% as stated", "discrepancy", "does not match", "despite the", "as you mentioned"
HISTORICAL PATTERNS: If [HISTORICAL PATTERNS] present → reference at least one. "This setup mirrors [event] in [date] when the stock [return outcome]."
STYLE: 1-2 tight sentences per section. Each section adds new info. Expand where data is strong.- [UNAVAILABLE] / [NO DATA] / [LIMITED] → skip that section entirely.- Low signal fallback: "No strong directional signal. Momentum is neutral — exercise caution."
OUTPUT — summary queries:## What's Happening## Fundamentals## Technical Trend## Analyst Sentiment## Recent Drivers## Key Risks## Signals That Matter (always include for trader mode)
OUTPUT — focused queries: Answer directly. No headers. Max 150 words. Always state directional bias.
For buy/sell queries: current signals + key risk, end with:This is market intelligence, not financial advice — trading decisions rest with you.NEVER give absolute directives ("you should buy", "go long now")."""
def _cache_key(ticker: str, query: str, user_mode: str) -> str: fingerprint = hashlib.sha256(query.lower().strip().encode()).hexdigest()[:12] return f"{ticker}:{fingerprint}:{user_mode}"
def _call_groq(client: Groq, model: str, system_prompt: str, fused_context: str) -> str: resp = client.chat.completions.create( model=model, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": fused_context}, ], max_tokens=_MAX_TOKENS, temperature=_TEMPERATURE, ) return resp.choices[0].message.content or ""
def response_node(state: FiNoraState) -> dict: fused_context = state.get("fused_context", "") confidence = state.get("confidence_score", 0.0) disclaimer = state.get("disclaimer_text", "") locale = os.getenv("DISCLAIMER_LOCALE", "IN") user_mode = state.get("user_mode", "insight") ticker = state.get("ticker", "") query = state.get("query", "") current_pct = (state.get("realtime_context") or {}).get("pct_change")
if not fused_context: return {"response": "I don't have enough data to answer that query."}
system_prompt = _SYSTEM_TRADER if user_mode == "trader" else _SYSTEM_INSIGHT
# Cache lookup — skip for volatile/live queries cache_hit = False text = "" if ticker and query and not is_volatile_query(query): key = cache_key(ticker, query, user_mode) cached = get_cached(key, current_pct) if cached: log.info("response_cache_hit", ticker=ticker, user_mode=user_mode) text = cached cache_hit = True
if not cache_hit: client = Groq(api_key=os.getenv("GROQ_API_KEY")) model_used = _GROQ_MODEL_PRIMARY try: text = _call_groq(client, _GROQ_MODEL_PRIMARY, system_prompt, fused_context) except Exception as exc: err_str = str(exc) # 429 rate limit → fall back to 8B (separate TPD bucket on Groq free tier) if "429" in err_str or "rate_limit" in err_str.lower(): log.warning("groq_primary_rate_limited_falling_back_to_8b", error=err_str[:120]) try: text = _call_groq(client, _GROQ_MODEL_FALLBACK, system_prompt, fused_context) model_used = _GROQ_MODEL_FALLBACK except Exception as fallback_exc: log.error("groq_fallback_also_failed", error=str(fallback_exc)) text = "I encountered an error generating the analysis. Please try again." else: log.error("groq_generation_failed", error=err_str) text = "I encountered an error generating the analysis. Please try again."
# Cache successful primary-model responses only if text and model_used == _GROQ_MODEL_PRIMARY and ticker and query and not is_volatile_query(query): set_cached(cache_key(ticker, query, user_mode), text, current_pct)
text = apply_output_guardrail( response=text, fused_context=fused_context, confidence_score=confidence, disclaimer_text=disclaimer, locale=locale, )
log.info( "response_ok", chars=len(text), confidence=confidence, cache_hit=cache_hit, user_mode=user_mode, ) return {"response": text}12345678910111213141516171819202122232425262728293031323334353637383940414243from __future__ import annotations
import operatorfrom typing import Annotated, Literal, TypedDict
Intent = Literal["real_time", "news", "historical", "fundamental", "comparative", "screener"]UserMode = Literal["insight", "trader"]
class FiNoraState(TypedDict): # Input query: str ticker: str # display ticker (e.g. "TCS", "RELIANCE") yf_ticker: str # Yahoo Finance ticker (e.g. "TCS.NS", "RELIANCE.NS") company_name: str # full company name (e.g. "Infosys Limited") currency: str # ISO currency code (e.g. "INR", "USD") user_mode: UserMode # "insight" (default) or "trader" session_id: str conversation_history: list[dict]
# Routing intents: list[Intent] guardrail_flags: list[str] guardrail_blocked: bool
# Retrieval outputs (parallel branches append — operator.add merges lists) realtime_context: dict | None news_chunks: Annotated[list[dict], operator.add] historical_chunks: Annotated[list[dict], operator.add] fundamental_data: dict | None sector_context: dict | None # sector ETF performance + similar stocks
# Generation fused_context: str response: str citations: list[dict] confidence_score: float disclaimer_text: str
# Observability trace_id: str retrieval_scores: dict123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""Input guardrail — llama-3.1-8b-instant classifies query safety (~150ms).First node in the LangGraph — blocks unsafe queries before any retrieval."""from __future__ import annotations
import jsonimport os
import structlogfrom groq import Groq
from backend.graph.state import FiNoraStatefrom backend.guardrails.disclaimers import get_disclaimer
log = structlog.get_logger()
_MODEL = os.getenv("GROQ_MODEL_FAST", "llama-3.1-8b-instant")
# Always blocked — regardless of user_mode_ALWAYS_BLOCKED = { "insider_trading_context", "market_manipulation", "tax_evasion_advice", "specific_options_strategy",}
# Blocked in INSIGHT mode only — TRADER mode receives signal-based response instead_INSIGHT_ONLY_BLOCKED = { "direct_buy_sell_recommendation", "personal_financial_planning",}
# Combined set for insight mode_BLOCKED_INTENTS = _ALWAYS_BLOCKED | _INSIGHT_ONLY_BLOCKED
_SYSTEM = """\You are a financial query safety classifier.Classify the query intent as one of:- allowed: fundamental_analysis, technical_analysis, news_analysis, historical_pattern, sector_comparison, earnings_analysis, market_overview, screener, educational- blocked: direct_buy_sell_recommendation, specific_options_strategy, insider_trading_context, market_manipulation, personal_financial_planning, tax_evasion_advice
Return JSON: {"intent": "<intent>", "blocked": true/false}Return ONLY the JSON."""
_REDIRECT_MSG = ( "I can't make specific investment recommendations, but I can pull what analysts " "currently say about {ticker} and the key metrics to consider. " "Want me to surface the consensus view and recent developments?")
def guardrail_check_node(state: FiNoraState) -> dict: if os.getenv("GUARDRAILS_ENABLED", "true").lower() != "true": return {"guardrail_blocked": False, "guardrail_flags": []}
query = state["query"] ticker = state.get("ticker", "the stock")
user_mode = state.get("user_mode", "insight") # In trader mode, buy/sell and personal planning queries are allowed through # (response_node handles them with signal-based framing + risk disclosure) blocked_set = _ALWAYS_BLOCKED if user_mode == "trader" else _BLOCKED_INTENTS
try: client = Groq(api_key=os.getenv("GROQ_API_KEY")) resp = client.chat.completions.create( model=_MODEL, messages=[ {"role": "system", "content": _SYSTEM}, {"role": "user", "content": f"Query: {query}"}, ], max_tokens=60, temperature=0.0, ) raw = resp.choices[0].message.content or "{}" start, end = raw.find("{"), raw.rfind("}") + 1 result = json.loads(raw[start:end]) if start >= 0 else {} intent = result.get("intent", "allowed") blocked = intent in blocked_set except Exception as exc: log.warning("guardrail_classifier_failed", error=str(exc)) blocked = False intent = "allowed"
flags = [intent] if blocked else [] log.info("guardrail_check", query=query[:60], blocked=blocked, intent=intent, user_mode=user_mode)
if blocked: redirect = _REDIRECT_MSG.format(ticker=ticker) disclaimer = get_disclaimer(os.getenv("DISCLAIMER_LOCALE", "IN")) return { "guardrail_blocked": True, "guardrail_flags": flags, "response": redirect, "disclaimer_text": disclaimer, "fused_context": "", "confidence_score": 0.0, "citations": [], }
return {"guardrail_blocked": False, "guardrail_flags": flags}
def route_after_guardrail(state: FiNoraState) -> str: return "blocked" if state.get("guardrail_blocked") else "allowed"1234567891011121314151617181920from __future__ import annotations
_DISCLAIMERS = { "IN": ( "⚠ For informational purposes only. Not financial advice. " "Consult a SEBI-registered investment advisor before making decisions." ), "US": ( "⚠ For informational purposes only. Not financial advice per SEC rules. " "Consult a registered investment advisor." ), "GLOBAL": ( "⚠ Informational only. Not investment advice. " "Past performance does not guarantee future results." ),}
def get_disclaimer(locale: str = "IN") -> str: return _DISCLAIMERS.get(locale.upper(), _DISCLAIMERS["GLOBAL"])1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586"""Output guardrail pipeline — runs post-generation, pre-client.
Steps:1. Hallucination check: numbers/% in response verified against fused_context2. PII scrub: regex over response for account numbers, personal identifiers3. Confidence signal: if score < 0.6, inject moderate-confidence warning4. Directional language: detected → inject disclaimer"""from __future__ import annotations
import re
import structlog
from backend.guardrails.disclaimers import get_disclaimer
log = structlog.get_logger()
# Matches percentages and dollar/rupee amounts with optional sign_NUMBER_RE = re.compile(r"[+-]?\d+(?:\.\d+)?%|[₹$]\s*\d[\d,.]+")
# PII patterns: account numbers (10–18 digits), Aadhaar (XXXX XXXX XXXX), PAN_PII_PATTERNS = [ (re.compile(r"\b\d{10,18}\b"), "[ACCOUNT_REDACTED]"), (re.compile(r"\b[A-Z]{5}\d{4}[A-Z]\b"), "[PAN_REDACTED]"), (re.compile(r"\b\d{4}\s\d{4}\s\d{4}\b"), "[AADHAAR_REDACTED]"),]
_DIRECTIONAL_PHRASES = { "will rise", "will fall", "will go up", "will go down", "you should buy", "you should sell", "guaranteed", "certain to", "definitely go up", "definitely go down", "sure to",}
def _extract_numbers(text: str) -> list[str]: return _NUMBER_RE.findall(text)
def _hallucination_check(response: str, fused_context: str) -> str: """Log unverified numbers for observability. No user-facing annotation.""" if not fused_context: return response context_numbers = set(_extract_numbers(fused_context)) flagged = [n for n in _extract_numbers(response) if n not in context_numbers] if flagged: log.warning("hallucination_flag", unverified=flagged[:5]) return response # no inline annotation — clean UX
def _scrub_pii(text: str) -> str: for pattern, replacement in _PII_PATTERNS: text = pattern.sub(replacement, text) return text
def _has_directional_language(text: str) -> bool: lower = text.lower() return any(phrase in lower for phrase in _DIRECTIONAL_PHRASES)
def apply_output_guardrail( response: str, fused_context: str, confidence_score: float, disclaimer_text: str, locale: str = "IN",) -> str: """Apply all output guardrails. Returns the final safe response string.""" # Step 1: hallucination check response = _hallucination_check(response, fused_context)
# Step 2: PII scrub response = _scrub_pii(response)
# Step 3: confidence is tracked in SSE event — no inline annotation needed
# Step 4: disclaimer ONLY when response contains directional language # (otherwise it fires via the separate SSE "disclaimer" event once per session) if _has_directional_language(response): disclaimer = disclaimer_text or get_disclaimer(locale) if disclaimer not in response: response += f"\n\n{disclaimer}"
return response123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293import osfrom contextlib import asynccontextmanagerfrom pathlib import Path
import structlogimport uvicornfrom fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom slowapi import _rate_limit_exceeded_handlerfrom slowapi.errors import RateLimitExceededfrom slowapi.middleware import SlowAPIMiddleware
from dotenv import load_dotenv
ROOT = Path(__file__).resolve().parents[1]if os.getenv("ENV", "development") != "production": load_dotenv(ROOT / ".env")
EVAL_DIR = ROOT / "backend" / "data" / "eval_results"EVAL_DIR.mkdir(parents=True, exist_ok=True)
from backend.api.middleware.guardrails import FinancialGuardrailMiddlewarefrom backend.api.middleware.rate_limit import limiterfrom backend.api.routes import chat, health, stocksfrom backend.rag.ingestion.universe import universe
log = structlog.get_logger()
def _warm_yahoo_session() -> None: """Prime curl_cffi session cookies + crumb before first real request.""" try: from backend.rag.yahoo_client import _warm_session, _get_crumb _warm_session("AAPL") _warm_session("AAPL") crumb = _get_crumb() log.info("yahoo_session_warmed", crumb_ok=bool(crumb)) except Exception as exc: log.warning("yahoo_warm_failed", error=str(exc))
@asynccontextmanagerasync def lifespan(app: FastAPI): log.info("startup", universe_size=len(universe.stocks))
import asyncio loop = asyncio.get_event_loop() await loop.run_in_executor(None, _warm_yahoo_session)
scheduler = None if os.getenv("ENV", "development") == "production" or os.getenv("SCHEDULER_ENABLED", "false") == "true": from backend.rag.ingestion.scheduler import start_scheduler scheduler = start_scheduler()
yield
if scheduler: from backend.rag.ingestion.scheduler import stop_scheduler stop_scheduler()
log.info("shutdown")
app = FastAPI(title="Finora API", version="1.0.0", lifespan=lifespan)
# ========================= Verify Backend Log (REMOVE LATER) =========================@app.get("/")def root(): return {"message": "Finora API is running"}
cors_origins = os.getenv("CORS_ORIGINS", "http://localhost:3000").split(",")app.add_middleware( CORSMiddleware, allow_origins=[o.strip() for o in cors_origins], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
app.state.limiter = limiterapp.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)app.add_middleware(SlowAPIMiddleware)app.add_middleware(FinancialGuardrailMiddleware)
app.include_router(health.router, prefix="/api")app.include_router(stocks.router, prefix="/api/stocks")app.include_router(chat.router, prefix="/api")
if __name__ == "__main__": port = int(os.getenv("PORT", "7860")) uvicorn.run("backend.main:app", host="0.0.0.0", port=port)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""LangSmith tracing wrapper for all LangGraph runs.
LangSmith auto-instruments via environment variables when: LANGCHAIN_TRACING_V2=true LANGCHAIN_API_KEY=ls__... LANGCHAIN_PROJECT=finora-prod
This module provides explicit trace helpers for non-graph code paths(MCP tools, batch ingestion, eval) that don't run through LangGraph."""from __future__ import annotations
import osfrom contextlib import contextmanagerfrom typing import Any, Generator
import structlog
log = structlog.get_logger()
_TRACING_ENABLED = ( os.getenv("LANGCHAIN_TRACING_V2", "false").lower() == "true" and bool(os.getenv("LANGCHAIN_API_KEY")))
@contextmanagerdef trace_run( name: str, run_type: str = "chain", metadata: dict[str, Any] | None = None,) -> Generator[Any, None, None]: """Context manager that wraps a code block in a LangSmith trace span.""" if not _TRACING_ENABLED: yield None return
try: from langsmith import trace as ls_trace
with ls_trace(name=name, run_type=run_type, metadata=metadata or {}) as run: yield run except ImportError: yield None except Exception as exc: log.warning("langsmith_trace_failed", name=name, error=str(exc)) yield None
def log_retrieval_scores(run_id: str, scores: dict[str, float]) -> None: """Attach retrieval scores as feedback to a LangSmith run.""" if not _TRACING_ENABLED or not scores: return try: from langsmith import Client as LSClient
client = LSClient() for key, value in scores.items(): client.create_feedback( run_id=run_id, key=key, score=value, ) except Exception as exc: log.warning("langsmith_feedback_failed", error=str(exc))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""Resolve the correct LangSmith project URL at startup and cache it."""from __future__ import annotations
import os
import structlog
log = structlog.get_logger()
_cached_url: str | None = None_resolved = False
def get_project_url() -> str | None: """ Return the full LangSmith project URL. Resolution order: 1. Env vars LANGSMITH_ORG_ID + LANGSMITH_PROJECT_ID (fastest, no API call) 2. LangSmith Client API (reads project by name, uses client._tenant_id) 3. None if LANGCHAIN_API_KEY not set Result is cached — API call happens at most once per process lifetime. """ global _cached_url, _resolved if _resolved: return _cached_url
_resolved = True api_key = os.getenv("LANGCHAIN_API_KEY") if not api_key: return None
project_name = os.getenv("LANGCHAIN_PROJECT", "finora-prod")
# Fast path — both IDs set explicitly in env org_id = os.getenv("LANGSMITH_ORG_ID") project_id = os.getenv("LANGSMITH_PROJECT_ID") if org_id and project_id: _cached_url = f"https://smith.langchain.com/o/{org_id}/projects/p/{project_id}" log.info("langsmith_traced", url=_cached_url) return _cached_url
# Slow path — fetch from LangSmith API (once per process) try: from langsmith import Client client = Client(api_key=api_key)
project = client.read_project(project_name=project_name) project_id = str(project.id)
# _tenant_id is private but stable across SDK versions resolved_org_id = org_id or str(getattr(client, "_tenant_id", None) or "")
if resolved_org_id and project_id: _cached_url = f"https://smith.langchain.com/o/{resolved_org_id}/projects/p/{project_id}" elif project_id: # Fallback: no org id available — link to project by name (less precise) _cached_url = f"https://smith.langchain.com/projects/{project_name}"
log.info("langsmith_url_resolved_from_api", url=_cached_url, project_id=project_id) except Exception as exc: log.warning("langsmith_url_resolution_failed", error=str(exc)) _cached_url = None
return _cached_url1234567891011121314151617181920212223"""Prometheus metrics — optional, enabled via METRICS_ENABLED=true."""from __future__ import annotations
import os
_ENABLED = os.getenv("METRICS_ENABLED", "false").lower() == "true"
if _ENABLED: try: from prometheus_client import Counter, Histogram, start_http_server
chat_requests_total = Counter("finora_chat_requests_total", "Total chat requests") chat_latency_seconds = Histogram("finora_chat_latency_seconds", "Chat end-to-end latency") retrieval_chunks = Histogram( "finora_retrieval_chunks", "Chunks retrieved per branch", labelnames=["branch"], ) guardrail_blocks_total = Counter("finora_guardrail_blocks_total", "Guardrail blocked requests")
def start_metrics_server(port: int = 9090) -> None: start_http_server(port) except ImportError: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125from __future__ import annotations
from dataclasses import dataclass, fieldfrom datetime import datefrom typing import Any, Literal
import numpy as npimport pandas as pd
EventType = Literal["earnings_week", "macro_shock", "sector_rotation", "fed_meeting", "unusual_volume"]
@dataclassclass FinancialChunk: text: str # embeddable summary_text metadata: dict[str, Any] = field(default_factory=dict)
class FinancialEventChunker: """ Detects significant events in OHLCV data and creates 5-trading-day windows around each. Each chunk is embedded via its LLM-generated summary_text. """
VOLUME_Z_THRESHOLD = 2.0 RETURN_THRESHOLD = 0.03 # 3% single-day move WINDOW_DAYS = 5 # days before+after event
def chunk(self, df: pd.DataFrame, ticker: str) -> list[FinancialChunk]: """ df: DataFrame with DatetimeIndex, columns [Open, High, Low, Close, Volume]. Returns FinancialChunk list, one per detected event window. """ if df.empty or len(df) < 20: return []
df = df.copy() df["return_pct"] = df["Close"].pct_change() vol_mean = df["Volume"].rolling(30, min_periods=10).mean() vol_std = df["Volume"].rolling(30, min_periods=10).std().replace(0, 1) df["volume_z"] = (df["Volume"] - vol_mean) / vol_std
event_indices = self._detect_events(df) chunks: list[FinancialChunk] = [] seen_windows: set[int] = set()
for idx in event_indices: # 5-day window: 2 before, event, 2 after start = max(0, idx - 2) end = min(len(df), idx + 3)
# Skip if this window overlaps a seen one if any(i in seen_windows for i in range(start, end)): continue seen_windows.update(range(start, end))
window = df.iloc[start:end] event_type = self._classify_event(df.iloc[idx]) chunk = self._build_chunk(window, ticker, event_type, df.iloc[idx]) chunks.append(chunk)
return chunks
def _detect_events(self, df: pd.DataFrame) -> list[int]: events: list[int] = [] for i in range(len(df)): row = df.iloc[i] ret = abs(row.get("return_pct", 0) or 0) vol_z = row.get("volume_z", 0) or 0 if (ret >= self.RETURN_THRESHOLD) or (vol_z >= self.VOLUME_Z_THRESHOLD): events.append(i) return events
def _classify_event(self, row: pd.Series) -> EventType: vol_z = row.get("volume_z", 0) or 0 ret = row.get("return_pct", 0) or 0 if vol_z >= 3.0 and abs(ret) >= 0.05: return "earnings_week" if abs(ret) >= 0.05: return "macro_shock" if vol_z >= self.VOLUME_Z_THRESHOLD: return "unusual_volume" return "sector_rotation"
def _build_chunk( self, window: pd.DataFrame, ticker: str, event_type: EventType, event_row: pd.Series, ) -> FinancialChunk: start_date = str(window.index[0].date()) if hasattr(window.index[0], "date") else str(window.index[0]) end_date = str(window.index[-1].date()) if hasattr(window.index[-1], "date") else str(window.index[-1])
ret_pct = float(event_row.get("return_pct", 0) or 0) * 100 vol_z = float(event_row.get("volume_z", 0) or 0) close_start = float(window["Close"].iloc[0]) close_end = float(window["Close"].iloc[-1]) window_return = (close_end - close_start) / close_start * 100 if close_start else 0
summary = ( f"{ticker} experienced a {event_type.replace('_', ' ')} event from {start_date} to {end_date}. " f"On the event day, the stock moved {ret_pct:+.2f}% with volume {vol_z:+.1f}x the 30-day average. " f"Over the 5-day window, {ticker} returned {window_return:+.2f}% " f"(from ${close_start:.2f} to ${close_end:.2f})." )
return FinancialChunk( text=summary, metadata={ "ticker": ticker, "event_type": event_type, "date_range": f"{start_date}:{end_date}", "start_date": start_date, "end_date": end_date, "return_pct": round(ret_pct, 4), "volume_z_score": round(vol_z, 4), "window_return_pct": round(window_return, 4), "open": round(float(window["Open"].iloc[0]), 4), "high": round(float(window["High"].max()), 4), "low": round(float(window["Low"].min()), 4), "close": round(float(window["Close"].iloc[-1]), 4), "volume": int(window["Volume"].sum()), }, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124from __future__ import annotations
import refrom dataclasses import dataclass, fieldfrom typing import Any
@dataclassclass Chunk: text: str metadata: dict[str, Any] = field(default_factory=dict)
class SlidingWindowChunker: """ Overlapping token-window chunker for news articles and analyst reports. window=512 tokens, stride=128 tokens. """
def __init__(self, window: int = 512, stride: int = 128) -> None: self.window = window self.stride = stride
def _tokenize(self, text: str) -> list[str]: return text.split()
def chunk(self, text: str, metadata: dict[str, Any] | None = None) -> list[Chunk]: meta = metadata or {} tokens = self._tokenize(text) chunks: list[Chunk] = []
start = 0 while start < len(tokens): end = min(start + self.window, len(tokens)) chunk_text = " ".join(tokens[start:end]) if len(chunk_text.strip()) > 50: chunks.append(Chunk( text=chunk_text, metadata={**meta, "chunk_start_token": start, "chunk_end_token": end}, )) if end == len(tokens): break start += self.stride
return chunks
class SemanticChunker: """ Boundary-detection chunker for SEC filings and earnings transcripts. Splits on cosine similarity drops between adjacent sentence embeddings. chunk size: 300-800 tokens (variable, topic-coherent). """
def __init__(self, threshold: float = 0.75, min_tokens: int = 300, max_tokens: int = 800) -> None: self.threshold = threshold self.min_tokens = min_tokens self.max_tokens = max_tokens
def _split_sentences(self, text: str) -> list[str]: sentences = re.split(r'(?<=[.!?])\s+', text.strip()) return [s.strip() for s in sentences if len(s.strip()) > 20]
def chunk(self, text: str, metadata: dict[str, Any] | None = None) -> list[Chunk]: from backend.rag.embedder import get_embedder import numpy as np
meta = metadata or {} sentences = self._split_sentences(text) if not sentences: return []
if len(sentences) <= 3: return [Chunk(text=text, metadata=meta)]
embedder = get_embedder() embeddings = embedder.encode(sentences, normalize_embeddings=True, batch_size=32)
# Detect boundary: cosine similarity drop between adjacent sentences boundaries = [0] current_tokens = len(sentences[0].split())
for i in range(1, len(sentences)): sim = float(np.dot(embeddings[i - 1], embeddings[i])) current_tokens += len(sentences[i].split())
is_boundary = ( (sim < self.threshold and current_tokens >= self.min_tokens) or current_tokens >= self.max_tokens ) if is_boundary: boundaries.append(i) current_tokens = 0
boundaries.append(len(sentences))
chunks: list[Chunk] = [] for j in range(len(boundaries) - 1): chunk_sentences = sentences[boundaries[j]:boundaries[j + 1]] chunk_text = " ".join(chunk_sentences) if len(chunk_text.strip()) > 100: chunks.append(Chunk( text=chunk_text, metadata={**meta, "chunk_index": j}, ))
return chunks
class FixedTokenChunker: """Simple fixed-size chunker, no overlap. Fallback for structured data."""
def __init__(self, size: int = 512) -> None: self.size = size
def chunk(self, text: str, metadata: dict[str, Any] | None = None) -> list[Chunk]: meta = metadata or {} tokens = text.split() chunks: list[Chunk] = [] for i in range(0, len(tokens), self.size): chunk_text = " ".join(tokens[i:i + self.size]) if chunk_text.strip(): chunks.append(Chunk(text=chunk_text, metadata={**meta, "chunk_index": i // self.size})) return chunks12345678910111213141516171819202122import osfrom functools import lru_cache
import numpy as np
@lru_cache(maxsize=1)def get_embedder(): from sentence_transformers import SentenceTransformer model = os.getenv("EMBEDDING_MODEL", "sentence-transformers/all-MiniLM-L6-v2") return SentenceTransformer(model)
def embed(text: str) -> list[float]: return get_embedder().encode(text, normalize_embeddings=True).tolist()
def embed_batch(texts: list[str]) -> list[list[float]]: return get_embedder().encode(texts, normalize_embeddings=True, batch_size=32).tolist()
VECTOR_SIZE = 384123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147"""RAGAS evaluation runner for Finora RAG pipeline.
Uses Groq llama-3.1-8b-instant (GROQ_MODEL_FAST) as the evaluation LLMand all-MiniLM-L6-v2 (local HF) for embeddings — zero OpenAI dependency.
Targets: Faithfulness > 0.85 Answer Relevance > 0.80 Context Recall > 0.75 Context Precision > 0.70
Usage: from backend.rag.evaluation.ragas_eval import run_ragas_eval results = run_ragas_eval(qa_pairs, tickers=["AAPL", "MSFT"])"""from __future__ import annotations
import osimport warningsfrom typing import Any
import structlog
log = structlog.get_logger()
TARGETS = { "faithfulness": 0.85, "answer_relevancy": 0.80, "context_recall": 0.75, "context_precision": 0.70,}
def _build_llm(): """Groq llama-3.1-8b-instant wrapped for RAGAS.
Groq rejects n > 1. RAGAS passes n=3 via LangchainLLMWrapper.generate(n=3). Subclass the wrapper itself to hard-cap n=1 at the exact call site. """ from langchain_groq import ChatGroq from ragas.llms import LangchainLLMWrapper
groq = ChatGroq( model=os.getenv("GROQ_MODEL_FAST", "llama-3.1-8b-instant"), api_key=os.getenv("GROQ_API_KEY"), temperature=0.0, max_tokens=512, n=1, )
return LangchainLLMWrapper(groq, bypass_n=True)
def _build_embeddings(): """Local all-MiniLM-L6-v2 wrapped for RAGAS — no API key needed.""" from langchain_community.embeddings import HuggingFaceEmbeddings from ragas.embeddings import LangchainEmbeddingsWrapper
return LangchainEmbeddingsWrapper(HuggingFaceEmbeddings( model_name=os.getenv("EMBEDDING_MODEL", "sentence-transformers/all-MiniLM-L6-v2"), cache_folder=os.getenv("HF_CACHE_DIR", "data/hf_cache"), ))
def run_ragas_eval( qa_pairs: list[dict], tickers: list[str] | None = None,) -> dict[str, Any]: """ Run RAGAS evaluation over QA pairs.
qa_pairs schema: [{"question": str, "answer": str, "contexts": list[str], "ground_truth": str}]
Returns metrics dict with scores + pass/fail per metric. """ try: from datasets import Dataset from ragas import evaluate from ragas.metrics import ( answer_relevancy, context_precision, context_recall, faithfulness, ) except ImportError as exc: log.error("ragas_import_failed", error=str(exc)) return {"error": "ragas / datasets not installed"}
if not qa_pairs: return {"error": "no QA pairs provided"}
try: llm = _build_llm() embeddings = _build_embeddings() except Exception as exc: log.error("ragas_llm_build_failed", error=str(exc)) return {"error": f"LLM/embeddings init failed: {exc}"}
dataset = Dataset.from_list(qa_pairs)
# Cap answer_relevancy to n=1 — Groq free tier can't handle n=3 sequential calls answer_relevancy.n = 1 # type: ignore[attr-defined]
metrics = [faithfulness, answer_relevancy, context_recall, context_precision]
log.info("ragas_eval_start", pairs=len(qa_pairs), tickers=tickers)
try: with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) result = evaluate( dataset, metrics=metrics, llm=llm, embeddings=embeddings, raise_exceptions=False, show_progress=True, ) # EvaluationResult is DataFrame-like — extract per-row scores then average result_df = result.to_pandas() metric_cols = [c for c in result_df.columns if c in TARGETS] scores: dict[str, float] = result_df[metric_cols].mean().dropna().to_dict() except Exception as exc: log.error("ragas_eval_failed", error=str(exc)) return {"error": str(exc)}
report: dict[str, Any] = {"scores": scores, "results": {}} for metric, target in TARGETS.items(): score = scores.get(metric) if score is None: continue report["results"][metric] = { "score": round(score, 4), "target": target, "passed": score >= target, "delta": round(score - target, 4), }
all_pass = all(r["passed"] for r in report["results"].values()) report["overall_pass"] = all_pass report["tickers"] = tickers or [] report["n_pairs"] = len(qa_pairs)
log.info("ragas_eval_complete", pass_all=all_pass, scores=scores) return report.dockerignoreAdded+26
.env.exampleAdded+81
.gitignoreAdded+22
DockerfileAdded+25
README.mdAdded+17
backend/__init__.pyAdded
backend/api/__init__.pyAdded
backend/api/middleware/__init__.pyAdded
backend/api/middleware/guardrails.pyAdded+38
backend/api/middleware/rate_limit.pyAdded+12
backend/api/routes/__init__.pyAdded
backend/api/routes/chat.pyAdded+330
backend/api/routes/health.pyAdded+116
backend/api/routes/stocks.pyAdded+382
backend/finora_mcp/__init__.pyAdded
backend/finora_mcp/server.pyAdded+43
backend/finora_mcp/tools/__init__.pyAdded
backend/finora_mcp/tools/fundamentals.pyAdded+9
backend/finora_mcp/tools/historical.pyAdded+26
backend/finora_mcp/tools/news.pyAdded+27
backend/finora_mcp/tools/quote.pyAdded+9
backend/finora_mcp/tools/screener.pyAdded+63
backend/graph/__init__.pyAdded
backend/graph/finora_graph.pyAdded+96
backend/graph/nodes/__init__.pyAdded
backend/graph/nodes/fundamentals_node.pyAdded+131
backend/graph/nodes/fusion_node.pyAdded+595
backend/graph/nodes/historical_rag_node.pyAdded+41
backend/graph/nodes/intent_classifier.pyAdded+102
backend/graph/nodes/news_rag_node.pyAdded+72
backend/graph/nodes/realtime_node.pyAdded+118
backend/graph/nodes/response_cache.pyAdded+45
backend/graph/nodes/response_node.pyAdded+193
backend/graph/state.pyAdded+43
backend/guardrails/__init__.pyAdded
backend/guardrails/classifier.pyAdded+108
backend/guardrails/disclaimers.pyAdded+20
backend/guardrails/output_filter.pyAdded+86
backend/main.pyAdded+93
backend/observability/__init__.pyAdded
backend/observability/langsmith_client.pyAdded+66
backend/observability/langsmith_url.pyAdded+64
backend/observability/metrics.pyAdded+23
backend/rag/__init__.pyAdded
backend/rag/chunking/__init__.pyAdded
backend/rag/chunking/financial.pyAdded+125
backend/rag/chunking/strategies.pyAdded+124
backend/rag/embedder.pyAdded+22
backend/rag/evaluation/__init__.pyAdded
backend/rag/evaluation/ragas_eval.pyAdded+147