{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1c280f35",
   "metadata": {},
   "source": [
    "# ✍️ Large language models in Python\n",
    "\n",
    "In the chapter [Large language models](https://ai.kuleuven.be/aivooriedereen/en/large-language-models), a chatbot became an agent as soon as it could use tools. In this notebook you do that yourself, in Python: you talk to a free language model through its API, and you turn it into an assistant that plans your train to class, with the live timetable of the Belgian railways and the weather forecast.\n",
    "\n",
    "You will:\n",
    "\n",
    "1. 🔑 get a free key, 💬 send your first messages to a language model, and see what it can't know;\n",
    "2. 🛠️ give it its first tool: the live train timetable;\n",
    "3. 🔁 let it use several tools in a loop, until it can tell you which train to take to be on time for your first class.\n",
    "\n",
    "**Prior knowledge**: the chapter [Large language models](https://ai.kuleuven.be/aivooriedereen/en/large-language-models), especially the part about tools and agents.\n",
    "\n",
    "**Estimated time**: about 35 minutes. You need a free account at OpenRouter, which gives you 50 free requests per day; the whole notebook uses about 15 of them.\n",
    "\n",
    "*This notebook is part of [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en) (KU Leuven). The latest version is always at [ai.kuleuven.be/aivooriedereen/en/notebook/large-language-models](https://ai.kuleuven.be/aivooriedereen/en/notebook/large-language-models), and you can open it directly in [Google Colab](https://colab.research.google.com/drive/1sXwPN8DHDkTPJ6ICP2de3E5rF_QAxwJQ?usp=sharing).*"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ba192eb3",
   "metadata": {},
   "source": [
    "## 🚀 First time in a notebook?\n",
    "\n",
    "Then the short [introductory notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics) explains everything step by step. The most important things:\n",
    "\n",
    "1. **Make your own copy**: *File → Save a copy in Drive* (in the menu at the top left), and work in that copy.\n",
    "2. **Run a cell** by clicking in it and pressing **Shift+Enter**, or with the ▶ button to its left. The result appears below the cell.\n",
    "3. **Run the cells in order, from top to bottom**, because a cell uses what the cells above it made. Does something behave strangely? Choose *Runtime → Restart session* and run everything again from the top.\n",
    "\n",
    "**Prefer not to use Google?** Download [the notebook file](https://ai.kuleuven.be/aivooriedereen/notebooks/large-language-models.ipynb) and open it in [Jupyter](https://jupyter.org/install) or [Visual Studio Code](https://code.visualstudio.com/docs/datascience/jupyter-notebooks). Put your key in an environment variable `OPENROUTER_API_KEY`, or type it in when the notebook asks for it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "76b52371",
   "metadata": {},
   "source": [
    "## 🐍 Python in this notebook\n",
    "\n",
    "New to Python? The [introductory notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics) explains the basics: variables, lists, loops and functions. On top of those, this notebook uses:\n",
    "\n",
    "| Code | Meaning |\n",
    "| --- | --- |\n",
    "| `{\"role\": \"user\", \"content\": \"Hi\"}` | A dictionary: values with a name. Here it's one message, saying who speaks and what they say. A conversation is a list of them. |\n",
    "| `client.chat.completions.create(model=..., messages=...)` | Sends a conversation to a language model, and waits for its answer. |\n",
    "| `response.choices[0].message.content` | The text of that answer. |\n",
    "| `def f(day: str) -> dict:` with `\"\"\"...\"\"\"` below it | A function with type hints (what goes in and comes out) and a docstring (what it does). The model reads both. |\n",
    "| `f(**arguments)` | Calls a function with the values in a dictionary as its arguments, such as the ones the model chose. |\n",
    "| `def ask(messages, **options):` | Accepts any other named arguments as a dictionary `options`, and `create(**options)` passes them on. |\n",
    "| `requests.get(url, params=...)` | Asks a web API for data. `.json()` turns its answer into Python lists and dictionaries. |\n",
    "| `json.dumps(data)`, `json.loads(text)` | Turns lists and dictionaries into text in the [JSON](https://en.wikipedia.org/wiki/JSON) format, and back. |\n",
    "| `datetime.now(BRUSSELS)`, `timedelta(days=1)` | The date and time in Belgium now, and one day, to add to a date. |\n",
    "| `f\"{now:%A %d %B}\"` | Writes a date out inside an f-string, such as \"Thursday 29 October\". |\n",
    "| `try: ... except Exception as error:` | Catches an error, so that the code can carry on instead of stopping. |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9eeed75b",
   "metadata": {},
   "source": [
    "## 🔑 A free key\n",
    "\n",
    "A language model like the ones in the chapter runs on the computers of a company. Your program sends it a question over the internet, through an **API** (*application programming interface*): a door for programs instead of people. To use that door, you need a **key**: a long secret code that says who is knocking.\n",
    "\n",
    "This notebook uses [OpenRouter](https://openrouter.ai): with one key you can reach hundreds of models from different companies, and some of them are free. To get a key:\n",
    "\n",
    "1. Make an account at [openrouter.ai](https://openrouter.ai). For the free models, you don't need to buy anything.\n",
    "2. Create a key on the page [Keys](https://openrouter.ai/settings/keys), and copy it right away: OpenRouter only shows it once.\n",
    "3. In Colab, click the 🔑 key icon in the bar on the left (*Secrets*), choose *Add new secret*, call it `OPENROUTER_API_KEY`, paste the key as its value, and switch on *Notebook access*.\n",
    "\n",
    "Never put a key in the code itself: whoever gets your notebook would also get your key. A Secret stays in your own Colab account.\n",
    "\n",
    "**Free, but not private and not fast.** The free models run at companies that may keep and learn from what you send them, so treat everything you send as if you posted it in public: no personal data, no passwords, nothing confidential (see [Privacy](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#privacy) in the chapter). Everybody shares those free models, so they are sometimes busy, and you get at most **20 requests per minute and 50 per day**. Does a free model answer *No endpoints found matching your data policy*? Then allow the free models under [*Settings → Privacy*](https://openrouter.ai/settings/privacy) on OpenRouter."
   ]
  },
  {
   "cell_type": "code",
   "id": "5a434f40",
   "metadata": {},
   "source": [
    "# Colab already has these packages; elsewhere, this installs them (tzdata: the time zones, for Windows)\n",
    "%pip install --quiet openai markdown tzdata"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "6def1ce0",
   "metadata": {},
   "source": [
    "import getpass\n",
    "import html\n",
    "import inspect\n",
    "import json\n",
    "import os\n",
    "import re\n",
    "import time\n",
    "from datetime import datetime, timedelta\n",
    "from zoneinfo import ZoneInfo\n",
    "\n",
    "import markdown\n",
    "import pandas as pd\n",
    "import requests\n",
    "from IPython.display import HTML, display\n",
    "from openai import OpenAI\n",
    "\n",
    "BRUSSELS = ZoneInfo(\"Europe/Brussels\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "88e11606",
   "metadata": {},
   "source": [
    "try:\n",
    "    from google.colab import userdata                     # in Colab: the key from the 🔑 Secrets\n",
    "    api_key = userdata.get(\"OPENROUTER_API_KEY\")\n",
    "except ImportError:                                         # elsewhere: an environment variable, or type it in\n",
    "    api_key = os.environ.get(\"OPENROUTER_API_KEY\") or getpass.getpass(\"Your OpenRouter key: \")\n",
    "\n",
    "client = OpenAI(base_url=\"https://openrouter.ai/api/v1\", api_key=api_key)\n",
    "\n",
    "# The free model we use, followed by the free models that OpenRouter tries when it's busy\n",
    "MODEL = \"nvidia/nemotron-3.5-super-vl:free\"\n",
    "MODELS = [MODEL, \"google/gemma-4-31b-it:free\", \"openrouter/free\"]\n",
    "\n",
    "answer = requests.get(\"https://openrouter.ai/api/v1/key\", headers={\"Authorization\": f\"Bearer {api_key}\"})\n",
    "answer.raise_for_status()                                   # error 401 here: the key is wrong\n",
    "print(\"Your key works. Free requests left today:\",\n",
    "      answer.json()[\"data\"].get(\"free_model_daily_requests\", {}).get(\"remaining\"))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "c5e088a9",
   "metadata": {},
   "source": [
    "## 💬 Your first call\n",
    "\n",
    "A request to a language model has two parts: which **model** you want, and the **messages** of the conversation so far. Every message is a dictionary that says who speaks (`role`) and what they say (`content`). A first question is a single message from the user. The answer can take half a minute; you'll see why below."
   ]
  },
  {
   "cell_type": "code",
   "id": "83f95fb3",
   "metadata": {},
   "source": [
    "start = time.perf_counter()\n",
    "response = client.chat.completions.create(\n",
    "    model=MODEL,\n",
    "    messages=[{\"role\": \"user\", \"content\": \"Write a limerick about the train from Leuven to Ghent.\"}],\n",
    "    extra_body={\"models\": MODELS},                          # an option of OpenRouter: the backup models\n",
    ")\n",
    "seconds = time.perf_counter() - start\n",
    "\n",
    "print(response.choices[0].message.content)\n",
    "print(f\"\\n{seconds:.1f} seconds, answered by {response.model}\")\n",
    "print(f\"{response.usage.prompt_tokens} tokens in, {response.usage.completion_tokens} tokens out\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "ff54657c",
   "metadata": {},
   "source": [
    "The answer is a message too, with the role `assistant`, and `response.choices[0].message.content` is its text. Below it, you see how long it took, which model answered, and how many [tokens](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#tokens-large-language-models-do-not-see-letters) went in and came out. Models you pay for charge per token; the free ones count your requests instead. `extra_body` holds options that only OpenRouter knows, such as `models`: when the first model is busy, OpenRouter passes your question on to the next one in the list.\n",
    "\n",
    "Probably many more tokens came out than five lines of a limerick need, and that's why it took a while. Most of these models are [reasoning models](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#reasoning-models): before the answer you get to see, they write out their thoughts. Those are in the response too:"
   ]
  },
  {
   "cell_type": "code",
   "id": "5ec0b94e",
   "metadata": {},
   "source": [
    "message = response.choices[0].message\n",
    "print((getattr(message, \"reasoning\", None) or \"(this model shows no thoughts)\")[:1000], \"...\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "38161b23",
   "metadata": {},
   "source": [
    "For a limerick, that's a lot of thinking. For a task with several steps, like the planning at the end of this notebook, it pays off. From now on, `ask` sends a conversation with the same backup models, so that the code stays short:"
   ]
  },
  {
   "cell_type": "code",
   "id": "b6f3c688",
   "metadata": {},
   "source": [
    "def ask(messages, **options):\n",
    "    # Sends a conversation to the model (or a backup when it's busy), and returns the response\n",
    "    return client.chat.completions.create(model=MODEL, messages=messages, extra_body={\"models\": MODELS}, **options)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "646caa4b",
   "metadata": {},
   "source": [
    "OpenRouter's list of free models changes every few weeks. This cell asks for the current list, and only keeps the models that can use tools, which you'll need later. The number behind each model is how many tokens it can take in at once. To try another model, change `MODEL` in the cell with your key, and run the cells again from there."
   ]
  },
  {
   "cell_type": "code",
   "id": "93ac4180",
   "metadata": {},
   "source": [
    "models = requests.get(\"https://openrouter.ai/api/v1/models\").json()[\"data\"]\n",
    "for model in models:\n",
    "    if model[\"id\"].endswith(\":free\") and \"tools\" in model[\"supported_parameters\"]:\n",
    "        print(f\"{model['id']:50} {model['context_length'] or 0:>11,} tokens\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "319d6407",
   "metadata": {},
   "source": [
    "## 🎭 A system prompt and a conversation\n",
    "\n",
    "A chatbot is a language model with a **system prompt** in front of the conversation: a first message, with the role `system`, that says who the model is and how it should answer (see [From autocomplete to chatbot](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#from-autocomplete-to-chatbot)).\n",
    "\n",
    "And the API remembers nothing. To continue a conversation, you send the whole conversation again, with the model's answer and your next question added to the end. `show_messages` draws such a conversation the way the model reads it: as one long script. You don't need to read its code; it only draws."
   ]
  },
  {
   "cell_type": "code",
   "id": "57d351be",
   "metadata": {},
   "source": [
    "STYLES = {  # role: label, background, edge\n",
    "    \"system\": (\"⚙️ System\", \"#f1f5f9\", \"#94a3b8\"),\n",
    "    \"user\": (\"🧑 User\", \"#eff6ff\", \"#60a5fa\"),\n",
    "    \"assistant\": (\"🤖 Assistant\", \"#fff7ed\", \"#fb923c\"),\n",
    "    \"tool\": (\"🛠️ Tool\", \"#ecfdf5\", \"#34d399\"),\n",
    "}\n",
    "CODE = '<code style=\"color:#0f172a;background:none\">'\n",
    "\n",
    "\n",
    "def script(messages):\n",
    "    # A conversation as the script that the model reads, in HTML: thoughts, tool calls and tool results included\n",
    "    blocks = []\n",
    "    for message in messages:\n",
    "        label, background, edge = STYLES[message[\"role\"]]\n",
    "        parts = []\n",
    "        if message.get(\"reasoning\"):\n",
    "            parts.append(f'<i style=\"color:#64748b\">💭 {html.escape(message[\"reasoning\"][:300])} …</i>')\n",
    "        if message[\"role\"] == \"tool\":\n",
    "            result = message[\"content\"] if len(message[\"content\"]) < 400 else message[\"content\"][:400] + \" …\"\n",
    "            parts.append(CODE + html.escape(result) + \"</code>\")\n",
    "        elif message[\"role\"] == \"assistant\" and message.get(\"content\"):\n",
    "            answer = markdown.markdown(message[\"content\"], extensions=[\"tables\"])    # bold, lists and tables\n",
    "            answer = answer.replace(\"<p>\", '<p style=\"margin:0\">').replace(\"<table>\", '<table style=\"border-collapse:collapse\">')\n",
    "            parts.append(re.sub(r\"<(td|th)( [^>]*)?>\", r'<\\1 style=\"border:1px solid #fdba74;padding:2px 8px\">', answer))\n",
    "        elif message.get(\"content\"):\n",
    "            parts.append(html.escape(message[\"content\"]).replace(\"\\n\", \"<br>\"))\n",
    "        for call in message.get(\"tool_calls\") or []:\n",
    "            parts.append(CODE + f'{call[\"function\"][\"name\"]}({html.escape(call[\"function\"][\"arguments\"])})</code>')\n",
    "        blocks.append(f'<div style=\"background:{background};border-left:4px solid {edge};color:#0f172a;'\n",
    "                      f'padding:6px 10px;margin:4px 0;font:14px/1.5 sans-serif\"><b>{label}</b><br>{\"<br>\".join(parts)}</div>')\n",
    "    return \"\".join(blocks)\n",
    "\n",
    "\n",
    "def show_messages(messages):\n",
    "    # Draws a conversation as that script\n",
    "    display(HTML(script(messages)))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "c6bce043",
   "metadata": {},
   "source": [
    "conversation = [\n",
    "    {\"role\": \"system\", \"content\": \"You help students of KU Leuven. Answer in at most two sentences.\"},\n",
    "    {\"role\": \"user\", \"content\": \"My first exam is on Monday. Any tips?\"},\n",
    "]\n",
    "response = ask(conversation)\n",
    "conversation.append({\"role\": \"assistant\", \"content\": response.choices[0].message.content})\n",
    "print(response.usage.prompt_tokens, \"tokens in\")\n",
    "\n",
    "conversation.append({\"role\": \"user\", \"content\": \"And what if I can't sleep the night before?\"})\n",
    "response = ask(conversation)\n",
    "conversation.append({\"role\": \"assistant\", \"content\": response.choices[0].message.content})\n",
    "print(response.usage.prompt_tokens, \"tokens in\")\n",
    "\n",
    "show_messages(conversation)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "5660d3c1",
   "metadata": {},
   "source": [
    "The second question only makes sense after the first one: the night before *what*? The model knows, because the whole conversation went along, and you see that in the number of tokens that went in, which grows with every turn. That's the [context](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#context-the-working-memory-of-an-agent) from the chapter: all the model knows about this conversation is what you send it.\n",
    "\n",
    "Change the system prompt (for example to \"Answer like a pirate\") and run the cell again."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7047d760",
   "metadata": {},
   "source": [
    "## 🚆 Asking about trains without tools\n",
    "\n",
    "Now the question that this notebook is about. Ask the model about a train:"
   ]
  },
  {
   "cell_type": "code",
   "id": "86cf927f",
   "metadata": {},
   "source": [
    "question = [{\"role\": \"user\", \"content\": \"What day is it today, and when does the next train from Leuven to Ghent leave?\"}]\n",
    "response = ask(question)\n",
    "show_messages(question + [response.choices[0].message.model_dump(exclude_none=True)])"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "97eaddf1",
   "metadata": {},
   "source": [
    "The model has no clock and no timetable: all it has is what it read during its training, which ended months ago. Depending on the model, it admits that it can't know, or it makes up a day and a train that sound real: a [hallucination](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#hallucinations).\n",
    "\n",
    "Both problems have a solution. The model always needs to know the date, so that goes into the system prompt, every time. The train times change all day, so for those, the model needs a **tool**."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47dd9b0b",
   "metadata": {},
   "source": [
    "## 🛠️ Your first tool\n",
    "\n",
    "A **tool** is a function in your own code. You describe it to the model, and when the model needs it, it doesn't answer, but asks *you* to run it, with arguments that it filled in itself. Your code runs the function and sends the result back, and only then does the model answer (see [Tool calling](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#tool-calling)).\n",
    "\n",
    "This first tool asks the [iRail API](https://docs.irail.be) for train connections: an open-source project that offers the timetable of the NMBS/SNCB for free, without a key. The tool takes the date and the time the way people write them, and converts them to the format that iRail wants: the model shouldn't have to know that. And it only keeps the few fields that matter, instead of the 11 kilobytes that iRail sends for three trains, because everything the model gets back takes up room in its context."
   ]
  },
  {
   "cell_type": "code",
   "id": "447c7b0d",
   "metadata": {},
   "source": [
    "# iRail asks every program to say who it is\n",
    "HEADERS = {\"User-Agent\": \"AI-voor-Iedereen-notebook/1.0 (https://ai.kuleuven.be/aivooriedereen)\"}\n",
    "\n",
    "\n",
    "def clock(timestamp):\n",
    "    # A time from iRail (seconds since 1 January 1970) as HH:MM in Belgium\n",
    "    return datetime.fromtimestamp(int(timestamp), BRUSSELS).strftime(\"%H:%M\")\n",
    "\n",
    "\n",
    "def find_trains(from_station: str, to_station: str, date: str, time: str, arrive_by: bool = False) -> list:\n",
    "    \"\"\"Train connections in Belgium, from the live timetable of the NMBS/SNCB.\n",
    "\n",
    "    Args:\n",
    "        from_station: The station to leave from, for example \"Gent-Sint-Pieters\".\n",
    "        to_station: The station to travel to, for example \"Leuven\".\n",
    "        date: The day of travel, as YYYY-MM-DD.\n",
    "        time: A time as HH:MM. The trains leave after this time, or arrive before it if arrive_by is true.\n",
    "        arrive_by: True for the trains that arrive before the time, instead of the ones that leave after it.\n",
    "    \"\"\"\n",
    "    moment = datetime.strptime(f\"{date} {time}\", \"%Y-%m-%d %H:%M\")\n",
    "    answer = requests.get(\"https://api.irail.be/v1/connections/\", headers=HEADERS, params={\n",
    "        \"from\": from_station, \"to\": to_station, \"format\": \"json\", \"lang\": \"en\",\n",
    "        \"date\": moment.strftime(\"%d%m%y\"), \"time\": moment.strftime(\"%H%M\"),\n",
    "        \"timesel\": \"arrival\" if arrive_by else \"departure\",\n",
    "    })\n",
    "    if answer.status_code == 400:                            # such as a station that doesn't exist:\n",
    "        raise ValueError(answer.json()[\"message\"])            # pass on the reason, so the model can fix it\n",
    "    answer.raise_for_status()\n",
    "    trains = []\n",
    "    for connection in answer.json()[\"connection\"]:\n",
    "        trains.append({\n",
    "            \"departure\": clock(connection[\"departure\"][\"time\"]),\n",
    "            \"arrival\": clock(connection[\"arrival\"][\"time\"]),\n",
    "            \"minutes\": int(connection[\"duration\"]) // 60,\n",
    "            \"transfers\": int(connection.get(\"vias\", {}).get(\"number\", 0)),\n",
    "            \"platform\": connection[\"departure\"][\"platform\"],\n",
    "            \"delay_minutes\": int(connection[\"departure\"][\"delay\"]) // 60,\n",
    "            \"canceled\": connection[\"departure\"][\"canceled\"] == \"1\",\n",
    "        })\n",
    "    return trains\n",
    "\n",
    "\n",
    "tomorrow = (datetime.now(BRUSSELS) + timedelta(days=1)).strftime(\"%Y-%m-%d\")\n",
    "HTML(pd.DataFrame(find_trains(\"Gent-Sint-Pieters\", \"Leuven\", tomorrow, \"09:00\", arrive_by=True)).to_html(index=False))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "da0dfa76",
   "metadata": {},
   "source": [
    "Those are the trains that arrive in Leuven before 9 tomorrow, as Python sees the function. The model sees something else: a description in JSON, with the name of the function, what it does, and its arguments. `tool_schema` writes that description from the function itself, from its type hints (`str`, `bool`) and its docstring. That's why the docstring matters so much: it's the only manual the model gets."
   ]
  },
  {
   "cell_type": "code",
   "id": "a99105db",
   "metadata": {},
   "source": [
    "JSON_TYPES = {str: \"string\", int: \"integer\", float: \"number\", bool: \"boolean\"}\n",
    "\n",
    "\n",
    "def tool_schema(function):\n",
    "    # The description of a Python function that the model gets to see\n",
    "    description, _, args_text = inspect.getdoc(function).partition(\"Args:\")\n",
    "    explained = dict(re.findall(r\"^\\s*(\\w+): (.+)$\", args_text, re.MULTILINE))\n",
    "    properties, required = {}, []\n",
    "    for name, parameter in inspect.signature(function).parameters.items():\n",
    "        properties[name] = {\"type\": JSON_TYPES[parameter.annotation], \"description\": explained.get(name, \"\")}\n",
    "        if parameter.default is inspect.Parameter.empty:\n",
    "            required.append(name)\n",
    "    return {\"type\": \"function\", \"function\": {\n",
    "        \"name\": function.__name__,\n",
    "        \"description\": description.strip(),\n",
    "        \"parameters\": {\"type\": \"object\", \"properties\": properties, \"required\": required},\n",
    "    }}\n",
    "\n",
    "\n",
    "print(json.dumps(tool_schema(find_trains), indent=2))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "395c60a1",
   "metadata": {},
   "source": [
    "Now the model gets a question, today's date in the system prompt, and this description in `tools`. Look at what comes back:"
   ]
  },
  {
   "cell_type": "code",
   "id": "bf796c58",
   "metadata": {},
   "source": [
    "now = datetime.now(BRUSSELS)\n",
    "messages = [\n",
    "    {\"role\": \"system\", \"content\": f\"Today is {now:%A %d %B %Y}, and it is {now:%H:%M}.\"},\n",
    "    {\"role\": \"user\", \"content\": \"Which trains from Ghent get me to Leuven before 9 tomorrow morning?\"},\n",
    "]\n",
    "response = ask(messages, tools=[tool_schema(find_trains)])\n",
    "message = response.choices[0].message\n",
    "\n",
    "print(\"Text:\", message.content)\n",
    "for call in message.tool_calls or []:\n",
    "    print(\"Tool call:\", call.function.name, call.function.arguments)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "6060caa3",
   "metadata": {},
   "source": [
    "Usually there's no answer yet, but a **tool call**: the name of a function and its arguments, in JSON. The model filled in a form, the description of the tool. Look at the arguments: did \"Ghent\" become a station, \"tomorrow\" a date (thanks to the date in the system prompt), and \"before 9\" `arrive_by`? Nothing has run yet: a model can only write text. Running the function is up to your code, which then sends the result back:"
   ]
  },
  {
   "cell_type": "code",
   "id": "9105f8eb",
   "metadata": {},
   "source": [
    "messages.append(message.model_dump(exclude_none=True))       # the model's turn, with its tool call\n",
    "for call in message.tool_calls or []:\n",
    "    result = find_trains(**json.loads(call.function.arguments))\n",
    "    messages.append({\"role\": \"tool\", \"tool_call_id\": call.id, \"content\": json.dumps(result)})\n",
    "\n",
    "response = ask(messages, tools=[tool_schema(find_trains)])\n",
    "messages.append(response.choices[0].message.model_dump(exclude_none=True))\n",
    "show_messages(messages)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "254d4b77",
   "metadata": {},
   "source": [
    "That's the whole script that the model read, from top to bottom: the system prompt, the question, its own thoughts and tool call, the result from iRail, and finally its answer, now with real train times. It's the script from the chapter, with a timetable instead of a calculator. Check the times in the answer against the tool result: the model should only use times that iRail sent."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b32f48e6",
   "metadata": {},
   "source": [
    "## 🔁 Several tools in a loop\n",
    "\n",
    "One question, one tool call: that's still a chatbot with a timetable. An [agent](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#agents) keeps going: it calls a tool, reads the result, decides which tool it needs next, and only stops when it can answer. That loop is short enough to write yourself. `run_agent` sends the conversation with the descriptions of all the tools, runs every tool call (sometimes several at once), and stops as soon as the model answers without calling a tool. Meanwhile, it shows the script as it grows. When a tool fails, it sends the error back as the result, so that the model can try again, for example with another station name."
   ]
  },
  {
   "cell_type": "code",
   "id": "f102f9af",
   "metadata": {},
   "source": [
    "def run_agent(question, tools, system, max_steps=10):\n",
    "    # Lets the model call tools until it has an answer; shows the script while it grows, and returns it\n",
    "    functions = {function.__name__: function for function in tools}\n",
    "    schemas = [tool_schema(function) for function in tools]\n",
    "    messages = [{\"role\": \"system\", \"content\": system}, {\"role\": \"user\", \"content\": question}]\n",
    "    screen = display(HTML(script(messages)), display_id=True)\n",
    "    for step in range(max_steps):\n",
    "        message = ask(messages, tools=schemas).choices[0].message\n",
    "        messages.append(message.model_dump(exclude_none=True))\n",
    "        for call in message.tool_calls or []:\n",
    "            try:\n",
    "                result = functions[call.function.name](**json.loads(call.function.arguments))\n",
    "            except Exception as error:                         # the model gets the error, and can react to it\n",
    "                result = f\"Error: {error}\"\n",
    "            messages.append({\"role\": \"tool\", \"tool_call_id\": call.id, \"content\": json.dumps(result)})\n",
    "        screen.update(HTML(script(messages)))\n",
    "        if not message.tool_calls:                             # no tool call: this was the answer\n",
    "            break\n",
    "    return messages"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "b0a116e9",
   "metadata": {},
   "source": [
    "The planner needs two more tools. The first one is your timetable. Here it's an example week, which you can replace with your own classes. Every class also says how long it takes to get there from Leuven station. The second tool asks [Open-Meteo](https://open-meteo.com), a free weather service without a key, for the forecast at one hour, after looking up where the place is."
   ]
  },
  {
   "cell_type": "code",
   "id": "76a01700",
   "metadata": {},
   "source": [
    "# An example week: start, end, course, building, and the way there from Leuven station\n",
    "TIMETABLE = {\n",
    "    \"Monday\": [(\"10:30\", \"12:30\", \"Statistics\", \"Aula Pieter De Somer\", \"20 minutes on foot\"),\n",
    "               (\"14:00\", \"16:00\", \"Programming\", \"Arenberg campus, Heverlee\", \"15 minutes by bus\")],\n",
    "    \"Tuesday\": [(\"08:30\", \"10:30\", \"Chemistry\", \"Gasthuisberg campus\", \"15 minutes by bus\"),\n",
    "                (\"13:00\", \"15:00\", \"Statistics\", \"Aula Pieter De Somer\", \"20 minutes on foot\")],\n",
    "    \"Wednesday\": [(\"10:30\", \"12:30\", \"Economics\", \"Erasmushuis\", \"15 minutes on foot\")],\n",
    "    \"Thursday\": [(\"09:00\", \"11:00\", \"Programming\", \"Arenberg campus, Heverlee\", \"15 minutes by bus\"),\n",
    "                 (\"14:00\", \"17:00\", \"Lab session\", \"Arenberg campus, Heverlee\", \"15 minutes by bus\")],\n",
    "    \"Friday\": [(\"08:30\", \"10:30\", \"Academic writing\", \"Erasmushuis\", \"15 minutes on foot\"),\n",
    "               (\"11:00\", \"13:00\", \"Economics\", \"Erasmushuis\", \"15 minutes on foot\")],\n",
    "}\n",
    "\n",
    "\n",
    "def get_timetable(date: str) -> dict:\n",
    "    \"\"\"The classes of the student on one day, with where they are and how to get there from Leuven station.\n",
    "\n",
    "    Args:\n",
    "        date: The day, as YYYY-MM-DD.\n",
    "    \"\"\"\n",
    "    weekday = datetime.strptime(date, \"%Y-%m-%d\").strftime(\"%A\")\n",
    "    classes = [{\"start\": start, \"end\": end, \"course\": course, \"building\": building, \"from_leuven_station\": way}\n",
    "               for start, end, course, building, way in TIMETABLE.get(weekday, [])]\n",
    "    return {\"date\": date, \"weekday\": weekday, \"classes\": classes}\n",
    "\n",
    "\n",
    "def get_weather(place: str, date: str, hour: int) -> dict:\n",
    "    \"\"\"The weather forecast for a place in Belgium at one hour of a day, up to two weeks ahead.\n",
    "\n",
    "    Args:\n",
    "        place: A town or city in Belgium, for example \"Leuven\".\n",
    "        date: The day, as YYYY-MM-DD.\n",
    "        hour: The hour of the day, from 0 to 23.\n",
    "    \"\"\"\n",
    "    found = requests.get(\"https://geocoding-api.open-meteo.com/v1/search\",\n",
    "                         params={\"name\": place, \"count\": 1, \"countryCode\": \"BE\"}).json()\n",
    "    if not found.get(\"results\"):\n",
    "        raise ValueError(f\"There is no place called {place} in Belgium\")\n",
    "    spot = found[\"results\"][0]\n",
    "    hourly = requests.get(\"https://api.open-meteo.com/v1/forecast\", params={\n",
    "        \"latitude\": spot[\"latitude\"], \"longitude\": spot[\"longitude\"], \"timezone\": \"Europe/Brussels\",\n",
    "        \"hourly\": \"temperature_2m,precipitation_probability,precipitation,wind_speed_10m\",\n",
    "        \"start_date\": date, \"end_date\": date,\n",
    "    }).json()[\"hourly\"]\n",
    "    return {\n",
    "        \"place\": spot[\"name\"],\n",
    "        \"time\": hourly[\"time\"][hour],\n",
    "        \"temperature_celsius\": hourly[\"temperature_2m\"][hour],\n",
    "        \"chance_of_rain_percent\": hourly[\"precipitation_probability\"][hour],\n",
    "        \"rain_mm\": hourly[\"precipitation\"][hour],\n",
    "        \"wind_km_per_hour\": hourly[\"wind_speed_10m\"][hour],\n",
    "    }"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "21c64774",
   "metadata": {},
   "source": [
    "The system prompt holds what the model must always know: whom it helps, the date and the time, and how early the student wants to be in class. Then the question. The model thinks before every step, so this takes a minute or so. Is tomorrow a Saturday or a Sunday? Then there are no classes, so ask about Monday instead."
   ]
  },
  {
   "cell_type": "code",
   "id": "841b4906",
   "metadata": {},
   "source": [
    "now = datetime.now(BRUSSELS)\n",
    "SYSTEM = f\"\"\"You help a student of KU Leuven who lives in Ghent and takes the train to Leuven.\n",
    "Today is {now:%A %d %B %Y}, and it is {now:%H:%M}.\n",
    "Use the tools for classes, trains and the weather: never guess them.\n",
    "The student wants to be in the classroom 10 minutes before a class starts.\n",
    "Answer in at most five sentences.\"\"\"\n",
    "TOOLS = [get_timetable, find_trains, get_weather]\n",
    "\n",
    "trip = run_agent(\"Which train should I take tomorrow to be on time for my first class? Do I need a rain jacket?\", TOOLS, SYSTEM)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "462b187e",
   "metadata": {},
   "source": [
    "Read the script from top to bottom. Did the model look up the timetable first? Before what time did it want to arrive in Leuven, and does that fit the start of the first class, the way from the station and the 10 minutes? Nobody told it which tools to use, or in which order: that followed from the question and from the descriptions of the tools. Then check the answer against the tool results: the tools give the model the right data, but the model still has to combine them, and it can still pick the wrong train or count back wrong.\n",
    "\n",
    "Your turn: ask something else. A few ideas:\n",
    "\n",
    "- \"Do I need an umbrella on the way home on Tuesday?\"\n",
    "- \"I'm in Brussels-Central at 8. Can I still make my first class tomorrow?\"\n",
    "- \"Which day this week can I sleep in the longest?\""
   ]
  },
  {
   "cell_type": "code",
   "id": "1a17b6d1",
   "metadata": {},
   "source": [
    "trip = run_agent(\"I want to go home to Ghent after my last class on Friday. Which train can I take?\", TOOLS, SYSTEM)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "043e0d0e",
   "metadata": {},
   "source": [
    "## 🧰 An agent for your own problem\n",
    "\n",
    "The recipe for an agent of your own:\n",
    "\n",
    "1. Write every tool as an ordinary Python function, with type hints and a docstring that says what it does and when to use it. The docstring is the only manual the model gets: \"Use this for every question about …\" helps more than you'd think. Let the function return little: a few fields, not everything an API sends.\n",
    "2. Put in the system prompt what the model must always know: whom it helps, today's date, the rules.\n",
    "3. Call `run_agent(question, [my_tool, my_other_tool], system)`, and read the script before you trust the answer.\n",
    "\n",
    "A tool can be anything you can write as a function: a model from another notebook (a decision tree that predicts something), a [CPMpy solver](https://ai.kuleuven.be/aivooriedereen/en/notebook/constraint-solving) that makes a schedule, a search through your own data with pandas, or another free API, such as the departure boards of [iRail](https://docs.irail.be) or the history of [Open-Meteo](https://open-meteo.com). Prefer tools that only read. An agent that can also act (send an e-mail, delete a file, book a room) should ask a person first, for the reasons in the chapter's section on [keeping watch](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#oversight). And when you want data instead of text, such as a label for every message, ask for **structured output**: with the option `response_format`, which `ask` passes on, the model fills in the fields that you describe.\n",
    "\n",
    "Two more tips. Every run costs requests and gives a slightly different answer, so save the conversations you want to keep with `json.dump`, and load them again with `json.load` instead of asking the model a second time. And most other providers understand the same requests: give `client` another `base_url` and key, and leave out the OpenRouter option in `ask`. Agent frameworks and the [Model Context Protocol](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#connecting-tools-with-mcp) run the same loop as `run_agent`, with more around it; now you know what happens inside."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eb4e88bf",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "*By [Thomas Winters](https://thomaswinters.be) for [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en), KU Leuven. The latest version of this notebook: [ai.kuleuven.be/aivooriedereen/en/notebook/large-language-models](https://ai.kuleuven.be/aivooriedereen/en/notebook/large-language-models).*"
   ]
  }
 ],
 "metadata": {
  "aivi": {
   "chapters": [
    "grote-taalmodellen"
   ],
   "language": "en",
   "title": "Large language models in Python",
   "requires_env": [
    "OPENROUTER_API_KEY"
   ]
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
