File size: 19,647 Bytes
b955740
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5fba64
 
 
 
b955740
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33cca3f
b955740
 
 
a5fba64
b955740
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5fba64
b955740
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5fba64
b955740
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5fba64
b955740
 
 
 
 
 
 
 
 
 
 
33cca3f
b955740
 
33cca3f
b955740
 
a5fba64
b955740
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5fba64
b955740
 
 
 
 
 
33cca3f
b955740
 
 
 
 
a5fba64
 
 
b955740
a5fba64
b955740
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4b0577
b955740
 
 
52bcf6f
a5fba64
d93a02a
1ddf839
 
52bcf6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b955740
 
 
 
 
 
c96a076
8f745ad
960b9a4
b955740
303c77b
 
 
 
8f745ad
23a6beb
c57b42a
57faea7
d041952
7d6df6f
b955740
 
 
544e44c
 
 
 
b955740
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ed5846
b955740
 
db2271c
4b9eae2
 
b955740
 
c114b77
4ed5846
b955740
c114b77
 
 
b955740
 
7d6df6f
b955740
1a8f67e
b955740
a5fba64
 
b955740
 
 
b321a9e
b955740
e45a9e0
 
 
 
b955740
 
c114b77
99d6a6b
b955740
 
 
544e44c
 
 
 
b955740
b321a9e
 
 
 
 
 
 
a5fba64
b955740
a5fba64
b955740
a5fba64
b5df2e9
 
 
 
a5fba64
b955740
 
 
 
b09e2a2
b955740
a67a239
b955740
 
 
216d995
4ed5846
10b149f
 
b955740
db2271c
4ed5846
b955740
 
 
db2271c
10b149f
b955740
 
 
 
33cca3f
b955740
 
 
 
10b149f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12e76e8
b955740
 
 
33cca3f
 
 
 
 
 
 
b955740
33cca3f
ab91b6a
b955740
33cca3f
db2271c
b955740
 
544e44c
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
from typing import List
from langchain_core.callbacks import CallbackManagerForRetrieverRun
from langchain_core.documents import Document
from langchain_core.retrievers import BaseRetriever
from extract import extract_list
from openai import OpenAI
from pinecone import Pinecone
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain.chains.question_answering import load_qa_chain
from langchain.memory import ConversationBufferMemory
from langchain.prompts import PromptTemplate

import os, json, random
from dotenv import load_dotenv
import gradio as gr

load_dotenv()
openai_api_key = os.getenv("OPENAI_API_KEY")
pinecone_index = os.getenv("PINECONE_INDEX")
pinecone_api_key = os.getenv("PINECONE_API_KEY")

openai_client = OpenAI(api_key=openai_api_key)

practice_list = ', '.join(extract_list())

