File size: 13,842 Bytes
7a56e2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import os
# https://stackoverflow.com/questions/76175046/how-to-add-prompt-to-langchain-conversationalretrievalchain-chat-over-docs-with
# again from: 
# https://python.langchain.com/docs/integrations/providers/vectara/vectara_chat
from langchain.document_loaders import PyPDFDirectoryLoader
import pandas as pd
import langchain
from queue import Queue
from typing import Any
from langchain.llms.huggingface_text_gen_inference import HuggingFaceTextGenInference
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
from langchain.schema import LLMResult
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.vectorstores import FAISS
from langchain.prompts.prompt import PromptTemplate
from anyio.from_thread import start_blocking_portal #For model callback streaming

from langchain.prompts import SystemMessagePromptTemplate, HumanMessagePromptTemplate, ChatPromptTemplate
import os
from dotenv import load_dotenv

import streamlit as st

from langchain.document_loaders import PyPDFLoader
from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings
from langchain.chains.question_answering import load_qa_chain
from langchain.chat_models import ChatOpenAI
from langchain.vectorstores import Chroma
import chromadb

from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.llms import OpenAI
from langchain.chains import RetrievalQA
from langchain.document_loaders import TextLoader
from langchain.document_loaders import DirectoryLoader
from langchain_community.document_loaders import PyMuPDFLoader
from langchain.schema import Document

from langchain.memory import ConversationBufferMemory

from langchain.chains import ConversationalRetrievalChain
from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT
from langchain.chains.conversational_retrieval.prompts import QA_PROMPT
import gradio as gr
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationalRetrievalChain

persist_directory = '/projects/bcjp/marshad/agllm/db5'
csv_filepath1 = "./agllm-data/corrected/Corrected_supplemented-insect_data-2500-sorted.xlsx"
csv_filepath2 = "./agllm-data/corrected/Corrected_supplemented-insect_data-remaining.xlsx"
model_name=4
max_tokens=400
system_message = {"role": "system", "content": "You are a helpful assistant."} # TODO: double check how this plays out later. 
langchain.debug=True # TODO: DOUBLE CHECK
retriever_k_value=2
embedding = OpenAIEmbeddings()

######### todo: skipping the first step

embedding = OpenAIEmbeddings()
vectordb = Chroma(persist_directory=persist_directory, 
                  embedding_function=embedding)

retriever = vectordb.as_retriever()

print(# Single example
vectordb.as_retriever(k=2, search_kwargs={"filter": {"matched_specie_0": "Hypagyrtis unipunctata"}, 'k':1}).get_relevant_documents(
    "Checking if retriever is correctly initalized?"
))

columns = ['species', 'common name', 'order', 'family',
           'genus', 'Updated role in ecosystem', 'Proof',
           'ipm strategies', 'size of insect', 'geographical spread',
           'life cycle specifics', 'pest for plant species', 'species status',
           'distribution area', 'appearance', 'identification']

df1 = pd.read_excel(csv_filepath1, usecols=columns)
df2 = pd.read_excel(csv_filepath2, usecols=columns)

all_insects_data = pd.concat([df1, df2], ignore_index=True)

