File size: 41,683 Bytes
55f6aba 675d7d2 6b317ef 8e10f84 c6ed986 8f4d711 c6ed986 8f4d711 7e6e211 c8ab99f c6ed986 8f4d711 8e10f84 8f4d711 c8ab99f 8f4d711 c8ab99f 8f4d711 c8ab99f 8f4d711 c8ab99f 8f4d711 c8ab99f 8f4d711 c8ab99f 8f4d711 fdbfd81 8f4d711 8e10f84 346b86f 76470b4 8e10f84 76470b4 8e10f84 8f4d711 8e10f84 8f4d711 8e10f84 9a6f26a 8e10f84 73b6675 8e10f84 c6ed986 8e10f84 524dc9d 8e10f84 524dc9d 5bec20a 524dc9d 5bec20a 524dc9d 5bec20a 524dc9d 5bec20a 524dc9d 5bec20a 524dc9d 5bec20a 524dc9d 8f4d711 |
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 |
# import os
# import tempfile
# import streamlit as st
# from langchain_openai import ChatOpenAI
# from langchain.document_loaders import UnstructuredFileLoader
# from langchain_community.vectorstores import FAISS
# from langchain.embeddings import HuggingFaceEmbeddings
# from langchain.text_splitter import CharacterTextSplitter
# from langchain.chains import RetrievalQA
# from langchain_openai import OpenAIEmbeddings
# from langchain.vectorstores import FAISS
# from langchain import PromptTemplate
# from langchain_text_splitters import (
# Language,
# RecursiveCharacterTextSplitter,
# )
# import io
# import PyPDF2
# import requests
# from bs4 import BeautifulSoup
# from selenium import webdriver
# from selenium.webdriver.chrome.service import Service
# from selenium.webdriver.chrome.options import Options
# from selenium.webdriver.common.by import By
# from selenium.webdriver.support.ui import WebDriverWait
# from selenium.webdriver.support import expected_conditions as EC
# from urllib.parse import urlparse, urljoin
# from firecrawl import FirecrawlApp
# import pymupdf4llm
# import pathlib
# import time
# # Models and parameters
# embedding_model = "text-embedding-3-small"
# llm_model = "gpt-4o-mini-2024-07-18"
# llm = ChatOpenAI(model=llm_model, temperature=0)
# # Hyperparameters
# PDF_CHUNK_SIZE = 1024
# PDF_CHUNK_OVERLAP = 256
# WEB_CHUNK_SIZE = 1024
# WEB_CHUNK_OVERLAP = 256
# TEXT_BLOB_CHUNK_SIZE = 1024
# TEXT_BLOB_CHUNK_OVERLAP = 256
# QA_CHUNK_SIZE = 1024
# QA_CHUNK_OVERLAP = 256
# k = 3
# system_prompt = """You are a helpful assistant designed to answer questions based on the provided context.
# Using the context provided, please answer the user question as accurately and informatively as possible. If no relevant context is available, inform the user that you do not have the information needed to answer their question.
# """
# def setup_driver():
# options = Options()
# options.add_argument("--verbose")
# options.add_argument('--no-sandbox')
# options.add_argument('--headless')
# options.add_argument('--disable-gpu')
# options.add_argument("--window-size=1920, 1200")
# options.add_argument('--disable-dev-shm-usage')
# return webdriver.Chrome(options=options)
# def normalize_url(url):
# parsed = urlparse(url)
# normalized = f"https://{parsed.netloc.replace('www.', '')}{parsed.path.rstrip('/')}"
# if parsed.query:
# normalized += f"?{parsed.query}"
# return normalized
# def parse_web_page(url, base_url, visited_urls, driver, max_urls=None):
# normalized_url = normalize_url(url)
# if normalized_url in visited_urls:
# return
# visited_urls.add(normalized_url)
# driver.get(url)
# page_source = driver.page_source
# soup = BeautifulSoup(page_source, 'html.parser')
# for link in soup.find_all('a', href=True):
# next_url = urljoin(url, link['href'])
# parsed_next_url = urlparse(next_url)
# normalized_next_url = normalize_url(next_url)
# if (parsed_next_url.netloc == urlparse(base_url).netloc and
# normalized_next_url not in visited_urls):
# if max_urls is None or len(visited_urls) < max_urls:
# parse_web_page(normalized_next_url, base_url, visited_urls, driver, max_urls)
# if max_urls is not None and len(visited_urls) >= max_urls:
# break
# def crawl_url(url, max_urls):
# driver = setup_driver()
# visited_urls = set()
# parse_web_page(url, url, visited_urls, driver, max_urls)
# driver.quit()
# return visited_urls
# def process_webpage(web_content):
# md_splitter = RecursiveCharacterTextSplitter.from_language(
# language=Language.MARKDOWN, chunk_size=WEB_CHUNK_SIZE, chunk_overlap=WEB_CHUNK_OVERLAP
# )
# return md_splitter.create_documents([web_content])
# # def process_pdf(pdf_file):
# # md_text = pymupdf4llm.to_markdown(pdf_file)
# # md_splitter = RecursiveCharacterTextSplitter.from_language(
# # language=Language.MARKDOWN, chunk_size=PDF_CHUNK_SIZE, chunk_overlap=PDF_CHUNK_OVERLAP
# # )
# # return md_splitter.create_documents([md_text])
# def process_pdf(pdf_file):
# # Create a temporary file
# with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
# # Write the contents of the uploaded file to the temporary file
# temp_file.write(pdf_file.getvalue())
# temp_file_path = temp_file.name
# try:
# # Use the temporary file path with pymupdf4llm
# md_text = pymupdf4llm.to_markdown(temp_file_path)
# md_splitter = RecursiveCharacterTextSplitter.from_language(
# language=Language.MARKDOWN, chunk_size=PDF_CHUNK_SIZE, chunk_overlap=PDF_CHUNK_OVERLAP
# )
# return md_splitter.create_documents([md_text])
# finally:
# # Remove the temporary file
# os.unlink(temp_file_path)
# def process_text_blob(text_blob):
# text_splitter = RecursiveCharacterTextSplitter(chunk_size=TEXT_BLOB_CHUNK_SIZE, chunk_overlap=TEXT_BLOB_CHUNK_OVERLAP
# )
# return text_splitter.create_documents([text_blob])
# def process_qa_document(qa_data):
# qa_pairs = qa_data.splitlines()
# formatted_qa_text = ""
# for pair in qa_pairs:
# if ';' in pair:
# question, answer = pair.split(';', 1)
# formatted_qa_text += f"Q: {question.strip()}\nA: {answer.strip()}\n\n"
# qa_splitter = RecursiveCharacterTextSplitter(chunk_size=QA_CHUNK_SIZE, chunk_overlap=QA_CHUNK_OVERLAP
# )
# return qa_splitter.create_documents([formatted_qa_text])
# def create_combined_knowledge_base(all_text_chunks):
# embeddings = OpenAIEmbeddings(model=embedding_model)
# return FAISS.from_documents(all_text_chunks, embeddings)
# def main():
# st.title("Interactive Chatbot with Custom Knowledge Base")
# all_text_chunks = []
# st.sidebar.header("Select Knowledge Sources")
# pdf_files = st.sidebar.file_uploader("Upload PDF files", type="pdf", accept_multiple_files=True)
# if pdf_files:
# for pdf_file in pdf_files:
# pdf_text_chunks = process_pdf(pdf_file)
# for chunk in pdf_text_chunks:
# chunk.metadata['source'] = pdf_file.name
# all_text_chunks.extend(pdf_text_chunks)
# text_blob = st.sidebar.text_area("Enter a large text blob")
# if text_blob:
# text_blob_chunks = process_text_blob(text_blob.strip())
# for chunk in text_blob_chunks:
# chunk.metadata['source'] = "Text Blob"
# all_text_chunks.extend(text_blob_chunks)
# qa_data = st.sidebar.text_area("Enter QA data (Q;A per line)")
# if qa_data:
# qa_doc_chunks = process_qa_document(qa_data.strip())
# for chunk in qa_doc_chunks:
# chunk.metadata['source'] = "QA Document"
# all_text_chunks.extend(qa_doc_chunks)
# url = st.sidebar.text_input("Enter webpage URL")
# if url:
# max_urls = st.sidebar.number_input("Max URLs to crawl", min_value=1, value=10)
# sub_urls = crawl_url(url, max_urls)
# sub_urls_list = list(sub_urls)
# selected_urls = st.sidebar.multiselect("Select sub-URLs to scrape", sub_urls_list)
# for selected_sub_url in selected_urls:
# app = FirecrawlApp(api_key=os.getenv("FIRECRAWL_API_KEY"))
# web_content = app.scrape_url(selected_sub_url)['markdown']
# webpage_chunks = process_webpage(web_content)
# for chunk in webpage_chunks:
# chunk.metadata['source'] = selected_sub_url
# all_text_chunks.extend(webpage_chunks)
# if st.sidebar.button("Create Knowledge Base"):
# combined_knowledge_base = create_combined_knowledge_base(all_text_chunks)
# st.session_state['knowledge_base'] = combined_knowledge_base
# st.success("Knowledge base created successfully!")
# if 'knowledge_base' in st.session_state:
# st.header("Ask a Question")
# question = st.text_input("Enter your question")
# if st.button("Get Answer"):
# knowledge_base = st.session_state['knowledge_base']
# template = '''
# %s
# -------------------------------
# Context: {context}
# Question: {question}
# Answer:
# ''' % (system_prompt)
# prompt = PromptTemplate(
# template=template,
# input_variables=['context', 'question']
# )
# qa_chain = RetrievalQA.from_chain_type(
# llm,
# retriever=knowledge_base.as_retriever(search_kwargs={"k": k}),
# return_source_documents=True,
# chain_type_kwargs={"prompt": prompt}
# )
# response = qa_chain.invoke({"query": question})
# st.write(f"**Answer:** {response['result']}")
# with st.expander("Sources used"):
# for doc in response['source_documents']:
# st.write(f"**Source:** {doc.metadata['source']}")
# st.write(f"**Content:**\n{doc.page_content}\n{'-'*40}")
# if __name__ == "__main__":
# main()
# import os
# import tempfile
# import streamlit as st
# from langchain_openai import ChatOpenAI
# from langchain.document_loaders import UnstructuredFileLoader
# from langchain_community.vectorstores import FAISS
# from langchain.embeddings import HuggingFaceEmbeddings
# from langchain.text_splitter import CharacterTextSplitter
# from langchain.chains import RetrievalQA
# from langchain_openai import OpenAIEmbeddings
# from langchain.vectorstores import FAISS
# from langchain import PromptTemplate
# from langchain_text_splitters import (
# Language,
# RecursiveCharacterTextSplitter,
# )
# # import asyncio
# # from crawl4ai import AsyncWebCrawler
# import pymupdf4llm
# import pathlib
# import time
# from firecrawl import FirecrawlApp
# # Models and parameters
# embedding_model = "text-embedding-3-small"
# llm_model = "gpt-4o-mini-2024-07-18"
# llm = ChatOpenAI(model=llm_model, temperature=0)
# # Hyperparameters
# PDF_CHUNK_SIZE = 1024
# PDF_CHUNK_OVERLAP = 256
# WEB_CHUNK_SIZE = 1024
# WEB_CHUNK_OVERLAP = 256
# k = 3
# system_prompt = """You are a helpful assistant designed to answer questions based on the provided context.
# Using the context provided, please answer the user question as accurately and informatively as possible. If no relevant context is available, inform the user that you do not have the information needed to answer their question.
# """
# def process_pdf(pdf_file):
# with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
# temp_file.write(pdf_file.getvalue())
# temp_file_path = temp_file.name
# try:
# md_text = pymupdf4llm.to_markdown(temp_file_path)
# md_splitter = RecursiveCharacterTextSplitter.from_language(
# language=Language.MARKDOWN, chunk_size=PDF_CHUNK_SIZE, chunk_overlap=PDF_CHUNK_OVERLAP
# )
# return md_splitter.create_documents([md_text])
# finally:
# os.unlink(temp_file_path)
# async def crawl_urls(urls):
# async with AsyncWebCrawler() as crawler:
# tasks = [crawler.arun(url=url) for url in urls]
# results = await asyncio.gather(*tasks)
# return {url: result.markdown for url, result in zip(urls, results)}
# def create_combined_knowledge_base(all_text_chunks):
# embeddings = OpenAIEmbeddings(model=embedding_model)
# return FAISS.from_documents(all_text_chunks, embeddings)
# def main():
# st.title("Interactive Chatbot with Custom Knowledge Base")
# all_text_chunks = []
# st.sidebar.header("Select Knowledge Sources")
# pdf_files = st.sidebar.file_uploader("Upload PDF files", type="pdf", accept_multiple_files=True)
# if pdf_files:
# for pdf_file in pdf_files:
# pdf_text_chunks = process_pdf(pdf_file)
# for chunk in pdf_text_chunks:
# chunk.metadata['source'] = pdf_file.name
# all_text_chunks.extend(pdf_text_chunks)
# urls_input = st.sidebar.text_area("Enter webpage URLs (separated by ';')")
# urls = [url.strip() for url in urls_input.split(';') if url.strip()]
# # if urls and st.sidebar.button("Fetch Content"):
# # app = FirecrawlApp(api_key=os.getenv("FIRECRAWL_API_KEY"))
# # web_contents = app.scrape_url(urls)['markdown']
# # if urls and st.sidebar.button("Fetch Content"):
# # app = FirecrawlApp(api_key=os.getenv("FIRECRAWL_API_KEY"))
# # web_contents = app.scrape_url(urls if isinstance(urls, list) else [urls])['markdown']
# # for url, content in web_contents.items():
# # webpage_chunks = RecursiveCharacterTextSplitter.from_language(
# # language=Language.MARKDOWN, chunk_size=WEB_CHUNK_SIZE, chunk_overlap=WEB_CHUNK_OVERLAP
# # ).create_documents([content])
# # for chunk in webpage_chunks:
# # chunk.metadata['source'] = url
# # all_text_chunks.extend(webpage_chunks)
# if urls and st.sidebar.button("Fetch Content"):
# app = FirecrawlApp(api_key=os.getenv("FIRECRAWL_API_KEY"))
# web_contents = {}
# # Loop through each URL and scrape individually
# for url in urls:
# try:
# result = app.scrape_url(url) # Scrape a single URL
# web_contents[url] = result['markdown']
# except Exception as e:
# st.error(f"Error scraping URL {url}: {e}")
# # Process the content of the scraped URLs
# for url, content in web_contents.items():
# webpage_chunks = RecursiveCharacterTextSplitter.from_language(
# language=Language.MARKDOWN, chunk_size=WEB_CHUNK_SIZE, chunk_overlap=WEB_CHUNK_OVERLAP
# ).create_documents([content])
# for chunk in webpage_chunks:
# chunk.metadata['source'] = url
# all_text_chunks.extend(webpage_chunks)
# if st.sidebar.button("Create Knowledge Base"):
# combined_knowledge_base = create_combined_knowledge_base(all_text_chunks)
# st.session_state['knowledge_base'] = combined_knowledge_base
# st.success("Knowledge base created successfully!")
# if 'knowledge_base' in st.session_state:
# st.header("Ask a Question")
# question = st.text_input("Enter your question")
# if question and st.button("Get Answer"):
# knowledge_base = st.session_state['knowledge_base']
# template = '''
# %s
# -------------------------------
# Context: {context}
# Question: {question}
# Answer:
# ''' % (system_prompt)
# prompt = PromptTemplate(
# template=template,
# input_variables=['context', 'question']
# )
# qa_chain = RetrievalQA.from_chain_type(
# llm,
# retriever=knowledge_base.as_retriever(search_kwargs={"k": k}),
# return_source_documents=True,
# chain_type_kwargs={"prompt": prompt}
# )
# response = qa_chain.invoke({"query": question})
# st.write(f"**Answer:** {response['result']}")
# with st.expander("Sources used"):
# for doc in response['source_documents']:
# st.write(f"**Source:** {doc.metadata['source']}")
# st.write(f"**Content:** {doc.page_content}\n{'-'*40}")
# if __name__ == "__main__":
# main()
# import os
# import tempfile
# import streamlit as st
# from langchain_openai import ChatOpenAI
# from langchain.document_loaders import UnstructuredFileLoader
# from langchain_community.vectorstores import FAISS
# from langchain.embeddings import HuggingFaceEmbeddings
# from langchain.text_splitter import CharacterTextSplitter
# from langchain.chains import RetrievalQA
# from langchain_openai import OpenAIEmbeddings
# from langchain.vectorstores import FAISS
# from langchain import PromptTemplate
# from langchain_text_splitters import (
# Language,
# RecursiveCharacterTextSplitter,
# )
# import pymupdf4llm
# import pathlib
# import time
# from firecrawl import FirecrawlApp
# # Models and parameters
# embedding_model = "text-embedding-3-small"
# llm_model = "gpt-4o-mini-2024-07-18"
# llm = ChatOpenAI(model=llm_model, temperature=0)
# # Hyperparameters
# PDF_CHUNK_SIZE = 1024
# PDF_CHUNK_OVERLAP = 256
# WEB_CHUNK_SIZE = 1024
# WEB_CHUNK_OVERLAP = 256
# k = 3
# system_prompt = """You are a helpful assistant designed to answer questions based on the provided context.
# Using the context provided, please answer the user question as accurately and informatively as possible. If no relevant context is available, inform the user that you do not have the information needed to answer their question.
# """
# def process_pdf(pdf_file):
# with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
# temp_file.write(pdf_file.getvalue())
# temp_file_path = temp_file.name
# try:
# md_text = pymupdf4llm.to_markdown(temp_file_path)
# md_splitter = RecursiveCharacterTextSplitter.from_language(
# language=Language.MARKDOWN, chunk_size=PDF_CHUNK_SIZE, chunk_overlap=PDF_CHUNK_OVERLAP
# )
# return md_splitter.create_documents([md_text])
# finally:
# os.unlink(temp_file_path)
# def create_combined_knowledge_base(all_text_chunks):
# embeddings = OpenAIEmbeddings(model=embedding_model)
# return FAISS.from_documents(all_text_chunks, embeddings)
# def main():
# st.title("Dex Agent with Dynamic Knowledge Base")
# all_text_chunks = []
# st.sidebar.header("Select Knowledge Sources")
# # Upload PDF files
# pdf_files = st.sidebar.file_uploader("Upload PDF files", type="pdf", accept_multiple_files=True)
# if pdf_files:
# for pdf_file in pdf_files:
# pdf_text_chunks = process_pdf(pdf_file)
# for chunk in pdf_text_chunks:
# chunk.metadata['source'] = pdf_file.name
# all_text_chunks.extend(pdf_text_chunks)
# # Input webpage URLs
# urls_input = st.sidebar.text_area("Enter webpage URLs (separated by ';')")
# urls = [url.strip() for url in urls_input.split(';') if url.strip()]
# if urls:
# # Scrape URLs and process their content
# app = FirecrawlApp(api_key=os.getenv("FIRECRAWL_API_KEY"))
# web_contents = {}
# # Loop through each URL and scrape individually
# for url in urls:
# try:
# result = app.scrape_url(url) # Scrape a single URL
# web_contents[url] = result['markdown']
# except Exception as e:
# st.error(f"Error scraping URL {url}: {e}")
# # Process the content of the scraped URLs
# for url, content in web_contents.items():
# webpage_chunks = RecursiveCharacterTextSplitter.from_language(
# language=Language.MARKDOWN, chunk_size=WEB_CHUNK_SIZE, chunk_overlap=WEB_CHUNK_OVERLAP
# ).create_documents([content])
# for chunk in webpage_chunks:
# chunk.metadata['source'] = url
# all_text_chunks.extend(webpage_chunks)
# if st.sidebar.button("Create Knowledge Base"):
# if not all_text_chunks:
# st.error("No data available to create knowledge base. Please upload PDFs or provide URLs.")
# else:
# combined_knowledge_base = create_combined_knowledge_base(all_text_chunks)
# st.session_state['knowledge_base'] = combined_knowledge_base
# st.success("Knowledge base created successfully!")
# if 'knowledge_base' in st.session_state:
# st.header("Ask a Question")
# question = st.text_input("Enter your question")
# # Display the "Get Answer" button immediately after the knowledge base is created
# if question and st.button("Get Answer"):
# knowledge_base = st.session_state['knowledge_base']
# template = '''
# %s
# -------------------------------
# Context: {context}
# Question: {question}
# Answer:
# ''' % (system_prompt)
# prompt = PromptTemplate(
# template=template,
# input_variables=['context', 'question']
# )
# qa_chain = RetrievalQA.from_chain_type(
# llm,
# retriever=knowledge_base.as_retriever(search_kwargs={"k": k}),
# return_source_documents=True,
# chain_type_kwargs={"prompt": prompt}
# )
# response = qa_chain.invoke({"query": question})
# st.write(f"Answer: {response['result']}")
# with st.expander("Sources used"):
# for doc in response['source_documents']:
# st.write(f"Source: {doc.metadata['source']}")
# st.write(f"Content: {doc.page_content}")
# if __name__ == "__main__":
# main()
# import os
# import tempfile
# import streamlit as st
# from langchain_openai import ChatOpenAI
# from langchain.document_loaders import UnstructuredFileLoader
# from langchain_community.vectorstores import FAISS
# from langchain.embeddings import HuggingFaceEmbeddings
# from langchain.text_splitter import CharacterTextSplitter
# from langchain.chains import RetrievalQA
# from langchain_openai import OpenAIEmbeddings
# from langchain.vectorstores import FAISS
# from langchain import PromptTemplate
# from langchain_text_splitters import (
# Language,
# RecursiveCharacterTextSplitter,
# )
# import pymupdf4llm
# import pathlib
# import time
# from firecrawl import FirecrawlApp
# # Models and parameters
# embedding_model = "text-embedding-3-small"
# llm_model = "gpt-4o-mini-2024-07-18"
# llm = ChatOpenAI(model=llm_model, temperature=0)
# # Hyperparameters
# PDF_CHUNK_SIZE = 1024
# PDF_CHUNK_OVERLAP = 256
# WEB_CHUNK_SIZE = 1024
# WEB_CHUNK_OVERLAP = 256
# k = 3
# system_prompt = """You are a helpful assistant designed to answer questions based on the provided context.
# Using the context provided, please answer the user question as accurately and informatively as possible. If no relevant context is available, inform the user that you do not have the information needed to answer their question.
# """
# def process_pdf(pdf_file):
# with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
# temp_file.write(pdf_file.getvalue())
# temp_file_path = temp_file.name
# try:
# md_text = pymupdf4llm.to_markdown(temp_file_path)
# md_splitter = RecursiveCharacterTextSplitter.from_language(
# language=Language.MARKDOWN, chunk_size=PDF_CHUNK_SIZE, chunk_overlap=PDF_CHUNK_OVERLAP
# )
# return md_splitter.create_documents([md_text])
# finally:
# os.unlink(temp_file_path)
# def create_combined_knowledge_base(all_text_chunks):
# embeddings = OpenAIEmbeddings(model=embedding_model)
# return FAISS.from_documents(all_text_chunks, embeddings)
# def main():
# st.title("Interactive Chatbot with Custom Knowledge Base")
# all_text_chunks = []
# st.sidebar.header("Select Knowledge Sources")
# # Upload PDF files
# pdf_files = st.sidebar.file_uploader("Upload PDF files", type="pdf", accept_multiple_files=True)
# if pdf_files:
# for pdf_file in pdf_files:
# pdf_text_chunks = process_pdf(pdf_file)
# for chunk in pdf_text_chunks:
# chunk.metadata['source'] = pdf_file.name
# all_text_chunks.extend(pdf_text_chunks)
# # Input webpage URLs
# urls_input = st.sidebar.text_area("Enter webpage URLs (separated by ';')")
# urls = [url.strip() for url in urls_input.split(';') if url.strip()]
# if urls:
# # Scrape URLs and process their content
# app = FirecrawlApp(api_key=os.getenv("FIRECRAWL_API_KEY"))
# web_contents = {}
# # Loop through each URL and scrape individually
# for url in urls:
# try:
# result = app.scrape_url(url) # Scrape a single URL
# web_contents[url] = result['markdown']
# except Exception as e:
# st.error(f"Error scraping URL {url}: {e}")
# # Process the content of the scraped URLs
# for url, content in web_contents.items():
# webpage_chunks = RecursiveCharacterTextSplitter.from_language(
# language=Language.MARKDOWN, chunk_size=WEB_CHUNK_SIZE, chunk_overlap=WEB_CHUNK_OVERLAP
# ).create_documents([content])
# for chunk in webpage_chunks:
# chunk.metadata['source'] = url
# all_text_chunks.extend(webpage_chunks)
# if st.sidebar.button("Create Knowledge Base"):
# if not all_text_chunks:
# st.error("No data available to create knowledge base. Please upload PDFs or provide URLs.")
# else:
# combined_knowledge_base = create_combined_knowledge_base(all_text_chunks)
# st.session_state['knowledge_base'] = combined_knowledge_base
# st.success("Knowledge base created successfully!")
# if 'knowledge_base' in st.session_state:
# st.header("Ask a Question")
# # Make sure the "Get Answer" button is always visible
# question = st.text_input("Enter your question")
# # Always show the "Get Answer" button if the knowledge base is created
# if st.button("Get Answer"):
# knowledge_base = st.session_state['knowledge_base']
# template = '''
# %s
# -------------------------------
# Context: {context}
# Question: {question}
# Answer:
# ''' % (system_prompt)
# prompt = PromptTemplate(
# template=template,
# input_variables=['context', 'question']
# )
# qa_chain = RetrievalQA.from_chain_type(
# llm,
# retriever=knowledge_base.as_retriever(search_kwargs={"k": k}),
# return_source_documents=True,
# chain_type_kwargs={"prompt": prompt}
# )
# response = qa_chain.invoke({"query": question})
# st.write(f"**Answer:** {response['result']}")
# with st.expander("Sources used"):
# for doc in response['source_documents']:
# st.write(f"**Source:** {doc.metadata['source']}")
# st.write(f"**Content:** {doc.page_content}\n{'-'*40}")
# if __name__ == "__main__":
# main()
# import os
# import tempfile
# import streamlit as st
# from langchain_openai import ChatOpenAI
# from langchain.document_loaders import UnstructuredFileLoader
# from langchain_community.vectorstores import FAISS
# from langchain.embeddings import HuggingFaceEmbeddings
# from langchain.text_splitter import CharacterTextSplitter
# from langchain.chains import RetrievalQA
# from langchain_openai import OpenAIEmbeddings
# from langchain.vectorstores import FAISS
# from langchain import PromptTemplate
# from langchain_text_splitters import (
# Language,
# RecursiveCharacterTextSplitter,
# )
# import pymupdf4llm
# import pathlib
# import time
# from firecrawl import FirecrawlApp
# import tempfile
# import pymupdf4llm
# # Models and parameters
# embedding_model = "text-embedding-3-small"
# llm_model = "gpt-4o-mini-2024-07-18"
# llm = ChatOpenAI(model=llm_model, temperature=0)
# # Hyperparameters
# PDF_CHUNK_SIZE = 2048
# PDF_CHUNK_OVERLAP = 512
# WEB_CHUNK_SIZE = 2048
# WEB_CHUNK_OVERLAP = 512
# k = 5
# system_prompt = """You are a helpful assistant designed to answer questions based on the provided context.
# Using the context provided, please answer the user question as accurately and informatively as possible. If no relevant context is available, inform the user that you do not have the information needed to answer their question.
# """
# # Log current working directory
# # st.write("Current working directory:", os.getcwd())
# # # List all files in the current directory
# # st.write("Files in current directory:", os.listdir(os.getcwd()))
# # def process_pdf(pdf_file):
# # with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
# # temp_file.write(pdf_file.getvalue())
# # temp_file_path = temp_file.name
# # try:
# # md_text = pymupdf4llm.to_markdown(temp_file_path)
# # md_splitter = RecursiveCharacterTextSplitter.from_language(
# # language=Language.MARKDOWN, chunk_size=PDF_CHUNK_SIZE, chunk_overlap=PDF_CHUNK_OVERLAP
# # )
# # return md_splitter.create_documents([md_text])
# # finally:
# # os.unlink(temp_file_path)
# def process_pdf(pdf_file):
# # Create a temporary file to store the uploaded PDF
# with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
# temp_file.write(pdf_file.read()) # Read the content of the uploaded PDF file
# temp_file_path = temp_file.name
# try:
# md_text = pymupdf4llm.to_markdown(temp_file_path) # Process the PDF content
# md_splitter = RecursiveCharacterTextSplitter.from_language(
# language=Language.MARKDOWN, chunk_size=PDF_CHUNK_SIZE, chunk_overlap=PDF_CHUNK_OVERLAP
# )
# return md_splitter.create_documents([md_text])
# finally:
# # Clean up the temporary file
# os.unlink(temp_file_path)
# def create_combined_knowledge_base(all_text_chunks):
# embeddings = OpenAIEmbeddings(model=embedding_model)
# return FAISS.from_documents(all_text_chunks, embeddings)
# def main():
# st.title("Interactive Chatbot with Custom Knowledge Base")
# all_text_chunks = []
# st.sidebar.header("Select Knowledge Sources")
# # Specify your PDF files and URLs here
# pdf_files = ["bitcoin.pdf", "whitepaper-v3.pdf"] # Replace with actual paths
# pdf_file_paths = [os.path.join(os.getcwd(), pdf_file) for pdf_file in pdf_files]
# urls = ["https://www.coinbase.com/it/learn/crypto-basics/what-is-a-dex", "https://ethereum.org/en/whitepaper/"] # Replace with actual URLs
# # Process PDF files
# for pdf_file_path in pdf_file_paths:
# with open(pdf_file_path, "rb") as pdf_file:
# pdf_text_chunks = process_pdf(pdf_file)
# for chunk in pdf_text_chunks:
# chunk.metadata['source'] = pdf_file_path
# all_text_chunks.extend(pdf_text_chunks)
# # Scrape content from URLs
# app = FirecrawlApp(api_key=os.getenv("FIRECRAWL_API_KEY"))
# web_contents = {}
# for url in urls:
# try:
# result = app.scrape_url(url)
# web_contents[url] = result['markdown']
# except Exception as e:
# st.error(f"Error scraping URL {url}: {e}")
# # Process the content of the scraped URLs
# for url, content in web_contents.items():
# webpage_chunks = RecursiveCharacterTextSplitter.from_language(
# language=Language.MARKDOWN, chunk_size=WEB_CHUNK_SIZE, chunk_overlap=WEB_CHUNK_OVERLAP
# ).create_documents([content])
# for chunk in webpage_chunks:
# chunk.metadata['source'] = url
# all_text_chunks.extend(webpage_chunks)
# # Check if the FAISS index exists locally
# current_dir = os.getcwd()
# # Define the path to save the FAISS index within the current directory
# faiss_index_path = os.path.join(current_dir, "faiss_index")
# # faiss_index_path = "faiss_index"
# if os.path.exists(faiss_index_path):
# # Load the existing FAISS index
# embeddings = OpenAIEmbeddings(model=embedding_model)
# knowledge_base = FAISS.load_local(faiss_index_path, embeddings, allow_dangerous_deserialization=True)
# st.success("Knowledge base loaded successfully!")
# else:
# # Create and save the new FAISS index
# knowledge_base = create_combined_knowledge_base(all_text_chunks)
# knowledge_base.save_local(faiss_index_path)
# st.success("Knowledge base created and saved successfully!")
# # Allow users to ask questions
# st.header("Ask a Question")
# # Always show the "Get Answer" button, and input the question
# question = st.text_input("Enter your question")
# # Always display the button
# if st.button("Get Answer"):
# if question: # Proceed only if a question is entered
# template = '''
# %s
# -------------------------------
# Context: {context}
# Question: {question}
# Answer:
# ''' % (system_prompt)
# prompt = PromptTemplate(
# template=template,
# input_variables=['context', 'question']
# )
# # Check if the knowledge base is loaded in session state
# knowledge_base = st.session_state.get('knowledge_base')
# if knowledge_base:
# try:
# qa_chain = RetrievalQA.from_chain_type(
# llm,
# retriever=knowledge_base.as_retriever(search_kwargs={"k": k}),
# return_source_documents=True,
# chain_type_kwargs={"prompt": prompt}
# )
# # Get the response from the QA chain
# response = qa_chain.invoke({"query": question})
# # Display the answer
# st.write(f"**Answer:** {response['result']}")
# with st.expander("Sources used"):
# for doc in response['source_documents']:
# st.write(f"**Source:** {doc.metadata['source']}")
# st.write(f"**Content:** {doc.page_content}\n{'-'*40}")
# except Exception as e:
# st.error(f"An error occurred while fetching the answer: {e}")
# else:
# st.error("Knowledge base is not loaded. Please create or load the knowledge base.")
# else:
# st.warning("Please enter a question to get an answer.")
# if __name__ == "__main__":
# main()
import os
import tempfile
import streamlit as st
from langchain_openai import ChatOpenAI
from langchain.document_loaders import UnstructuredFileLoader
from langchain_community.vectorstores import FAISS
from langchain.embeddings import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.chains import RetrievalQA
from langchain import PromptTemplate
from langchain_text_splitters import (
Language,
RecursiveCharacterTextSplitter,
)
import pymupdf4llm
import pathlib
import time
from firecrawl import FirecrawlApp
import tempfile
# Models and parameters
embedding_model = "text-embedding-3-small"
llm_model = "gpt-4o-mini-2024-07-18"
llm = ChatOpenAI(model=llm_model, temperature=0)
# Hyperparameters
PDF_CHUNK_SIZE = 2048
PDF_CHUNK_OVERLAP = 512
WEB_CHUNK_SIZE = 2048
WEB_CHUNK_OVERLAP = 512
k = 5
system_prompt = """You are a helpful assistant designed to answer questions based on the provided context.
Using the context provided, please answer the user question as accurately and informatively as possible. If no relevant context is available, inform the user that you do not have the information needed to answer their question.
"""
def process_pdf(pdf_file):
# Create a temporary file to store the uploaded PDF
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
temp_file.write(pdf_file.read()) # Read the content of the uploaded PDF file
temp_file_path = temp_file.name
try:
md_text = pymupdf4llm.to_markdown(temp_file_path) # Process the PDF content
md_splitter = RecursiveCharacterTextSplitter.from_language(
language=Language.MARKDOWN, chunk_size=PDF_CHUNK_SIZE, chunk_overlap=PDF_CHUNK_OVERLAP
)
return md_splitter.create_documents([md_text])
finally:
# Clean up the temporary file
os.unlink(temp_file_path)
def create_combined_knowledge_base(all_text_chunks):
embeddings = OpenAIEmbeddings(model=embedding_model)
return FAISS.from_documents(all_text_chunks, embeddings)
def main():
st.title("Dex agent with Dynamic Knowledge Base")
all_text_chunks = []
st.sidebar.header("Select Knowledge Sources")
# Specify your PDF files and URLs here
pdf_files = ["bitcoin.pdf", "whitepaper-v3.pdf"] # Replace with actual paths
pdf_file_paths = [os.path.join(os.getcwd(), pdf_file) for pdf_file in pdf_files]
urls = ["https://www.coinbase.com/it/learn/crypto-basics/what-is-a-dex", "https://ethereum.org/en/whitepaper/"] # Replace with actual URLs
# Process PDF files
for pdf_file_path in pdf_file_paths:
with open(pdf_file_path, "rb") as pdf_file:
pdf_text_chunks = process_pdf(pdf_file)
for chunk in pdf_text_chunks:
chunk.metadata['source'] = pdf_file_path
all_text_chunks.extend(pdf_text_chunks)
# Scrape content from URLs
app = FirecrawlApp(api_key=os.getenv("FIRECRAWL_API_KEY"))
web_contents = {}
for url in urls:
try:
result = app.scrape_url(url)
web_contents[url] = result['markdown']
except Exception as e:
st.error(f"Error scraping URL {url}: {e}")
# Process the content of the scraped URLs
for url, content in web_contents.items():
webpage_chunks = RecursiveCharacterTextSplitter.from_language(
language=Language.MARKDOWN, chunk_size=WEB_CHUNK_SIZE, chunk_overlap=WEB_CHUNK_OVERLAP
).create_documents([content])
for chunk in webpage_chunks:
chunk.metadata['source'] = url
all_text_chunks.extend(webpage_chunks)
# Check if the FAISS index exists locally
current_dir = os.getcwd()
# Define the path to save the FAISS index within the current directory
faiss_index_path = os.path.join(current_dir, "faiss_index")
if os.path.exists(faiss_index_path):
# Load the existing FAISS index
embeddings = OpenAIEmbeddings(model=embedding_model)
knowledge_base = FAISS.load_local(faiss_index_path, embeddings, allow_dangerous_deserialization=True)
st.success("Knowledge base loaded successfully!")
else:
# Create and save the new FAISS index
knowledge_base = create_combined_knowledge_base(all_text_chunks)
knowledge_base.save_local(faiss_index_path)
st.success("Knowledge base created and saved successfully!")
# Store the knowledge base in session state to persist between interactions
st.session_state['knowledge_base'] = knowledge_base
# Allow users to ask questions
st.header("Ask a Question")
# Always show the "Get Answer" button, and input the question
question = st.text_input("Enter your question")
# Always display the button
if st.button("Get Answer"):
if question: # Proceed only if a question is entered
template = '''
%s
-------------------------------
Context: {context}
Question: {question}
Answer:
''' % (system_prompt)
prompt = PromptTemplate(
template=template,
input_variables=['context', 'question']
)
# Check if the knowledge base is loaded in session state
knowledge_base = st.session_state.get('knowledge_base')
if knowledge_base:
try:
qa_chain = RetrievalQA.from_chain_type(
llm,
retriever=knowledge_base.as_retriever(search_kwargs={"k": k}),
return_source_documents=True,
chain_type_kwargs={"prompt": prompt}
)
# Get the response from the QA chain
response = qa_chain.invoke({"query": question})
# Display the answer
st.write(f"**Answer:** {response['result']}")
with st.expander("Sources used"):
for doc in response['source_documents']:
st.write(f"**Source:** {doc.metadata['source']}")
st.write(f"**Content:** {doc.page_content}\n{'-'*40}")
except Exception as e:
st.error(f"An error occurred while fetching the answer: {e}")
else:
st.error("Knowledge base is not loaded. Please create or load the knowledge base.")
else:
st.warning("Please enter a question to get an answer.")
if __name__ == "__main__":
main()
|