description = "Extract mediator's practice field that user want to search. Available mediator practice fields are " + practice_list
metadata_list = ['fullname', 'mediator profile on mediate.com', 'mediator Biography', 'mediator state']
metadata_value = ['Name', "Profile", "Biography", "State"]
class MediatorRetriever(BaseRetriever):
    def getMetadata(self, message):
        tools = [
            {
                "type": "function",
                "name": "get_info",
                "description": "Extract the information of mediator.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "mediator state": {
                            "type": "string",
                            "description": "Extract mediator's state that user wants to search. If both mediator city and mediator state are possible, please extract as mediator state."
                        },
                        "mediator country": {
                            "type": "string",
                            "description": "Extract mediator's country that user wants to search."
                        },
                        "mediator city": {
                            "type": "string",
                            "description": "Extract mediator's city that user wants to search."
                        },
                        "mediator areas of practice": {
                            "type": "array",
                            "description": description,
                            "enum": extract_list()
                        }
                    }
                }
            }
        ]
        
        response = openai_client.chat.completions.create(
            model="gpt-4-1106-preview",
            messages=[
                {"role": "system", "content": "You are a professional arbitration field searcher. Your role is to extract information about the moderator from the user's message. If you have less than 3 mediators in a particular city, you should search for mediators in your state. If you have less than 3 mediators in a particular state that you are searching for, you should search for mediators in the states closest to the state that you are searching for.  For example, if you have less than 3 mediators in California, you should search for mediators in Oregon, Arizona, or Nevada closest to California. Important: You must provide at least three moderators."},
                {"role": "user", "content": message}
            ],
            functions=tools,
            stream=True
        )
        new_message = ""
        for chunk in response:
            delta = chunk.choices[0].delta
            if delta and delta.content:
                yield {"search_status" : False, "data" : delta.content}
            elif delta and delta.function_call:
                new_message += delta.function_call.arguments
        if new_message:
            yield {"search_status" : True, "data" : new_message}

    def _get_relevant_documents(self, query: str, *, run_manager: CallbackManagerForRetrieverRun) -> List[Document]:
        """Sync implementations for retriever."""
        matching_documents = []
        message = ""
        metaData = self.getMetadata(query)
        
        for data in metaData:
            if data['data'] is None:
                break

            search_status = data['search_status']
            if search_status == True:
                metadata = json.loads(data['data'])
                practice_data = ""
                try:
                    if 'mediator areas of practice' in metadata:
                        practice_data = metadata['mediator areas of practice']
                        del metadata['mediator areas of practice']
                    elif 'mediator practice field' in metadata:
                        practice_data = metadata['mediator practice field']
                        del metadata['mediator practice field']
                    
                except:
                    practice_data = ""

                if "mediator city" in metadata:
                    try:
                        del metadata['mediator state']
                        del metadata['mediator country']
                    except:
                        pass
                if not practice_data:
                    response = openai_client.chat.completions.create(
                        model="gpt-4-1106-preview",
                        messages=[
                            {"role": "system", "content": "Generate a message asking the user about the conflict to better match them with mediators."},
                            {"role": "user", "content": query}
                        ],
                        stream=True
                    )
                    
                    for chunk in response:
                        delta = chunk.choices[0].delta
                        if delta and delta.content:
                            message += delta.content
                            yield {"message": message}
                
                elif not any(k in metadata for k in ['mediator country', 'mediator state', 'mediator city']):
                    response = openai_client.chat.completions.create(
                        model="gpt-4-1106-preview",
                        messages=[
                            {"role": "system", "content": "Generate a message asking the user for their location to find mediators in their area."},
                            {"role": "user", "content": query}
                        ],
                        stream=True
                    )
                  
                    for chunk in response:
                        delta = chunk.choices[0].delta
                        if delta and delta.content:
                            message += delta.content
                            yield {"message": message}
                else:
                    tools = [
                        {
                            "type": "function",
                            "name": "mediator_search",
                            "description": "Extract how many mediators the user wants to search.",
                            "parameters": {
                                "type": "object",
                                "properties": {
                                    "mediator": {
                                        "type": "number",
                                        "description": "The number of mediators the user wants to search for. If a user requests a list of mediators, this means that the user wants to search for at least three mediators. If your message does not include information about the number of mediators, you must provide at least three mediators. If you only have one arbitrator, you must search three mediators in the state and out of state. In example, If there is no three mediators in California search the mediators from Oregon, Arizona, or Nevada. So you must provide at least three mediators. IMPORTANT: you must provide at least three mediators.",
                                        "default": 3
                                    }
                                },
                                "required": ["mediator"]
                            }
                        }
                    ]
                    
                    response = openai_client.chat.completions.create(
                        model="gpt-4-1106-preview",
                        messages=[
                            {"role": "system", "content": "Please extract how many mediators users want to search for."},
                            {"role": "user", "content": query}
                        ],
                        functions=tools
                    )
                    try:
                        number_str = response.choices[0].message.function_call.arguments
                        mediator_num = max(int(json.loads(number_str)['mediator']), 3)
                    except:
                        mediator_num = 3

                    template = """"""
                    prompt = "You are a professional mediator information analyzer. You have to analyze the following mediators based on the user's message. You shouldn't write the mediator's information again. You shouldn't write the mediators in context as the excellent choice or ideal candidate. You have to analyze the mediators at once. Please respond with no more than 300 characters."
                    end = """Context: {context}
                        Chat history: {chat_history}
                        Human: {human_input}
                        Your Response as Chatbot:"""
                    
                    template += prompt + end

                    prompt = PromptTemplate(
                        input_variables=["chat_history", "human_input", "context"], 
                        template=template
                    )

                    pc = Pinecone(api_key=pinecone_api_key)

                    embeddings = OpenAIEmbeddings(api_key=openai_api_key)
                    
                    index = pc.Index(pinecone_index)
                        
                    results = index.query(
                        vector=embeddings.embed_query(query),
                        top_k=5,
                        filter=metadata,
                        include_metadata=True
                    )

                    new_data = []
                    for result in results['matches']:
                        data = {}
                        for metadata_key in metadata_list:      
                            data[metadata_key] = result['metadata'].get(metadata_key, "N/A")
                        # practice_data = result['metadata'].get('mediator areas of practice', "N/A")
                        if not practice_data:
                            continue
                        
                        if practice_data:
                            new_data.append(data)
                    random.shuffle(new_data)

                    if new_data:
                        if practice_data and mediator_num == 1:
                            message += f"I have located a mediator who specializes in {practice_data}. Here are their details:\n\n"
                        elif practice_data and mediator_num > 1:
                            message += f"I have located mediators who specialize in {practice_data}. Here are their details:\n\n"
                        elif not practice_data and mediator_num == 1:
                            message += f"I have located a mediator. Here are their details:\n\n"
                        elif not practice_data and mediator_num > 1:
                            message += f"I have located mediators. Here are their details:\n\n"

                    for index, new_datum in enumerate(new_data):
                        if index < mediator_num:
                            content = ""

                            for metadata_index, metadata_key in enumerate(metadata_list):
                                value = new_datum[metadata_key]
                                content += f"<b>{metadata_value[metadata_index]}</b>: {value if value else 'N/A'} \n"
                                message += f"<b>{metadata_value[metadata_index]}</b>: {value if value else 'N/A'} \n"

                            message += "\n\n"
                            new_doc = Document(page_content=content)
                            matching_documents.append(new_doc)
                        else:
                            break
                    
                    chat_openai = ChatOpenAI(model='gpt-4-1106-preview', 
                            openai_api_key=openai_api_key)
                    
                    memory = ConversationBufferMemory(memory_key="chat_history", input_key="human_input")
                    chain = load_qa_chain(chat_openai, chain_type="stuff", prompt=prompt, memory=memory)

                    output = chain.invoke(
                        {"input_documents": matching_documents, "human_input": query}, 
                        return_only_outputs=False
                    )
                    
                    message += f"Why appropriate: {output['output_text']}"

            else:
                message += data['data']

            yield {"documents": matching_documents, "message": message}

