thrag commited on
Commit
da4b287
1 Parent(s): d5bc134

Getting ready for app.py

Browse files
Files changed (2) hide show
  1. app.py +264 -37
  2. demo-tools-1.ipynb +14 -47
app.py CHANGED
@@ -1,44 +1,271 @@
 
1
  import os
2
- import gradio as gr
3
- from huggingface_hub import Repository
 
 
 
 
4
 
5
- def greet(name):
6
- # returnValue = "Hello " + name + "!!"
7
- returnValue = ""
8
 
9
- textFilename = f'./data/test.txt'
10
 
11
- try:
12
-
13
- returnValue = os.listdir(name)
14
-
15
- except Exception as err:
16
- returnValue = str(err)
17
-
18
- return returnValue
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- # try:
21
 
22
- # with open(textFilename, 'w') as f:
23
- # f.write(returnValue)
24
-
25
- # except Exception as err:
26
- # returnValue = str(err)
27
- ##################################
28
- # try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- # file = open(textFilename, "r")
31
- # content = file.read()
32
- # returnValue = content
33
- # file.close()
34
-
35
- # except Exception as err:
36
- # returnValue = str(err)
37
-
38
- # return returnValue
39
-
40
- iface = gr.Interface(fn=greet,
41
- inputs=gr.TextArea(label="Name"),
42
- outputs="text")
43
-
44
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%
2
  import os
3
+ import json
4
+
5
+ # Load setting from Json outside of project.
6
+ f = open('../../env/ai.json')
7
+ settingsJson = json.load(f)
8
+ del f
9
 
10
+ for key in settingsJson:
11
+ os.environ[key] = settingsJson[key]
 
12
 
13
+ del settingsJson
14
 
15
+ # # OR manually set them
16
+ # os.environ['REQUESTS_CA_BUNDLE'] = '../../env/ZCert.pem'
17
+ # os.environ['HUGGING_FACE_API_KEY'] = 'Get here: https://huggingface.co/settings/tokens'
18
+ # os.environ['OPENAI_API_KEY'] = 'Get here: https://platform.openai.com/account/api-keys'
19
+ # os.environ["SERPAPI_API_KEY"] = 'serpapi KEY, Get here: https://serpapi.com/manage-api-key'
20
+
21
+ # %% [markdown]
22
+ # # Setup Web Crawler and Lookup functions
23
+
24
+ # %%
25
+ import requests
26
+ from bs4 import BeautifulSoup
27
+ import json
28
+ import validators
29
+
30
+ def remove_keys(dictionary: dict, keyList: list):
31
+ for key in keyList:
32
+ if key in dictionary:
33
+ del dictionary[key]
34
+
35
+ def get_recipe_as_json(url: str) -> dict:
36
 
37
+ url = url.replace("'", "").replace('"', '')
38
 
