File size: 3,789 Bytes
a4ab72e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import json
import networkx as nx
import os
from groq import Groq
from dotenv import load_dotenv

load_dotenv()

client = Groq(api_key=os.getenv("GROQ_API_KEY"))


def build_graph() -> nx.Graph:
    chunks = json.load(
        open(
            "data/chunks.json",
            encoding="utf-8"
        )
    )

    entities = json.load(
        open(
            "data/entities.json",
            encoding="utf-8"
        )
    )

    G = nx.Graph()

    for c in chunks:
        G.add_node(
            c["chunk_id"],
            type="chunk",
            text=c["text"],
            company=c["company"],
            doc=c["doc_name"]
        )

        G.add_node(
            c["company"],
            type="company"
        )

        G.add_node(
            c["doc_name"],
            type="filing"
        )

        G.add_edge(
            c["company"],
            c["doc_name"],
            rel="FILED"
        )

        G.add_edge(
            c["doc_name"],
            c["chunk_id"],
            rel="CONTAINS"
        )

    for e in entities:
        for ent in e["entities"]:
            ent_id = (
                f"{ent['label']}_"
                f"{ent['text'][:50]}"
            )

            G.add_node(
                ent_id,
                type="entity",
                label=ent["label"],
                text=ent["text"]
            )

            G.add_edge(
                e["chunk_id"],
                ent_id,
                rel="MENTIONS"
            )

    return G


def query_graphrag(
    question: str,
    G: nx.Graph
) -> dict:

    stopwords = {
        "what", "was", "the", "in",
        "of", "a", "an", "is",
        "are", "how", "did",
        "does", "we", "if",
        "that", "you", "as",
        "based", "on", "which",
        "has", "for", "by", "per"
    }

    keywords = [
        w.lower().strip("?.,")
        for w in question.split()
        if (
            w.lower() not in stopwords
            and len(w) > 2
        )
    ]

    chunk_scores = {}

    for node, data in G.nodes(data=True):

        if data.get("type") != "chunk":
            continue

        text = (
            data.get("text", "")
            + " "
            + data.get("company", "")
        ).lower()

        score = sum(
            1
            for kw in keywords
            if kw in text
        )

        if score > 0:
            chunk_scores[node] = score

    top_chunks = sorted(
        chunk_scores,
        key=chunk_scores.get,
        reverse=True
    )[:1]

    if not top_chunks:
        top_chunks = [
            n
            for n, d in G.nodes(data=True)
            if d.get("type") == "chunk"
        ][:1]

    context = "\n\n".join([
        G.nodes[n].get(
            "text",
            ""
        )
        for n in top_chunks
    ])

    prompt = (
        f"Context:\n{context}\n\n"
        f"Question: {question}\n"
        f"Answer:"
    )

    input_tokens = len(
        prompt.split()
    )

    response = client.chat.completions.create(
        model="llama-3.1-8b-instant",
        messages=[{
            "role": "user",
            "content": prompt
        }],
        max_tokens=200
    )

    answer = (
        response
        .choices[0]
        .message.content
    )

    total_tokens = (
        response
        .usage
        .total_tokens
    )

    return {
        "answer": answer,
        "input_tokens": input_tokens,
        "total_tokens": total_tokens,
        "context_chunks": len(top_chunks)
    }


if __name__ == "__main__":
    G = build_graph()

    print(
        f"Graph: "
        f"{G.number_of_nodes()} nodes, "
        f"{G.number_of_edges()} edges"
    )

    result = query_graphrag(
        "What was Apple's revenue in 2022?",
        G
    )

    print(result)