Spaces:
Sleeping
Sleeping
Zwea Htet commited on
Commit ·
f5254ad
1
Parent(s): b1a958d
integrated open source llms
Browse files- app.py +7 -16
- models/llamaCustom.py +52 -13
- models/llms.py +47 -31
- pages/llama_custom_demo.py +96 -47
- utils/util.py +7 -3
app.py
CHANGED
|
@@ -29,22 +29,13 @@ st.set_page_config(page_title="RegBotBeta", page_icon="📜🤖")
|
|
| 29 |
st.title("Welcome to RegBotBeta2.0")
|
| 30 |
st.header("Powered by `LlamaIndex🦙`, `Langchain🦜🔗 ` and `OpenAI API`")
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
# isKeyValid = False
|
| 40 |
-
# if openai_api_key:
|
| 41 |
-
# resp = validate(openai_api_key)
|
| 42 |
-
# if "error" in resp.json():
|
| 43 |
-
# st.info("Invalid Token! Try again.")
|
| 44 |
-
# else:
|
| 45 |
-
# st.info("Success")
|
| 46 |
-
# st.session_state.openai_api_key = openai_api_key
|
| 47 |
-
# isKeyValid = True
|
| 48 |
|
| 49 |
uploaded_files = st.file_uploader(
|
| 50 |
"Upload Files",
|
|
|
|
| 29 |
st.title("Welcome to RegBotBeta2.0")
|
| 30 |
st.header("Powered by `LlamaIndex🦙`, `Langchain🦜🔗 ` and `OpenAI API`")
|
| 31 |
|
| 32 |
+
|
| 33 |
+
def init_session_state():
|
| 34 |
+
if "huggingface_token" not in st.session_state:
|
| 35 |
+
st.session_state.huggingface_token = ""
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
init_session_state()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
uploaded_files = st.file_uploader(
|
| 41 |
"Upload Files",
|
models/llamaCustom.py
CHANGED
|
@@ -58,7 +58,43 @@ Reference:
|
|
| 58 |
[END_FORMAT]
|
| 59 |
"""
|
| 60 |
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
The following is a friendly conversation between a user and an AI assistant.
|
| 63 |
The assistant is talkative and provides lots of specific details from its context.
|
| 64 |
If the assistant does not know the answer to a question, it truthfully says it
|
|
@@ -73,7 +109,7 @@ Include references to the specific sections of the documents that support your a
|
|
| 73 |
Answer "don't know" if not present in the document.
|
| 74 |
"""
|
| 75 |
|
| 76 |
-
|
| 77 |
Given the following conversation between a user and an AI assistant and a follow up question from user,
|
| 78 |
rephrase the follow up question to be a standalone question.
|
| 79 |
|
|
@@ -144,21 +180,24 @@ class LlamaCustom:
|
|
| 144 |
self.index = index
|
| 145 |
self.chat_mode = "condense_plus_context"
|
| 146 |
self.memory = ChatMemoryBuffer.from_defaults()
|
|
|
|
| 147 |
|
| 148 |
def get_response(self, query_str: str, chat_history: List[ChatMessage]):
|
| 149 |
# https://docs.llamaindex.ai/en/stable/module_guides/deploying/chat_engines/
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
chat_mode=self.chat_mode,
|
| 155 |
-
memory=self.memory,
|
| 156 |
-
context_prompt=CONTEXT_PROMPT_TEMPLATE,
|
| 157 |
-
condense_prompt=CONDENSE_PROMPT_TEMPLATE,
|
| 158 |
-
# verbose=True,
|
| 159 |
)
|
| 160 |
-
#
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
return str(response)
|
| 164 |
|
|
|
|
| 58 |
[END_FORMAT]
|
| 59 |
"""
|
| 60 |
|
| 61 |
+
# query engine templates
|
| 62 |
+
QUERY_ENGINE_QA_TEMPLATE = """
|
| 63 |
+
We have provided context information below:
|
| 64 |
+
[CONTEXT]
|
| 65 |
+
{context_str}
|
| 66 |
+
[END_CONTEXT]
|
| 67 |
+
Given this information, please answer the following question:
|
| 68 |
+
[QUESTION]
|
| 69 |
+
{query_str}
|
| 70 |
+
[END_QUESTION]
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
QUERY_ENGINE_REFINE_TEMPLATE = """
|
| 74 |
+
The original query is as follows:
|
| 75 |
+
[QUESTION]
|
| 76 |
+
{query_str}
|
| 77 |
+
[END_QUESTION]
|
| 78 |
+
|
| 79 |
+
We have providec an existing answer:
|
| 80 |
+
[ANSWER]
|
| 81 |
+
{existing_answer}
|
| 82 |
+
[END_ANSWER]
|
| 83 |
+
|
| 84 |
+
We have the opportunity to refine the existing answer (only if needed) with some more
|
| 85 |
+
context below.
|
| 86 |
+
[CONTEXT]
|
| 87 |
+
{context_msg}
|
| 88 |
+
[END_CONTEXT]
|
| 89 |
+
|
| 90 |
+
Given the new context, refine the original answer to include more details like references \
|
| 91 |
+
to the specific sections of the documents that support your answer.
|
| 92 |
+
|
| 93 |
+
Refined Answer:
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
CHAT_ENGINE_CONTEXT_PROMPT_TEMPLATE = """
|
| 98 |
The following is a friendly conversation between a user and an AI assistant.
|
| 99 |
The assistant is talkative and provides lots of specific details from its context.
|
| 100 |
If the assistant does not know the answer to a question, it truthfully says it
|
|
|
|
| 109 |
Answer "don't know" if not present in the document.
|
| 110 |
"""
|
| 111 |
|
| 112 |
+
CHAT_ENGINE_CONDENSE_PROMPT_TEMPLATE = """
|
| 113 |
Given the following conversation between a user and an AI assistant and a follow up question from user,
|
| 114 |
rephrase the follow up question to be a standalone question.
|
| 115 |
|
|
|
|
| 180 |
self.index = index
|
| 181 |
self.chat_mode = "condense_plus_context"
|
| 182 |
self.memory = ChatMemoryBuffer.from_defaults()
|
| 183 |
+
self.verbose = True
|
| 184 |
|
| 185 |
def get_response(self, query_str: str, chat_history: List[ChatMessage]):
|
| 186 |
# https://docs.llamaindex.ai/en/stable/module_guides/deploying/chat_engines/
|
| 187 |
+
query_engine = self.index.as_query_engine(
|
| 188 |
+
text_qa_template=PromptTemplate(QUERY_ENGINE_QA_TEMPLATE),
|
| 189 |
+
refine_template=PromptTemplate(QUERY_ENGINE_REFINE_TEMPLATE),
|
| 190 |
+
verbose=self.verbose,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
)
|
| 192 |
+
# chat_engine = self.index.as_chat_engine(
|
| 193 |
+
# chat_mode=self.chat_mode,
|
| 194 |
+
# memory=self.memory,
|
| 195 |
+
# context_prompt=CHAT_ENGINE_CONTEXT_PROMPT_TEMPLATE,
|
| 196 |
+
# condense_prompt=CHAT_ENGINE_CONDENSE_PROMPT_TEMPLATE,
|
| 197 |
+
# # verbose=True,
|
| 198 |
+
# )
|
| 199 |
+
response = query_engine.query(query_str)
|
| 200 |
+
# response = chat_engine.chat(message=query_str, chat_history=chat_history)
|
| 201 |
|
| 202 |
return str(response)
|
| 203 |
|
models/llms.py
CHANGED
|
@@ -1,16 +1,13 @@
|
|
| 1 |
-
from llama_index.llms.huggingface import HuggingFaceLLM
|
| 2 |
from llama_index.llms.openai import OpenAI
|
| 3 |
-
|
|
|
|
| 4 |
from dotenv import load_dotenv
|
| 5 |
import os
|
|
|
|
| 6 |
|
| 7 |
load_dotenv()
|
| 8 |
|
| 9 |
-
# llm_mixtral_8x7b = HuggingFaceInferenceAPI(
|
| 10 |
-
# model_name="mistralai/Mixtral-8x7B-Instruct-v0.1",
|
| 11 |
-
# token=os.getenv("HUGGINGFACE_API_TOKEN"),
|
| 12 |
-
# )
|
| 13 |
-
|
| 14 |
# download the model from the Hugging Face Hub and run it locally
|
| 15 |
# llm_mixtral_8x7b = HuggingFaceLLM(model_name="mistralai/Mixtral-8x7B-Instruct-v0.1")
|
| 16 |
|
|
@@ -19,27 +16,46 @@ load_dotenv()
|
|
| 19 |
# token=os.getenv("HUGGINGFACE_API_TOKEN"),
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from llama_index.llms.huggingface import HuggingFaceLLM, HuggingFaceInferenceAPI
|
| 2 |
from llama_index.llms.openai import OpenAI
|
| 3 |
+
from llama_index.llms.replicate import Replicate
|
| 4 |
+
|
| 5 |
from dotenv import load_dotenv
|
| 6 |
import os
|
| 7 |
+
import streamlit as st
|
| 8 |
|
| 9 |
load_dotenv()
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
# download the model from the Hugging Face Hub and run it locally
|
| 12 |
# llm_mixtral_8x7b = HuggingFaceLLM(model_name="mistralai/Mixtral-8x7B-Instruct-v0.1")
|
| 13 |
|
|
|
|
| 16 |
# token=os.getenv("HUGGINGFACE_API_TOKEN"),
|
| 17 |
# )
|
| 18 |
|
| 19 |
+
# dict = {"source": "model_name"}
|
| 20 |
+
integrated_llms = {
|
| 21 |
+
"gpt-3.5-turbo-0125": "openai",
|
| 22 |
+
"meta/llama-2-13b-chat": "replicate",
|
| 23 |
+
"mistralai/Mistral-7B-Instruct-v0.2": "huggingface",
|
| 24 |
+
# "mistralai/Mixtral-8x7B-v0.1": "huggingface", # 93 GB model
|
| 25 |
+
# "meta-llama/Meta-Llama-3-8B": "huggingface", # too large >10G for llama index hf interference to load
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def load_llm(model_name: str, source: str = "huggingface"):
|
| 30 |
+
print("model_name: ", model_name, "source: ", source)
|
| 31 |
+
if integrated_llms.get(model_name) is None:
|
| 32 |
+
return None
|
| 33 |
+
try:
|
| 34 |
+
if source.startswith("openai"):
|
| 35 |
+
llm_gpt_3_5_turbo_0125 = OpenAI(
|
| 36 |
+
model=model_name,
|
| 37 |
+
api_key=st.session_state.openai_api_key,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
return llm_gpt_3_5_turbo_0125
|
| 41 |
+
|
| 42 |
+
elif source.startswith("replicate"):
|
| 43 |
+
llm_llama_13b_v2_replicate = Replicate(
|
| 44 |
+
model=model_name,
|
| 45 |
+
is_chat_model=True,
|
| 46 |
+
additional_kwargs={"max_new_tokens": 250},
|
| 47 |
+
prompt_key=st.session_state.replicate_api_token,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
return llm_llama_13b_v2_replicate
|
| 51 |
+
|
| 52 |
+
elif source.startswith("huggingface"):
|
| 53 |
+
llm_mixtral_8x7b = HuggingFaceInferenceAPI(
|
| 54 |
+
model_name=model_name,
|
| 55 |
+
token=st.session_state.hf_token,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
return llm_mixtral_8x7b
|
| 59 |
+
|
| 60 |
+
except Exception as e:
|
| 61 |
+
print(e)
|
pages/llama_custom_demo.py
CHANGED
|
@@ -1,18 +1,16 @@
|
|
| 1 |
-
import random
|
| 2 |
-
import time
|
| 3 |
import streamlit as st
|
| 4 |
import os
|
| 5 |
import pathlib
|
| 6 |
from typing import List
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
)
|
| 11 |
from models.embeddings import hf_embed_model, openai_embed_model
|
| 12 |
from models.llamaCustom import LlamaCustom
|
| 13 |
-
|
| 14 |
-
# from models.llamaCustom import LlamaCustom
|
| 15 |
from utils.chatbox import show_previous_messages, show_chat_input
|
|
|
|
|
|
|
|
|
|
| 16 |
from llama_index.core import (
|
| 17 |
SimpleDirectoryReader,
|
| 18 |
Document,
|
|
@@ -24,21 +22,18 @@ from llama_index.core import (
|
|
| 24 |
from llama_index.core.memory import ChatMemoryBuffer
|
| 25 |
from llama_index.core.base.llms.types import ChatMessage
|
| 26 |
|
|
|
|
|
|
|
|
|
|
| 27 |
SAVE_DIR = "uploaded_files"
|
| 28 |
VECTOR_STORE_DIR = "vectorStores"
|
|
|
|
| 29 |
|
| 30 |
# global
|
| 31 |
Settings.embed_model = hf_embed_model
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
# "mistral/mixtral": llm_mixtral_8x7b,
|
| 36 |
-
# "meta-llama/Llama-2-7b-chat-hf": llm_llama_2_7b_chat,
|
| 37 |
-
# "openai/gpt-3.5-turbo": llm_gpt_3_5_turbo,
|
| 38 |
-
"openai/gpt-3.5-turbo-0125": llm_gpt_3_5_turbo_0125,
|
| 39 |
-
# "openai/gpt-4-0125-preview": llm_gpt_4_0125,
|
| 40 |
-
# "meta/llama-2-13b-chat": llm_llama_13b_v2_replicate,
|
| 41 |
-
}
|
| 42 |
|
| 43 |
|
| 44 |
def init_session_state():
|
|
@@ -56,6 +51,15 @@ def init_session_state():
|
|
| 56 |
if "llama_custom" not in st.session_state:
|
| 57 |
st.session_state.llama_custom = None
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
# @st.cache_resource
|
| 61 |
def index_docs(
|
|
@@ -68,9 +72,6 @@ def index_docs(
|
|
| 68 |
storage_context = StorageContext.from_defaults(persist_dir=index_path)
|
| 69 |
index = load_index_from_storage(storage_context=storage_context)
|
| 70 |
|
| 71 |
-
# test the index
|
| 72 |
-
index.as_query_engine().query("What is the capital of France?")
|
| 73 |
-
|
| 74 |
else:
|
| 75 |
reader = SimpleDirectoryReader(input_files=[f"{SAVE_DIR}/{filename}"])
|
| 76 |
docs = reader.load_data(show_progress=True)
|
|
@@ -84,12 +85,62 @@ def index_docs(
|
|
| 84 |
|
| 85 |
except Exception as e:
|
| 86 |
print(f"Error: {e}")
|
| 87 |
-
|
| 88 |
return index
|
| 89 |
|
| 90 |
|
| 91 |
-
def
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
|
| 95 |
init_session_state()
|
|
@@ -101,43 +152,41 @@ st.header("Llama Index with Custom LLM Demo")
|
|
| 101 |
tab1, tab2 = st.tabs(["Config", "Chat"])
|
| 102 |
|
| 103 |
with tab1:
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
if selected_llm_name.startswith("openai"):
|
| 110 |
-
# ask for the api key
|
| 111 |
-
if st.secrets.get("OPENAI_API_KEY") is None:
|
| 112 |
-
# st.stop()
|
| 113 |
-
st.info("OpenAI API Key not found in secrets. Please enter it below.")
|
| 114 |
-
st.secrets["OPENAI_API_KEY"] = st.text_input(
|
| 115 |
-
"OpenAI API Key",
|
| 116 |
-
type="password",
|
| 117 |
-
help="Get your API key from https://platform.openai.com/account/api-keys",
|
| 118 |
-
)
|
| 119 |
|
| 120 |
-
|
| 121 |
-
label="Choose a file to chat with: ", options=os.listdir(SAVE_DIR)
|
| 122 |
-
)
|
| 123 |
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
st.write("Loading Model ...")
|
| 127 |
-
llama_llm = load_llm(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
Settings.llm = llama_llm
|
| 129 |
|
| 130 |
st.write("Processing Data ...")
|
| 131 |
index = index_docs(selected_file)
|
| 132 |
-
if index is None:
|
| 133 |
-
st.error("Failed to index the documents.")
|
| 134 |
-
st.stop()
|
| 135 |
|
| 136 |
st.write("Finishing Up ...")
|
| 137 |
llama_custom = LlamaCustom(model_name=selected_llm_name, index=index)
|
| 138 |
st.session_state.llama_custom = llama_custom
|
| 139 |
|
| 140 |
status.update(label="Ready to query!", state="complete", expanded=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
with tab2:
|
| 143 |
messages_container = st.container(height=300)
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import os
|
| 3 |
import pathlib
|
| 4 |
from typing import List
|
| 5 |
+
|
| 6 |
+
# local imports
|
| 7 |
+
from models.llms import load_llm, integrated_llms
|
|
|
|
| 8 |
from models.embeddings import hf_embed_model, openai_embed_model
|
| 9 |
from models.llamaCustom import LlamaCustom
|
|
|
|
|
|
|
| 10 |
from utils.chatbox import show_previous_messages, show_chat_input
|
| 11 |
+
from utils.util import validate_openai_api_key
|
| 12 |
+
|
| 13 |
+
# llama_index
|
| 14 |
from llama_index.core import (
|
| 15 |
SimpleDirectoryReader,
|
| 16 |
Document,
|
|
|
|
| 22 |
from llama_index.core.memory import ChatMemoryBuffer
|
| 23 |
from llama_index.core.base.llms.types import ChatMessage
|
| 24 |
|
| 25 |
+
# huggingface
|
| 26 |
+
from huggingface_hub import HfApi
|
| 27 |
+
|
| 28 |
SAVE_DIR = "uploaded_files"
|
| 29 |
VECTOR_STORE_DIR = "vectorStores"
|
| 30 |
+
HF_REPO_ID = "zhtet/RegBotBeta"
|
| 31 |
|
| 32 |
# global
|
| 33 |
Settings.embed_model = hf_embed_model
|
| 34 |
|
| 35 |
+
# huggingface api
|
| 36 |
+
hf_api = HfApi()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
def init_session_state():
|
|
|
|
| 51 |
if "llama_custom" not in st.session_state:
|
| 52 |
st.session_state.llama_custom = None
|
| 53 |
|
| 54 |
+
if "openai_api_key" not in st.session_state:
|
| 55 |
+
st.session_state.openai_api_key = ""
|
| 56 |
+
|
| 57 |
+
if "replicate_api_token" not in st.session_state:
|
| 58 |
+
st.session_state.replicate_api_token = ""
|
| 59 |
+
|
| 60 |
+
if "hf_token" not in st.session_state:
|
| 61 |
+
st.session_state.hf_token = ""
|
| 62 |
+
|
| 63 |
|
| 64 |
# @st.cache_resource
|
| 65 |
def index_docs(
|
|
|
|
| 72 |
storage_context = StorageContext.from_defaults(persist_dir=index_path)
|
| 73 |
index = load_index_from_storage(storage_context=storage_context)
|
| 74 |
|
|
|
|
|
|
|
|
|
|
| 75 |
else:
|
| 76 |
reader = SimpleDirectoryReader(input_files=[f"{SAVE_DIR}/{filename}"])
|
| 77 |
docs = reader.load_data(show_progress=True)
|
|
|
|
| 85 |
|
| 86 |
except Exception as e:
|
| 87 |
print(f"Error: {e}")
|
| 88 |
+
raise e
|
| 89 |
return index
|
| 90 |
|
| 91 |
|
| 92 |
+
def check_api_key(model_name: str, source: str):
|
| 93 |
+
if source.startswith("openai"):
|
| 94 |
+
if not st.session_state.openai_api_key:
|
| 95 |
+
with st.expander("OpenAI API Key", expanded=True):
|
| 96 |
+
openai_api_key = st.text_input(
|
| 97 |
+
label="Enter your OpenAI API Key:",
|
| 98 |
+
type="password",
|
| 99 |
+
help="Get your key from https://platform.openai.com/account/api-keys",
|
| 100 |
+
value=st.session_state.openai_api_key,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
if openai_api_key and st.spinner("Validating OpenAI API Key ..."):
|
| 104 |
+
result = validate_openai_api_key(openai_api_key)
|
| 105 |
+
if result["status"] == "success":
|
| 106 |
+
st.session_state.openai_api_key = openai_api_key
|
| 107 |
+
st.success(result["message"])
|
| 108 |
+
else:
|
| 109 |
+
st.error(result["message"])
|
| 110 |
+
st.info("You can still select a different model to proceed.")
|
| 111 |
+
st.stop()
|
| 112 |
+
|
| 113 |
+
elif source.startswith("replicate"):
|
| 114 |
+
if not st.session_state.replicate_api_token:
|
| 115 |
+
with st.expander("Replicate API Token", expanded=True):
|
| 116 |
+
replicate_api_token = st.text_input(
|
| 117 |
+
label="Enter your Replicate API Token:",
|
| 118 |
+
type="password",
|
| 119 |
+
help="Get your key from https://replicate.ai/account",
|
| 120 |
+
value=st.session_state.replicate_api_token,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
# TODO: need to validate the token
|
| 124 |
+
|
| 125 |
+
if replicate_api_token:
|
| 126 |
+
st.session_state.replicate_api_token = replicate_api_token
|
| 127 |
+
# set the environment variable
|
| 128 |
+
os.environ["REPLICATE_API_TOKEN"] = replicate_api_token
|
| 129 |
+
|
| 130 |
+
elif source.startswith("huggingface"):
|
| 131 |
+
if not st.session_state.hf_token:
|
| 132 |
+
with st.expander("Hugging Face Token", expanded=True):
|
| 133 |
+
hf_token = st.text_input(
|
| 134 |
+
label="Enter your Hugging Face Token:",
|
| 135 |
+
type="password",
|
| 136 |
+
help="Get your key from https://huggingface.co/settings/token",
|
| 137 |
+
value=st.session_state.hf_token,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
if hf_token:
|
| 141 |
+
st.session_state.hf_token = hf_token
|
| 142 |
+
# set the environment variable
|
| 143 |
+
os.environ["HF_TOKEN"] = hf_token
|
| 144 |
|
| 145 |
|
| 146 |
init_session_state()
|
|
|
|
| 152 |
tab1, tab2 = st.tabs(["Config", "Chat"])
|
| 153 |
|
| 154 |
with tab1:
|
| 155 |
+
selected_llm_name = st.selectbox(
|
| 156 |
+
label="Select a model:",
|
| 157 |
+
options=[f"{key} | {value}" for key, value in integrated_llms.items()],
|
| 158 |
+
)
|
| 159 |
+
model_name, source = selected_llm_name.split("|")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
+
check_api_key(model_name=model_name.strip(), source=source.strip())
|
|
|
|
|
|
|
| 162 |
|
| 163 |
+
selected_file = st.selectbox(
|
| 164 |
+
label="Choose a file to chat with: ", options=os.listdir(SAVE_DIR)
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
if st.button("Submit", key="submit", help="Submit the form"):
|
| 168 |
+
with st.status("Loading ...", expanded=True) as status:
|
| 169 |
+
try:
|
| 170 |
st.write("Loading Model ...")
|
| 171 |
+
llama_llm = load_llm(
|
| 172 |
+
model_name=model_name.strip(), source=source.strip()
|
| 173 |
+
)
|
| 174 |
+
if llama_llm is None:
|
| 175 |
+
raise ValueError("Model not found!")
|
| 176 |
Settings.llm = llama_llm
|
| 177 |
|
| 178 |
st.write("Processing Data ...")
|
| 179 |
index = index_docs(selected_file)
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
st.write("Finishing Up ...")
|
| 182 |
llama_custom = LlamaCustom(model_name=selected_llm_name, index=index)
|
| 183 |
st.session_state.llama_custom = llama_custom
|
| 184 |
|
| 185 |
status.update(label="Ready to query!", state="complete", expanded=False)
|
| 186 |
+
except Exception as e:
|
| 187 |
+
status.update(label="Error!", state="error", expanded=False)
|
| 188 |
+
st.error(f"Error: {e}")
|
| 189 |
+
st.stop()
|
| 190 |
|
| 191 |
with tab2:
|
| 192 |
messages_container = st.container(height=300)
|
utils/util.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import requests
|
|
|
|
| 2 |
|
| 3 |
-
|
| 4 |
-
def validate(token: str):
|
| 5 |
api_endpoint = "https://api.openai.com/v1/chat/completions"
|
| 6 |
api_key = token
|
| 7 |
|
|
@@ -12,4 +12,8 @@ def validate(token: str):
|
|
| 12 |
data = {"model": "gpt-3.5-turbo", "messages": messages}
|
| 13 |
|
| 14 |
response = requests.post(api_endpoint, json=data, headers=headers)
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import requests
|
| 2 |
+
from typing import Dict
|
| 3 |
|
| 4 |
+
def validate_openai_api_key(token: str) -> Dict[str, str]:
|
|
|
|
| 5 |
api_endpoint = "https://api.openai.com/v1/chat/completions"
|
| 6 |
api_key = token
|
| 7 |
|
|
|
|
| 12 |
data = {"model": "gpt-3.5-turbo", "messages": messages}
|
| 13 |
|
| 14 |
response = requests.post(api_endpoint, json=data, headers=headers)
|
| 15 |
+
|
| 16 |
+
if response.status_code == 200:
|
| 17 |
+
return {"status": "success", "message": "API key is valid"}
|
| 18 |
+
else:
|
| 19 |
+
return {"status": "error", "message": response.json()["error"]["message"]}
|