39
+ if not validators.url(url):
40
+ return {'error': 'Invalid url format', 'url': url }
41
+
42
+ html = requests.get(url).text
43
+ soup = BeautifulSoup(html, features='html.parser')
44
+ script = soup.find_all("script", {"id": "allrecipes-schema_1-0"})
45
+
46
+ recipeDict = json.loads(script[0].text)[0]
47
+ remove_keys(recipeDict, ['review', 'image', 'mainEntityOfPage', 'publisher'])
48
+
49
+ return recipeDict
50
+
51
+ # url = "https://www.allrecipes.com/recipe/212498/easy-chicken-and-broccoli-alfredo/"
52
+ # obj = get_recipe_as_json(url)
53
+ # x = get_recipe_as_json('https://www.allrecipes.com/recipe/235153/easy-baked-chicken-thighs/')
54
+ # print(x)
55
+
56
+ # %% [markdown]
57
+ # # Static recipe lists
58
+
59
+ # %%
60
+ dessertList = [
61
+ {
62
+ "title": "Chocolate Snack Cake",
63
+ "url": "https://www.allrecipes.com/chocolate-snack-cake-recipe-8350343"
64
+ },
65
+ {
66
+ "title": "Charred Spiced Pears with Smoky Vanilla Cherry Sauce",
67
+ "url": "https://www.allrecipes.com/charred-spiced-pears-with-smoky-vanilla-cherry-sauce-recipe-8347080"
68
+ },
69
+ {
70
+ "title": "Meringue Topped Banana Pudding",
71
+ "url": "https://www.allrecipes.com/meringue-topped-banana-pudding-recipe-8347040"
72
+ },
73
+ {
74
+ "title": "White Chocolate Cinnamon Toast Crunch Bars",
75
+ "url": "https://www.allrecipes.com/white-chocolate-cinnamon-toast-crunch-bars-recipe-7556790"
76
+ },
77
+ {
78
+ "title": "Plum Cobbler for Two",
79
+ "url": "https://www.allrecipes.com/plum-cobbler-for-two-recipe-8304143"
80
+ },
81
+ {
82
+ "title": "Pumpkin Cheesecake Cookies",
83
+ "url": "https://www.allrecipes.com/pumpkin-cheesecake-cookies-recipe-7972485"
84
+ },
85
+ {
86
+ "title": "Chocolate Whipped Cottage Cheese",
87
+ "url": "https://www.allrecipes.com/chocolate-whipped-cottage-cheese-recipe-8303272"
88
+ },
89
+ {
90
+ "title": "Nutella Ice Cream",
91
+ "url": "https://www.allrecipes.com/nutella-ice-cream-recipe-7508716"
92
+ },
93
+ {
94
+ "title": "3-Ingredient Banana Oatmeal Cookies",
95
+ "url": "https://www.allrecipes.com/3-ingredient-banana-oatmeal-cookies-recipe-7972686"
96
+ },
97
+ {
98
+ "title": "Caramel Apple Pie Cookies",
99
+ "url": "https://www.allrecipes.com/caramel-apple-pie-cookies-recipe-7642173"
100
+ }
101
+ ]
102
+
103
+ chickenDishList = [
104
+ {
105
+ "title": "Crispy Roasted Chicken",
106
+ "url": "https://www.allrecipes.com/recipe/228363/crispy-roasted-chicken/"
107
+ },
108
+ {
109
+ "title": "Roasted Spatchcocked Chicken With Potatoes",
110
+ "url": "https://www.allrecipes.com/recipe/254877/roasted-spatchcocked-chicken-with-potatoes/"
111
+ },
112
+ {
113
+ "title": "Easy Baked Chicken Thighs",
114
+ "url": "https://www.allrecipes.com/recipe/235153/easy-baked-chicken-thighs/"
115
+ },
116
+ {
117
+ "title": "Crispy Baked Chicken Thighs",
118
+ "url": "https://www.allrecipes.com/recipe/258878/crispy-baked-chicken-thighs/"
119
+ },
120
+ {
121
+ "title": "Crispy and Tender Baked Chicken Thighs",
122
+ "url": "https://www.allrecipes.com/recipe/235151/crispy-and-tender-baked-chicken-thighs/"
123
+ },
124
+ {
125
+ "title": "Million Dollar Chicken",
126
+ "url": "https://www.allrecipes.com/recipe/233953/million-dollar-chicken/"
127
+ },
128
+ {
129
+ "title": "Simple Whole Roasted Chicken",
130
+ "url": "https://www.allrecipes.com/recipe/70679/simple-whole-roasted-chicken/"
131
+ },
132
+ {
133
+ "title": "Beer Can Chicken",
134
+ "url": "https://www.allrecipes.com/recipe/214618/beer-can-chicken/"
135
+ },
136
+ {
137
+ "title": "Air Fryer Chicken Thighs",
138
+ "url": "https://www.allrecipes.com/recipe/272858/air-fryer-chicken-thighs/"
139
+ },
140
+ {
141
+ "title": "Happy Roast Chicken",
142
+ "url": "https://www.allrecipes.com/recipe/214478/happy-roast-chicken/"
143
+ }
144
+ ]
145
+
146
+
147
+
148
+ # %% [markdown]
149
+ # # Setup Tools
150
+
151
+ # %%
152
+ # Tools
153
+ from langchain.agents import Tool
154
+
155
+
156
+ # Chicken functions
157
+ def list_chicken_recipes(query: str):
158
+ return chickenDishList
159
+
160
+ 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.")
161
+
162
+ # Dessert functions
163
+ def list_dessert_recipes(query: str):
164
+ return dessertList
165
+
166
+ list_dessert_recipes_tool = Tool(name='Dessert Recipes tool', func=list_dessert_recipes,
167
+ 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.")
168
+
169
+ # Recipe fetcher functions
170
+ def get_recipe(url: str):
171
+ return get_recipe_as_json(url)
172
+
173
+ get_recipe_as_json_tool = Tool(name='Get a Recipe tool', func=get_recipe, description="""
174
+ Useful for fetching a particular recipe, you can only fetch a recipe with it's url, you must get that using another tool
175
+ It uses the https://schema.org/Recipe format to store it's recipes.
176
+ """)
177
+
178
+ # Tool list
179
+ tools = [list_chicken_recipes_tool, list_dessert_recipes_tool, get_recipe_as_json_tool]
180
+
181
+ # %%
182
+ print('Chicken dishes:')
183
+ for i in chickenDishList:
184
+ print(i['title'])
185
 
186
+ print('')
187
+ print('Desserts:')
188
+ for i in dessertList:
189
+ print(i['title'])
190
+
191
+ # %% [markdown]
192
+ # # LLM
193
+ # Links
194
+ #
195
+ #
196
+ # 1 [tracking-inspecting-prompts-langchain-agents-weights-and-biases](https://kleiber.me/blog/2023/05/14/tracking-inspecting-prompts-langchain-agents-weights-and-biases/)
197
+
198
+ # %%
199
+ from langchain.agents import load_tools
200
+ from langchain.agents import initialize_agent
201
+ from langchain.llms import OpenAI
202
+ from langchain.chat_models import ChatOpenAI
203
+ from langchain.callbacks import StdOutCallbackHandler
204
+ from langchain.agents import initialize_agent
205
+
206
+ # llm = ChatOpenAI(temperature=0, model_name='gpt-4') # 'gpt-3.5-turbo'
207
+ # agent = initialize_agent(agent="zero-shot-react-description", tools=tools, llm=llm, verbose=True, max_iterations=7, return_intermediate_steps=True)
208
+
209
+ # 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."
210
+ # #query = "Can you show tell me what ingredients I need for the first baked chicken recipe?"
211
+ # #query = "Can you show tell me what ingredients I need for the last baked chicken recipe? "
212
+ # #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
213
+ # #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?"
214
+ # #query = "Which is healthier the Caramel Apple Pie Cookies or the beer chicken? Please explain how you got to your answer."
215
+ # #query = "Is the moon closer to earth or the sun?"
216
+ # #query = "How good are the apple pie cookies?"
217
+ # query = "What tools do I need for the Nutella Ice Cream?"
218
+
219
+ # #query = "My bowl is broken, can I still make Nutella Ice Cream? Answer as a yes/no."
220
+
221
+ # response = agent({"input": f"{system} {query}"})
222
+
223
+ # %%
224
+ from langchain.load.dump import dumps
225
+
226
+ # %% [markdown]
227
+ # # UI - Simple UI
228
+
229
+ # %%
230
+ import gradio as gr
231
+
232
+ def ask_query(query):
233
+
234
+ # LLM
235
+ llm = ChatOpenAI(temperature=0, model_name='gpt-4') # 'gpt-3.5-turbo'
236
+ agent = initialize_agent(agent="zero-shot-react-description", tools=tools, llm=llm, verbose=True, max_iterations=7, return_intermediate_steps=True)
237
+ 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."
238
+ # #query = "Can you show tell me what ingredients I need for the first baked chicken recipe?"
239
+ # #query = "Can you show tell me what ingredients I need for the last baked chicken recipe? "
240
+ # #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
241
+ # #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?"
242
+ # #query = "Which is healthier the Caramel Apple Pie Cookies or the beer chicken? Please explain how you got to your answer."
243
+ # #query = "Is the moon closer to earth or the sun?"
244
+ # #query = "How good are the apple pie cookies?"
245
+ #query = "What tools do I need for the Nutella Ice Cream?"
246
+ # #query = "My bowl is broken, can I still make Nutella Ice Cream? Answer as a yes/no."
247
+ response = agent({"input": f"{system} {query}"})
248
+
249
+ # Show response
250
+ stepsDict = json.loads(dumps(response["intermediate_steps"], pretty=True))
251
+ 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. '
252
+ resp += '\n\n'
253
+ resp += 'Steps to solve answer using ReAct\n'
254
+ for i in range(len(stepsDict)):
255
+ resp += '##########################################\n'
256
+ resp += f'Step: {i+1} of {len(stepsDict)}\n'
257
+ resp += f"Thought: {stepsDict[i][0]['kwargs']['log']}\n"
258
+ resp += 'Below is what the tool returned...\n'
259
+ resp += f"Action response: {stepsDict[i][1]}\n"
260
+ resp += '\n'
261
+
262
+ resp += '\nFinal Thought:\n'
263
+ resp += response['output']
264
+ return resp
265
+
266
+ demo = gr.Interface(fn=ask_query, inputs="text", outputs="text", allow_flagging=False)
267
+ #gr.Markdown("# Hello there")
268
+ #gr.Examples("text", "text")
269
+ demo.launch(show_error=True)
270
+
271
+
demo-tools-1.ipynb CHANGED
@@ -274,37 +274,9 @@
274
  },
