File size: 8,586 Bytes
8a874da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f0d7fd
8a874da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9144a20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241

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)