{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "9597802c",
   "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.\n",
    "\n",
    "This example goes over how to use LangChain to interact with `Clarifai` [models](https://clarifai.com/explore/models). \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": "2a773d8d",
   "metadata": {},
   "source": [
    "# Dependencies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91ea14ce-831d-409a-a88f-30353acdabd1",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Install required dependencies\n",
    "!pip install clarifai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "326395b1-27e0-4cb6-9321-27c04466362b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Declare clarifai pat token as environment variable or you can pass it as argument in clarifai class.\n",
    "import os\n",
    "\n",
    "os.environ[\"CLARIFAI_PAT\"] = \"CLARIFAI_PAT_TOKEN\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "426f1156",
   "metadata": {},
   "source": [
    "# Imports\n",
    "Here we will be setting the personal access token. You can find your PAT under [settings/security](https://clarifai.com/settings/security) in your Clarifai account."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "3f5dc9d7-65e3-4b5b-9086-3327d016cfe0",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "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": "6fb585dd",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Import the required modules\n",
    "from langchain.chains import LLMChain\n",
    "from langchain.llms import Clarifai\n",
    "from langchain.prompts import PromptTemplate"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "16521ed2",
   "metadata": {},
   "source": [
    "# Input\n",
    "Create a prompt template to be used with the LLM Chain:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "035dea0f",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "template = \"\"\"Question: {question}\n",
    "\n",
    "Answer: Let's think step by step.\"\"\"\n",
    "\n",
    "prompt = PromptTemplate(template=template, input_variables=[\"question\"])"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c8905eac",
   "metadata": {},
   "source": [
    "# Setup\n",
    "Setup the user id and app id where the model resides. You can find a list of public models on https://clarifai.com/explore/models\n",
    "\n",
    "You will have to also initialize the model id and if needed, the model version id. Some models have many versions, you can choose the one appropriate for your task.\n",
    "\n",
    "                                                                 or\n",
    "                                                                 \n",
    "You can use the model_url (for ex: \"https://clarifai.com/anthropic/completion/models/claude-v2\") for intialization."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "1fe9bf15",
   "metadata": {},
   "outputs": [],
   "source": [
    "USER_ID = \"openai\"\n",
    "APP_ID = \"chat-completion\"\n",
    "MODEL_ID = \"GPT-3_5-turbo\"\n",
    "\n",
    "# You can provide a specific model version as the model_version_id arg.\n",
    "# MODEL_VERSION_ID = \"MODEL_VERSION_ID\"\n",
    "# or\n",
    "\n",
    "MODEL_URL = \"https://clarifai.com/openai/chat-completion/models/GPT-4\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "3f3458d9",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Initialize a Clarifai LLM\n",
    "clarifai_llm = Clarifai(user_id=USER_ID, app_id=APP_ID, model_id=MODEL_ID)\n",
    "# or\n",
    "# Initialize through Model URL\n",
    "clarifai_llm = Clarifai(model_url=MODEL_URL)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a641dbd9",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Create LLM chain\n",
    "llm_chain = LLMChain(prompt=prompt, llm=clarifai_llm)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "3e87c71a",
   "metadata": {},
   "source": [
    "# Run Chain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "9f844993",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "' Okay, here are the steps to figure this out:\\n\\n1. Justin Bieber was born on March 1, 1994.\\n\\n2. The Super Bowl that took place in the year of his birth was Super Bowl XXVIII. \\n\\n3. Super Bowl XXVIII was played on January 30, 1994.\\n\\n4. The two teams that played in Super Bowl XXVIII were the Dallas Cowboys and the Buffalo Bills. \\n\\n5. The Dallas Cowboys defeated the Buffalo Bills 30-13 to win Super Bowl XXVIII.\\n\\nTherefore, the NFL team that won the Super Bowl in the year Justin Bieber was born was the Dallas Cowboys.'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "question = \"What NFL team won the Super Bowl in the year Justin Beiber was born?\"\n",
    "\n",
    "llm_chain.run(question)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2604c17f-a410-4159-ac1c-fdd7c60b725c",
   "metadata": {},
   "source": [
    "## Model Predict with Inference parameters for GPT.\n",
    "Alternatively you can use GPT models with inference parameters (like temperature, max_tokens etc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "59ae8cd9-3d07-40f2-b4b5-b7908b2fc71d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Intialize the parameters as dict.\n",
    "params = dict(temperature=str(0.3), max_tokens=100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "c14c7940-4fd3-41a4-9ed4-f4ecead08edf",
   "metadata": {},
   "outputs": [],
   "source": [
    "clarifai_llm = Clarifai(user_id=USER_ID, app_id=APP_ID, model_id=MODEL_ID)\n",
    "llm_chain = LLMChain(\n",
    "    prompt=prompt, llm=clarifai_llm, llm_kwargs={\"inference_params\": params}\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "80fef923-0473-4119-aa7e-868374560fdd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Step 1: The first digit can be any even number from 1 to 9, except for 5. So there are 4 choices for the first digit.\\n\\nStep 2: If the first digit is not 5, then the second digit must be 7. So there is only 1 choice for the second digit.\\n\\nStep 3: The third digit can be any even number from 0 to 9, except for 5 and 7. So there are '"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "question = \"How many 3 digit even numbers you can form that if one of the digits is 5 then the following digit must be 7?\"\n",
    "\n",
    "llm_chain.run(question)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c9ab08e2-4bc9-49b8-9b7a-88ae840ac3f8",
   "metadata": {},
   "source": [
    "Generate responses for list of prompts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "fb3b8cea-5cc9-46f3-9334-1994f195cde3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "LLMResult(generations=[[Generation(text=' Here is a 5 sentence summary of the key events of the American Revolution:\\n\\nThe American Revolution began with growing tensions between American colonists and the British government over issues of taxation without representation. In 1775, fighting broke out between British troops and American militiamen in Lexington and Concord, starting the Revolutionary War. The Continental Congress appointed George Washington as commander of the Continental Army, which went on to win key victories over the British. In 1776, the Declaration of Independence was adopted, formally declaring the 13 American colonies free from British rule. After years of fighting, the Revolutionary War ended with the British defeat at Yorktown in 1781 and recognition of American independence.')], [Generation(text=\" Here's a humorous take on explaining rocket science:\\n\\nRocket science is so easy, it's practically child's play! Just strap a big metal tube full of explosive liquid to your butt and light the fuse. What could go wrong? Blastoff!  Whoosh, you'll be zooming to the moon in no time. Just remember your helmet or your head might go pop like a zit when you leave the atmosphere. \\n\\nMaking rockets is a cinch too. Simply mix together some spicy spices, garlic powder, chili powder, a dash of gunpowder and voila - rocket fuel! Add a pinch of baking soda and vinegar if you want an extra kick. Shake well and pour into your DIY soda bottle rocket. Stand back and watch that baby soar!\\n\\nGuiding a rocket is fun for the whole family. Just strap in, push some random buttons and see where you end up. It's like the ultimate surprise vacation! You never know if you'll wind up on Venus, crash land on Mars, or take a quick dip through the rings of Saturn. \\n\\nAnd if anything goes wrong, don't sweat it. Rocket science is easy breezy. Just troubleshoot on the fly with some duct tape and crazy glue and you'll be back on course in a jiffy. Who needs mission control when you've got this!\")], [Generation(text=\" Here is a draft welcome speech for a college sports day:\\n\\nGood morning everyone and welcome to our college's annual sports day! It's wonderful to see so many students, faculty, staff, alumni, and guests gathered here today to celebrate sportsmanship and athletic achievement at our college. \\n\\nLet's begin by thanking all the organizers, volunteers, coaches, and staff members who worked tirelessly behind the scenes to make this event possible. Our sports day would not happen without your dedication and commitment. \\n\\nI also want to recognize all the student-athletes with us today. You inspire us with your talent, spirit, and determination. Sports have a unique power to unite and energize our community. Through both individual and team sports, you demonstrate focus, collaboration, perseverance and resilience – qualities that will serve you well both on and off the field.\\n\\nThe spirit of competition and fair play are core values of any sports event. I encourage all of you to compete enthusiastically today. Play to the best of your ability and have fun. Applaud the effort and sportsmanship of your fellow athletes, regardless of the outcome. \\n\\nWin or lose, this sports day is a day for us to build camaraderie and create lifelong memories. Let's make it a day of fitness and friendship for all. With that, let the games begin. Enjoy the day!\")]], llm_output=None, run=None)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# We can use _generate to generate the response for list of prompts.\n",
    "clarifai_llm._generate(\n",
    "    [\n",
    "        \"Help me summarize the events of american revolution in 5 sentences\",\n",
    "        \"Explain about rocket science in a funny way\",\n",
    "        \"Create a script for welcome speech for the college sports day\",\n",
    "    ],\n",
    "    inference_params=params,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cb080d00-7b5c-4726-ae4f-df9374997c7f",
   "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
}