def get_prompt_with_vetted_info_from_specie_name(search_for_specie, mode):

       def read_and_format_filtered_csv_better(insect_specie):
              filtered_data = all_insects_data[all_insects_data['species'] == insect_specie]
              formatted_data = ""
              # Format the filtered data
              for index, row in filtered_data.iterrows():
                     row_data = [f"{col}: {row[col]}" for col in filtered_data.columns]
                     formatted_row = "\n".join(row_data)
                     formatted_data += f"{formatted_row}\n"

              return formatted_data

              # Use the path to your CSV file here
              
       vetted_info=read_and_format_filtered_csv_better(search_for_specie)
       if mode=="user":
              language_constraint="The language should be acustomed to the end user. This question is likely asked by a farmer. So, answer things in their language. Bur for referencing information, you can use the original content. This is only for the main answer to be provided by you."
       elif mode=="researcher":
              language_constraint="The language should be acustomed to a researcher. This question is likely asked by an academic researcher. So you can use all the technical terms freely. And for referencing information, you can use the original content. This is only for the main answer to be provided by you."
       else:
              print("No  valid model provided. Exiting")
              exit()
       general_system_template = """ 
       In every question you are provided information about the insect. Two types of information are: First,  Vetted Information (which is same in every questinon) and Second, some context from external documents about an insect specie and a question by the user. answer the question according to these two types of informations. 
       ---- 
       Vetted info is as follows:
       {vetted_info}
       ----
       The context retrieved for documents about this particular question is a as follows:
       {context}
       ----
       Additional Instruction:
       1. Reference Constraint
       At the end of each answer provide the source/reference for the given data in following format: 
       \n\n[enter two new lines before writing below] References:
       Vetted Information Used: Write what was used from the document for coming up with the answer above. Write exact part of lines. If nothing, write 'Nothing'. 
       Documents Used: Write what was used from the document for coming up with the answer above. If nothing, write 'Nothing'. Write exact part of lines and document used. 
       2. Information Constraint: 
       Only answer the question from information provided otherwise say you dont know. You have to answer in 150 words including references. Prioritize information in documents/context over vetted information. And first mention the warnings/things to be careful about. 
       3. Language constraint:
       {language_constraint}

       ----
       """.format(vetted_info=vetted_info, language_constraint=language_constraint,context="{context}", )


       general_user_template = "Question:```{question}```"
       messages_formatted = [
              SystemMessagePromptTemplate.from_template(general_system_template),
              # HumanMessagePromptTemplate.from_template(general_system_template),
              HumanMessagePromptTemplate.from_template(general_user_template)
       ]
       qa_prompt = ChatPromptTemplate.from_messages( messages_formatted )
       print(qa_prompt)
       return qa_prompt
qa_prompt=get_prompt_with_vetted_info_from_specie_name("Papaipema nebris", "researcher")
print("First prompt is intialized as: " , qa_prompt, "\n\n")


memory = ConversationBufferMemory(memory_key="chat_history",output_key='answer', return_messages=True) # https://github.com/langchain-ai/langchain/issues/9394#issuecomment-1683538834


if model_name==4:
    llm_openai = ChatOpenAI(model_name="gpt-4-1106-preview" , temperature=0, max_tokens=max_tokens)  # TODO: NEW MODEL VERSION AVAILABLE 
else:
    llm_openai = ChatOpenAI(model_name="gpt-3.5-turbo-0125" , temperature=0, max_tokens=max_tokens)

specie_selector="Papaipema nebris"
filter = {
    "$or": [
        {"matched_specie_0": specie_selector},
        {"matched_specie_1": specie_selector},
        {"matched_specie_2": specie_selector},
    ]
}
retriever = vectordb.as_retriever(search_kwargs={'k':retriever_k_value, 'filter': filter})

qa_chain = ConversationalRetrievalChain.from_llm(
    llm_openai, retriever, memory=memory, verbose=False, return_source_documents=True,\
          combine_docs_chain_kwargs={'prompt': qa_prompt}

)
# 

def initialize_qa_chain(specie_selector, application_mode):

    filter = {
        "$or": [
            {"matched_specie_0": specie_selector},
            {"matched_specie_1": specie_selector},
            {"matched_specie_2": specie_selector},
        ]
    }
    retriever = vectordb.as_retriever(search_kwargs={'k':2, 'filter': filter})
    
    memory = ConversationBufferMemory(memory_key="chat_history", output_key='answer', return_messages=True)
    qa_prompt=get_prompt_with_vetted_info_from_specie_name(specie_selector, application_mode)
    qa_chain = ConversationalRetrievalChain.from_llm(
        llm_openai, retriever, memory=memory, verbose=False, return_source_documents=True,
        combine_docs_chain_kwargs={'prompt': qa_prompt}
    )
    
    return qa_chain
result = qa_chain.invoke({"question": "where are stalk borer eggs laid?"})
print("Got the first LLM task working: ", result)


