Spaces:
Sleeping

File size: 8,995 Bytes
45e7ae0
 
 
17d3a25
45e7ae0
 
17d3a25
45e7ae0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17d3a25
45e7ae0
 
17d3a25
 
45e7ae0
 
 
 
 
 
 
 
 
 
 
 
 
17d3a25
45e7ae0
 
17d3a25
 
 
 
 
 
 
 
 
 
 
 
 
 
45e7ae0
 
 
 
 
 
 
 
 
 
 
17d3a25
45e7ae0
 
17d3a25
 
45e7ae0
 
 
 
 
 
 
 
 
 
 
 
17d3a25
45e7ae0
 
 
 
 
17d3a25
73f057f
45e7ae0
 
 
 
 
 
 
 
 
 
 
 
17d3a25
73f057f
 
17d3a25
 
 
 
 
 
 
 
73f057f
17d3a25
73f057f
17d3a25
 
45e7ae0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17d3a25
 
 
45e7ae0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17d3a25
 
45e7ae0
17d3a25
45e7ae0
 
 
 
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import os
import json
import httpx
import time
from dotenv import load_dotenv
from app.services.vector_service import get_document_chunks, search_chunks
from app.utils.logging import log_llm_usage

load_dotenv()

GROQ_API_KEY = os.getenv("GROQ_API_KEY")

if not GROQ_API_KEY:
    raise ValueError("GROQ_API_KEY is missing in .env file")


BROAD_QUERY_HINTS = (
    "what is this pdf about",
    "what is this document about",
    "summarize this document",
    "summary of this document",
    "give me an overview",
    "document overview",
    "what does this pdf say",
    "what is in this pdf",
    "is this a resume",
    "is this resume",
    "what kind of document is this",
    "what are the projects",
    "list the projects",
    "what projects are mentioned",
)


def is_broad_overview_query(query: str) -> bool:
    lowered_query = query.strip().lower()
    return any(hint in lowered_query for hint in BROAD_QUERY_HINTS)


def merge_context_docs(primary_docs, additional_docs):
    merged_docs = []
    seen_keys = set()

    for doc in [*primary_docs, *additional_docs]:
        metadata = doc.get("metadata", {})
        key = (
            metadata.get("document_id"),
            metadata.get("chunk_index"),
            doc.get("page_content", ""),
        )

        if key in seen_keys:
            continue

        seen_keys.add(key)
        merged_docs.append(doc)

    return merged_docs


def retrieve_context(query: str, user_id: str, document_id: str):
    semantic_docs = search_chunks(
        query=query,
        k=10,
        user_id=user_id,
        document_id=document_id,
    )

    if is_broad_overview_query(query):
        leading_docs = get_document_chunks(
            user_id=user_id,
            document_id=document_id,
            limit=10,
        )
        return merge_context_docs(leading_docs, semantic_docs)

    return semantic_docs


def build_prompt(query: str, docs):
    context_blocks = []

    for doc in docs:
        metadata = doc.get("metadata", {})
        chunk_number = metadata.get("chunk_index")
        chunk_label = (
            f"Chunk {int(chunk_number) + 1}"
            if isinstance(chunk_number, int)
            else "Chunk"
        )
        context_blocks.append(f"[{chunk_label}]\n{doc['page_content']}")

    context = "\n\n".join(context_blocks)

    system_message = f"""You are DocBrain, a document-grounded assistant.

Rules:
- Answer using ONLY the document excerpts below.
- For broad questions, synthesize the overall document purpose from multiple excerpts.
- If the document appears to be a resume, CV, report, proposal, or similar, say that clearly.
- Do not invent facts, names, titles, dates, or project details.
- If the answer is not supported by the excerpts, say "I don't know based on the provided document excerpts."
- Keep the answer concise, factual, and directly relevant to the question.

Document excerpts:
{context}"""

    return query, system_message


def build_messages(query: str, system_message: str, chat_history: list):
    messages = [
        {
            "role": "system",
            "content": system_message,
        }
    ]
    for msg in chat_history:
        # Groq expects strictly 'user' or 'assistant'
        messages.append({
            "role": msg["role"],
            "content": msg["content"]
        })
    messages.append({
        "role": "user",
        "content": query,
    })
    return messages


