app.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import os
  2. from embedchain import Pipeline as App
  3. import streamlit as st
  4. with st.sidebar:
  5. huggingface_access_token = st.text_input("Hugging face Token", key="chatbot_api_key", type="password")
  6. "[Get Hugging Face Access Token](https://huggingface.co/settings/tokens)"
  7. "[View the source code](https://github.com/embedchain/examples/mistral-streamlit)"
  8. st.title("💬 Chatbot")
  9. st.caption("🚀 An Embedchain app powered by Mistral!")
  10. if "messages" not in st.session_state:
  11. st.session_state.messages = [
  12. {
  13. "role": "assistant",
  14. "content": """
  15. Hi! I'm a chatbot. I can answer questions and learn new things!\n
  16. Ask me anything and if you want me to learn something do `/add <source>`.\n
  17. I can learn mostly everything. :)
  18. """,
  19. }
  20. ]
  21. for message in st.session_state.messages:
  22. with st.chat_message(message["role"]):
  23. st.markdown(message["content"])
  24. if prompt := st.chat_input("Ask me anything!"):
  25. if not st.session_state.chatbot_api_key:
  26. st.error("Please enter your Hugging Face Access Token")
  27. st.stop()
  28. os.environ["HUGGINGFACE_ACCESS_TOKEN"] = st.session_state.chatbot_api_key
  29. app = App.from_config(config_path="config.yaml")
  30. if prompt.startswith("/add"):
  31. with st.chat_message("user"):
  32. st.markdown(prompt)
  33. st.session_state.messages.append({"role": "user", "content": prompt})
  34. prompt = prompt.replace("/add", "").strip()
  35. with st.chat_message("assistant"):
  36. message_placeholder = st.empty()
  37. message_placeholder.markdown("Adding to knowledge base...")
  38. app.add(prompt)
  39. message_placeholder.markdown(f"Added {prompt} to knowledge base!")
  40. st.session_state.messages.append({"role": "assistant", "content": f"Added {prompt} to knowledge base!"})
  41. st.stop()
  42. with st.chat_message("user"):
  43. st.markdown(prompt)
  44. st.session_state.messages.append({"role": "user", "content": prompt})
  45. with st.chat_message("assistant"):
  46. msg_placeholder = st.empty()
  47. msg_placeholder.markdown("Thinking...")
  48. full_response = ""
  49. for response in app.chat(prompt):
  50. msg_placeholder.empty()
  51. full_response += response
  52. msg_placeholder.markdown(full_response)
  53. st.session_state.messages.append({"role": "assistant", "content": full_response})