Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
Create rag_utils.py
Browse files- appStore/rag_utils.py +126 -0
appStore/rag_utils.py
ADDED
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
import requests
|
3 |
+
import streamlit as st
|
4 |
+
|
5 |
+
def truncate_to_tokens(text, max_tokens):
|
6 |
+
"""
|
7 |
+
Truncate a text to an approximate token count by splitting on whitespace.
|
8 |
+
|
9 |
+
Args:
|
10 |
+
text (str): The text to truncate.
|
11 |
+
max_tokens (int): Maximum number of tokens/words to keep.
|
12 |
+
|
13 |
+
Returns:
|
14 |
+
str: The truncated text.
|
15 |
+
"""
|
16 |
+
tokens = text.split()
|
17 |
+
if len(tokens) > max_tokens:
|
18 |
+
return " ".join(tokens[:max_tokens])
|
19 |
+
return text
|
20 |
+
|
21 |
+
def build_context_for_result(res, compute_title_fn):
|
22 |
+
"""
|
23 |
+
Build a context string (title + objective + description) from a search result.
|
24 |
+
|
25 |
+
Args:
|
26 |
+
res (dict): A result dictionary with 'payload' key containing metadata.
|
27 |
+
compute_title_fn (callable): Function to compute the title from metadata.
|
28 |
+
|
29 |
+
Returns:
|
30 |
+
str: Combined text from title, objective, and description.
|
31 |
+
"""
|
32 |
+
metadata = res.payload.get('metadata', {})
|
33 |
+
title = metadata.get("title", compute_title_fn(metadata))
|
34 |
+
objective = metadata.get("objective", "")
|
35 |
+
desc_en = metadata.get("description.en", "").strip()
|
36 |
+
desc_de = metadata.get("description.de", "").strip()
|
37 |
+
description = desc_en if desc_en else desc_de
|
38 |
+
return f"{title}\n{objective}\n{description}"
|
39 |
+
|
40 |
+
def highlight_query(text, query):
|
41 |
+
"""
|
42 |
+
Highlight the query text in the given string with red/bold HTML styling.
|
43 |
+
|
44 |
+
Args:
|
45 |
+
text (str): The full text in which to highlight matches.
|
46 |
+
query (str): The substring (query) to highlight.
|
47 |
+
|
48 |
+
Returns:
|
49 |
+
str: The HTML-formatted string with highlighted matches.
|
50 |
+
"""
|
51 |
+
pattern = re.compile(re.escape(query), re.IGNORECASE)
|
52 |
+
return pattern.sub(lambda m: f"<span style='color:red; font-weight:bold;'>{m.group(0)}</span>", text)
|
53 |
+
|
54 |
+
def format_project_id(pid):
|
55 |
+
"""
|
56 |
+
Format a numeric project ID into the typical GIZ format (e.g. '201940485' -> '2019.4048.5').
|
57 |
+
|
58 |
+
Args:
|
59 |
+
pid (str|int): The project ID to format.
|
60 |
+
|
61 |
+
Returns:
|
62 |
+
str: Formatted project ID if it has enough digits, otherwise the original string.
|
63 |
+
"""
|
64 |
+
s = str(pid)
|
65 |
+
if len(s) > 5:
|
66 |
+
return s[:4] + "." + s[4:-1] + "." + s[-1]
|
67 |
+
return s
|
68 |
+
|
69 |
+
def compute_title(metadata):
|
70 |
+
"""
|
71 |
+
Compute a default title from metadata using name.en (or name.de if empty).
|
72 |
+
If an ID is present, append it in brackets.
|
73 |
+
|
74 |
+
Args:
|
75 |
+
metadata (dict): Project metadata dictionary.
|
76 |
+
|
77 |
+
Returns:
|
78 |
+
str: Computed title string or 'No Title'.
|
79 |
+
"""
|
80 |
+
name_en = metadata.get("name.en", "").strip()
|
81 |
+
name_de = metadata.get("name.de", "").strip()
|
82 |
+
base = name_en if name_en else name_de
|
83 |
+
pid = metadata.get("id", "")
|
84 |
+
if base and pid:
|
85 |
+
return f"{base} [{format_project_id(pid)}]"
|
86 |
+
return base or "No Title"
|
87 |
+
|
88 |
+
def get_rag_answer(query, top_results, endpoint, token):
|
89 |
+
"""
|
90 |
+
Send a prompt to the LLM endpoint, including the context from top results.
|
91 |
+
|
92 |
+
Args:
|
93 |
+
query (str): The user question.
|
94 |
+
top_results (list): List of top search results from which to build context.
|
95 |
+
endpoint (str): The HuggingFace Inference endpoint URL.
|
96 |
+
token (str): The Bearer token (from st.secrets, for instance).
|
97 |
+
|
98 |
+
Returns:
|
99 |
+
str: The LLM-generated answer, or an error message if the call fails.
|
100 |
+
"""
|
101 |
+
# Build the context
|
102 |
+
from appStore.rag_utils import truncate_to_tokens, build_context_for_result, compute_title
|
103 |
+
context = "\n\n".join([build_context_for_result(res, compute_title) for res in top_results])
|
104 |
+
context = truncate_to_tokens(context, 11500) # Truncate to ~11.5k tokens
|
105 |
+
|
106 |
+
# Construct the prompt
|
107 |
+
prompt = (
|
108 |
+
"You are a project portfolio adviser at the development cooperation GIZ. "
|
109 |
+
"Using the following context, answer the question in English precisely. "
|
110 |
+
"Ensure that any project title mentioned in your answer is wrapped in ** (markdown bold). "
|
111 |
+
"Only output the final answer below, without repeating the context or question.\n\n"
|
112 |
+
f"Context:\n{context}\n\n"
|
113 |
+
f"Question: {query}\n\n"
|
114 |
+
"Answer:"
|
115 |
+
)
|
116 |
+
headers = {"Authorization": f"Bearer {token}"}
|
117 |
+
payload = {"inputs": prompt, "parameters": {"max_new_tokens": 300}}
|
118 |
+
response = requests.post(endpoint, headers=headers, json=payload)
|
119 |
+
if response.status_code == 200:
|
120 |
+
result = response.json()
|
121 |
+
answer = result[0].get("generated_text", "")
|
122 |
+
if "Answer:" in answer:
|
123 |
+
answer = answer.split("Answer:")[-1].strip()
|
124 |
+
return answer
|
125 |
+
else:
|
126 |
+
return f"Error in generating answer: {response.text}"
|