def call_groq(query: str, system_message: str, chat_history: list, user_id: int = None) -> str:
    try:
        messages = build_messages(query, system_message, chat_history)
        
        start_time = time.time()
        response = httpx.post(
            "https://api.groq.com/openai/v1/chat/completions",
            headers={
                "Authorization": f"Bearer {GROQ_API_KEY}",
                "Content-Type": "application/json",
            },
            json={
                "model": "llama-3.3-70b-versatile",
                "messages": messages,
                "temperature": 0.1,
            },
            timeout=30,
        )
        response_time = time.time() - start_time

        response.raise_for_status()
        res_json = response.json()
        
        # Log usage if user_id is provided
        if user_id and "usage" in res_json:
            usage = res_json["usage"]
            log_llm_usage(
                user_id=user_id,
                model="llama-3.3-70b-versatile",
                prompt_tokens=usage.get("prompt_tokens", 0),
                completion_tokens=usage.get("completion_tokens", 0),
                response_time=response_time
            )

        return res_json["choices"][0]["message"]["content"]

    except httpx.TimeoutException:
        raise Exception("Groq API timeout. Please try again.")

    except httpx.HTTPStatusError as e:
        raise Exception(f"Groq API error: {e.response.text}")

    except httpx.HTTPError as e:
        raise Exception(f"Groq request failed: {str(e)}")


def stream_groq(query: str, system_message: str, chat_history: list, user_id: int = None):
    try:
        messages = build_messages(query, system_message, chat_history)
        start_time = time.time()
        
        with httpx.stream(
            "POST",
            "https://api.groq.com/openai/v1/chat/completions",
            headers={
                "Authorization": f"Bearer {GROQ_API_KEY}",
                "Content-Type": "application/json",
            },
            json={
                "model": "llama-3.3-70b-versatile",
                "messages": messages,
                "temperature": 0.1,
                "stream": True,
                "stream_options": {"include_usage": True}
            },
            timeout=60,
        ) as response:

            response.raise_for_status()
            response_time = time.time() - start_time
            logged_usage = False

            for line in response.iter_lines():
                if not line:
                    continue

                if line.startswith("data: "):
                    data = line.replace("data: ", "")

                    if data == "[DONE]":
                        break

                    chunk = json.loads(data)
                    
                    # Log usage only ONCE per stream
                    if user_id and not logged_usage and "usage" in chunk and chunk["usage"]:
                        usage = chunk["usage"]
                        log_llm_usage(
                            user_id=user_id,
                            model="llama-3.3-70b-versatile",
                            prompt_tokens=usage.get("prompt_tokens", 0),
                            completion_tokens=usage.get("completion_tokens", 0),
                            response_time=response_time
                        )
                        logged_usage = True

                    if not chunk.get("choices"):
                        continue
                        
                    delta = chunk["choices"][0]["delta"].get("content")

                    if delta:
                        yield delta

    except httpx.TimeoutException:
        raise Exception("Groq API timeout. Please try again.")

    except httpx.HTTPStatusError as e:
        raise Exception(f"Groq API error: {e.response.text}")

    except httpx.HTTPError as e:
        raise Exception(f"Groq request failed: {str(e)}")


def ask_question(query: str, user_id: str, document_id: str, chat_history: list = None):
    if chat_history is None:
        chat_history = []

    docs = retrieve_context(
        query=query,
        user_id=user_id,
        document_id=document_id,
    )

    if not docs:
        return {
            "answer": "No relevant information found in this document.",
            "sources": [],
        }

    q, system_message = build_prompt(query, docs)
    # Convert user_id string to int for logging
    uid = int(user_id) if user_id and user_id.isdigit() else None
    answer = call_groq(q, system_message, chat_history, user_id=uid)

    return {
        "answer": answer,
        "sources": [doc["metadata"] for doc in docs],
    }


def stream_answer_events(query: str, user_id: str, document_id: str, chat_history: list = None):
    if chat_history is None:
        chat_history = []

    docs = retrieve_context(
        query=query,
        user_id=user_id,
        document_id=document_id,
    )

    yield {
        "type": "sources",
        "sources": [doc["metadata"] for doc in docs],
    }

    if not docs:
        yield {
            "type": "delta",
            "content": "No relevant information found in this document.",
        }
        return

    q, system_message = build_prompt(query, docs)
    # Convert user_id string to int for logging
    uid = int(user_id) if user_id and user_id.isdigit() else None

    for token in stream_groq(q, system_message, chat_history, user_id=uid):
        yield {
            "type": "delta",
            "content": token,
        }