{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Function calling for nearby places: Leveraging the Google Places API and customer profiles\n",
    "\n",
    "This notebook is centered around the integration of the Google Places API and custom user profiles to enhance location-based searches. Our approach involves using the Google Places API in combination with user preferences, aiming to make location discovery more personal and relevant. Please note that while we focus on the Google Places API in this instance, there are numerous other APIs you could explore and apply in a similar fashion.\n",
    "\n",
    "We'll explore the application of three main components:\n",
    "\n",
    "- Customer profile: This mock profile captures individual preferences for types of places (e.g., restaurants, parks, museums), budget, preferred ratings, and other specific requirements. \n",
    "\n",
    "- Google Places API: This API provides real-time data about nearby places. It factors in various data points such as ratings, types of venues, costs, and more from the locations around you.\n",
    "\n",
    "- Function calling: A single command such as \"I'm hungry\" or \"I want to visit a museum\" activates the function which combines the user profile data and Google Places API to identify suitable venues.\n",
    "\n",
    "This notebook introduces two primary use cases:\n",
    "\n",
    "- Profile-based recommendations: Learn how to create a user profile and make place recommendations based on individual preferences.\n",
    "\n",
    "- API integration with function calling: Understand how to integrate and call Google Places API effectively to source real-time data of various places using function calling.\n",
    "\n",
    "Please note that while this system is highly versatile, its effectiveness may vary based on user preferences and available place data. For the purposes of this notebook, the customer data is fake and the location is hardcoded. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "Google Places API\n",
    "\n",
    "To use the Google Places API, you'll need two things:\n",
    "\n",
    "- Google Account: If you don't already have one, you will need to create a Google account.\n",
    "\n",
    "- Google Places API Key: The API key is a unique identifier that is used to authenticate requests associated with your project for usage and billing purposes. You can get your API key from the [Google Cloud Console](https://console.cloud.google.com/getting-started?authuser=1). \n",
    "\n",
    "\n",
    "\n",
    "Please note that Google Places API is a paid service, and the cost is associated with the number of API calls made. Keep track of your usage to avoid any unexpected charges.\n",
    "\n",
    "\n",
    "\n",
    "The requests library is also needed, you can download it by using the following command: \n",
    "\n",
    "```python\n",
    "pip install requests"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import openai\n",
    "import os\n",
    "import requests"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this code snippet, we are defining a function `fetch_customer_profile` that accepts a `user_id` and returns a mock user profile.\n",
    "\n",
    "This function simulates an API call that fetches user data from a database. For this demo, we're using hard-coded data. The user profile contains various details such as the user's location (set to the coordinates of the Golden Gate Bridge for this example), preferences in food and activities, app usage metrics, recent interactions, and user rank.\n",
    "\n",
    "In a production environment, you would replace this hard-coded data with a real API call to your user database.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fetch_customer_profile(user_id):\n",
    "    # You can replace this with a real API call in the production code\n",
    "    if user_id == \"user1234\":\n",
    "        return {\n",
    "            \"name\": \"John Doe\",\n",
    "            \"location\": {\n",
    "                \"latitude\": 37.7955,\n",
    "                \"longitude\": -122.4026,\n",
    "            },\n",
    "            \"preferences\": {\n",
    "                \"food\": [\"Italian\", \"Sushi\"],\n",
    "                \"activities\": [\"Hiking\", \"Reading\"],\n",
    "            },\n",
    "            \"behavioral_metrics\": {\n",
    "                \"app_usage\": {\n",
    "                    \"daily\": 2,  # hours\n",
    "                    \"weekly\": 14  # hours\n",
    "                },\n",
    "                \"favourite_post_categories\": [\"Nature\", \"Food\", \"Books\"],\n",
    "                \"active_time\": \"Evening\",\n",
    "            },\n",
    "            \"recent_searches\": [\"Italian restaurants nearby\", \"Book clubs\"],\n",
    "            \"recent_interactions\": [\"Liked a post about 'Best Pizzas in New York'\", \"Commented on a post about 'Central Park Trails'\"],\n",
    "            \"user_rank\": \"Gold\",  # based on some internal ranking system\n",
    "        }\n",
    "    else:\n",
    "        return None\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Requesting and processing data from Google Places API\n",
    "\n",
    "The function call_google_places_api serves to request information from the Google Places API and provide a list of the top two places based on a given place_type and optional food_preference. We've limited this function to the top two results to manage usage since this is a paid service. However, you can modify this to retrieve any number of results as per your requirement.\n",
    "\n",
    "The function is configured with a hardcoded location (set to the coordinates of the Transamerica Pyramid), your Google API key, and specific request parameters. Depending on the place_type, it formulates the appropriate API request URL. If the place_type is a restaurant and a food_preference is specified, it is included in the API request.\n",
    "\n",
    "After sending the GET request, the function checks the response status. If it's successful, it processes the JSON response, extracts the relevant details using the get_place_details function, and returns them in a human-readable format. If the request fails, it prints out the error for debugging.\n",
    "\n",
    "The get_place_details function is used to retrieve more detailed information about a place, given its place_id. It sends a GET request to the Google Place Details API and returns the result if the request is successful. If the request fails, it prints out the error for debugging.\n",
    "\n",
    "Both functions handle exceptions and return an error message if something goes wrong. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_place_details(place_id, api_key):\n",
    "    URL = f\"https://maps.googleapis.com/maps/api/place/details/json?place_id={place_id}&key={api_key}\"\n",
    "    response = requests.get(URL)\n",
    "    if response.status_code == 200:\n",
    "        result = json.loads(response.content)[\"result\"]\n",
    "        return result\n",
    "    else:\n",
    "        print(f\"Google Place Details API request failed with status code {response.status_code}\")\n",
    "        print(f\"Response content: {response.content}\")\n",
    "        return None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def call_google_places_api(user_id, place_type, food_preference=None):\n",
    "    try:\n",
    "        # Fetch customer profile\n",
    "        customer_profile = fetch_customer_profile(user_id)\n",
    "        if customer_profile is None:\n",
    "            return \"I couldn't find your profile. Could you please verify your user ID?\"\n",
    "\n",
    "        # Get location from customer profile\n",
    "        lat = customer_profile[\"location\"][\"latitude\"]\n",
    "        lng = customer_profile[\"location\"][\"longitude\"]\n",
    "\n",
    "        API_KEY = os.getenv('GOOGLE_PLACES_API_KEY')  # retrieve API key from environment variable\n",
    "        LOCATION = f\"{lat},{lng}\"\n",
    "        RADIUS = 500  # search within a radius of 500 meters\n",
    "        TYPE = place_type\n",
    "\n",
    "        # If the place_type is restaurant and food_preference is not None, include it in the API request\n",
    "        if place_type == 'restaurant' and food_preference:\n",
    "            URL = f\"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={LOCATION}&radius={RADIUS}&type={TYPE}&keyword={food_preference}&key={API_KEY}\"\n",
    "        else:\n",
    "            URL = f\"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={LOCATION}&radius={RADIUS}&type={TYPE}&key={API_KEY}\"\n",
    "\n",
    "        response = requests.get(URL)\n",
    "        if response.status_code == 200:\n",
    "            results = json.loads(response.content)[\"results\"]\n",
    "            places = []\n",
    "            for place in results[:2]:  # limit to top 2 results\n",
    "                place_id = place.get(\"place_id\")\n",
    "                place_details = get_place_details(place_id, API_KEY)  # Get the details of the place\n",
    "                \n",
    "                place_name = place_details.get(\"name\", \"N/A\")\n",
    "                place_types = next((t for t in place_details.get(\"types\", []) if t not in [\"food\", \"point_of_interest\"]), \"N/A\")  # Get the first type of the place, excluding \"food\" and \"point_of_interest\"\n",
    "                place_rating = place_details.get(\"rating\", \"N/A\")  # Get the rating of the place\n",
    "                total_ratings = place_details.get(\"user_ratings_total\", \"N/A\")  # Get the total number of ratings\n",
    "                place_address = place_details.get(\"vicinity\", \"N/A\")  # Get the vicinity of the place\n",
    "                \n",
    "                if ',' in place_address:  # If the address contains a comma\n",
    "                    street_address = place_address.split(',')[0]  # Split by comma and keep only the first part\n",
    "                else:\n",
    "                    street_address = place_address\n",
    "                \n",
    "                # Prepare the output string for this place\n",
    "                place_info = f\"{place_name} is a {place_types} located at {street_address}. It has a rating of {place_rating} based on {total_ratings} user reviews.\"\n",
    "                \n",
    "                places.append(place_info)\n",
    "\n",
    "            return places\n",
    "        else:\n",
    "            print(f\"Google Places API request failed with status code {response.status_code}\")\n",
    "            print(f\"Response content: {response.content}\")  # print out the response content for debugging\n",
    "            return []\n",
    "    except Exception as e:\n",
    "        print(f\"Error during the Google Places API call: {e}\")\n",
    "        return []"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Generating user-specific recommendations with GPT-3.5-Turbo and Google Places API\n",
    "\n",
    "The function `provide_user_specific_recommendations` interacts with GPT-3.5-Turbo and the Google Places API to provide responses tailored to a user's preferences and location.\n",
    "\n",
    "First, it fetches the customer's profile using their `user_id`. If no profile is found, it returns an error message.\n",
    "\n",
    "With a valid profile, it extracts the customer's food preferences and then interacts with the OpenAI model. It provides an initial system message, giving context to the AI model about its role, user preferences, and the usage of the Google Places API function.\n",
    "\n",
    "The user input is also sent to the model as a message, and the function `call_google_places_api` is defined in the `functions` parameter for the AI model to call as needed.\n",
    "\n",
    "Finally, it processes the model's response. If the model makes a function call to the Google Places API, the function is executed with the appropriate arguments, and the names of nearby places are returned. If there are no such places or the request isn't understood, appropriate error messages are returned.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "def provide_user_specific_recommendations(user_input, user_id):\n",
    "    customer_profile = fetch_customer_profile(user_id)\n",
    "    if customer_profile is None:\n",
    "        return \"I couldn't find your profile. Could you please verify your user ID?\"\n",
    "    \n",
    "    customer_profile_str = json.dumps(customer_profile)\n",
    "\n",
    "    food_preference = customer_profile.get('preferences', {}).get('food', [])[0] if customer_profile.get('preferences', {}).get('food') else None\n",
    "  \n",
    "\n",
    "    response = openai.ChatCompletion.create(\n",
    "        model=\"gpt-3.5-turbo\",\n",
    "        messages=[\n",
    "    {\n",
    "        \"role\": \"system\",\n",
    "        \"content\": f\"You are a sophisticated AI assistant, a specialist in user intent detection and interpretation. Your task is to perceive and respond to the user's needs, even when they're expressed in an indirect or direct manner. You excel in recognizing subtle cues: for example, if a user states they are 'hungry', you should assume they are seeking nearby dining options such as a restaurant or a cafe. If they indicate feeling 'tired', 'weary', or mention a long journey, interpret this as a request for accommodation options like hotels or guest houses. However, remember to navigate the fine line of interpretation and assumption: if a user's intent is unclear or can be interpreted in multiple ways, do not hesitate to politely ask for additional clarification. Make sure to tailor your responses to the user based on their preferences and past experiences which can be found here {customer_profile_str}\"\n",
    "    },\n",
    "    {\"role\": \"user\", \"content\": user_input}\n",
    "],\n",
    "        temperature=0,\n",
    "        functions=[\n",
    "            {\n",
    "                \"name\": \"call_google_places_api\",\n",
    "                \"description\": \"This function calls the Google Places API to find the top places of a specified type near a specific location. It can be used when a user expresses a need (e.g., feeling hungry or tired) or wants to find a certain type of place (e.g., restaurant or hotel).\",\n",
    "                \"parameters\": {\n",
    "                    \"type\": \"object\",\n",
    "                    \"properties\": {\n",
    "                        \"place_type\": {\n",
    "                            \"type\": \"string\",\n",
    "                            \"description\": \"The type of place to search for.\"\n",
    "                        }\n",
    "                    }\n",
    "                },\n",
    "                \"result\": {\n",
    "                    \"type\": \"array\",\n",
    "                    \"items\": {\n",
    "                        \"type\": \"string\"\n",
    "                    }\n",
    "                }\n",
    "            }\n",
    "        ],\n",
    "    )\n",
    "\n",
    "    if 'message' in response.choices[0] and 'function_call' in response.choices[0]['message']:\n",
    "        function_call = response.choices[0]['message']['function_call']\n",
    "        if function_call[\"name\"] == \"call_google_places_api\":\n",
    "            place_type = json.loads(function_call[\"arguments\"])[\"place_type\"]\n",
    "            places = call_google_places_api(user_id, place_type, food_preference)\n",
    "            if places:  # If the list of places is not empty\n",
    "                return f\"Here are some places you might be interested in: {' '.join(places)}\"\n",
    "            else:\n",
    "                return \"I couldn't find any places of interest nearby.\"\n",
    "\n",
    "    return \"I am sorry, but I could not understand your request.\"\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Executing user-specific recommendations\n",
    "\n",
    "Upon execution, the function fetches the user's profile, interacts with the AI model, processes the model's response, calls the Google Places API if necessary, and ultimately returns a list of recommendations tailored to the user's preferences and location. The printed output would consist of these personalized recommendations.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Here are some places you might be interested in: Mona Lisa Restaurant is a restaurant located at 353 Columbus Avenue #3907. It has a rating of 4.3 based on 1784 user reviews. Tommaso's Ristorante Italiano is a restaurant located at 1042 Kearny Street. It has a rating of 4.5 based on 732 user reviews.\n"
     ]
    }
   ],
   "source": [
    "user_id = \"user1234\"  \n",
    "user_input = \"I'm hungry\"  \n",
    "output = provide_user_specific_recommendations(user_input, user_id)\n",
    "print(output)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.9"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
