chatbot / lv_recipe_chatbot /vegan_recipe_tools.py
Evan Lesmez
Fix errored imports
6b5c559
raw
history blame
3.49 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 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 54
@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 should be returned.
If the cause of the failure was due to no recipes found, prompt the user to try again with a provided shorter query with one word removed.
"""
max_chars = 45 # 5 chars per word * 9 max words
if len(query) > max_chars:
return f"The query is too long, try again with a query that is under {max_chars} characters in length."
# 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}"
)
if response.json()["count"] <= 0:
return f"""No recipes found for query {query}.
This usually occurs when there are too many keywords or ingredients that are not commonly found together in recipes.
I recommend trying again with `{' '.join(query.split(' ')[0:-1])}.`"""
return str([r["recipe"] for r in response.json()["hits"][0:3]])