File size: 2,928 Bytes
63ae673
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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]])