retriever = MediatorRetriever()

from langchain_openai import ChatOpenAI
from langchain.chains import create_history_aware_retriever
from langchain import hub
from langchain_core.messages import HumanMessage

rephrase_prompt = hub.pull("langchain-ai/chat-langchain-rephrase")
llm = ChatOpenAI(model="gpt-4-1106-preview", api_key=openai_api_key)

history_aware_retriever = create_history_aware_retriever(
    llm, retriever, rephrase_prompt
)

chat_history = []

def search(query, history):
    try:
        response = history_aware_retriever.stream({"input": query, "chat_history": chat_history})
        for chunks in response:
            for chunk in chunks:
                if 'documents' in chunk:
                    chat_history.extend([HumanMessage(content=query), chunk['documents']])
                yield chunk['message']
    except StopAsyncIteration:
        print("Async iteration ended unexpectedly")
    except Exception as e:
        print(f"An error occurred: {e}")
        yield f"An error occurred: {e}"

chatbot = gr.Chatbot(avatar_images=["user_.png", "bot.png"], height="100%",container=False)

js_code = """
<style>

    html body {
        background: transparent !important;
    }
    
    ::-webkit-scrollbar {
      width: 10px;
    }
    
    ::-webkit-scrollbar-track {
      box-shadow: inset 0 0 5px grey; 
      border-radius: 10px;
    }
     
    ::-webkit-scrollbar-thumb {
      background: gray; 
      border-radius: 10px;
    }
    
    ::-webkit-scrollbar-thumb:hover {
      background: #b30000; 
    }
    
    #component-0 {
        border-radius: 0px;
    }
    
    #component-4 h1 {
        color: white;
        text-align: center;
        font-size: 22px;
        padding-top: 13px;
    }
    .avatar-container img {
        border: 1px solid white;
        padding: 4px;
    }
    
    textarea {
        height: 90px !important;
        padding: 25px !important;
        font-size: 16px !important;
    }
    
    #component-6 {
        margin-top: 0%;
        border-top-left-radius: 0px;
        border-top-right-radius: 0px;
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
    }
    
    #component-9 {
        display: none;
    }
    
    #component-10 {
        display: none;
    }
    
    footer {
        display: none !important;
    }
    
    .svelte-1b6s6s {
        display: none !important;
    }
    
    #message-btn {
        position: fixed;
        right: 5px;
        bottom: 5px;
        transition: transform 0.5s ease-out; 
    }
    #custom-btn {
        padding: 15px;
        width: 70px;
        height: 70px;
        cursor: pointer;
        border-radius: 50%;
        background: #6f6f6f;
        transition: transform 0.5s ease-out;
    }
    #component-0 {
        background-color: #dcdcdc;
    }
    
    #component-2 {
        padding: 64px 0px 0px 0px;
        border-radius: 9px;
        height: 92%;
        opacity: 0;
        transform: scaleY(0); 
        transform-origin: bottom; 
        transition: transform 0.5s ease-out, opacity 0.5s ease-out;
        overflow: hidden;
        position:fixed;
        bottom:5.7rem;
        gap: unset;
        box-shadow: -14px 5px 16px 0px rgba(0,0,0,0.08),
            0px 2px 2px 0px rgba(0,0,0,0.12),
            0px 4px 4px 0px rgba(0,0,0,0.16),
            0px 8px 8px 0px rgba(0,0,0,0.2);
    }
    #component-4 {
        background-color: #6f6f6f;
        height: 85px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        border-bottom-left-radius: 0px;
        border-bottom-right-radius: 0px;
    }

    .section::-webkit-scrollbar-thumb {
        background-image: linear-gradient(180deg, #d0368a 0%, #708ad4 99%);
        box-shadow: inset 2px 2px 5px 0 rgba(#fff, 0.5);
        border-radius: 100px;
    }
    
    .gradio-container{
        padding:0 !important;
        background-color:transparent;
    }
    
    gradio-app {
        background: none !important;
    }
    
</style>
<script>
    function toggleChatbox() {
        window.parent.postMessage(
            {
                type: "toggleChat",
            },
            "*"
        );
        
        const chatbox = document.getElementById('component-2');
        const buttonImg = document.getElementById('custom-btn');
        const messageBtn = document.getElementById('message-btn');
        if ((chatbox.style.transform === 'scaleY(0)') || (chatbox.style.transform === '')) {
            chatbox.style.transform = 'scaleY(1)';
            chatbox.style.opacity = '1';
            buttonImg.src = "/file=close.png";
            messageBtn.style.transform = 'rotate(360deg)';
        } else {
            chatbox.style.transform = 'scaleY(0)';
            chatbox.style.opacity = '0';
            buttonImg.src = "/file=chat.png";
            messageBtn.style.transform = 'rotate(0deg)';
        }
    }
    
    function autoScroll() {
        const chatbox = document.querySelector('.bubble-wrap');
        if (chatbox) {
            chatbox.scrollTop = chatbox.scrollHeight;
        }
    }
    
    const timer = setInterval(isElements, 1000);
    
    function isElements() {
        const messageBtn = document.getElementById('message-btn');
        if (messageBtn) {
            messageBtn.addEventListener('click', toggleChatbox);
        }
        const userInputBox = document.querySelector('textarea.scroll-hide');
        if (userInputBox) {
            userInputBox.addEventListener('keypress', autoScroll, false);
        }
        if (messageBtn && userInputBox) {
            clearInterval(timer);
        }
    }
</script>
"""

def toggle_chatbox():
    global chatbox_visible
    chatbox_visible = not chatbox_visible
    return gr.update(visible=chatbox_visible)

chatbox_visible = True

with gr.Blocks(head=js_code) as demo:
    with gr.Column(visible=chatbox_visible) as chatbox_container:
        chatbox = gr.ChatInterface(fn=search, title="Mediate Chatbot", multimodal=False, retry_btn=None, clear_btn=None, undo_btn=None, chatbot=chatbot)
    
 
    gr.HTML(f'<button id="message-btn"/><img style="display: inline;" src="/file=chat.png" id="custom-btn"/><button>')

if __name__ == "__main__":
    demo.launch(debug=True, allowed_paths=["./"])