File size: 24,096 Bytes
b08295c
 
 
 
b96faa7
b08295c
b96faa7
 
 
 
 
 
 
 
 
b08295c
 
 
 
b96faa7
 
 
 
 
 
 
b08295c
b96faa7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b08295c
 
 
 
 
 
 
 
 
 
 
d5bc134
b08295c
 
 
 
 
 
91bd517
b08295c
38a37a6
 
 
 
 
b08295c
91bd517
38a37a6
91bd517
 
 
 
b08295c
 
 
 
 
38a37a6
b08295c
 
 
 
91bd517
 
 
b08295c
 
 
 
 
 
 
 
 
 
 
d5bc134
b08295c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5bc134
b08295c
 
 
 
 
91bd517
b08295c
 
91bd517
b08295c
 
 
 
 
 
 
 
 
 
 
 
91bd517
b08295c
 
 
38a37a6
b08295c
 
 
 
 
 
 
 
 
d5bc134
b08295c
d5bc134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38a37a6
 
 
d5bc134
38a37a6
d5bc134
38a37a6
 
 
 
 
91bd517
 
 
 
 
 
 
 
 
 
 
38a37a6
 
da4b287
38a37a6
da4b287
b08295c
 
 
 
 
91bd517
b08295c
 
38a37a6
b08295c
38a37a6
b08295c
 
 
 
38a37a6
 
b08295c
38a37a6
91bd517
 
 
 
 
 
 
d5bc134
91bd517
d5bc134
91bd517
b08295c
da4b287
b08295c
38a37a6
 
 
d5bc134
38a37a6
 
 
 
 
 
91bd517
 
 
 
 
 
 
 
 
d5bc134
91bd517
 
 
 
 
 
 
d5bc134
38a37a6
 
 
 
da4b287
91bd517
da4b287
 
 
 
 
 
 
 
91bd517
da4b287
 
91bd517
38a37a6
 
 
 
 
 
91bd517
38a37a6
 
 
 
d5bc134
38a37a6
 
91bd517
 
 
 
 
 
 
 
38a37a6
 
 
 
d5bc134
38a37a6
 
 
 
 
 
 
d5bc134
38a37a6
 
 
 
 
 
 
 
 
 
 
 
d5bc134
38a37a6
 
 
 
 
 
 
91bd517
 
 
 
 
 
 
 
 
 
 
 
 
 
38a37a6
91bd517
 
 
38a37a6
91bd517
d5bc134
 