275
  {
276
  "cell_type": "code",
277
- "execution_count": 227,
278
  "metadata": {},
279
- "outputs": [
280
- {
281
- "name": "stdout",
282
- "output_type": "stream",
283
- "text": [
284
- "\n",
285
- "\n",
286
- "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n"
287
- ]
288
- },
289
- {
290
- "name": "stdout",
291
- "output_type": "stream",
292
- "text": [
293
- "\u001b[32;1m\u001b[1;3mI need to find the recipe for Nutella Ice Cream to know what tools are needed.\n",
294
- "Action: Dessert Recipes tool\n",
295
- "Action Input: Nutella Ice Cream\u001b[0m\n",
296
- "Observation: \u001b[33;1m\u001b[1;3m[{'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'}]\u001b[0m\n",
297
- "Thought:\u001b[32;1m\u001b[1;3mI found the recipe for Nutella Ice Cream. Now I need to fetch the recipe to see what tools are needed.\n",
298
- "Action: Get a Recipe tool\n",
299
- "Action Input: https://www.allrecipes.com/nutella-ice-cream-recipe-7508716\u001b[0m\n",
300
- "Observation: \u001b[38;5;200m\u001b[1;3m{'@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': []}\u001b[0m\n",
301
- "Thought:\u001b[32;1m\u001b[1;3mI now know the tools needed for the Nutella Ice Cream recipe.\n",
302
- "Final Answer: 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.\u001b[0m\n",
303
- "\n",
304
- "\u001b[1m> Finished chain.\u001b[0m\n"
305
- ]
306
- }
307
- ],
308
  "source": [
309
  "from langchain.agents import load_tools\n",
310
  "from langchain.agents import initialize_agent\n",
@@ -336,7 +308,7 @@
336
  "\n",
337
  "#query = \"My bowl is broken, can I still make Nutella Ice Cream? Answer as a yes/no.\"\n",
338
  "\n",
339
- "response = agent({\"input\": f\"{system} {query}\"})\n"
340
  ]
341
  },
