{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "\n",
        "# Lyrics Finder Tool using OpenAGI and Serper API\n",
        "\n",
        "This notebook demonstrates how to create a Custom Lyrics Finder Tool using OpenAGI and the Serper API. The tool searches for song information based on the artist and song title.\n",
        "\n",
        "## Setup Instructions\n",
        "\n",
        "1. **Restart the Colab session**: To avoid dependency errors, please restart the Colab session before running the code.\n",
        "\n",
        "   - Go to Runtime > Restart runtime\n",
        "   - After restarting, run all cells from the beginning\n",
        "\n",
        "2. **Install required packages**:\n",
        "   Run the following cell to install the necessary packages:"
      ],
      "metadata": {
        "id": "u5H3RmYIpX15"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "fNBlyeuJZ_7V"
      },
      "outputs": [],
      "source": [
        "pip install openagi langchain-google-genai"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Importing necessary modules"
      ],
      "metadata": {
        "id": "9eqapL3yqB-8"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "import json\n",
        "import http.client\n",
        "from typing import Any\n",
        "from openagi.actions.base import BaseAction\n",
        "from pydantic import Field\n",
        "from openagi.agent import Admin\n",
        "from openagi.llms.openai import OpenAIModel\n",
        "from openagi.memory import Memory\n",
        "from openagi.planner.task_decomposer import TaskPlanner\n",
        "from openagi.worker import Worker\n",
        "from openagi.actions.tools.serper_search import SerperSearch"
      ],
      "metadata": {
        "id": "9Shu0F8KaEL8"
      },
      "execution_count": 21,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        " **Set up API keys**:\n",
        "You'll need to set up the OpenAI API key"
      ],
      "metadata": {
        "id": "OGaA2eHxpXZ8"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "os.environ['OPENAI_API_KEY'] = \"sk-<your-api-key>\"\n",
        "\n",
        "config = OpenAIModel.load_from_env_config()\n",
        "llm = OpenAIModel(config=config)"
      ],
      "metadata": {
        "id": "3ryV6JKSaFzC"
      },
      "execution_count": 22,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### LyricsFinderTool Class:\n",
        "- Custom tool utilizing Serper API for song information searches\n",
        "- Implements the execute method for performing searches\n"
      ],
      "metadata": {
        "id": "zxEwG7eUqPNl"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "\n",
        "class LyricsFinderTool(BaseAction):\n",
        "    \"\"\"\n",
        "    This tool searches for song lyrics based on the artist and song title using Serper.\n",
        "    \"\"\"\n",
        "    artist: str = Field(\n",
        "        default_factory=str,\n",
        "        description=\"Name of the artist whose lyrics are to be searched.\"\n",
        "    )\n",
        "    song_title: str = Field(\n",
        "        default_factory=str,\n",
        "        description=\"Title of the song whose lyrics are to be searched.\"\n",
        "    )\n",
        "\n",
        "    def execute(self):\n",
        "        # Construct the search query\n",
        "        query = f\"{self.artist} {self.song_title} lyrics\"\n",
        "\n",
        "        # Set up the connection to Serper API\n",
        "        conn = http.client.HTTPSConnection(\"google.serper.dev\")\n",
        "        payload = json.dumps({\"q\": query})\n",
        "        headers = {\n",
        "            'X-API-KEY': '<your-serper-api-key>',\n",
        "            'Content-Type': 'application/json'\n",
        "        }\n",
        "\n",
        "        # Make the request\n",
        "        conn.request(\"POST\", \"/search\", payload, headers)\n",
        "        res = conn.getresponse()\n",
        "        data = json.loads(res.read().decode(\"utf-8\"))\n",
        "\n",
        "        # Extract lyrics from the search results\n",
        "        full_lyrics = \"\"\n",
        "        for result in data.get('organic', []):\n",
        "            if 'snippet' in result:\n",
        "                full_lyrics += result['snippet'] + \"\\n\\n\"\n",
        "\n",
        "        if full_lyrics:\n",
        "            return full_lyrics.strip()\n",
        "        else:\n",
        "            return \"Sorry, no lyrics found for the given artist and song title.\""
      ],
      "metadata": {
        "id": "tjuoBcqDaJP5"
      },
      "execution_count": 30,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Worker Setup:\n",
        "- Creates a specialized worker for song information retrieval\n",
        "- Defines the role and instructions for the worker"
      ],
      "metadata": {
        "id": "BIYcltXfrHpC"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Create a worker for searching lyrics\n",
        "song_searcher = Worker(\n",
        "    role=\"Lyrics Searcher\",\n",
        "    instructions=\"\"\"\n",
        "    You are an Expert Music Search Assistant with a deep understanding of song lyrics and music databases.\n",
        "    - Focus on finding lyrics for specific songs based on user queries.\n",
        "    - Utilize the Lyrics Finder Tool to search for song lyrics by song name and optional artist name.\n",
        "    - Ensure accurate retrieval of lyrics and provide them in a user-friendly format.\n",
        "    - Be attentive to user preferences and provide additional context about the song when available.\n",
        "    \"\"\",\n",
        "    actions=[LyricsFinderTool],\n",
        ")"
      ],
      "metadata": {
        "id": "0soLpQnHaNQR"
      },
      "execution_count": 33,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Admin Setup:\n",
        "- Configures an Admin to manage the worker and execute tasks\n",
        "- Utilizes OpenAI's language model for natural language processing"
      ],
      "metadata": {
        "id": "6sgLJSYCrL89"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "admin = Admin(\n",
        "    actions=[],\n",
        "    planner=TaskPlanner(human_intervene=False),\n",
        "    llm=llm,\n",
        ")\n",
        "\n",
        "admin.assign_workers([song_searcher])\n"
      ],
      "metadata": {
        "id": "Nw2Ed8kYaTB-"
      },
      "execution_count": 34,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Execution:\n",
        "- Runs the admin with a specific query to find song information"
      ],
      "metadata": {
        "id": "MTjb9murrSLQ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "res = admin.run(\n",
        "    query=\"provide the lyrics of the song\",\n",
        "    description=\"\"\"\n",
        "    Please provide the lyrics for the song \"Bohemian Rhapsody\"( 1975) by the band Queen. The lyrics should be formatted in a clear and easy-to-read manner, with each verse and chorus clearly separated.\n",
        "    \"\"\",\n",
        ")\n",
        "print(res)\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "xd351T05aZOb",
        "outputId": "4ed3daeb-9551-4f48-aad7-e80b9bac031a"
      },
      "execution_count": 37,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "WARNING:root:No Tasks to summarize.\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "\n",
            "Tasks: [{'task_name': \"Retrieve Lyrics for 'Bohemian Rhapsody' by Queen\", 'description': \"Use the LyricsFinderTool to search and retrieve the lyrics for the song 'Bohemian Rhapsody' by the band Queen. The lyrics should be formatted in a clear and easy-to-read manner, with each verse and chorus clearly separated. Provide the lyrics in a user-friendly format and ensure the accuracy of the content.\", 'worker_id': '5d3a5fde7ab84b299c079fc9c15aa26b'}]\n",
            "\n",
            "\n",
            "### Final Output\n",
            "\n",
            "[Intro]  \n",
            "Is this the real life? Is this just fantasy?  \n",
            "Caught in a landslide, no escape from reality.  \n",
            "Open your eyes, look up to the skies and see  \n",
            "\n",
            "[Guitar Solo 2]  \n",
            "Ooh, yeah. Ooh, yeah  \n",
            "\n",
            "[Outro: Freddie Mercury & (Audience)]  \n",
            "Nothing really matters, anyone can see (Nothing really matters)  \n",
            "\n",
            "Is this the real life? Is this just fantasy?  \n",
            "Caught in a landslide. No escape from reality.  \n",
            "Open your eyes. Look up to the skies and see  \n",
            "\n",
            "I'm just a poor boy and nobody loves me.  \n",
            "He's just a poor boy from a poor family,  \n",
            "Spare him his life from this monstrosity.  \n",
            "Easy come, easy go, will you let me...\n"
          ]
        }
      ]
    }
  ]
}
