chatbot / lv_recipe_chatbot /vegan_recipe_tools.py
Evan Lesmez
Change from langchain to openAI assistant + other apis #1206495920334457
3811482
raw
history blame
2.58 kB
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/02_vegan_recipe_tools.ipynb.
# %% auto 0
__all__ = ['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 openai import OpenAI
import json
from .utils import load_json, dump_json
import constants
from tenacity import retry, wait_random_exponential, stop_after_attempt
# %% ../nbs/02_vegan_recipe_tools.ipynb 9
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"
query = params["q"]
if "vegan" not in query.lower():
params["q"] = "vegan " + query
return requests.get("https://api.edamam.com/api/recipes/v2", params=params)
# %% ../nbs/02_vegan_recipe_tools.ipynb 13
def vegan_recipe_edamam_search(query: str) -> str:
"""
Searches for vegan recipes based on a query.
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 json.dumps(
{
"ok": False,
"msg": f"The query is too long, try again with a query that is under {max_chars} characters in length.",
}
)
params = {
"q": query,
"field": ["label", "url", "totalTime", "ingredientLines", "image"],
}
response = get_vegan_recipes_edamam_api(params)
if not response.ok:
return json.dumps(
{
"ok": False,
"msg": f"Received an error from Edamam API: {response.status_code} {response.text}",
}
)
if response.json()["count"] <= 0:
return json.dumps(
{
"ok": False,
"msg": 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.
Recommend trying again with fewer words in the query.""",
}
)
return json.dumps(
{"ok": True, "recipes": [r["recipe"] for r in response.json()["hits"][0:3]]}
)