91bd517
38a37a6
056bbbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b08295c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 239,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Reading settings from ../../env/ai.json\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import json\n",
    "\n",
    "pathToSettings = '../../env/ai.json'\n",
    "if os.path.exists(pathToSettings):\n",
    "    # Load setting from Json outside of project.\n",
    "    print(f'Reading settings from {pathToSettings}')\n",
    "    f = open(pathToSettings)\n",
    "    settingsJson = json.load(f)\n",
    "    del f\n",
    "\n",
    "    for key in settingsJson:\n",
    "        os.environ[key] = settingsJson[key]\n",
    "        \n",
    "    del settingsJson\n",
    "else:    \n",
    "    # Manually set settings    \n",
    "    os.environ['HUGGING_FACE_API_KEY'] = 'Get here: https://huggingface.co/settings/tokens'\n",
    "    os.environ['OPENAI_API_KEY'] = 'Get here: https://platform.openai.com/account/api-keys'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 237,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 237,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "os.path.exists('noono.pj')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Setup Web Crawler and Lookup functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 223,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "from bs4 import BeautifulSoup\n",
    "import json\n",
    "import validators \n",
    "\n",
    "def remove_keys(dictionary: dict, keyList: list):\n",
    "    for key in keyList:        \n",
    "        if key in dictionary:\n",
    "            del dictionary[key]    \n",
    "\n",
    "def get_recipe_as_json(url: str) -> dict: \n",
    "    \n",
    "    url = url.replace(\"'\", \"\").replace('\"', '')\n",
    "    \n",
    "    if not validators.url(url):\n",
    "        return {'error': 'Invalid url format', 'url': url }\n",
    "\n",
    "    html = requests.get(url).text   \n",
    "    soup = BeautifulSoup(html)\n",
    "    script = soup.find_all(\"script\", {\"id\": \"allrecipes-schema_1-0\"})\n",
    "\n",
    "    recipeDict = json.loads(script[0].text)[0]\n",
    "    remove_keys(recipeDict, ['review', 'image', 'mainEntityOfPage', 'publisher'])\n",
    "    \n",
    "    return recipeDict\n",
    "\n",
    "# url = \"https://www.allrecipes.com/recipe/212498/easy-chicken-and-broccoli-alfredo/\"\n",
    "# obj = get_recipe_as_json(url)\n",
    "# x = get_recipe_as_json('https://www.allrecipes.com/recipe/235153/easy-baked-chicken-thighs/')\n",
    "# print(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Static recipe lists"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 224,
   "metadata": {},
   "outputs": [],
   "source": [
    "dessertList = [\n",
    "   {\n",
    "      \"title\": \"Chocolate Snack Cake\",\n",
    "      \"url\": \"https://www.allrecipes.com/chocolate-snack-cake-recipe-8350343\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"Charred Spiced Pears with Smoky Vanilla Cherry Sauce\",\n",
    "      \"url\": \"https://www.allrecipes.com/charred-spiced-pears-with-smoky-vanilla-cherry-sauce-recipe-8347080\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"Meringue Topped Banana Pudding\",\n",
    "      \"url\": \"https://www.allrecipes.com/meringue-topped-banana-pudding-recipe-8347040\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"White Chocolate Cinnamon Toast Crunch Bars\",\n",
    "      \"url\": \"https://www.allrecipes.com/white-chocolate-cinnamon-toast-crunch-bars-recipe-7556790\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"Plum Cobbler for Two\",\n",
    "      \"url\": \"https://www.allrecipes.com/plum-cobbler-for-two-recipe-8304143\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"Pumpkin Cheesecake Cookies\",\n",
    "      \"url\": \"https://www.allrecipes.com/pumpkin-cheesecake-cookies-recipe-7972485\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"Chocolate Whipped Cottage Cheese\",\n",
    "      \"url\": \"https://www.allrecipes.com/chocolate-whipped-cottage-cheese-recipe-8303272\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"Nutella Ice Cream\",\n",
    "      \"url\": \"https://www.allrecipes.com/nutella-ice-cream-recipe-7508716\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"3-Ingredient Banana Oatmeal Cookies\",\n",
    "      \"url\": \"https://www.allrecipes.com/3-ingredient-banana-oatmeal-cookies-recipe-7972686\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"Caramel Apple Pie Cookies\",\n",
    "      \"url\": \"https://www.allrecipes.com/caramel-apple-pie-cookies-recipe-7642173\"\n",
    "   }\n",
    "]\n",
    "\n",
    "chickenDishList = [\n",
    "   {\n",
    "      \"title\": \"Crispy Roasted Chicken\",\n",
    "      \"url\": \"https://www.allrecipes.com/recipe/228363/crispy-roasted-chicken/\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"Roasted Spatchcocked Chicken With Potatoes\",\n",
    "      \"url\": \"https://www.allrecipes.com/recipe/254877/roasted-spatchcocked-chicken-with-potatoes/\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"Easy Baked Chicken Thighs\",\n",
    "      \"url\": \"https://www.allrecipes.com/recipe/235153/easy-baked-chicken-thighs/\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"Crispy Baked Chicken Thighs\",\n",
    "      \"url\": \"https://www.allrecipes.com/recipe/258878/crispy-baked-chicken-thighs/\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"Crispy and Tender Baked Chicken Thighs\",\n",
    "      \"url\": \"https://www.allrecipes.com/recipe/235151/crispy-and-tender-baked-chicken-thighs/\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"Million Dollar Chicken\",\n",
    "      \"url\": \"https://www.allrecipes.com/recipe/233953/million-dollar-chicken/\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"Simple Whole Roasted Chicken\",\n",
    "      \"url\": \"https://www.allrecipes.com/recipe/70679/simple-whole-roasted-chicken/\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"Beer Can Chicken\",\n",
    "      \"url\": \"https://www.allrecipes.com/recipe/214618/beer-can-chicken/\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"Air Fryer Chicken Thighs\",\n",
    "      \"url\": \"https://www.allrecipes.com/recipe/272858/air-fryer-chicken-thighs/\"\n",
    "   },\n",
    "   {\n",
    "      \"title\": \"Happy Roast Chicken\",\n",
    "      \"url\": \"https://www.allrecipes.com/recipe/214478/happy-roast-chicken/\"\n",
    "   }\n",
    "]\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Setup Tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 225,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Tools \n",
    "from langchain.agents import Tool\n",
    "\n",
    "\n",
    "# Chicken functions\n",
    "def list_chicken_recipes(query: str):     \n",
    "    return chickenDishList\n",
    "\n",
    "list_chicken_recipes_tool = Tool(name='Chicken Recipes tool', func= list_chicken_recipes, description=\"This tools lists the available Chicken Recipes it returns a list of recipes with a TITLE and a URL where you can fetch the recipe.\")\n",
    "\n",
    "# Dessert functions\n",
    "def list_dessert_recipes(query: str):        \n",
    "    return dessertList\n",
    "\n",
    "list_dessert_recipes_tool = Tool(name='Dessert Recipes tool', func=list_dessert_recipes, \n",
    "    description=\"This tools lists the available Dessert Recipes it returns a list of recipes with a TITLE and a URL where you can fetch the recipe.\")\n",
    "\n",
    "# Recipe fetcher functions\n",
    "def get_recipe(url: str):     \n",
    "    return get_recipe_as_json(url)\n",
    "\n",
    "get_recipe_as_json_tool = Tool(name='Get a Recipe tool', func=get_recipe, description=\"\"\"\n",
    "    Useful for fetching a particular recipe, you can only fetch a recipe with it's url, you must get that using another tool\n",
    "    It uses the https://schema.org/Recipe format to store it's recipes. \n",
    "    \"\"\")\n",
    "\n",
    "# Tool list\n",
    "tools = [list_chicken_recipes_tool, list_dessert_recipes_tool, get_recipe_as_json_tool]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 226,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Chicken dishes:\n",
      "Crispy Roasted Chicken\n",
      "Roasted Spatchcocked Chicken With Potatoes\n",
      "Easy Baked Chicken Thighs\n",
      "Crispy Baked Chicken Thighs\n",
      "Crispy and Tender Baked Chicken Thighs\n",
      "Million Dollar Chicken\n",
      "Simple Whole Roasted Chicken\n",
      "Beer Can Chicken\n",
      "Air Fryer Chicken Thighs\n",
      "Happy Roast Chicken\n",
      "\n",
      "Desserts:\n",
      "Chocolate Snack Cake\n",
      "Charred Spiced Pears with Smoky Vanilla Cherry Sauce\n",
      "Meringue Topped Banana Pudding\n",
      "White Chocolate Cinnamon Toast Crunch Bars\n",
      "Plum Cobbler for Two\n",
      "Pumpkin Cheesecake Cookies\n",
      "Chocolate Whipped Cottage Cheese\n",
      "Nutella Ice Cream\n",
      "3-Ingredient Banana Oatmeal Cookies\n",
      "Caramel Apple Pie Cookies\n"
     ]
    }
   ],
   "source": [
    "print('Chicken dishes:')\n",
    "for i in chickenDishList:\n",
    "    print(i['title'])\n",
    "    \n",
    "print('')\n",
    "print('Desserts:')\n",
    "for i in dessertList:\n",
    "    print(i['title'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# LLM\n",
    "Links\n",
    "\n",
    "\n",
    "1 [tracking-inspecting-prompts-langchain-agents-weights-and-biases](https://kleiber.me/blog/2023/05/14/tracking-inspecting-prompts-langchain-agents-weights-and-biases/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.agents import load_tools\n",
    "from langchain.agents import initialize_agent\n",
    "from langchain.llms import OpenAI\n",
    "from langchain.chat_models import ChatOpenAI\n",
    "from langchain.callbacks import StdOutCallbackHandler\n",
    "\n",
    "from langchain.agents import initialize_agent\n",
    "llm = ChatOpenAI(temperature=0, model_name='gpt-4') # 'gpt-3.5-turbo'\n",
    "\n",
    "agent = initialize_agent(\n",
    "    agent=\"zero-shot-react-description\", \n",
    "    tools=tools, \n",
    "    llm=llm,\n",
    "    verbose=True,\n",
    "    max_iterations=7,    \n",
    "    return_intermediate_steps=True\n",
    ")\n",
    "\n",
    "system = \"If the answer is not in the tools or context passed to you then don't answer. \\nIf you don't know the answer then say so.\" \n",
    "#query = \"Can you show tell me what ingredients I need for the first baked chicken recipe?\"\n",
    "#query = \"Can you show tell me what ingredients I need for the last baked chicken recipe? \"\n",
    "#query = \"What is the best baked chicken recipe? Please look across all recipes with the word 'baked' in the title\" # There are 3 baked chicken recipes\n",
    "#query = \"Is there a Chicken recipe that's prepared with an alchohol? And if so how long does it take in total from start time to finish?\"\n",
    "#query = \"Which is healthier the Caramel Apple Pie Cookies or the beer chicken? Please explain how you got to your answer.\"\n",
    "#query = \"Is the moon closer to earth or the sun?\"\n",
    "#query = \"How good are the apple pie cookies?\"\n",
    "query = \"What tools do I need for the Nutella Ice Cream?\"\n",
    "\n",
    "#query = \"My bowl is broken, can I still make Nutella Ice Cream? Answer as a yes/no.\"\n",
    "\n",
    "#response = agent({\"input\": f\"{system} {query}\"})\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 228,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Step: 1 of 2\n",
      "Thought: I need to find the recipe for Nutella Ice Cream to know what tools are needed.\n",
      "Action: Dessert Recipes tool\n",
      "Action Input: Nutella Ice Cream\n",
      "\n",
      "Action response: [{'title': 'Chocolate Snack Cake', 'url': 'https://www.allrecipes.com/chocolate-snack-cake-recipe-8350343'}, {'title': 'Charred Spiced Pears with Smoky Vanilla Cherry Sauce', 'url': 'https://www.allrecipes.com/charred-spiced-pears-with-smoky-vanilla-cherry-sauce-recipe-8347080'}, {'title': 'Meringue Topped Banana Pudding', 'url': 'https://www.allrecipes.com/meringue-topped-banana-pudding-recipe-8347040'}, {'title': 'White Chocolate Cinnamon Toast Crunch Bars', 'url': 'https://www.allrecipes.com/white-chocolate-cinnamon-toast-crunch-bars-recipe-7556790'}, {'title': 'Plum Cobbler for Two', 'url': 'https://www.allrecipes.com/plum-cobbler-for-two-recipe-8304143'}, {'title': 'Pumpkin Cheesecake Cookies', 'url': 'https://www.allrecipes.com/pumpkin-cheesecake-cookies-recipe-7972485'}, {'title': 'Chocolate Whipped Cottage Cheese', 'url': 'https://www.allrecipes.com/chocolate-whipped-cottage-cheese-recipe-8303272'}, {'title': 'Nutella Ice Cream', 'url': 'https://www.allrecipes.com/nutella-ice-cream-recipe-7508716'}, {'title': '3-Ingredient Banana Oatmeal Cookies', 'url': 'https://www.allrecipes.com/3-ingredient-banana-oatmeal-cookies-recipe-7972686'}, {'title': 'Caramel Apple Pie Cookies', 'url': 'https://www.allrecipes.com/caramel-apple-pie-cookies-recipe-7642173'}]\n",
      "###########################\n",
      "\n",
      "Step: 2 of 2\n",
      "Thought: I found the recipe for Nutella Ice Cream. Now I need to fetch the recipe to see what tools are needed.\n",
      "Action: Get a Recipe tool\n",
      "Action Input: https://www.allrecipes.com/nutella-ice-cream-recipe-7508716\n",
      "\n",
      "Action response: {'@context': 'http://schema.org', '@type': ['Recipe'], 'headline': 'Nutella Ice Cream', 'datePublished': '2023-09-28T17:27:33.088-04:00', 'dateModified': '2023-10-12T11:27:16.725-04:00', 'author': [{'@type': 'Person', 'name': 'Laka kuharika - Easy Cook', 'url': 'https://www.allrecipes.com/cook/lakakuharica'}], 'description': 'This exquisite homemade Nutella ice cream is full of nutty flavor, and everyone will simply love it. Nutella gives this ice cream an unbelievable hazelnut taste.', 'name': 'Nutella Ice Cream', 'cookTime': 'PT15M', 'nutrition': {'@type': 'NutritionInformation', 'calories': '305 kcal', 'carbohydrateContent': '16 g', 'cholesterolContent': '156 mg', 'fiberContent': '1 g', 'proteinContent': '8 g', 'saturatedFatContent': '14 g', 'sodiumContent': '78 mg', 'sugarContent': '14 g', 'fatContent': '23 g', 'unsaturatedFatContent': '0 g'}, 'prepTime': 'PT10M', 'recipeCategory': ['Dessert'], 'recipeCuisine': ['American'], 'recipeIngredient': ['2 cups whole milk', '1 cup heavy cream, divided', '4 egg yolks', '1/2 teaspoon vanilla extract', '1/2\\xa0 cup cocoa hazelnut spread (such as Nutella®)', 'Hazelnuts, crushed, for garnish'], 'recipeInstructions': [{'@type': 'HowToStep', 'text': 'Combine milk, cream, and 1/2 cup sugar in a saucepan over medium heat. Cook until sugar dissolves, about 5 minutes.'}, {'@type': 'HowToStep', 'text': 'Beat egg yolks with the remaining sugar in a bowl with an electric mixer until eggs become thick and pale yellow, about 4 minutes.'}, {'@type': 'HowToStep', 'text': 'Pour 1/2 cup warm milk mixture into egg mixture and stir. Add this mixture back into the saucepan. Cook over very low heat, stirring constantly, until the mixture becomes thick enough to coat the back of a wooden spoon, 7 to 10 minutes.'}, {'@type': 'HowToStep', 'text': 'Place a strainer over a bowl and pour the warm custard mixture through the strainer. Stir in vanilla and hazelnut spread until it dissolves.'}, {'@type': 'HowToStep', 'text': 'Chill mixture completely, about 1 hour. Pour into an ice cream maker and churn until frozen according to manufacturer’s instructions, 15 to 20 minutes.'}, {'@type': 'HowToStep', 'text': 'Transfer to a plastic container and place in the freezer for an hour before serving. Top with crushed hazelnuts for serving.'}], 'recipeYield': ['8'], 'totalTime': 'PT160M', 'about': []}\n",
      "###########################\n",
      "\n",
      "\n",
      "Final Thought: The tools needed for the Nutella Ice Cream recipe are a saucepan, an electric mixer, a wooden spoon, a strainer, a bowl, an ice cream maker, and a plastic container.\n"
     ]
    }
   ],
   "source": [
    "# from langchain.load.dump import dumps\n",
    "\n",
    "# stepsDict = json.loads(dumps(response[\"intermediate_steps\"], pretty=True))\n",
    "# for i in range(len(stepsDict)):\n",
    "#     print(f'Step: {i+1} of {len(stepsDict)}')\n",
    "#     print(f\"Thought: {stepsDict[i][0]['kwargs']['log']}\")\n",
    "#     print('')\n",
    "#     print(f\"Action response: {stepsDict[i][1]}\")\n",
    "#     print('###########################')\n",
    "#     print('')\n",
    "\n",
    "# print('')\n",
    "# print(f\"Final Thought: {response['output']}\")\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# UI - Simple UI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 236,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\sc\\ai\\rag-demo-1\\.venv\\lib\\site-packages\\gradio\\interface.py:330: UserWarning: The `allow_flagging` parameter in `Interface` nowtakes a string value ('auto', 'manual', or 'never'), not a boolean. Setting parameter to: 'never'.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running on local URL:  http://127.0.0.1:7899\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7899/\" 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": 236,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gradio as gr\n",
    "\n",
    "def ask_query(query):\n",
    "    response = agent({\"input\": f\"{system} {query}\"})\n",
    "    \n",
    "    stepsDict = json.loads(dumps(response[\"intermediate_steps\"], pretty=True))\n",
    "    resp = 'Below are the steps the agent took to get to the Final Answer. \\n\"Thought\" is the LLMs internal dialogue, \\n\"Action\" is the tool it will use to fetch the next piece of information. \\n\"Action Input\" is the input it passes the tool to fetch this information. \\n\"Action Response\" is what was returned from the tool to the LLM at that given step. '\n",
    "    resp += '\\n\\n'\n",
    "    resp += 'Steps to solve answer using ReAct\\n'\n",
    "    for i in range(len(stepsDict)):\n",
    "        resp += '##########################################\\n'\n",
    "        resp += f'Step: {i+1} of {len(stepsDict)}\\n'\n",
    "        resp += f\"Thought: {stepsDict[i][0]['kwargs']['log']}\\n\"\n",
    "        resp += 'Below is what the tool returned...\\n'\n",
    "        resp += f\"Action response: {stepsDict[i][1]}\\n\"        \n",
    "        resp += '\\n'\n",
    "\n",
    "    resp += '\\nFinal Thought:\\n'\n",
    "    resp += response['output']\n",
    "    return resp\n",
    "\n",
    "demo = gr.Interface(fn=ask_query, inputs=\"text\", outputs=\"text\", allow_flagging=False)\n",
    "#gr.Markdown(\"# Hello there\")\n",
    "#gr.Examples(\"text\", \"text\")\n",
    "demo.launch(show_error=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 240,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import gradio as gr\n",
    "\n",
    "# def ask_question(question):\n",
    "    \n",
    "#     # LLM   \n",
    "#    llm = ChatOpenAI(temperature=0, model_name='gpt-4') # 'gpt-3.5-turbo'\n",
    "#    agent = initialize_agent(agent=\"zero-shot-react-description\", tools=tools, llm=llm, verbose=True, max_iterations=7, return_intermediate_steps=True)\n",
    "#    system = \"If the answer is not in the tools or context passed to you then don't answer. \\nIf you don't know the answer then say so.\" \n",
    "#    # #question = \"Can you show tell me what ingredients I need for the first baked chicken recipe?\"\n",
    "#    # #question = \"Can you show tell me what ingredients I need for the last baked chicken recipe? \"\n",
    "#    # #question = \"What is the best baked chicken recipe? Please look across all recipes with the word 'baked' in the title\" # There are 3 baked chicken recipes\n",
    "#    # #question = \"Is there a Chicken recipe that's prepared with an alchohol? And if so how long does it take in total from start time to finish?\"\n",
    "#    # #question = \"Which is healthier the Caramel Apple Pie Cookies or the beer chicken? Please explain how you got to your answer.\"\n",
    "#    # #question = \"Is the moon closer to earth or the sun?\"\n",
    "#    # #question = \"How good are the apple pie cookies?\"\n",
    "#    # #question = \"What tools do I need for the Nutella Ice Cream?\"\n",
    "#    # #question = \"My bowl is broken, can I still make Nutella Ice Cream? Answer as a yes/no.\"\n",
    "#    response = agent({\"input\": f\"{system} {question}\"})\n",
    "\n",
    "#    # Show response    \n",
    "#    stepsDict = json.loads(dumps(response[\"intermediate_steps\"], pretty=True))\n",
    "#    resp = 'Below are the steps the agent took to get to the Final Answer. \\n\"Thought\" is the LLMs internal dialogue, \\n\"Action\" is the tool it will use to fetch the next piece of information. \\n\"Action Input\" is the input it passes the tool to fetch this information. \\n\"Action Response\" is what was returned from the tool to the LLM at that given step. '\n",
    "#    resp += '\\n\\n'\n",
    "#    resp += 'Steps to solve answer using ReAct\\n'\n",
    "#    for i in range(len(stepsDict)):\n",
    "#       resp += '##########################################\\n'\n",
    "#       resp += f'Step: {i+1} of {len(stepsDict)}\\n'\n",
    "#       resp += f\"Thought: {stepsDict[i][0]['kwargs']['log']}\\n\"\n",
    "#       resp += 'Below is what the tool returned...\\n'\n",
    "#       resp += f\"Action response: {stepsDict[i][1]}\\n\"        \n",
    "#       resp += '\\n'\n",
    "\n",
    "#    resp += '\\nFinal Thought:\\n'\n",
    "#    resp += response['output']\n",
    "#    return resp\n",
    "\n",
    "# with gr.Blocks() as demo:\n",
    "#     openAIKeyBox = gr.Text(label=\"OpenAI Key\")\n",
    "#     queryTB = gr.Textbox(label=\"Query\")\n",
    "#     submitBtn = gr.Button(\"Submit\")\n",
    "#     submitBtn.click(\n",
    "#         ask_question\n",
    "#     )\n",
    "\n",
    "# # demo = gr.Interface(fn=ask_query, inputs=\"text\", outputs=\"text\", allow_flagging=False)\n",
    "# # #gr.Markdown(\"# Hello there\")\n",
    "# # #gr.Examples(\"text\", \"text\")\n",
    "# # demo.launch(show_error=True)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "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.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}