scouter / app.py
VoidZeroe's picture
Update app.py
9144a20
Raw History Blame Contribute Delete
8.59 kB
import gradio as gr
import random
import time
import os
import requests
from langchain.document_loaders import TextLoader #for textfiles
from langchain.text_splitter import CharacterTextSplitter #text splitter
from langchain.embeddings.openai import OpenAIEmbeddings #for using HugginFace models
from langchain.vectorstores import FAISS #facebook vectorizationfrom langchain.chains.question_answering import load_qa_chain
from langchain.chains.question_answering import load_qa_chain
from langchain import OpenAI
from langchain.document_loaders import UnstructuredPDFLoader #load pdf
from langchain.indexes import VectorstoreIndexCreator #vectorize db index with chromadb
from langchain.chains import RetrievalQAWithSourcesChain
from langchain.document_loaders import DirectoryLoader
from langchain.document_loaders import UnstructuredFileLoader
from langchain.document_loaders.csv_loader import CSVLoader
from langchain.document_loaders import TextLoader
from langchain.document_loaders import Docx2txtLoader
from langchain.vectorstores import FAISS
from langchain.callbacks.base import BaseCallbackHandler
from openai.error import APIError
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.chat_models import ChatOpenAI
from langchain.vectorstores import FAISS
from langchain.chains import LLMChain
from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT
from langchain.prompts import MessagesPlaceholder
from langchain.callbacks.base import BaseCallbackHandler
from langchain.prompts import PromptTemplate
from langchain.prompts import ChatPromptTemplate
openAI_embeddings = OpenAIEmbeddings(openai_api_key = "sk***2T")
loader = CSVLoader(file_path='survey.csv', csv_args={
'delimiter': ',',
'quotechar': '"',
'fieldnames': ['Question', 'Answer']
})
docs = loader.load()
char_text_splitter = CharacterTextSplitter(chunk_size = 500, chunk_overlap = 15)
docs = char_text_splitter.split_documents(docs)
surveydb = FAISS.from_documents(docs, openAI_embeddings)
loader = TextLoader("transcript.txt")
docs = loader.load()
char_text_splitter = CharacterTextSplitter(chunk_size = 500, chunk_overlap = 15)
docs = char_text_splitter.split_documents(docs)
transcriptdb = FAISS.from_documents(docs, openAI_embeddings)
loader = TextLoader("virscout.txt")
docs = loader.load()
char_text_splitter = CharacterTextSplitter(chunk_size = 500, chunk_overlap = 15)
docs = char_text_splitter.split_documents(docs)
virscoutdb = FAISS.from_documents(docs, openAI_embeddings)
loader = TextLoader("evaluation.txt")
docs = loader.load()
char_text_splitter = CharacterTextSplitter(chunk_size = 500, chunk_overlap = 15)
docs = char_text_splitter.split_documents(docs)
evaluatedb = FAISS.from_documents(docs, openAI_embeddings)
loader = Docx2txtLoader("note.docx")
docs = loader.load()
char_text_splitter = CharacterTextSplitter(chunk_size = 500, chunk_overlap = 15)
docs = char_text_splitter.split_documents(docs)
notedb = FAISS.from_documents(docs, openAI_embeddings)
from queue import Queue, Empty
class QueueCallback(BaseCallbackHandler):
"""Callback handler for streaming LLM responses to a queue."""
def __init__(self, q):
self.q = q
def on_llm_new_token(self, token: str, **kwargs) -> None:
self.q.put(token)
def on_llm_end(self, *args, **kwargs) -> None:
return self.q.empty()
def stream_docs(input_text,
apikey,
chat_history = [],
role_grade = 7,
survey_vectorstore = surveydb,
note_vectorstore = notedb,
evaluation_vectorstore = evaluatedb,
virscout_vectorstore = virscoutdb,
interview_vectorstore = transcriptdb):
# Create a Queue
q = Queue()
job_done = object()
system_message = """Use the information from the below sources to answer any questions.
Role: You are a scout that helps in deciding if a player will be a good fit for a team.
The provided data is about a baseball player to be drafted.
Survey: Survey of medical questions and responses and general knowledge about the player
<survey>
{survey}
</survey>
Scouts' Note: Notes about the player
The note is in this format:
The date, followed by the scout name.
The next line is the scout title
The third line is the scout note about the player
<scouts note>
{scouts_note}
</scouts note>
Scouts' Evaluation Note: Evaluation Notes about the player
The note is in this format:
The first line is the scout last name
The second line is the scout evaluation of the player
<evaluation note>
{evaluation_note}
</evaluation note>
VirScout: Virscout Interview Notes and Mindset data about the player
The note is in this format:
Multiple interview question answer pair
Then followed by mindset data
The mindset data contains a key called Pro Sim, this measures the similarity of the player to an ideal pro player, it is a value that ranges from -1 to 1
<virscout>
{virscout}
</virscout>
Scout Interview: Transcript of the player interview with a scout.
This transcript consists only of words uttered by the player.
<interview>
{interview}
</interview>
Role Grade: The role grade given to the player by different scouts
The text is in this format:
Scout Name: Role grade
Use the following definitions to interprete the Role grade in the form `Role grade: Interpretation`
8: Hall of Fame / Elite
7: Consistent All-Star
6: All-Star
5.5: Solid Everyday
5: Everyday
4.5: Platoon / Bench
4: Up /Down
3: Org Player
2: Non-Prospect
<role_grade>
{role_grade}
</role_grade>
Use the following piece of context, if you don't know the answer, simply say I don't know. Always give the answer in Markdown.
{context}
"""
llm = ChatOpenAI(temperature=0, model_name='gpt-4', openai_api_key = apikey)
llm_chain = LLMChain(
llm=llm,
prompt=CONDENSE_QUESTION_PROMPT
)
standalone_question = llm_chain(
{"chat_history": chat_history, "question": input_text})['text']
qa_prompt = ChatPromptTemplate.from_messages(
[("system", system_message), ("human", "{question}")])
llm = ChatOpenAI(streaming=True, callbacks=[QueueCallback(
q)], temperature=0, model_name='gpt-3.5-turbo',
openai_api_key = apikey)
# Initialize the LLM we'll be using
full_chain = {
"survey": (lambda x: x['question']) | survey_vectorstore.as_retriever(),
"interview": (lambda x: x['question']) | interview_vectorstore.as_retriever(),
"scouts_note": (lambda x: x['question']) | note_vectorstore.as_retriever(),
"virscout": (lambda x: x['question']) | virscout_vectorstore.as_retriever(),
"evaluation_note": (lambda x: x['question']) | evaluation_vectorstore.as_retriever(),
"role_grade": (lambda x: x['role_grade']),
"question": lambda x: x['question'],
"context": lambda x: x['chat_history']
} | qa_prompt | llm
# Create a function to call - this will run in a thread
return(full_chain.invoke({"question": standalone_question,
"chat_history": chat_history,
"role_grade":role_grade}))
with gr.Blocks(theme= gr.themes.Monochrome()) as demo:
with gr.Group():
gr.Label("ScoutBot", show_label=False)
apikey = gr.Textbox(show_label=False, type="password", placeholder="OpenAI Key")
chatbot = gr.Chatbot(layout="bubble",bubble_full_width=False, label = "Test Suite")
msg = gr.Textbox(show_label = False, placeholder = "Type a message")
with gr.Row():
submit = gr.Button("Submit")
clear = gr.ClearButton([msg, chatbot])
def respond(message, chat_history, apikey):
try:
bot_message = stream_docs(message, apikey, chat_history=chat_history).content
except:
bot_message = "please verify your api key above"
chat_history.append((message, bot_message))
#time.sleep(2)
return "", chat_history
msg.submit(respond, [msg, chatbot, apikey], [msg, chatbot])
submit.click(respond, [msg, chatbot, apikey], [msg, chatbot])
demo.launch(share = True)