File size: 14,175 Bytes
ebd834c
 
 
c65382c
ebd834c
a55ad28
ebd834c
 
c99694c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebd834c
 
c65382c
 
 
 
 
 
 
 
 
 
 
 
 
a55ad28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2228f6
 
a55ad28
c65382c
35b8855
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a596a8
35b8855
 
 
 
 
 
 
 
ebd834c
 
a55ad28
 
ebd834c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9815e49
 
ebd834c
 
 
 
 
 
 
 
 
 
9815e49
ebd834c
c65382c
 
ebd834c
 
 
 
 
 
 
 
 
 
c65382c
 
 
 
 
 
 
 
 
 
 
8f35c1b
 
 
 
c65382c
8f35c1b
 
 
c65382c
ebd834c
 
 
 
 
 
fbd18c8
ebd834c
 
 
 
 
 
 
9815e49
ebd834c
c65382c
 
ebd834c
 
 
 
c99694c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a596a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c99694c
a55ad28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebd834c
a55ad28
ebd834c
 
 
 
 
 
 
 
 
 
 
 
1330e5c
ebd834c
1330e5c
 
 
 
 
 
 
 
ebd834c
 
 
 
 
 
9815e49
ebd834c
c65382c
 
ebd834c
 
 
 
 
 
 
 
9815e49
ebd834c
 
 
 
c65382c
 
ebd834c
 
 
9815e49
9093d8f
 
 
9815e49
9093d8f
 
 
c65382c
a8fd301
 
c65382c
 
9093d8f
106354e
9093d8f
 
ebd834c
 
9815e49
 
ebd834c
c65382c
 
ebd834c
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
"""Query understanding layer: reformulates user queries for better retrieval."""

import json
import os
import re
from typing import Dict

from src.llm import generate
from src.prompts import (build_query_understanding_prompt, 
                         build_categorizer_prompt, build_init_prompt, build_vc_analyzer_prompt)

def analyze_committment_to_vc(value_chain:str,
                              cfg:Dict,):
    domain = cfg.get("chatbot", {}).get("domain", "research")
    
    prompt = build_vc_analyzer_prompt(value_chain, domain)

    try:
        raw = generate(
            "",
            prompt,
            cfg,
            max_tokens=512,
        )
        return _parse_vc_analyzer_result(raw)
    except Exception:
        # LLM failure: fall back to raw query
        return {
            "value_chain": None,

            "financial_commitment": {
                "budget_start_year": "",
                "budget_start_value": "",
                "budget_end_year": "",
                "budget_end_value": "",
                "currency": "",
                "responsible_institution": "",
                "evidence": [
                {
                    "quote": "",
                    "source_document": "",
                    "page_or_section": ""
                }
                ]
            },

            "strategic_commitment": {
                "documents_examined": 0,
                "documents_discussing_value_chain": 0,
                "coverage_weight": 0,

                "development_plan": {
                "value": "NOT_FOUND",
                "evidence": []
                },

                "agricultural_strategy": {
                "value": "NOT_FOUND",
                "evidence": []
                },

                "standalone_vc_strategy": {
                "value": "NOT_FOUND",
                "evidence": []
                },

                "flagship_project": {
                "value": "NOT_FOUND",
                "evidence": []
                }
            },

            "institutional_commitment": {
                "dedicated_agency": {
                "value": "NOT_FOUND",
                "evidence": []
                },

                "dedicated_research_institute": {
                "value": "NOT_FOUND",
                "evidence": []
                },

                "dedicated_ministerial_department": {
                "value": "NOT_FOUND",
                "evidence": []
                }
            }
        }


def _load_sql_schema_summary(sql_db_dir: str) -> str:
    """Load SQL schema summary from sql_schemas.json if it exists."""
    schema_path = os.path.join(sql_db_dir, "sql_schemas.json")
    if not os.path.exists(schema_path):
        return ""
    try:
        with open(schema_path, "r", encoding="utf-8") as f:
            schema = json.load(f)
        from src.sql_retriever import build_schema_summary
        return build_schema_summary(schema)
    except Exception:
        return ""

def categorize_query(user_query:str, 
                     cfg:Dict,
                    conversation_history: list[dict] | None = None,):
    domain = cfg.get("chatbot", {}).get("domain", "research")
    cat_cfg = cfg.get("query_categorization", {})
    max_history = cat_cfg.get("max_history", 6)

    # Trim conversation history
    history = conversation_history or []
    if len(history) > max_history:
        history = history[-max_history:]

    prompt = build_categorizer_prompt(user_query, domain)

    try:
        raw = generate(
            "You are a query-routing classifier. Return only JSON.",
            prompt,
            cfg,
            max_tokens=512,
        )
        return _parse_qcat_result(raw)
    except Exception:
        # LLM failure: fall back to raw query
        return {
            "category": "complete",
            "sub-action": "unresolved",
        }