342
  {
@@ -370,24 +342,19 @@
370
  }
371
  ],
372
  "source": [
373
- "from langchain.load.dump import dumps\n",
374
- "\n",
375
- "# for k in response:\n",
376
- "# print(k)\n",
377
  "\n",
378
- "# print(response['output'])\n",
 
 
 
 
 
 
 
379
  "\n",
380
- "stepsDict = json.loads(dumps(response[\"intermediate_steps\"], pretty=True))\n",
381
- "for i in range(len(stepsDict)):\n",
382
- " print(f'Step: {i+1} of {len(stepsDict)}')\n",
383
- " print(f\"Thought: {stepsDict[i][0]['kwargs']['log']}\")\n",
384
- " print('')\n",
385
- " print(f\"Action response: {stepsDict[i][1]}\")\n",
386
- " print('###########################')\n",
387
- " print('')\n",
388
- "\n",
389
- "print('')\n",
390
- "print(f\"Final Thought: {response['output']}\")\n",
391
  "\n"
392
  ]
393
  },
 
274
  },
275
  {
276
  "cell_type": "code",
277
+ "execution_count": null,
278
  "metadata": {},
279
+ "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  "source": [
281
  "from langchain.agents import load_tools\n",
282
  "from langchain.agents import initialize_agent\n",
 
308
  "\n",
309
  "#query = \"My bowl is broken, can I still make Nutella Ice Cream? Answer as a yes/no.\"\n",
310
  "\n",
311
+ "#response = agent({\"input\": f\"{system} {query}\"})\n"
312
  ]
313
  },
314
  {
 
342
  }
343
  ],
344
  "source": [
345
+ "# from langchain.load.dump import dumps\n",
 
 
 
346
  "\n",
347
+ "# stepsDict = json.loads(dumps(response[\"intermediate_steps\"], pretty=True))\n",
348
+ "# for i in range(len(stepsDict)):\n",
349
+ "# print(f'Step: {i+1} of {len(stepsDict)}')\n",
350
+ "# print(f\"Thought: {stepsDict[i][0]['kwargs']['log']}\")\n",
351
+ "# print('')\n",
352
+ "# print(f\"Action response: {stepsDict[i][1]}\")\n",
353
+ "# print('###########################')\n",
354
+ "# print('')\n",
355
  "\n",
356
+ "# print('')\n",
357
+ "# print(f\"Final Thought: {response['output']}\")\n",
 
 
 
 
 
 
 
 
 
358
  "\n"
359
  ]
360
  },