chatbot / lv_recipe_chatbot /vegan_recipe_tools.py
Evan Lesmez
Update prompting to direct towards edamam tool
63ae673
raw
history blame
2.93 kB
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/02_vegan_recipe_tools.ipynb.
# %% auto 0
__all__ = ['RecipeSerpAPIWrapper', 'get_vegan_recipes_edamam_api', 'vegan_recipe_edamam_search']
# %% ../nbs/02_vegan_recipe_tools.ipynb 3
import os
from typing import Dict
import requests
from IPython.display import Image, Markdown, display
from langchain.agents import (
AgentExecutor,
AgentType,
OpenAIFunctionsAgent,
Tool,
initialize_agent,
load_tools,
)
from langchain.agents.agent_toolkits import create_python_agent
from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory
from langchain.prompts import MessagesPlaceholder
from langchain.python import PythonREPL
from langchain.schema import SystemMessage
from langchain.tools import tool
from langchain.tools.python.tool import PythonREPLTool
from langchain.utilities import GoogleSerperAPIWrapper, SerpAPIWrapper
from serpapi import GoogleSearch
# %% ../nbs/02_vegan_recipe_tools.ipynb 21
class RecipeSerpAPIWrapper(SerpAPIWrapper):
@staticmethod
def _process_response(res: dict) -> str:
"""Process response from SerpAPI."""
if "error" in res.keys():
raise ValueError(f"Got error from SerpAPI: {res['error']}")
if "recipes_results" in res.keys():
return res["recipes_results"]
# %% ../nbs/02_vegan_recipe_tools.ipynb 48
def get_vegan_recipes_edamam_api(params: Dict) -> requests.Response:
"""
type is required and can be "any", "public", "user"
"""
if "health" in params:
params["health"].append("vegan")
else:
params["health"] = ["vegan"]
params["app_id"] = os.environ["EDAMAM_APP_ID"]
params["app_key"] = os.environ["EDAMAM_APP_KEY"]
params["type"] = "public"
return requests.get("https://api.edamam.com/api/recipes/v2", params=params)
# %% ../nbs/02_vegan_recipe_tools.ipynb 55
@tool
def vegan_recipe_edamam_search(query: str) -> str:
"""
Searches for vegan recipes based on a query.
If the query is not vegan friendly, adapt it to be.
If the request fails an explanation message will be returned instead of the recipe JSON.
"""
# Veganize the query more
if "vegan" not in query.lower():
query = "vegan " + query
# TODO integrate additional params like totalTime range, cuisineType choice, nutrients[PROCNT] range of protein, health additional health params like gluten-free
params = {
"q": query,
"field": ["label", "url", "totalTime", "ingredientLines"]
# todo figure out how to include "image", "totalNutrients", "ingredientLines" without going over token limits immediately.
}
response = get_vegan_recipes_edamam_api(params)
if not response.ok:
return f"Received an error from Edamam API: {response.status_code} {response.text }"
return str([r["recipe"] for r in response.json()["hits"][0:3]])