Spaces:
Sleeping

File size: 2,018 Bytes
45994d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1a0142
45994d6
 
 
 
e1a0142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45994d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"""Financials RAG node — structured financial statement context from Qdrant."""

from __future__ import annotations

import asyncio

import structlog

from backend.graph.state import FiNoraState
from backend.rag.pipeline import run_rag_branch
from backend.rag.retrieval.router import RetrievalBranch

log = structlog.get_logger()

_BRANCH = RetrievalBranch(
    intent="financials",  # type: ignore[arg-type]
    collection="financials",
    use_hyde=False,  # structured numeric data — HyDE adds noise
    description="Financial statements — income, balance sheet, cashflow for US + Indian stocks",
    allow_global_fallback=False,
)

_TOP_K = 4


async def financials_rag_node(state: FiNoraState) -> dict:
    """
    Retrieve pre-ingested financial statement chunks from Qdrant finora_financials.
    Works for ALL stocks (US + Indian) — no ticker skip needed.
    Silently returns empty if the collection doesn't exist yet (not ingested).
    """
    query = state["query"]
    ticker = state.get("ticker", "")

    _empty = {
        "financials_chunks": [],
        "retrieval_scores": {**state.get("retrieval_scores", {}), "financials": {}},
    }

    try:
        loop = asyncio.get_running_loop()
        result = await loop.run_in_executor(
            None,
            run_rag_branch,
            query,
            ticker,
            _BRANCH,
        )
    except Exception as exc:
        log.warning("financials_rag_failed", ticker=ticker, error=str(exc))
        return _empty

    chunks = [
        {
            "text": ch.text,
            "score": ch.score,
            **ch.metadata,
        }
        for ch in result.chunks[:_TOP_K]
    ]

    scores = result.retrieval_scores

    log.info(
        "financials_rag_done",
        ticker=ticker,
        chunks=len(chunks),
        scores=scores,
    )

    return {
        "financials_chunks": chunks,
        "retrieval_scores": {
            **state.get("retrieval_scores", {}),
            "financials": scores,
        },
    }