{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cf34cf59-9ded-45a9-a76b-f2b6a0e546eb",
   "metadata": {},
   "source": [
    "# Chapter 1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e5de66a-1fb7-4359-82da-3fec44f33f95",
   "metadata": {},
   "source": [
    "# LangChain examples"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a1d84516-cb8e-479b-8a88-d89ef01092da",
   "metadata": {},
   "source": [
    "## Sentence completion example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "090dee16-1747-4d81-a3fc-1ee5580e6237",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "import getpass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "5103ab31-31a7-469a-b0ae-75f5c836c041",
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "Enter your OPENAI_API_KEY ········\n"
     ]
    }
   ],
   "source": [
    "OPENAI_API_KEY = getpass.getpass('Enter your OPENAI_API_KEY')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f9300c93-580a-4be1-8677-89150bec1763",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='Sounds like you want to beat the heat. Do you prefer indoor or outdoor activities? And where are you located? If you share your city and how much time you have, I can tailor it.\\n\\nIn the meantime, here are quick ideas:\\n\\n- Indoor to stay cool: a shopping mall, cinema, museum or aquarium, library, science center, or an air-conditioned cafe with a cold drink.\\n- Water fun: a pool, water park, splash pad, lake/river beach (best in the early morning or late afternoon to avoid peak sun), or a shady river walk.\\n- Quick nature options (cooler shady spots): a botanical garden or forested trail, or a park with lots of shade and a nearby cafe.\\n- Simple and refreshing: an ice cream shop, smoothie bar, or a cold-brew/cold-pressed juice spot.\\n\\nWant me to tailor a plan for your city, time window, and budget? I can also give weather-safe tips for hot days.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 848, 'prompt_tokens': 19, 'total_tokens': 867, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 640, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_provider': 'openai', 'model_name': 'gpt-5-nano-2025-08-07', 'system_fingerprint': None, 'id': 'chatcmpl-CXanO7MQVtVGxM4XwJh84h0vtTiyh', 'service_tier': 'default', 'finish_reason': 'stop', 'logprobs': None}, id='lc_run--7a8b1045-0efd-4e41-a2a2-f2324a4cf5ae-0', usage_metadata={'input_tokens': 19, 'output_tokens': 848, 'total_tokens': 867, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 640}})"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY,\n",
    "                 model_name=\"gpt-5-nano\")\n",
    "llm.invoke(\"It's a hot day, I would like to go to the...\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f6b7ccc-f577-4f64-939f-1696c259bb60",
   "metadata": {},
   "source": [
    "## Simple prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "7abd29fe-92c4-46e8-a158-7aaefcb31a9b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Stay vigilant against phishing: don’t click suspicious links or open unexpected attachments, verify the sender’s address, and report anything suspicious to IT. When in doubt, pause and verify before acting.\n"
     ]
    }
   ],
   "source": [
    "prompt_input = \"\"\"Write a short message to remind users to be \n",
    "vigilant about phishing attacks.\"\"\"\n",
    "response = llm.invoke(prompt_input)\n",
    "\n",
    "print(response.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f67b643-e39a-4cd3-bafa-6aef5c20eb00",
   "metadata": {},
   "source": [
    "## Prompt instantiated thorugh a PromptTemplate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "973baffb-bd6b-4ae3-8718-5aa4803524ae",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Segovia's Roman Aqueduct brought water 17 km, built in 1st century AD; 167 arches, UNESCO-listed, iconic symbol, used until 1973.\n"
     ]
    }
   ],
   "source": [
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "segovia_aqueduct_text = \"\"\"The Aqueduct of Segovia \n",
    "(Spanish: Acueducto de Segovia) is a Roman aqueduct in Segovia, \n",
    "Spain. It was built around the first century AD to channel water \n",
    "from springs in the mountains 17 kilometres (11 mi) away to the \n",
    "city's fountains, public baths and private houses, and was in \n",
    "use until 1973. Its elevated section, with its complete arcade \n",
    "of 167 arches, is one of the best-preserved Roman aqueduct \n",
    "bridges and the foremost symbol of Segovia, as evidenced by \n",
    "its presence on the city's coat of arms. The Old Town of \n",
    "Segovia and the aqueduct, were declared a UNESCO World \n",
    "Heritage Site in 1985. As the aqueduct lacks a legible \n",
    "inscription (one was apparently located in the structure's \n",
    "attic, or top portion[citation needed]), the date of \n",
    "construction cannot be definitively determined. The general \n",
    "date of the Aqueduct's construction was long a mystery, \n",
    "although it was thought to have been during the 1st century AD, \n",
    "during the reigns of the Emperors Domitian, Nerva, and Trajan. \n",
    "At the end of the 20th century, Géza Alföldy deciphered the \n",
    "text on the dedication plaque by studying the anchors that held \n",
    "the now missing bronze letters in place. He determined that Emperor \n",
    "Domitian (AD 81–96) ordered its construction[1] and the year 98 AD\n",
    "was proposed as the most likely date of completion.[2] However, \n",
    "in 2016 archeological evidence was published which points to a \n",
    "slightly later date, after 112 AD, during the government of \n",
    "Trajan or in the beginning of the government of emperor Hadrian, \n",
    "from 117 AD.\"\"\"\n",
    "\n",
    "prompt_template = PromptTemplate.from_template(\"\"\"You are an \n",
    "experienced copywriter. Write a {num_words} words summary of \n",
    "the following text, using a {tone} tone: {text}\"\"\")\n",
    "\n",
    "prompt_input = prompt_template.format(\n",
    "    text=segovia_aqueduct_text, \n",
    "    num_words=20, \n",
    "    tone=\"knowledgeable and engaging\")\n",
    "response = llm.invoke(prompt_input)\n",
    "print(response.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d344e4b9-30af-4e72-95ab-a8c652c7f900",
   "metadata": {},
   "source": [
    "## Chain example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "232b13ad-625b-4191-bf89-21ef4868020e",
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt_template = PromptTemplate.from_template(\"You are an experienced copywriter. Write a {num_words} words summary of the following text, using a {tone} tone: {text}\")\n",
    "llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY,\n",
    "                 model_name=\"gpt-5-nano\")\n",
    "\n",
    "chain = prompt_template | llm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "89fc88c7-8b77-43cf-90fd-05fb4c00a497",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The Segovia Aqueduct, a Roman 1st-century marvel, carried water 17 km, symbolizing the city; date debated, UNESCO site for centuries.\n"
     ]
    }
   ],
   "source": [
    "response = chain.invoke({\"text\": segovia_aqueduct_text, \n",
    "              \"num_words\": 20, \n",
    "              \"tone\": \"knowledgeable and engaging\"})\n",
    "print(response.content)"
   ]
  }
 ],
 "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.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