def init_query(user_query:str, 
                     cfg:Dict,
                    conversation_history: list[dict] | None = None,):
    domain = cfg.get("chatbot", {}).get("domain", "research")
    cat_cfg = cfg.get("query_categorization", {})
    max_history = cat_cfg.get("max_history", 6)

    # Trim conversation history
    history = conversation_history or []
    if len(history) > max_history:
        history = history[-max_history:]

    prompt = build_init_prompt(user_query, domain)

    try:
        raw = generate(
            "You are a query-routing classifier. Return only JSON.",
            prompt,
            cfg,
            max_tokens=512,
        )
        return _parse_qinit_result(raw)
    except Exception:
        # LLM failure: fall back to raw query
        return {
            "country": None,
            "value_chain": None,
            "investment": None,
        }

def understand_query(
    user_query: str,
    cfg: Dict,
    conversation_history: list[Dict] | None = None,
) -> dict:
    """Analyze and reformulate a user query for better retrieval.

    Uses the LLM to either:
    - SEARCH: Rewrite the query into a search-optimized form
    - CLARIFY: Ask the user a clarification question

    Args:
        user_query: Raw user input.
        cfg: App config (provides domain, LLM settings).
        conversation_history: Recent messages for pronoun/reference resolution.

    Returns:
        Dict with keys:
        - ``action``: ``"search"`` or ``"clarify"``
        - ``search_query``: Keyword-optimized query for retrieval (always present)
        - ``display_query``: Clear natural-language question for response generation
        - ``original_query``: The raw user input
        - ``clarification_question``: Question to ask (only if action is "clarify")
    """
    qu_cfg = cfg.get("query_understanding", {})

    # Disabled: pass through raw query
    if not qu_cfg.get("enabled", True):
        return {
            "action": "search",
            "search_query": user_query,
            "display_query": user_query,
            "original_query": user_query,
            "route": "vector",
            "sql_query": None,
        }

    domain = cfg.get("chatbot", {}).get("domain", "research")
    max_history = qu_cfg.get("max_history", 6)

    # Trim conversation history
    history = conversation_history or []
    if len(history) > max_history:
        history = history[-max_history:]

    # Load SQL schema summary for prompt injection
    sql_enabled = cfg.get("sql", {}).get("enabled", True)
    schema_summary = ""
    if sql_enabled:
        sql_db_dir = cfg.get("paths", {}).get("sql_db", "sql_db")
        if not os.path.isabs(sql_db_dir):
            from pathlib import Path as _Path
            project_root = _Path(__file__).resolve().parent.parent
            sql_db_dir = os.path.join(str(project_root), sql_db_dir)
        schema_summary = _load_sql_schema_summary(sql_db_dir)

    # Load KB meta overview for routing awareness
    from src.kb_meta import load_kb_meta
    kb_overview = load_kb_meta(cfg)

    prompt = build_query_understanding_prompt(
        user_query, domain, history,
        sql_schema_summary=schema_summary,
        kb_overview=kb_overview,
    )

    try:
        raw = generate(
            "You are a query reformulation assistant. Return only JSON.",
            prompt,
            cfg,
            max_tokens=512,
        )
        result = _parse_qu_result(raw, user_query)
    except Exception:
        # LLM failure: fall back to raw query
        result = {
            "action": "search",
            "search_query": user_query,
            "display_query": user_query,
            "original_query": user_query,
            "route": "vector",
            "sql_query": None,
        }

    return result

