|
import os |
|
from typing import Dict, List, Union |
|
|
|
import numpy as np |
|
import openai |
|
import pandas as pd |
|
import streamlit as st |
|
from langchain.document_loaders import TextLoader |
|
from langchain.embeddings.sentence_transformer import SentenceTransformerEmbeddings |
|
from langchain.text_splitter import CharacterTextSplitter |
|
from langchain.vectorstores import Chroma |
|
from scipy.spatial.distance import cosine |
|
|
|
openai.api_key = os.environ["OPENAI_API_KEY"] |
|
|
|
|
|
def call_chatgpt(prompt: str) -> str: |
|
""" |
|
Uses the OpenAI API to generate an AI response to a prompt. |
|
|
|
Args: |
|
prompt: A string representing the prompt to send to the OpenAI API. |
|
|
|
Returns: |
|
A string representing the AI's generated response. |
|
|
|
""" |
|
|
|
|
|
response = openai.Completion.create( |
|
model="gpt-3.5-turbo-instruct", |
|
prompt=prompt, |
|
temperature=0.5, |
|
max_tokens=500, |
|
top_p=1, |
|
frequency_penalty=0, |
|
presence_penalty=0, |
|
) |
|
|
|
|
|
ans = response.choices[0]["text"] |
|
|
|
|
|
return ans |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
from datasets import load_dataset |
|
import chromadb |
|
import string |
|
|
|
dataset = load_dataset("eagle0504/youthless-homeless-shelter-web-scrape-dataset-qa-formatted") |
|
client = chromadb.Client() |
|
random_number = np.random.randint(low=1e9, high=1e10) |
|
random_string = ''.join(np.random.choice(list(string.ascii_uppercase + string.digits), size=10)) |
|
combined_string = f"{random_number}{random_string}" |
|
collection = client.create_collection(combined_string) |
|
|
|
|
|
L = len(dataset["train"]['questions']) |
|
collection.add( |
|
ids=[str(i) for i in range(0, L)], |
|
documents=dataset["train"]['questions'], |
|
metadatas=[{"type": "support"} for _ in range(0, L)], |
|
) |
|
|
|
st.title("Youth Homelessness Chatbot") |
|
|
|
|
|
if "messages" not in st.session_state: |
|
st.session_state.messages = [] |
|
|
|
|
|
for message in st.session_state.messages: |
|
with st.chat_message(message["role"]): |
|
st.markdown(message["content"]) |
|
|
|
st.sidebar.markdown( |
|
r"""## Instructions: |
|
|
|
This is an app to help you navigate the website of YSA. The created the RAG-ready data [here](https://huggingface.co/datasets/eagle0504/youthless-homeless-shelter-web-scrape-dataset-qa-formatted) which consists of questions and answers that help the chatbot. |
|
|
|
Once entered a question, the system will search for relevant questions in the database and then produce an answer based on the context answers in the database with a distance score. The distance score represents how similar the user question is comparing with the question in the database. The smaller the distance score the more similar / relevant the database is at producing similar context. For hallucination cases, a viable strategy is to collect user preferences and update the database. |
|
""") |
|
|
|
clear_button = st.sidebar.button("Clear Conversation", key="clear") |
|
|
|
if clear_button: |
|
st.session_state.messages = [] |
|
|
|
|
|
if prompt := st.chat_input("Tell me about YSA"): |
|
|
|
st.chat_message("user").markdown(prompt) |
|
|
|
st.session_state.messages.append({"role": "user", "content": prompt}) |
|
|
|
question = prompt |
|
|
|
with st.spinner("Wait for it..."): |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
results = collection.query( |
|
query_texts=question, |
|
n_results=5 |
|
) |
|
idx = results["ids"][0] |
|
idx = [int(i) for i in idx] |
|
ref = pd.DataFrame( |
|
{ |
|
"idx": idx, |
|
"question": [dataset["train"]['questions'][i] for i in idx], |
|
"answers": [dataset["train"]['answers'][i] for i in idx], |
|
"distances": results["distances"][0] |
|
} |
|
) |
|
special_threshold = 0.3 |
|
filtered_ref = ref[ref["distances"] < special_threshold] |
|
if filtered_ref.shape[0] > 0: |
|
st.success("There are highly relevant information in our database.") |
|
ref_from_db_search = filtered_ref["answers"] |
|
final_ref = filtered_ref |
|
else: |
|
st.warning("The database may not have relevant information to help your question so please be aware of hallucinations.") |
|
ref_from_db_search = ref["answers"] |
|
final_ref = ref |
|
|
|
engineered_prompt = f""" |
|
Based on the context: {ref_from_db_search}, |
|
answer the user question: {question}. |
|
Answer the question directly (don't say "based on the context, ...") |
|
""" |
|
|
|
answer = call_chatgpt(engineered_prompt) |
|
response = answer |
|
|
|
|
|
with st.chat_message("assistant"): |
|
with st.spinner("Wait for it..."): |
|
st.markdown(response) |
|
with st.expander("See reference:"): |
|
st.table(ref) |
|
|
|
st.session_state.messages.append({"role": "assistant", "content": response}) |
|
st.session_state.messages.append( |
|
{"role": "assistant", "content": ref.to_json()} |
|
) |
|
|