app.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. import os
  2. import queue
  3. import re
  4. import tempfile
  5. import threading
  6. import streamlit as st
  7. from embedchain import App
  8. from embedchain.config import BaseLlmConfig
  9. from embedchain.helpers.callbacks import (StreamingStdOutCallbackHandlerYield,
  10. generate)
  11. def embedchain_bot(db_path, api_key):
  12. return App.from_config(
  13. config={
  14. "llm": {
  15. "provider": "openai",
  16. "config": {
  17. "model": "gpt-3.5-turbo-1106",
  18. "temperature": 0.5,
  19. "max_tokens": 1000,
  20. "top_p": 1,
  21. "stream": True,
  22. "api_key": api_key,
  23. },
  24. },
  25. "vectordb": {
  26. "provider": "chroma",
  27. "config": {"collection_name": "chat-pdf", "dir": db_path, "allow_reset": True},
  28. },
  29. "embedder": {"provider": "openai", "config": {"api_key": api_key}},
  30. "chunker": {"chunk_size": 2000, "chunk_overlap": 0, "length_function": "len"},
  31. }
  32. )
  33. def get_db_path():
  34. tmpdirname = tempfile.mkdtemp()
  35. return tmpdirname
  36. def get_ec_app(api_key):
  37. if "app" in st.session_state:
  38. print("Found app in session state")
  39. app = st.session_state.app
  40. else:
  41. print("Creating app")
  42. db_path = get_db_path()
  43. app = embedchain_bot(db_path, api_key)
  44. st.session_state.app = app
  45. return app
  46. with st.sidebar:
  47. openai_access_token = st.text_input("OpenAI API Key", key="api_key", type="password")
  48. "WE DO NOT STORE YOUR OPENAI KEY."
  49. "Just paste your OpenAI API key here and we'll use it to power the chatbot. [Get your OpenAI API key](https://platform.openai.com/api-keys)" # noqa: E501
  50. if st.session_state.api_key:
  51. app = get_ec_app(st.session_state.api_key)
  52. pdf_files = st.file_uploader("Upload your PDF files", accept_multiple_files=True, type="pdf")
  53. add_pdf_files = st.session_state.get("add_pdf_files", [])
  54. for pdf_file in pdf_files:
  55. file_name = pdf_file.name
  56. if file_name in add_pdf_files:
  57. continue
  58. try:
  59. if not st.session_state.api_key:
  60. st.error("Please enter your OpenAI API Key")
  61. st.stop()
  62. temp_file_name = None
  63. with tempfile.NamedTemporaryFile(mode="wb", delete=False, prefix=file_name, suffix=".pdf") as f:
  64. f.write(pdf_file.getvalue())
  65. temp_file_name = f.name
  66. if temp_file_name:
  67. st.markdown(f"Adding {file_name} to knowledge base...")
  68. app.add(temp_file_name, data_type="pdf_file")
  69. st.markdown("")
  70. add_pdf_files.append(file_name)
  71. os.remove(temp_file_name)
  72. st.session_state.messages.append({"role": "assistant", "content": f"Added {file_name} to knowledge base!"})
  73. except Exception as e:
  74. st.error(f"Error adding {file_name} to knowledge base: {e}")
  75. st.stop()
  76. st.session_state["add_pdf_files"] = add_pdf_files
  77. st.title("📄 Embedchain - Chat with PDF")
  78. styled_caption = '<p style="font-size: 17px; color: #aaa;">🚀 An <a href="https://github.com/embedchain/embedchain">Embedchain</a> app powered by OpenAI!</p>' # noqa: E501
  79. st.markdown(styled_caption, unsafe_allow_html=True)
  80. if "messages" not in st.session_state:
  81. st.session_state.messages = [
  82. {
  83. "role": "assistant",
  84. "content": """
  85. Hi! I'm chatbot powered by Embedchain, which can answer questions about your pdf documents.\n
  86. Upload your pdf documents here and I'll answer your questions about them!
  87. """,
  88. }
  89. ]
  90. for message in st.session_state.messages:
  91. with st.chat_message(message["role"]):
  92. st.markdown(message["content"])
  93. if prompt := st.chat_input("Ask me anything!"):
  94. if not st.session_state.api_key:
  95. st.error("Please enter your OpenAI API Key", icon="🤖")
  96. st.stop()
  97. app = get_ec_app(st.session_state.api_key)
  98. with st.chat_message("user"):
  99. st.session_state.messages.append({"role": "user", "content": prompt})
  100. st.markdown(prompt)
  101. with st.chat_message("assistant"):
  102. msg_placeholder = st.empty()
  103. msg_placeholder.markdown("Thinking...")
  104. full_response = ""
  105. q = queue.Queue()
  106. def app_response(result):
  107. llm_config = app.llm.config.as_dict()
  108. llm_config["callbacks"] = [StreamingStdOutCallbackHandlerYield(q=q)]
  109. config = BaseLlmConfig(**llm_config)
  110. answer, citations = app.chat(prompt, config=config, citations=True)
  111. result["answer"] = answer
  112. result["citations"] = citations
  113. results = {}
  114. thread = threading.Thread(target=app_response, args=(results,))
  115. thread.start()
  116. for answer_chunk in generate(q):
  117. full_response += answer_chunk
  118. msg_placeholder.markdown(full_response)
  119. thread.join()
  120. answer, citations = results["answer"], results["citations"]
  121. if citations:
  122. full_response += "\n\n**Sources**:\n"
  123. sources = []
  124. for i, citation in enumerate(citations):
  125. source = citation[1]["url"]
  126. pattern = re.compile(r"([^/]+)\.[^\.]+\.pdf$")
  127. match = pattern.search(source)
  128. if match:
  129. source = match.group(1) + ".pdf"
  130. sources.append(source)
  131. sources = list(set(sources))
  132. for source in sources:
  133. full_response += f"- {source}\n"
  134. msg_placeholder.markdown(full_response)
  135. print("Answer: ", full_response)
  136. st.session_state.messages.append({"role": "assistant", "content": full_response})