def _parse_vc_analyzer_result(raw:str) -> Dict:
    parsed = None

    # Try direct parse
    try:
        parsed = json.loads(raw)
    except (json.JSONDecodeError, TypeError):
        pass

    # Fallback: scan for the first valid JSON object using raw_decode
    if parsed is None:
        decoder = json.JSONDecoder()
        for i, ch in enumerate(raw):
            if ch == '{':
                try:
                    parsed, _ = decoder.raw_decode(raw, i)
                    break
                except json.JSONDecodeError:
                    continue

    # Unparseable: fall back to raw query
    if not isinstance(parsed, dict):
        return {
            "value_chain": None,

            "financial_commitment": {
                "budget_start_year": "",
                "budget_start_value": "",
                "budget_end_year": "",
                "budget_end_value": "",
                "currency": "",
                "responsible_institution": "",
                "evidence": [
                {
                    "quote": "",
                    "source_document": "",
                    "page_or_section": ""
                }
                ]
            },

            "strategic_commitment": {
                "documents_examined": 0,
                "documents_discussing_value_chain": 0,
                "coverage_weight": 0,

                "development_plan": {
                "value": "NOT_FOUND",
                "evidence": []
                },

                "agricultural_strategy": {
                "value": "NOT_FOUND",
                "evidence": []
                },

                "standalone_vc_strategy": {
                "value": "NOT_FOUND",
                "evidence": []
                },

                "flagship_project": {
                "value": "NOT_FOUND",
                "evidence": []
                }
            },

            "institutional_commitment": {
                "dedicated_agency": {
                "value": "NOT_FOUND",
                "evidence": []
                },

                "dedicated_research_institute": {
                "value": "NOT_FOUND",
                "evidence": []
                },

                "dedicated_ministerial_department": {
                "value": "NOT_FOUND",
                "evidence": []
                }
            }
        }

    return parsed

def _parse_qinit_result(raw:str) -> Dict:
    parsed = None

    # Try direct parse
    try:
        parsed = json.loads(raw)
    except (json.JSONDecodeError, TypeError):
        pass

    # Fallback: scan for the first valid JSON object using raw_decode
    if parsed is None:
        decoder = json.JSONDecoder()
        for i, ch in enumerate(raw):
            if ch == '{':
                try:
                    parsed, _ = decoder.raw_decode(raw, i)
                    break
                except json.JSONDecodeError:
                    continue

    # Unparseable: fall back to raw query
    if not isinstance(parsed, dict) or "country" not in parsed:
        return {
            "country": None,
            "value_chain": None,
            "investment": None,
        }

    return parsed

def _parse_qcat_result(raw:str) -> Dict:
    parsed = None

    # Try direct parse
    try:
        parsed = json.loads(raw)
    except (json.JSONDecodeError, TypeError):
        pass

    # Fallback: scan for the first valid JSON object using raw_decode
    if parsed is None:
        decoder = json.JSONDecoder()
        for i, ch in enumerate(raw):
            if ch == '{':
                try:
                    parsed, _ = decoder.raw_decode(raw, i)
                    break
                except json.JSONDecodeError:
                    continue

    # Unparseable: fall back to raw query
    if not isinstance(parsed, dict) or "category" not in parsed:
        return {
            "category": "general",
            "action": "continue",
        }

    return parsed


def _parse_qu_result(raw: str, original_query: str) -> Dict:
    """Parse the LLM's JSON response into a structured result.

    Falls back to raw query passthrough if parsing fails.
    """
    parsed = None

    # Try direct parse
    try:
        parsed = json.loads(raw)
    except (json.JSONDecodeError, TypeError):
        pass

    # Fallback: scan for the first valid JSON object using raw_decode
    if parsed is None:
        decoder = json.JSONDecoder()
        for i, ch in enumerate(raw):
            if ch == '{':
                try:
                    parsed, _ = decoder.raw_decode(raw, i)
                    break
                except json.JSONDecodeError:
                    continue

    # Unparseable: fall back to raw query
    if not isinstance(parsed, dict) or "action" not in parsed:
        return {
            "action": "search",
            "search_query": original_query,
            "display_query": original_query,
            "original_query": original_query,
            "route": "vector",
            "sql_query": None,
        }

    action = parsed.get("action", "search")

    if action == "clarify":
        return {
            "action": "clarify",
            "search_query": original_query,  # fallback if clarification is skipped
            "display_query": original_query,  # fallback if clarification is skipped
            "original_query": original_query,
            "clarification_question": parsed.get(
                "clarification_question", "Could you be more specific?"
            ),
            "route": "vector",
            "sql_query": None,
        }

    # action == "search"
    search_query = parsed.get("search_query", original_query)
    if not isinstance(search_query, str):
        search_query = original_query

    display_query = parsed.get("display_query", original_query)
    if not isinstance(display_query, str):
        display_query = original_query

    route = parsed.get("route", "vector")
    if isinstance(route, str):
        route = route.strip().lower()
    if route not in ("sql", "vector", "both"):
        route = "vector"

    sql_query = parsed.get("sql_query") or None
    if sql_query is not None and not isinstance(sql_query, str):
        sql_query = None
    return {
        "action": "search",
        "search_query": search_query,
        "display_query": display_query,
        "original_query": original_query,
        "route": route,
        "sql_query": sql_query,
    }