#Application Interface: 
with gr.Blocks(theme=gr.themes.Soft())  as demo:
    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown(
                """
                ![Logo](file/logo1.png)
                """
            )
        with gr.Column(scale=1):
            gr.Markdown(
                """
                ![Logo](file/logo2.png)
                """
            )

    # Configure UI layout
    chatbot = gr.Chatbot(height=600, label="AgLLM22")
    with gr.Row():
        with gr.Column(scale=1):
            with gr.Row():
                # Model selection
                specie_selector = gr.Dropdown(
                    list(["Papaipema nebris", "Nomophila nearctica"]),
                    value="Papaipema nebris",
                    label="Species",
                    info="Select the Species",
                    interactive=True,
                    scale=2,
                    visible=True
                )
            with gr.Row():
                application_mode = gr.Dropdown(
                    list(["user", "researcher"]),
                    value="researcher",
                    label="Mode",
                    info="Select the Mode",
                    interactive=True,
                    scale=2,
                    visible=True
                )
            with gr.Row():
                pass
        with gr.Column(scale=2):
            # User input prompt text field
            user_prompt_message = gr.Textbox(placeholder="Please add user prompt here", label="User prompt")
            with gr.Row():
                # clear = gr.Button("Clear Conversation", scale=2)
                submitBtn = gr.Button("Submit", scale=8)

    state = gr.State([])
    qa_chain_state = gr.State(value=None)

    # Handle user message
    def user(user_prompt_message, history):
        print("HISTORY IS: ", history)  # TODO: REMOVE IT LATER
        if user_prompt_message != "":
            return history + [[user_prompt_message, None]]
        else:
            return history + [["Invalid prompts - user prompt cannot be empty", None]]

    # Chatbot logic for configuration, sending the prompts, rendering the streamed back generations, etc.
    def bot(application_mode, user_prompt_message, history, messages_history, qa_chain):
        if qa_chain == None:
            qa_chain=init_qa_chain("Papaipema nebris", application_mode)

        dialog = []
        bot_message = ""
        history[-1][1] = ""  # Placeholder for the answer
        
        dialog = [
            {"role": "user", "content": user_prompt_message},
        ]
        messages_history += dialog
        
        # Queue for streamed character rendering
        q = Queue()

        # Async task for streamed chain results wired to callbacks we previously defined, so we don't block the UI
        def task(user_prompt_message):
            ret = qa_chain.invoke({"question": user_prompt_message})["answer"]
            return ret
        
        history[-1][1] = task(user_prompt_message)
        return [history, messages_history]

    # Initialize the chat history with default system message
    def init_history(messages_history):
        messages_history = []
        messages_history += [system_message]
        return messages_history

    # Clean up the user input text field
    def input_cleanup():
        return ""

    def init_qa_chain(specie_selector, application_mode):
        qa_chain = initialize_qa_chain(specie_selector, application_mode)
        return qa_chain

    specie_selector.change(
        init_qa_chain,
        inputs=[specie_selector, application_mode],
        outputs=[qa_chain_state]
    )

    # When the user clicks Enter and the user message is submitted
    user_prompt_message.submit(
        user,
        [user_prompt_message, chatbot],
        [chatbot],
        queue=False
    ).then(
        bot,
        [application_mode, user_prompt_message, chatbot, state, qa_chain_state],
        [chatbot, state]
    ).then(input_cleanup,
        [],
        [user_prompt_message],
        queue=False
    )

    # When the user clicks the submit button
    submitBtn.click(
        user,
        [user_prompt_message, chatbot],
        [chatbot],
        queue=False
    ).then(
        bot,
        [application_mode, user_prompt_message, chatbot, state, qa_chain_state],
        [chatbot, state]
    ).then(
        input_cleanup,
        [],
        [user_prompt_message],
        queue=False
    )

    # When the user clicks the clear button
    # clear.click(lambda: None, None, chatbot, queue=False).success(init_history, [state], [state])
    if __name__ == "__main__":
    # demo.launch()
        demo.queue().launch(allowed_paths=["/"], server_name="0.0.0.0", share=True, debug=True)