File size: 21,071 Bytes
f796a18
 
 
 
cf38d1a
f796a18
cf38d1a
f796a18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf38d1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f796a18
 
 
cf38d1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f796a18
 
 
 
cf38d1a
f796a18
 
cf38d1a
f796a18
 
 
 
 
cf38d1a
 
 
 
 
 
 
 
 
f796a18
 
 
 
cf38d1a
f796a18
 
cf38d1a
 
 
 
 
 
 
 
 
f796a18
 
cf38d1a
 
 
f796a18
cf38d1a
f796a18
 
cf38d1a
 
 
 
 
 
 
 
f796a18
 
cf38d1a
 
 
 
 
 
 
 
 
f796a18
 
 
cf38d1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f796a18
cf38d1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f796a18
cf38d1a
 
 
 
 
 
 
f796a18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "context_dict = {\n",
    "    \"company; goliath; we\" : \n",
    "    \"\"\"\n",
    "    Our company builds AI Recommendation Systems for Matching Platforms using the latest technology. Our company is estabilished and operates in Japan. Our company uses the AWS Cloud to manage Servers. Our company can use GPT3 as well. Our company also builds GPT3-based chatbots. Our company can use open-source models, if requested. Our company uses open source models. Our company operates in Japan. Our company has been operating for 1 year, and we are expanding in Hong Kong. Our company offers other services apart from recommendation systems, like GPT3 chatbots. Our company can also build recommendation systems for mobile apps.\n",
    "    \"\"\"\n",
    "    ,\n",
    "    \"price\" :\n",
    "    \"\"\"\n",
    "    The price of a recommendation system depends on the amount of complexity that is required to build, as well as the volume of customers. Reach us to get a quotation. The price of a chatbot depends by its intended usage and complexity, contact us for a quotation.\n",
    "    \"\"\"\n",
    "    ,\n",
    "    \"recommendation system\" :\n",
    "    \"\"\"\n",
    "    If your company wants to recommend products to customers, we can build a recommendation system for you. GPT3 can be used to build recommendation systems by using embeddings, mapping choices in a mathematical space. Once the recommendation system has been built, we will manage it in the future as well. Recommendation system could also be built for startups, though they will be in smaller size. We use AWS OpenSearch to host recommendation system.\n",
    "    \"\"\"\n",
    "    ,\n",
    "    \"a matching platform\" :\n",
    "    \"\"\"\n",
    "    A matching platform is a business with thousands of users, who could be customers, individuals or companies, who are interacting with one another. For example dating apps, ecommerce platforms, or job recruiting platforms. \n",
    "    \"\"\"\n",
    "}\n",
    "\n",
    "def split_paragraph(text, keyword):\n",
    "    list1 = [x.strip() for x in text.split('.')]\n",
    "    list2 = []\n",
    "    \n",
    "    for sentence in list1:\n",
    "        # Check if the sentence contains the phrase \"chamber of commerce\"\n",
    "        if keyword in sentence.lower():\n",
    "            list2.append(1)\n",
    "        else:\n",
    "            list2.append(0)\n",
    "\n",
    "    #in case first sentence has no keyword, we add it\n",
    "    if list2[0] == 0:\n",
    "        list1[0] = f'the {keyword}: ' + list1[0]\n",
    "        list2[0] = 1\n",
    "\n",
    "    # print(list1)\n",
    "    # print(list2)\n",
    "\n",
    "    list3 = list()\n",
    "    current_string = ''\n",
    "    # Loop through each element of list1 and list2\n",
    "    for i in range(len(list1)):\n",
    "        # If the corresponding element in list2 is 1, add the current string to list3 and reset the current string\n",
    "\n",
    "        if list2[i] == 1:\n",
    "            list3.append(current_string)\n",
    "            current_string = \"\" #reset\n",
    "            current_string += list1[i]\n",
    "\n",
    "        # Otherwise, concatenate the current string with the current element of list1\n",
    "        if list2[i] == 0:\n",
    "            current_string += '. '+list1[i]\n",
    "\n",
    "    # Add the final concatenated string to list3\n",
    "    list3.append(current_string)\n",
    "\n",
    "    return [x.strip() for x in list3[1:]]\n",
    "\n",
    "def context_dict2context_list(context_dict):\n",
    "    list1 = list()\n",
    "    for all_keys in context_dict:\n",
    "        key = all_keys.split(';')[0]\n",
    "        try:\n",
    "            synonyms = all_keys.split(';')[1:]\n",
    "        except:\n",
    "            pass\n",
    "        # print(key)\n",
    "        str1 = context_dict[all_keys]\n",
    "        \n",
    "        split_list = [x.replace('\\n', '').strip() for x in str1.split('\\n\\n')]\n",
    "        split_list\n",
    "\n",
    "        for sentence in split_list:\n",
    "            for s in split_paragraph(sentence, key):\n",
    "                #add synonyms\n",
    "                for synonym in synonyms:\n",
    "                    #manual replacement causes a wrong grammar\n",
    "                    #gpt3 replacement\n",
    "                    print(s, key, synonym)\n",
    "                    prompt = f'in the following sentence: {s}. Replace {key} with {synonym} correcting the grammar'\n",
    "                    answer = gpt3_question(prompt).replace('\\n', '')\n",
    "                    list1.append(answer)\n",
    "                list1.append(s)\n",
    "    return list1\n",
    "\n",
    "#prepare context\n",
    "context_list = context_dict2context_list(context_dict)\n",
    "context_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "s = 'Our company builds AI Recommendation Systems for Matching Platforms using the latest technology'\n",
    "key = 'company'\n",
    "synonym = 'we'\n",
    "\n",
    "prompt = f'in the following sentence: {s}. Replace {key} with {synonym} correcting the grammar'\n",
    "gpt3_question(prompt).replace('\\n', '')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "import os\n",
    "import torch\n",
    "# os.system('pip install openpyxl')\n",
    "# os.system('pip install sentence-transformers==2.2.2')\n",
    "# os.system('pip install torch==1.13.0')\n",
    "\n",
    "def chatgpt3_question(context, question):\n",
    "    api_key = \"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\"\n",
    "    url = \"https://api.openai.com/v1/chat/completions\"\n",
    "\n",
    "    prompt = f\"\"\"\n",
    "    based on this context: {context}\n",
    "    answer this use question: {question}\n",
    "    \"\"\"\n",
    "\n",
    "    headers = {\n",
    "        \"Content-Type\": \"application/json\",\n",
    "        \"Authorization\": f\"Bearer {api_key}\"\n",
    "    }\n",
    "\n",
    "    data = {\n",
    "        \"model\": \"gpt-3.5-turbo\",\n",
    "        \"messages\": [{\"role\": \"user\", \"content\": prompt}]\n",
    "    }\n",
    "\n",
    "    response = requests.post(url, headers=headers, json=data)\n",
    "    generated_text = response.json()['choices'][0]['message']['content']\n",
    "\n",
    "    return generated_text\n",
    "\n",
    "import os\n",
    "import requests\n",
    "import pandas as pd\n",
    "\n",
    "def text2vec(query):\n",
    "    headers = {\n",
    "        'Content-Type': 'application/json',\n",
    "        'Authorization': 'Bearer ' + \"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\",\n",
    "    }\n",
    "\n",
    "    json_data = {\n",
    "        'input': query,\n",
    "        'model': 'text-embedding-ada-002',\n",
    "    }\n",
    "\n",
    "    response = requests.post('https://api.openai.com/v1/embeddings', headers=headers, json=json_data)\n",
    "    query = response.json()['data'][0]['embedding'] #len=1536 #pricing=0.0004\n",
    "    return query\n",
    "\n",
    "import pandas as pd\n",
    "from sentence_transformers import SentenceTransformer, util\n",
    "\n",
    "df = pd.read_parquet('df.parquet')\n",
    "df_qa = pd.read_parquet('df_qa.parquet')\n",
    "\n",
    "df_qa_ = df_qa.copy()\n",
    "df_ = df.copy()\n",
    "\n",
    "def qa(df_, df_qa_, min_qa_score, min_context_score, verbose, query):\n",
    "    query_vec = text2vec(query)\n",
    "    query_vec = torch.DoubleTensor(query_vec)\n",
    "\n",
    "    #first check if there is already a question in df_qa\n",
    "    df_qa_['score'] = df_qa_['text_vector_'].apply(lambda x : float(util.cos_sim(x, query_vec)))\n",
    "    df_qa_ = df_qa_.sort_values('score', ascending=False)\n",
    "    \n",
    "    df_qa_ = df_qa_[df_qa_['score']>=min_qa_score]\n",
    "    #if we find at least one possible preset answer\n",
    "    if len(df_qa_) > 0:\n",
    "        if verbose : display(df_qa_)\n",
    "        answer = df_qa_[0:1]['answer'].values.tolist()[0]\n",
    "        return answer\n",
    "    \n",
    "    #then check if we can use the context to answer a question\n",
    "    df_['score'] = df_['text_vector_'].apply(lambda x : float(util.cos_sim(x, query_vec)))\n",
    "    df_ = df_.sort_values('score', ascending=False)\n",
    "    df_ = df_[df_['score']>=min_context_score]\n",
    "    #if we find at least one possible preset answer\n",
    "    if len(df_) > 0:\n",
    "        if verbose : display(df_)\n",
    "        #in case we might decide to merge multiple context\n",
    "        context = ' '.join(df_['description'][0:1].values.tolist())\n",
    "        answer = chatgpt3_question(context, query)\n",
    "        return answer\n",
    "    else:\n",
    "        return 'impossible to give an answer'\n",
    "\n",
    "# print(\n",
    "#     qa(\n",
    "#         df_, \n",
    "#         df_qa_, \n",
    "#         min_qa_score=0.92, \n",
    "#         min_context_score=.75, \n",
    "#         verbose=False, \n",
    "#         query='What is a recommender system?'\n",
    "#     )\n",
    "# )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Query after coreference resolution: \"How much does your company charge for recommendation systems?\"'"
      ]
     },
     "execution_count": 111,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def gpt3_reference(last_context, query):\n",
    "    #needs to be referred to the second\n",
    "    # last_context = 'you are a company'\n",
    "    # query = \"\"\"what do you do\"\"\"\n",
    "\n",
    "    prompt = f\"\"\"\n",
    "    context : {last_context} \n",
    "    query : {query}\n",
    "    instructions:\n",
    "    apply a coreference resolution on the query and replace the pronoun with no temperature, no adjectives\n",
    "    \"\"\"\n",
    "    #only if pronoun is unclear, replace query pronoun with its reference\n",
    "    answer = chatgpt3_question(prompt)\n",
    "\n",
    "    #replacements\n",
    "    answer = answer.replace('\\n', '')\n",
    "    answer = answer.replace('Answer:', '')\n",
    "    answer = answer.replace('answer:', '')\n",
    "    answer = answer.replace('answer', '')\n",
    "    answer = answer.strip()\n",
    "    return answer\n",
    "\n",
    "gpt3_reference(\"you are a company. recommendation systems are expensive\", \"How much do you charge?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>question</th>\n",
       "      <th>answer</th>\n",
       "      <th>text_vector_</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>how much does it cost?</td>\n",
       "      <td>The price depends by its intended usage and co...</td>\n",
       "      <td>[0.02400375, -0.022719184, 0.010704716, -0.012...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>do you use GPT3 API?</td>\n",
       "      <td>yes, we can</td>\n",
       "      <td>[0.008728346, -0.0068335673, -0.008393759, -0....</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>do you use GPT3?</td>\n",
       "      <td>yes, we can</td>\n",
       "      <td>[0.00771756, -0.0016906569, -0.0074193655, -0....</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>do you use GPT4?</td>\n",
       "      <td>yes, we can</td>\n",
       "      <td>[0.007858252, -0.0008719981, -0.010744374, -0....</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>what do you do?</td>\n",
       "      <td>Our company builds AI recommendaion systems</td>\n",
       "      <td>[-0.0043235356, -0.018366648, -0.006951173, -0...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>what does goliath do?</td>\n",
       "      <td>Our company builds AI recommendaion systems</td>\n",
       "      <td>[-0.027456148, -0.017353108, -0.007992724, 0.0...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>what does your company do?</td>\n",
       "      <td>Our company builds AI recommendaion systems</td>\n",
       "      <td>[0.0022247417, -0.012323239, -0.004670404, -0....</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                     question  \\\n",
       "0      how much does it cost?   \n",
       "1        do you use GPT3 API?   \n",
       "2            do you use GPT3?   \n",
       "3            do you use GPT4?   \n",
       "4             what do you do?   \n",
       "5       what does goliath do?   \n",
       "6  what does your company do?   \n",
       "\n",
       "                                              answer  \\\n",
       "0  The price depends by its intended usage and co...   \n",
       "1                                        yes, we can   \n",
       "2                                        yes, we can   \n",
       "3                                        yes, we can   \n",
       "4        Our company builds AI recommendaion systems   \n",
       "5        Our company builds AI recommendaion systems   \n",
       "6        Our company builds AI recommendaion systems   \n",
       "\n",
       "                                        text_vector_  \n",
       "0  [0.02400375, -0.022719184, 0.010704716, -0.012...  \n",
       "1  [0.008728346, -0.0068335673, -0.008393759, -0....  \n",
       "2  [0.00771756, -0.0016906569, -0.0074193655, -0....  \n",
       "3  [0.007858252, -0.0008719981, -0.010744374, -0....  \n",
       "4  [-0.0043235356, -0.018366648, -0.006951173, -0...  \n",
       "5  [-0.027456148, -0.017353108, -0.007992724, 0.0...  \n",
       "6  [0.0022247417, -0.012323239, -0.004670404, -0....  "
      ]
     },
     "execution_count": 104,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df_qa_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>question</th>\n",
       "      <th>answer</th>\n",
       "      <th>text_vector_</th>\n",
       "      <th>score</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>what does goliath do?</td>\n",
       "      <td>Our company builds AI recommendaion systems</td>\n",
       "      <td>[-0.027456148, -0.017353108, -0.007992724, 0.0...</td>\n",
       "      <td>0.902588</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                question                                       answer  \\\n",
       "5  what does goliath do?  Our company builds AI recommendaion systems   \n",
       "\n",
       "                                        text_vector_     score  \n",
       "5  [-0.027456148, -0.017353108, -0.007992724, 0.0...  0.902588  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "'Our company builds AI recommendaion systems'"
      ]
     },
     "execution_count": 107,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bot_answer = qa(\n",
    "        df_, \n",
    "        df_qa_, \n",
    "        min_qa_score=0.88, \n",
    "        min_context_score=.75, \n",
    "        verbose=True, \n",
    "        query='how much does goliath charge?'\n",
    "    )\n",
    "bot_answer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running on local URL:  http://127.0.0.1:7876\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7876/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": []
     },
     "execution_count": 108,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sending request\n",
      "<Response [200]>\n",
      "@@@ How much does Goliath charge?\n"
     ]
    }
   ],
   "source": [
    "import subprocess\n",
    "import random\n",
    "import gradio as gr\n",
    "import requests\n",
    "\n",
    "history = None\n",
    "\n",
    "def predict(input, history, last_context):\n",
    "    last_context += 'you are a company'\n",
    "\n",
    "    #WE CAN PLAY WITH user_input AND bot_answer, as well as history\n",
    "    user_input = input\n",
    "\n",
    "    query = gpt3_reference(last_context, user_input)\n",
    "    print('@@@', query)\n",
    "    bot_answer = qa(\n",
    "        df_, \n",
    "        df_qa_, \n",
    "        min_qa_score=0.92, \n",
    "        min_context_score=.75, \n",
    "        verbose=False, \n",
    "        query=input\n",
    "    )\n",
    "\n",
    "    response = list()\n",
    "    response = [(input, bot_answer)]\n",
    "    \n",
    "    history.append(response[0])\n",
    "    response = history\n",
    "\n",
    "    last_context = input\n",
    "\n",
    "    # print('#history', history)\n",
    "    # print('#response', response)\n",
    "\n",
    "    return response, history, last_context\n",
    "\n",
    "demo = gr.Blocks()\n",
    "with demo:\n",
    "    gr.Markdown(\n",
    "    \"\"\"\n",
    "        Chatbot\n",
    "    \"\"\"\n",
    "    )\n",
    "    state = gr.Variable(value=[]) #beginning\n",
    "    last_context = gr.Variable(value='') #beginning\n",
    "    chatbot = gr.Chatbot() #color_map=(\"#00ff7f\", \"#00d5ff\")\n",
    "    text = gr.Textbox(\n",
    "        label=\"Question\",\n",
    "        value=\"What is a recommendation system?\",\n",
    "        placeholder=\"\",\n",
    "        max_lines=1,\n",
    "    )\n",
    "    text.submit(predict, [text, state, last_context], [chatbot, state, last_context])\n",
    "    text.submit(lambda x: \"\", text, text)\n",
    "    # btn = gr.Button(value=\"submit\")\n",
    "    # btn.click(chatbot_foo, None, [chatbot, state])\n",
    "\n",
    "demo.launch(share=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}