{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "683953b3",
   "metadata": {},
   "source": [
    "# Clarifai\n",
    "\n",
    ">[Clarifai](https://www.clarifai.com/) is an AI Platform that provides the full AI lifecycle ranging from data exploration, data labeling, model training, evaluation, and inference. A Clarifai application can be used as a vector database after uploading inputs. \n",
    "\n",
    "This notebook shows how to use functionality related to the `Clarifai` vector database. Examples are shown to demonstrate text semantic search capabilities. Clarifai also supports semantic search with images, video frames, and localized search (see [Rank](https://docs.clarifai.com/api-guide/search/rank)) and attribute search (see [Filter](https://docs.clarifai.com/api-guide/search/filter)).\n",
    "\n",
    "To use Clarifai, you must have an account and a Personal Access Token (PAT) key. \n",
    "[Check here](https://clarifai.com/settings/security) to get or create a PAT."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "1eecfb1c",
   "metadata": {},
   "source": [
    "# Dependencies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b4c41cad-08ef-4f72-a545-2151e4598efe",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Install required dependencies\n",
    "!pip install clarifai"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "93039ada",
   "metadata": {},
   "source": [
    "# Imports\n",
    "Here we will be setting the personal access token. You can find your PAT under settings/security on the platform."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c1e38361-c1fe-4ac6-86e9-c90ebaf7ae87",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " ········\n"
     ]
    }
   ],
   "source": [
    "# Please login and get your API key from  https://clarifai.com/settings/security\n",
    "from getpass import getpass\n",
    "\n",
    "CLARIFAI_PAT = getpass()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "aac9563e",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Import the required modules\n",
    "from langchain.document_loaders import TextLoader\n",
    "from langchain.text_splitter import CharacterTextSplitter\n",
    "from langchain.vectorstores import Clarifai"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "edcf5159",
   "metadata": {},
   "source": [
    "# Setup\n",
    "Setup the user id and app id where the text data will be uploaded. Note: when creating that application please select an appropriate base workflow for indexing your text documents such as the Language-Understanding workflow.\n",
    "\n",
    "You will have to first create an account on [Clarifai](https://clarifai.com/login) and then create an application."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "4d853395",
   "metadata": {},
   "outputs": [],
   "source": [
    "USER_ID = \"USERNAME_ID\"\n",
    "APP_ID = \"APPLICATION_ID\"\n",
    "NUMBER_OF_DOCS = 2"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "5631bdd5",
   "metadata": {},
   "source": [
    "## From Texts\n",
    "Create a Clarifai vectorstore from a list of texts. This section will upload each text with its respective metadata to a Clarifai Application. The Clarifai Application can then be used for semantic search to find relevant texts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "1d828f77",
   "metadata": {},
   "outputs": [],
   "source": [
    "texts = [\n",
    "    \"I really enjoy spending time with you\",\n",
    "    \"I hate spending time with my dog\",\n",
    "    \"I want to go for a run\",\n",
    "    \"I went to the movies yesterday\",\n",
    "    \"I love playing soccer with my friends\",\n",
    "]\n",
    "\n",
    "metadatas = [\n",
    "    {\"id\": i, \"text\": text, \"source\": \"book 1\", \"category\": [\"books\", \"modern\"]}\n",
    "    for i, text in enumerate(texts)\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e467c0b-e218-4cb2-a02e-2948670bbab7",
   "metadata": {},
   "source": [
    "Alternatively you have an option to give custom input ids to the inputs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "ffab62d6-8ef4-4c5e-b45e-6f1b39d0c013",
   "metadata": {},
   "outputs": [],
   "source": [
    "idlist = [\"text1\", \"text2\", \"text3\", \"text4\", \"text5\"]\n",
    "metadatas = [\n",
    "    {\"id\": idlist[i], \"text\": text, \"source\": \"book 1\", \"category\": [\"books\", \"modern\"]}\n",
    "    for i, text in enumerate(texts)\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "738bff27",
   "metadata": {},
   "outputs": [],
   "source": [
    "# There is an option to initialize clarifai vector store with pat as argument!\n",
    "clarifai_vector_db = Clarifai(\n",
    "    user_id=USER_ID,\n",
    "    app_id=APP_ID,\n",
    "    number_of_docs=NUMBER_OF_DOCS,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d3ca631f-8182-461f-b581-b649f7176a5f",
   "metadata": {},
   "source": [
    "Upload data into clarifai app."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77e4f544-e766-4e0e-934a-4e85f68a0286",
   "metadata": {},
   "outputs": [],
   "source": [
    "# upload with metadata and custom input ids.\n",
    "response = clarifai_vector_db.add_texts(texts=texts, ids=idlist, metadatas=metadatas)\n",
    "\n",
    "# upload without metadata (Not recommended)- Since you will not be able to perform Search operation with respect to metadata.\n",
    "# custom input_id (optional)\n",
    "response = clarifai_vector_db.add_texts(texts=texts)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09d97edf-014b-4a5b-86a9-6a5b255554ba",
   "metadata": {},
   "source": [
    "You can create a clarifai vector DB store and ingest all the inputs into your app directly by,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7c466ac9-6b50-48ff-8b23-9fc6a3cbdf97",
   "metadata": {},
   "outputs": [],
   "source": [
    "clarifai_vector_db = Clarifai.from_texts(\n",
    "    user_id=USER_ID,\n",
    "    app_id=APP_ID,\n",
    "    texts=texts,\n",
    "    metadatas=metadatas,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0bb2affb-48ca-410b-85c0-9e1275429bcb",
   "metadata": {},
   "source": [
    "Search similar texts using similarity search function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "e755cdce",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[Document(page_content='I really enjoy spending time with you', metadata={'text': 'I really enjoy spending time with you', 'id': 'text1', 'source': 'book 1', 'category': ['books', 'modern']})]"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docs = clarifai_vector_db.similarity_search(\"I would like to see you\")\n",
    "docs"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd703470-7efb-4be5-a556-eea896ca60f4",
   "metadata": {},
   "source": [
    "Further you can filter your search results by metadata."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "140103ec-0936-454a-9f4a-7d5beefc138f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# There is lots powerful filtering you can do within an app by leveraging metadata filters.\n",
    "# This one will limit the similarity query to only the texts that have key of \"source\" matching value of \"book 1\"\n",
    "book1_similar_docs = clarifai_vector_db.similarity_search(\n",
    "    \"I would love to see you\", filter={\"source\": \"book 1\"}\n",
    ")\n",
    "\n",
    "# you can also use lists in the input's metadata and then select things that match an item in the list. This is useful for categories like below:\n",
    "book_category_similar_docs = clarifai_vector_db.similarity_search(\n",
    "    \"I would love to see you\", filter={\"category\": [\"books\"]}\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c39504e4",
   "metadata": {},
   "source": [
    "## From Documents\n",
    "Create a Clarifai vectorstore from a list of Documents. This section will upload each document with its respective metadata to a Clarifai Application. The Clarifai Application can then be used for semantic search to find relevant documents."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a3c3999a",
   "metadata": {},
   "outputs": [],
   "source": [
    "loader = TextLoader(\"your_local_file_path.txt\")\n",
    "documents = loader.load()\n",
    "text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n",
    "docs = text_splitter.split_documents(documents)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "40bf1305",
   "metadata": {},
   "outputs": [],
   "source": [
    "USER_ID = \"USERNAME_ID\"\n",
    "APP_ID = \"APPLICATION_ID\"\n",
    "NUMBER_OF_DOCS = 4"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "52d86f01-3462-440e-8960-3c0c17b98f09",
   "metadata": {},
   "source": [
    "Create a clarifai vector DB class and ingest all your documents into clarifai App."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6e104aee",
   "metadata": {},
   "outputs": [],
   "source": [
    "clarifai_vector_db = Clarifai.from_documents(\n",
    "    user_id=USER_ID,\n",
    "    app_id=APP_ID,\n",
    "    documents=docs,\n",
    "    number_of_docs=NUMBER_OF_DOCS,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c608226",
   "metadata": {},
   "outputs": [],
   "source": [
    "docs = clarifai_vector_db.similarity_search(\"Texts related to population\")\n",
    "docs"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "7b332ca4-416b-4ea6-99da-b6949f399d72",
   "metadata": {},
   "source": [
    "## From existing App\n",
    "Within Clarifai we have great tools for adding data to applications (essentially projects) via API or UI. Most users will already have done that before interacting with LangChain so this example will use the data in an existing app to perform searches. Check out our [API docs](https://docs.clarifai.com/api-guide/data/create-get-update-delete) and [UI docs](https://docs.clarifai.com/portal-guide/data). The Clarifai Application can then be used for semantic search to find relevant documents."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "807c1141-591b-436d-abaa-f2c325e66d39",
   "metadata": {},
   "outputs": [],
   "source": [
    "USER_ID = \"USERNAME_ID\"\n",
    "APP_ID = \"APPLICATION_ID\"\n",
    "NUMBER_OF_DOCS = 4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "762d74ef-f7df-43d6-b121-4980c4059fc0",
   "metadata": {},
   "outputs": [],
   "source": [
    "clarifai_vector_db = Clarifai(\n",
    "    user_id=USER_ID,\n",
    "    app_id=APP_ID,\n",
    "    number_of_docs=NUMBER_OF_DOCS,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f7636b0f-68ab-4b8f-ba0f-3c27061e3631",
   "metadata": {},
   "outputs": [],
   "source": [
    "docs = clarifai_vector_db.similarity_search(\n",
    "    \"Texts related to ammuniction and president wilson\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "55ee5fc7-94c4-45d0-84ca-00defeca871e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"President Wilson, generally acclaimed as the leader of the world's democracies,\\nphrased for civilization the arguments against autocracy in the great peace conference\\nafter the war. The President headed the American delegation to that conclave of world\\nre-construction. With him as delegates to the conference were Robert Lansing, Secretary\\nof State; Henry White, former Ambassador to France and Italy; Edward M. House and\\nGeneral Tasker H. Bliss.\\nRepresenting American Labor at the International Labor conference held in Paris\\nsimultaneously with the Peace Conference were Samuel Gompers, president of the\\nAmerican Federation of Labor; William Green, secretary-treasurer of the United Mine\\nWorkers of America; John R. Alpine, president of the Plumbers' Union; James Duncan,\\npresident of the International Association of Granite Cutters; Frank Duffy, president of\\nthe United Brotherhood of Carpenters and Joiners, and Frank Morrison, secretary of the\\nAmerican Federation of Labor.\\nEstimating the share of each Allied nation in the great victory, mankind will\\nconclude that the heaviest cost in proportion to prewar population and treasure was paid\\nby the nations that first felt the shock of war, Belgium, Serbia, Poland and France. All\\nfour were the battle-grounds of huge armies, oscillating in a bloody frenzy over once\\nfertile fields and once prosperous towns.\\nBelgium, with a population of 8,000,000, had a casualty list of more than 350,000;\\nFrance, with its casualties of 4,000,000 out of a population (including its colonies) of\\n90,000,000, is really the martyr nation of the world. Her gallant poilus showed the world\\nhow cheerfully men may die in defense of home and liberty. Huge Russia, including\\nhapless Poland, had a casualty list of 7,000,000 out of its entire population of\\n180,000,000. The United States out of a population of 110,000,000 had a casualty list of\\n236,117 for nineteen months of war; of these 53,169 were killed or died of disease;\\n179,625 were wounded; and 3,323 prisoners or missing.\""
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docs[0].page_content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aa7b3260-2ee3-4619-836f-da64370a855c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
