Spaces:
Sleeping
Sleeping
File size: 47,110 Bytes
9502853 0354172 74e613f 6416439 da5e58a 9502853 ef3044e 0354172 9502853 2149a13 30234a7 dc6ea0c 4107bd4 9502853 f478447 9502853 0354172 9502853 0354172 9502853 0354172 9502853 a9c8456 0094e50 0354172 c87e1a9 0354172 9502853 74e613f 0354172 74e613f 0354172 9502853 0354172 9502853 4ed8a8b 74e613f 9502853 f478447 4e9f9bb f478447 9502853 4107bd4 9502853 4107bd4 4e9f9bb 4107bd4 d2155df 4107bd4 d2155df 4107bd4 d2155df 4107bd4 d2155df 4107bd4 d2155df 4107bd4 d2155df 4107bd4 d2155df 4107bd4 d2155df 47b8e16 a747844 bfd4bd9 d377f91 dc6ea0c d377f91 bfd4bd9 30234a7 63bcb8b d377f91 b2a1f87 dc6ea0c d377f91 1794809 dc6ea0c d377f91 60b3f78 d377f91 bfd4bd9 d377f91 bfd4bd9 d377f91 bfd4bd9 d377f91 bfd4bd9 d377f91 bfd4bd9 a747844 d377f91 1bba21a 47b8e16 9502853 1bba21a 2c95d47 dc6ea0c d377f91 dc6ea0c d377f91 b2a1f87 dc6ea0c d377f91 1a6953b d377f91 dc6ea0c d377f91 dc6ea0c d377f91 dc6ea0c 4879f09 9502853 d7880e6 0354172 9502853 3348c4b dc6ea0c 4f22430 dc6ea0c 2c95d47 dc6ea0c 4f22430 0354172 9502853 1cd5e38 0354172 eefaeba 1cd5e38 2149a13 9502853 d377f91 2c95d47 4f22430 2c95d47 d377f91 dc6ea0c 4f22430 a719329 4f22430 1cd5e38 4f22430 a719329 2c95d47 1bba21a 47b8e16 0fba843 47b8e16 0fba843 647a923 d377f91 1bba21a 647a923 1bba21a d8c6b86 dc6ea0c d8c6b86 dc6ea0c a719329 d377f91 71bf3a4 d377f91 2c95d47 4f22430 2c95d47 d377f91 d8c6b86 dc6ea0c d8c6b86 1bba21a 9502853 1bba21a 0354172 9502853 0354172 dc6ea0c a719329 dc6ea0c 0fba843 dc6ea0c 4f22430 dc6ea0c 9502853 4f22430 9502853 ffd0f02 9502853 4f22430 8775658 9502853 0354172 47b8e16 0fba843 1bba21a 0354172 9502853 4f22430 |
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 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 |
# app.py
import os
import re
import openai
from huggingface_hub import InferenceClient
import json
from huggingface_hub import HfApi
import streamlit as st
from typing import List, Dict, Any
from urllib.parse import quote_plus
from pymongo import MongoClient
from PyPDF2 import PdfReader
st.set_page_config(page_title="Grant Buddy RAG", page_icon="๐ค")
from typing import List
from langchain_community.embeddings import HuggingFaceInferenceAPIEmbeddings
from langchain.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import MongoDBAtlasVectorSearch
from langchain.prompts import PromptTemplate
from langchain.schema import Document
from langchain.schema.runnable import RunnableLambda, RunnablePassthrough
from huggingface_hub import InferenceClient
# =================== Secure Env via Hugging Face Secrets ===================
user = quote_plus(os.getenv("MONGO_USERNAME"))
password = quote_plus(os.getenv("MONGO_PASSWORD"))
cluster = os.getenv("MONGO_CLUSTER")
db_name = os.getenv("MONGO_DB_NAME", "files")
collection_name = os.getenv("MONGO_COLLECTION", "files_collection")
index_name = os.getenv("MONGO_VECTOR_INDEX", "vector_index")
HF_TOKEN = os.getenv("HF_TOKEN")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "").strip()
if OPENAI_API_KEY:
openai.api_key = OPENAI_API_KEY
from openai import OpenAI
client = OpenAI(api_key=OPENAI_API_KEY)
# MONGO_URI = f"mongodb+srv://{user}:{password}@{cluster}/{db_name}?retryWrites=true&w=majority"
MONGO_URI = f"mongodb+srv://{user}:{password}@{cluster}/{db_name}?retryWrites=true&w=majority&tls=true&tlsAllowInvalidCertificates=true"
# =================== Prompt ===================
grantbuddy_prompt = PromptTemplate.from_template(
"""You are Grant Buddy, a specialized language model fine-tuned with instruction-tuning and RLHF.
You help a nonprofit focused on social entrepreneurship, BIPOC empowerment, and edtech write clear, mission-aligned grant responses.
**Instructions:**
- Start with reasoning or context for your answer.
- Always align with the nonprofitโs mission.
- Use structured formatting: headings, bullet points, numbered lists.
- Include impact data or examples if relevant.
- Do NOT repeat the same sentence or answer multiple times.
- If no answer exists in the context, say: "This information is not available in the current context."
CONTEXT:
{context}
QUESTION:
{question}
"""
)
# =================== Vector Search Setup ===================
@st.cache_resource
def init_embedding_model():
return HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
@st.cache_resource
def init_vector_search() -> MongoDBAtlasVectorSearch:
HF_TOKEN = os.getenv("HF_TOKEN", "").strip()
model_name = "sentence-transformers/all-MiniLM-L6-v2"
st.write(f"๐ Connecting to Hugging Face model: `{model_name}`")
embedding_model = HuggingFaceEmbeddings(model_name=model_name)
# โ
Manual MongoClient with TLS settings
user = quote_plus(os.getenv("MONGO_USERNAME", "").strip())
password = quote_plus(os.getenv("MONGO_PASSWORD", "").strip())
cluster = os.getenv("MONGO_CLUSTER", "").strip()
db_name = os.getenv("MONGO_DB_NAME", "files").strip()
collection_name = os.getenv("MONGO_COLLECTION", "files_collection").strip()
index_name = os.getenv("MONGO_VECTOR_INDEX", "vector_index").strip()
mongo_uri = f"mongodb+srv://{user}:{password}@{cluster}/?retryWrites=true&w=majority"
try:
client = MongoClient(mongo_uri, tls=True, tlsAllowInvalidCertificates=True, serverSelectionTimeoutMS=20000)
db = client[db_name]
collection = db[collection_name]
st.success("โ
MongoClient connected successfully")
return MongoDBAtlasVectorSearch(
collection=collection,
embedding=embedding_model,
index_name=index_name,
)
except Exception as e:
st.error("โ Failed to connect to MongoDB Atlas manually")
st.error(str(e))
raise e
# =================== Question/Headers Extraction ===================
# def extract_questions_and_headers(text: str) -> List[str]:
# header_patterns = [
# r'\d+\.\s+\*\*([^\*]+)\*\*',
# r'\*\*([^*]+)\*\*',
# r'^([A-Z][^a-z]*[A-Z])$',
# r'^([A-Z][A-Za-z\s]{3,})$',
# r'^[A-Z][A-Za-z\s]+:$'
# ]
# question_patterns = [
# r'^.+\?$',
# r'^\*?Please .+',
# r'^How .+',
# r'^What .+',
# r'^Describe .+',
# ]
# combined_header_re = re.compile("|".join(header_patterns), re.MULTILINE)
# combined_question_re = re.compile("|".join(question_patterns), re.MULTILINE)
# headers = [match for group in combined_header_re.findall(text) for match in group if match]
# questions = combined_question_re.findall(text)
# return headers + questions
# def extract_with_llm(text: str) -> List[str]:
# client = InferenceClient(api_key=HF_TOKEN.strip())
# try:
# response = client.chat.completions.create(
# model="mistralai/Mistral-Nemo-Instruct-2407", # or "HuggingFaceH4/zephyr-7b-beta"
# messages=[
# {
# "role": "system",
# "content": "You are an assistant helping extract questions and headers from grant applications.",
# },
# {
# "role": "user",
# "content": (
# "Please extract all the grant application headers and questions from the following text. "
# "Include section titles, prompts, and any question-like content. Return them as a numbered list.\n\n"
# f"{text[:3000]}"
# ),
# },
# ],
# temperature=0.2,
# max_tokens=512,
# )
# return [
# line.strip("โข-1234567890. ").strip()
# for line in response.choices[0].message.content.strip().split("\n")
# if line.strip()
# ]
# except Exception as e:
# st.error("โ LLM extraction failed")
# st.error(str(e))
# return []
# def extract_with_llm_local(text: str) -> List[str]:
# prompt = (
# "You are an assistant helping extract useful questions and section headers from a grant application.\n"
# "Return only the important prompts as a numbered list.\n\n"
# "TEXT:\n"
# f"{text[:3000]}\n\n"
# "PROMPTS:"
# )
# inputs = tokenizer(prompt, return_tensors="pt", truncation=True)
# outputs = model.generate(
# **inputs,
# max_new_tokens=512,
# temperature=0.3,
# do_sample=False
# )
# raw_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
# # Extract prompts from the numbered list in the output
# lines = raw_output.split("\n")
# prompts = []
# for line in lines:
# line = line.strip("โข-1234567890. ").strip()
# if len(line) > 10:
# prompts.append(line)
# return prompts
# def extract_with_llm_local(text: str) -> List[str]:
# example_text = """TEXT:
# 1. Project Summary: Please describe the main goals of your project.
# 2. Contact Information: Address, phone, email.
# 3. What is the mission of your organization?
# 4. Who are the beneficiaries?
# 5. Budget Breakdown
# 6. Please describe how the funding will be used.
# 7. Website: www.example.org
# PROMPTS:
# 1. Project Summary
# 2. What is the mission of your organization?
# 3. Who are the beneficiaries?
# 4. Please describe how the funding will be used.
# """
# prompt = (
# "You are an assistant helping extract important grant application prompts and section headers.\n"
# "Return only questions and meaningful section titles that require thoughtful answers.\n"
# "Avoid metadata like phone numbers, dates, contact info, or websites.\n\n"
# f"{example_text}\n"
# f"TEXT:\n{text[:3000]}\n\n"
# "PROMPTS:"
# )
# inputs = tokenizer(prompt, return_tensors="pt", truncation=True)
# outputs = model.generate(
# **inputs,
# max_new_tokens=512,
# temperature=0.3,
# do_sample=False
# )
# raw_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
# # Clean and extract numbered or bulleted lines
# lines = raw_output.split("\n")
# prompts = []
# for line in lines:
# clean = line.strip("โข-1234567890. ").strip()
# if len(clean) > 10 and not any(bad in clean.lower() for bad in ["phone", "email", "address", "website"]):
# prompts.append(clean)
# return prompts
def extract_with_llm_local(text: str, use_openai: bool = False) -> List[str]:
# Example context to prime the model
example_text = """TEXT:
1. Project Summary: Please describe the main goals of your project.
2. Contact Information: Address, phone, email.
3. What is the mission of your organization?
4. Who are the beneficiaries?
5. Budget Breakdown
6. Please describe how the funding will be used.
7. Website: www.example.org
PROMPTS:
1. Project Summary
2. What is the mission of your organization?
3. Who are the beneficiaries?
4. Please describe how the funding will be used.
"""
prompt = (
"You are an assistant helping extract important grant application prompts and section headers.\n"
"Return only questions and meaningful section titles that require thoughtful answers.\n"
"Avoid metadata like phone numbers, dates, contact info, or websites.\n\n"
f"{example_text}\n"
f"TEXT:\n{text[:3000]}\n\n"
"PROMPTS:"
)
if use_openai:
if not openai.api_key:
st.error("โ OPENAI_API_KEY is not set.")
return "โ ๏ธ OpenAI key missing."
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You extract prompts and headers from grant text."},
{"role": "user", "content": prompt},
],
temperature=0.2,
max_tokens=500,
)
# raw_output = response["choices"][0]["message"]["content"]
raw_output = response.choices[0].message.content
st.markdown(f"๐งฎ Extract Tokens: Prompt = {response.usage.prompt_tokens}, "
f"Completion = {response.usage.completion_tokens}, Total = {response.usage.total_tokens}")
except Exception as e:
st.error(f"โ OpenAI extraction failed: {e}")
return []
else:
inputs = tokenizer(prompt, return_tensors="pt", truncation=True)
outputs = model.generate(
**inputs,
max_new_tokens=min(max_tokens,512),
temperature=0.3,
do_sample=False,
pad_token_id=tokenizer.eos_token_id
)
raw_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
# Clean and deduplicate prompts
lines = raw_output.split("\n")
prompts = []
seen = set()
for line in lines:
clean = line.strip("โข-1234567890. ").strip()
if (
len(clean) > 10
and not any(bad in clean.lower() for bad in ["phone", "email", "address", "website"])
and clean not in seen
):
prompts.append(clean)
seen.add(clean)
return prompts
# def is_meaningful_prompt(text: str) -> bool:
# too_short = len(text.strip()) < 10
# banned_keywords = ["phone", "email", "fax", "address", "date", "contact", "website"]
# contains_bad_word = any(word in text.lower() for word in banned_keywords)
# is_just_punctuation = all(c in ":.*- " for c in text.strip())
# return not (too_short or contains_bad_word or is_just_punctuation)
# =================== Format Retrieved Chunks ===================
def format_docs(docs: List[Document]) -> str:
return "\n\n".join(doc.page_content or doc.metadata.get("content", "") for doc in docs)
# =================== Generate Response from Hugging Face Model ===================
# def generate_response(input_dict: Dict[str, Any]) -> str:
# client = InferenceClient(api_key=HF_TOKEN.strip())
# prompt = grantbuddy_prompt.format(**input_dict)
# try:
# response = client.chat.completions.create(
# model="HuggingFaceH4/zephyr-7b-beta",
# messages=[
# {"role": "system", "content": prompt},
# {"role": "user", "content": input_dict["question"]},
# ],
# max_tokens=1000,
# temperature=0.2,
# )
# return response.choices[0].message.content
# except Exception as e:
# st.error(f"โ Error from model: {e}")
# return "โ ๏ธ Failed to generate response. Please check your model, HF token, or request format."
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
@st.cache_resource
def load_local_model():
model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
return tokenizer, model
tokenizer, model = load_local_model()
def generate_response(input_dict, use_openai=False, max_tokens=700):
prompt = grantbuddy_prompt.format(**input_dict)
if use_openai:
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": prompt},
{"role": "user", "content": input_dict["question"]},
],
temperature=0.2,
max_tokens=max_tokens,
)
answer = response.choices[0].message.content.strip()
# โ
Token logging
prompt_tokens = response.usage.prompt_tokens
completion_tokens = response.usage.completion_tokens
total_tokens = response.usage.total_tokens
return {
"answer": answer,
"tokens": {
"prompt": prompt_tokens,
"completion": completion_tokens,
"total": total_tokens
}
}
except Exception as e:
st.error(f"โ OpenAI error: {e}")
return {
"answer": "โ ๏ธ OpenAI request failed.",
"tokens": {}
}
else:
inputs = tokenizer(prompt, return_tensors="pt")
outputs = model.generate(
**inputs,
max_new_tokens=512,
temperature=0.7,
do_sample=True,
pad_token_id=tokenizer.eos_token_id
)
decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
return {
"answer": decoded[len(prompt):].strip(),
"tokens": {}
}
# =================== RAG Chain ===================
def get_rag_chain(retriever, use_openai=False, max_tokens=700):
def merge_contexts(inputs):
#use chunks if provided
retrieved_chunks = format_docs(inputs["context_docs"]) if "context_docs" in inputs \
else format_docs(retriever.invoke(inputs["question"]))
combined = "\n\n".join(filter(None, [
inputs.get("manual_context", ""),
retrieved_chunks
]))
return {
"context": combined,
"question": inputs["question"]
}
return RunnableLambda(merge_contexts) | RunnableLambda(
lambda input_dict: generate_response(input_dict, use_openai=use_openai, max_tokens=max_tokens)
)
def rerank_with_topics(chunks, topics, alpha=0.2):
"""
Boosts similarity based on topic overlap.
Since chunks don't have scores, we use rank order and topic matches.
"""
topics_lower = set(t.lower() for t in topics)
def score(chunk, rank):
chunk_topics = [t.lower() for t in chunk.metadata.get("topics", [])]
topic_matches = len(topics_lower.intersection(chunk_topics))
# Lower is better: original rank minus boost
return rank - alpha * topic_matches
reranked = sorted(
enumerate(chunks),
key=lambda x: score(x[1], x[0]) # x[0] is rank, x[1] is chunk
)
return [chunk for _, chunk in reranked]
# =================== Streamlit UI ===================
def gate_ui():
# Get password from secrets (optional env fallback)
APP_PASSWORD = st.secrets.get("APP_PASSWORD", os.getenv("APP_PASSWORD", "")).strip()
# Persist auth in session
if "authed" not in st.session_state:
st.session_state.authed = False
if st.session_state.authed:
return True
st.title("๐ Grant Buddy Login")
pwd = st.text_input("Enter password", type="password")
col1, col2 = st.columns([1,1])
with col1:
if st.button("Login"):
if APP_PASSWORD and pwd == APP_PASSWORD:
st.session_state.authed = True
st.experimental_rerun()
else:
st.error("Incorrect password.")
with col2:
if st.button("Forgot?"):
st.info("Contact the admin to reset the APP_PASSWORD secret.")
return False
def main():
if not gate_ui():
return
# st.set_page_config(page_title="Grant Buddy RAG", page_icon="๐ค")
st.title("๐ค Grant Buddy: Grant-Writing Assistant")
USE_OPENAI = st.sidebar.checkbox("Use OpenAI (Costs Tokens)", value=False)
st.sidebar.markdown("### Retrieval Settings")
k_value = st.sidebar.slider("How many chunks to retrieve (k)", min_value=5, max_value=40, step=5, value=10)
score_threshold = st.sidebar.slider("Minimum relevance score", min_value=0.0, max_value=1.0, step=0.05, value=0.75)
topic_input=st.sidebar.text_input("Optional: Focus on specific topics (comma-separated)")
topics=[t.strip() for t in topic_input.split(",") if t.strip()]
topic_weight= st.sidebar.slider("Topic relevance score", min_value=0.0, max_value=1.0, step=0.05, value=0.2)
st.sidebar.markdown("### Generation Settings")
max_tokens = st.sidebar.number_input("Max tokens in response", min_value=100, max_value=1500, value=700, step=50)
if "generated_queries" not in st.session_state:
st.session_state.generated_queries = {}
manual_context = st.text_area("๐ Optional: Add your own context (e.g., mission, goals)", height=150)
# # retriever = init_vector_search().as_retriever(search_kwargs={"k": k_value, "score_threshold": score_threshold})
retriever = init_vector_search().as_retriever()
vectorstore = init_vector_search()
# pre_k = k_value*4 # Retrieve more chunks first
# context_docs = retriever.get_relevant_documents(query, k=pre_k)
# if topics:
# context_docs = rerank_with_topics(context_docs, topics, alpha=topic_weight)
# context_docs = context_docs[:k_value] # Final top-k used in RAG
rag_chain = get_rag_chain(retriever, use_openai=USE_OPENAI, max_tokens=max_tokens)
uploaded_file = st.file_uploader("Upload PDF or TXT for extra context (optional)", type=["pdf", "txt"])
uploaded_text = ""
if uploaded_file:
with st.spinner("๐ Processing uploaded file..."):
if uploaded_file.name.endswith(".pdf"):
reader = PdfReader(uploaded_file)
uploaded_text = "\n".join([page.extract_text() for page in reader.pages if page.extract_text()])
elif uploaded_file.name.endswith(".txt"):
uploaded_text = uploaded_file.read().decode("utf-8")
# extract qs and headers using llms
questions = extract_with_llm_local(uploaded_text, use_openai=USE_OPENAI)
# filter out irrelevant text
def is_meaningful_prompt(text: str) -> bool:
too_short = len(text.strip()) < 10
banned_keywords = ["phone", "email", "fax", "address", "date", "contact", "website"]
contains_bad_word = any(word in text.lower() for word in banned_keywords)
is_just_punctuation = all(c in ":.*- " for c in text.strip())
return not (too_short or contains_bad_word or is_just_punctuation)
filtered_questions = [q for q in questions if is_meaningful_prompt(q)]
with st.form("question_selection_form"):
st.subheader("Choose prompts to answer:")
selected_questions=[]
for i,q in enumerate(filtered_questions):
if st.checkbox(q, key=f"q_{i}", value=True):
selected_questions.append(q)
submit_button = st.form_submit_button("Submit")
#Multi-Select Question
if 'submit_button' in locals() and submit_button:
if selected_questions:
with st.spinner("๐ก Generating answers..."):
answers = []
for q in selected_questions:
combined_context = "\n\n".join(filter(None, [manual_context.strip(), uploaded_text.strip()]))
pre_k=k_value*4
context_docs=retriever.get_relevant_documents(q, k=pre_k)
if topics:
context_docs=rerank_with_topics(context_docs,topics,alpha=topic_weight)
context_docs=context_docs[:k_value]
# full_query = f"{q}\n\nAdditional context:\n{uploaded_text}"
if q in st.session_state.generated_queries:
response = st.session_state.generated_queries[q]
else:
response = rag_chain.invoke({
"question": q,
"manual_context": combined_context,
"context_docs": context_docs
})
st.session_state.generated_queries[q] = response
answers.append({"question": q, "answer": response})
for item in answers:
st.markdown(f"### โ {item['question']}")
st.markdown(f"๐ฌ {item['answer']['answer']}")
tokens = item['answer'].get("tokens", {})
if tokens:
st.markdown(f"๐งฎ **Token Usage:** Prompt = {tokens.get('prompt')}, "
f"Completion = {tokens.get('completion')}, Total = {tokens.get('total')}")
else:
st.info("No prompts selected for answering.")
# โ๏ธ Manual single-question input
query = st.text_input("Ask a grant-related question")
if st.button("Submit"):
if not query:
st.warning("Please enter a question.")
return
# full_query = f"{query}\n\nAdditional context:\n{uploaded_text}" if uploaded_text else query
pre_k = k_value * 4
context_docs=retriever.get_relevant_documents(query, k=pre_k)
if topics:
context_docs=rerank_with_topics(context_docs, topics, alpha=topic_weight)
context_docs = context_docs[:k_value]
combined_context = "\n\n".join(filter(None, [manual_context.strip(), uploaded_text.strip()]))
with st.spinner("๐ค Thinking..."):
# response = rag_chain.invoke(full_query)
response = rag_chain.invoke({"question":query,"manual_context": combined_context, "context_docs": context_docs})
st.text_area("Grant Buddy says:", value=response["answer"], height=250, disabled=True)
tokens=response.get("tokens",{})
if tokens:
st.markdown(f"๐งฎ **Token Usage:** Prompt = {tokens.get('prompt')}, "
f"Completion = {tokens.get('completion')}, Total = {tokens.get('total')}")
with st.expander("๐ Retrieved Chunks"):
# context_docs = retriever.get_relevant_documents(query)
for doc in context_docs:
# st.json(doc.metadata)
st.markdown(f"**Chunk ID:** {doc.metadata.get('chunk_id', 'unknown')} | **Title:** {doc.metadata['metadata'].get('title', 'unknown')}")
st.markdown(doc.page_content[:700] + "...")
if topics:
matched_topics=set(doc.metadata['metadata'].get('topics',[])).intersection(topics)
st.markdown(f"**Matched Topics** {','.join(matched_topics)}")
st.markdown("---")
if __name__ == "__main__":
main()
# # app.py
# import os
# import re
# import openai
# from huggingface_hub import InferenceClient
# import json
# from huggingface_hub import HfApi
# import streamlit as st
# from typing import List, Dict, Any
# from urllib.parse import quote_plus
# from pymongo import MongoClient
# from PyPDF2 import PdfReader
# st.set_page_config(page_title="Grant Buddy RAG", page_icon="๐ค")
# from typing import List
# from langchain_community.embeddings import HuggingFaceInferenceAPIEmbeddings
# from langchain.embeddings import HuggingFaceEmbeddings
# from langchain_community.vectorstores import MongoDBAtlasVectorSearch
# from langchain.prompts import PromptTemplate
# from langchain.schema import Document
# from langchain.schema.runnable import RunnableLambda, RunnablePassthrough
# from huggingface_hub import InferenceClient
# # =================== Secure Env via Hugging Face Secrets ===================
# user = quote_plus(os.getenv("MONGO_USERNAME"))
# password = quote_plus(os.getenv("MONGO_PASSWORD"))
# cluster = os.getenv("MONGO_CLUSTER")
# db_name = os.getenv("MONGO_DB_NAME", "files")
# collection_name = os.getenv("MONGO_COLLECTION", "files_collection")
# index_name = os.getenv("MONGO_VECTOR_INDEX", "vector_index")
# HF_TOKEN = os.getenv("HF_TOKEN")
# OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "").strip()
# if OPENAI_API_KEY:
# openai.api_key = OPENAI_API_KEY
# from openai import OpenAI
# client = OpenAI(api_key=OPENAI_API_KEY)
# # MONGO_URI = f"mongodb+srv://{user}:{password}@{cluster}/{db_name}?retryWrites=true&w=majority"
# MONGO_URI = f"mongodb+srv://{user}:{password}@{cluster}/{db_name}?retryWrites=true&w=majority&tls=true&tlsAllowInvalidCertificates=true"
# # =================== Prompt ===================
# grantbuddy_prompt = PromptTemplate.from_template(
# """You are Grant Buddy, a specialized language model fine-tuned with instruction-tuning and RLHF.
# You help a nonprofit focused on social entrepreneurship, BIPOC empowerment, and edtech write clear, mission-aligned grant responses.
# **Instructions:**
# - Start with reasoning or context for your answer.
# - Always align with the nonprofitโs mission.
# - Use structured formatting: headings, bullet points, numbered lists.
# - Include impact data or examples if relevant.
# - Do NOT repeat the same sentence or answer multiple times.
# - If no answer exists in the context, say: "This information is not available in the current context."
# CONTEXT:
# {context}
# QUESTION:
# {question}
# """
# )
# # =================== Vector Search Setup ===================
# @st.cache_resource
# def init_embedding_model():
# return HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
# @st.cache_resource
# def init_vector_search() -> MongoDBAtlasVectorSearch:
# HF_TOKEN = os.getenv("HF_TOKEN", "").strip()
# model_name = "sentence-transformers/all-MiniLM-L6-v2"
# st.write(f"๐ Connecting to Hugging Face model: `{model_name}`")
# embedding_model = HuggingFaceEmbeddings(model_name=model_name)
# # โ
Manual MongoClient with TLS settings
# user = quote_plus(os.getenv("MONGO_USERNAME", "").strip())
# password = quote_plus(os.getenv("MONGO_PASSWORD", "").strip())
# cluster = os.getenv("MONGO_CLUSTER", "").strip()
# db_name = os.getenv("MONGO_DB_NAME", "files").strip()
# collection_name = os.getenv("MONGO_COLLECTION", "files_collection").strip()
# index_name = os.getenv("MONGO_VECTOR_INDEX", "vector_index").strip()
# mongo_uri = f"mongodb+srv://{user}:{password}@{cluster}/?retryWrites=true&w=majority"
# try:
# client = MongoClient(mongo_uri, tls=True, tlsAllowInvalidCertificates=True, serverSelectionTimeoutMS=20000)
# db = client[db_name]
# collection = db[collection_name]
# st.success("โ
MongoClient connected successfully")
# return MongoDBAtlasVectorSearch(
# collection=collection,
# embedding=embedding_model,
# index_name=index_name,
# )
# except Exception as e:
# st.error("โ Failed to connect to MongoDB Atlas manually")
# st.error(str(e))
# raise e
# # =================== Question/Headers Extraction ===================
# # def extract_questions_and_headers(text: str) -> List[str]:
# # header_patterns = [
# # r'\d+\.\s+\*\*([^\*]+)\*\*',
# # r'\*\*([^*]+)\*\*',
# # r'^([A-Z][^a-z]*[A-Z])$',
# # r'^([A-Z][A-Za-z\s]{3,})$',
# # r'^[A-Z][A-Za-z\s]+:$'
# # ]
# # question_patterns = [
# # r'^.+\?$',
# # r'^\*?Please .+',
# # r'^How .+',
# # r'^What .+',
# # r'^Describe .+',
# # ]
# # combined_header_re = re.compile("|".join(header_patterns), re.MULTILINE)
# # combined_question_re = re.compile("|".join(question_patterns), re.MULTILINE)
# # headers = [match for group in combined_header_re.findall(text) for match in group if match]
# # questions = combined_question_re.findall(text)
# # return headers + questions
# # def extract_with_llm(text: str) -> List[str]:
# # client = InferenceClient(api_key=HF_TOKEN.strip())
# # try:
# # response = client.chat.completions.create(
# # model="mistralai/Mistral-Nemo-Instruct-2407", # or "HuggingFaceH4/zephyr-7b-beta"
# # messages=[
# # {
# # "role": "system",
# # "content": "You are an assistant helping extract questions and headers from grant applications.",
# # },
# # {
# # "role": "user",
# # "content": (
# # "Please extract all the grant application headers and questions from the following text. "
# # "Include section titles, prompts, and any question-like content. Return them as a numbered list.\n\n"
# # f"{text[:3000]}"
# # ),
# # },
# # ],
# # temperature=0.2,
# # max_tokens=512,
# # )
# # return [
# # line.strip("โข-1234567890. ").strip()
# # for line in response.choices[0].message.content.strip().split("\n")
# # if line.strip()
# # ]
# # except Exception as e:
# # st.error("โ LLM extraction failed")
# # st.error(str(e))
# # return []
# # def extract_with_llm_local(text: str) -> List[str]:
# # prompt = (
# # "You are an assistant helping extract useful questions and section headers from a grant application.\n"
# # "Return only the important prompts as a numbered list.\n\n"
# # "TEXT:\n"
# # f"{text[:3000]}\n\n"
# # "PROMPTS:"
# # )
# # inputs = tokenizer(prompt, return_tensors="pt", truncation=True)
# # outputs = model.generate(
# # **inputs,
# # max_new_tokens=512,
# # temperature=0.3,
# # do_sample=False
# # )
# # raw_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
# # # Extract prompts from the numbered list in the output
# # lines = raw_output.split("\n")
# # prompts = []
# # for line in lines:
# # line = line.strip("โข-1234567890. ").strip()
# # if len(line) > 10:
# # prompts.append(line)
# # return prompts
# # def extract_with_llm_local(text: str) -> List[str]:
# # example_text = """TEXT:
# # 1. Project Summary: Please describe the main goals of your project.
# # 2. Contact Information: Address, phone, email.
# # 3. What is the mission of your organization?
# # 4. Who are the beneficiaries?
# # 5. Budget Breakdown
# # 6. Please describe how the funding will be used.
# # 7. Website: www.example.org
# # PROMPTS:
# # 1. Project Summary
# # 2. What is the mission of your organization?
# # 3. Who are the beneficiaries?
# # 4. Please describe how the funding will be used.
# # """
# # prompt = (
# # "You are an assistant helping extract important grant application prompts and section headers.\n"
# # "Return only questions and meaningful section titles that require thoughtful answers.\n"
# # "Avoid metadata like phone numbers, dates, contact info, or websites.\n\n"
# # f"{example_text}\n"
# # f"TEXT:\n{text[:3000]}\n\n"
# # "PROMPTS:"
# # )
# # inputs = tokenizer(prompt, return_tensors="pt", truncation=True)
# # outputs = model.generate(
# # **inputs,
# # max_new_tokens=512,
# # temperature=0.3,
# # do_sample=False
# # )
# # raw_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
# # # Clean and extract numbered or bulleted lines
# # lines = raw_output.split("\n")
# # prompts = []
# # for line in lines:
# # clean = line.strip("โข-1234567890. ").strip()
# # if len(clean) > 10 and not any(bad in clean.lower() for bad in ["phone", "email", "address", "website"]):
# # prompts.append(clean)
# # return prompts
# def extract_with_llm_local(text: str, use_openai: bool = False) -> List[str]:
# # Example context to prime the model
# example_text = """TEXT:
# 1. Project Summary: Please describe the main goals of your project.
# 2. Contact Information: Address, phone, email.
# 3. What is the mission of your organization?
# 4. Who are the beneficiaries?
# 5. Budget Breakdown
# 6. Please describe how the funding will be used.
# 7. Website: www.example.org
# PROMPTS:
# 1. Project Summary
# 2. What is the mission of your organization?
# 3. Who are the beneficiaries?
# 4. Please describe how the funding will be used.
# """
# prompt = (
# "You are an assistant helping extract important grant application prompts and section headers.\n"
# "Return only questions and meaningful section titles that require thoughtful answers.\n"
# "Avoid metadata like phone numbers, dates, contact info, or websites.\n\n"
# f"{example_text}\n"
# f"TEXT:\n{text[:3000]}\n\n"
# "PROMPTS:"
# )
# if use_openai:
# if not openai.api_key:
# st.error("โ OPENAI_API_KEY is not set.")
# return "โ ๏ธ OpenAI key missing."
# try:
# response = client.chat.completions.create(
# model="gpt-4o-mini",
# messages=[
# {"role": "system", "content": "You extract prompts and headers from grant text."},
# {"role": "user", "content": prompt},
# ],
# temperature=0.2,
# max_tokens=500,
# )
# # raw_output = response["choices"][0]["message"]["content"]
# raw_output = response.choices[0].message.content
# st.markdown(f"๐งฎ Extract Tokens: Prompt = {response.usage.prompt_tokens}, "
# f"Completion = {response.usage.completion_tokens}, Total = {response.usage.total_tokens}")
# except Exception as e:
# st.error(f"โ OpenAI extraction failed: {e}")
# return []
# else:
# inputs = tokenizer(prompt, return_tensors="pt", truncation=True)
# outputs = model.generate(
# **inputs,
# max_new_tokens=min(ax_tokens,512),
# temperature=0.3,
# do_sample=False,
# pad_token_id=tokenizer.eos_token_id
# )
# raw_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
# # Clean and deduplicate prompts
# lines = raw_output.split("\n")
# prompts = []
# seen = set()
# for line in lines:
# clean = line.strip("โข-1234567890. ").strip()
# if (
# len(clean) > 10
# and not any(bad in clean.lower() for bad in ["phone", "email", "address", "website"])
# and clean not in seen
# ):
# prompts.append(clean)
# seen.add(clean)
# return prompts
# # def is_meaningful_prompt(text: str) -> bool:
# # too_short = len(text.strip()) < 10
# # banned_keywords = ["phone", "email", "fax", "address", "date", "contact", "website"]
# # contains_bad_word = any(word in text.lower() for word in banned_keywords)
# # is_just_punctuation = all(c in ":.*- " for c in text.strip())
# # return not (too_short or contains_bad_word or is_just_punctuation)
# # =================== Format Retrieved Chunks ===================
# def format_docs(docs: List[Document]) -> str:
# return "\n\n".join(doc.page_content or doc.metadata.get("content", "") for doc in docs)
# # =================== Generate Response from Hugging Face Model ===================
# # def generate_response(input_dict: Dict[str, Any]) -> str:
# # client = InferenceClient(api_key=HF_TOKEN.strip())
# # prompt = grantbuddy_prompt.format(**input_dict)
# # try:
# # response = client.chat.completions.create(
# # model="HuggingFaceH4/zephyr-7b-beta",
# # messages=[
# # {"role": "system", "content": prompt},
# # {"role": "user", "content": input_dict["question"]},
# # ],
# # max_tokens=1000,
# # temperature=0.2,
# # )
# # return response.choices[0].message.content
# # except Exception as e:
# # st.error(f"โ Error from model: {e}")
# # return "โ ๏ธ Failed to generate response. Please check your model, HF token, or request format."
# from transformers import AutoModelForCausalLM, AutoTokenizer
# import torch
# @st.cache_resource
# def load_local_model():
# model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
# tokenizer = AutoTokenizer.from_pretrained(model_name)
# model = AutoModelForCausalLM.from_pretrained(model_name)
# return tokenizer, model
# tokenizer, model = load_local_model()
# def generate_response(input_dict, use_openai=False, max_tokens=700):
# prompt = grantbuddy_prompt.format(**input_dict)
# if use_openai:
# try:
# response = client.chat.completions.create(
# model="gpt-4o-mini",
# messages=[
# {"role": "system", "content": prompt},
# {"role": "user", "content": input_dict["question"]},
# ],
# temperature=0.2,
# max_tokens=max_tokens,
# )
# answer = response.choices[0].message.content.strip()
# # โ
Token logging
# prompt_tokens = response.usage.prompt_tokens
# completion_tokens = response.usage.completion_tokens
# total_tokens = response.usage.total_tokens
# return {
# "answer": answer,
# "tokens": {
# "prompt": prompt_tokens,
# "completion": completion_tokens,
# "total": total_tokens
# }
# }
# except Exception as e:
# st.error(f"โ OpenAI error: {e}")
# return {
# "answer": "โ ๏ธ OpenAI request failed.",
# "tokens": {}
# }
# else:
# inputs = tokenizer(prompt, return_tensors="pt")
# outputs = model.generate(
# **inputs,
# max_new_tokens=512,
# temperature=0.7,
# do_sample=True,
# pad_token_id=tokenizer.eos_token_id
# )
# decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
# return {
# "answer": decoded[len(prompt):].strip(),
# "tokens": {}
# }
# # =================== RAG Chain ===================
# def get_rag_chain(retriever, use_openai=False, max_tokens=700):
# def merge_contexts(inputs):
# retrieved_chunks = format_docs(retriever.invoke(inputs["question"]))
# combined = "\n\n".join(filter(None, [
# inputs.get("manual_context", ""),
# retrieved_chunks
# ]))
# return {
# "context": combined,
# "question": inputs["question"]
# }
# return RunnableLambda(merge_contexts) | RunnableLambda(
# lambda input_dict: generate_response(input_dict, use_openai=use_openai, max_tokens=max_tokens)
# )
# # =================== Streamlit UI ===================
# def main():
# # st.set_page_config(page_title="Grant Buddy RAG", page_icon="๐ค")
# st.title("๐ค Grant Buddy: Grant-Writing Assistant")
# USE_OPENAI = st.sidebar.checkbox("Use OpenAI (Costs Tokens)", value=False)
# st.sidebar.markdown("### Retrieval Settings")
# k_value = st.sidebar.slider("How many chunks to retrieve (k)", min_value=5, max_value=40, step=5, value=10)
# score_threshold = st.sidebar.slider("Minimum relevance score", min_value=0.0, max_value=1.0, step=0.05, value=0.75)
# st.sidebar.markdown("### Generation Settings")
# max_tokens = st.sidebar.number_input("Max tokens in response", min_value=100, max_value=1500, value=700, step=50)
# if "generated_queries" not in st.session_state:
# st.session_state.generated_queries = {}
# manual_context = st.text_area("๐ Optional: Add your own context (e.g., mission, goals)", height=150)
# retriever = init_vector_search().as_retriever(search_kwargs={"k": k_value, "score_threshold": score_threshold})
# rag_chain = get_rag_chain(retriever, use_openai=USE_OPENAI, max_tokens=max_tokens)
# uploaded_file = st.file_uploader("Upload PDF or TXT for extra context (optional)", type=["pdf", "txt"])
# uploaded_text = ""
# if uploaded_file:
# with st.spinner("๐ Processing uploaded file..."):
# if uploaded_file.name.endswith(".pdf"):
# reader = PdfReader(uploaded_file)
# uploaded_text = "\n".join([page.extract_text() for page in reader.pages if page.extract_text()])
# elif uploaded_file.name.endswith(".txt"):
# uploaded_text = uploaded_file.read().decode("utf-8")
# # extract qs and headers using llms
# questions = extract_with_llm_local(uploaded_text, use_openai=USE_OPENAI)
# # filter out irrelevant text
# def is_meaningful_prompt(text: str) -> bool:
# too_short = len(text.strip()) < 10
# banned_keywords = ["phone", "email", "fax", "address", "date", "contact", "website"]
# contains_bad_word = any(word in text.lower() for word in banned_keywords)
# is_just_punctuation = all(c in ":.*- " for c in text.strip())
# return not (too_short or contains_bad_word or is_just_punctuation)
# filtered_questions = [q for q in questions if is_meaningful_prompt(q)]
# with st.form("question_selection_form"):
# st.subheader("Choose prompts to answer:")
# selected_questions=[]
# for i,q in enumerate(filtered_questions):
# if st.checkbox(q, key=f"q_{i}", value=True):
# selected_questions.append(q)
# submit_button = st.form_submit_button("Submit")
# #Multi-Select Question
# if 'submit_button' in locals() and submit_button:
# if selected_questions:
# with st.spinner("๐ก Generating answers..."):
# answers = []
# for q in selected_questions:
# # full_query = f"{q}\n\nAdditional context:\n{uploaded_text}"
# combined_context = "\n\n".join(filter(None, [manual_context.strip(), uploaded_text.strip()]))
# if q in st.session_state.generated_queries:
# response = st.session_state.generated_queries[q]
# else:
# response = rag_chain.invoke({
# "question": q,
# "manual_context": combined_context
# })
# st.session_state.generated_queries[q] = response
# answers.append({"question": q, "answer": response})
# for item in answers:
# st.markdown(f"### โ {item['question']}")
# st.markdown(f"๐ฌ {item['answer']['answer']}")
# tokens = item['answer'].get("tokens", {})
# if tokens:
# st.markdown(f"๐งฎ **Token Usage:** Prompt = {tokens.get('prompt')}, "
# f"Completion = {tokens.get('completion')}, Total = {tokens.get('total')}")
# else:
# st.info("No prompts selected for answering.")
# # โ๏ธ Manual single-question input
# query = st.text_input("Ask a grant-related question")
# if st.button("Submit"):
# if not query:
# st.warning("Please enter a question.")
# return
# # full_query = f"{query}\n\nAdditional context:\n{uploaded_text}" if uploaded_text else query
# combined_context = "\n\n".join(filter(None, [manual_context.strip(), uploaded_text.strip()]))
# with st.spinner("๐ค Thinking..."):
# # response = rag_chain.invoke(full_query)
# response = rag_chain.invoke({"question":query,"manual_context": combined_context})
# st.text_area("Grant Buddy says:", value=response["answer"], height=250, disabled=True)
# tokens=response.get("tokens",{})
# if tokens:
# st.markdown(f"๐งฎ **Token Usage:** Prompt = {tokens.get('prompt')}, "
# f"Completion = {tokens.get('completion')}, Total = {tokens.get('total')}")
# with st.expander("๐ Retrieved Chunks"):
# context_docs = retriever.get_relevant_documents(query)
# for doc in context_docs:
# # st.json(doc.metadata)
# st.markdown(f"**Chunk ID:** {doc.metadata.get('chunk_id', 'unknown')} | **Title:** {doc.metadata['metadata'].get('title', 'unknown')}")
# st.markdown(doc.page_content[:700] + "...")
# st.markdown("---")
# if __name__ == "__main__":
# main()
|