{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "id": "4KqMWyVlwu4L" }, "outputs": [], "source": [ "# Copyright 2026 Google LLC\n", "#\n", "# Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# https://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License." ] }, { "cell_type": "markdown", "metadata": { "id": "8H5Di4ZXwu4M" }, "source": [ "# Building Knowledge Graphs with Gemini\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", "
\n", " \n", " \"Google
Open in Colab\n", "
\n", "
\n", " \n", " \"Google
Open in Colab Enterprise\n", "
\n", "
\n", " \n", " \"Workbench
Open in Workbench\n", "
\n", "
\n", " \n", " \"GitHub
View on GitHub\n", "
\n", "
\n", "\n", "
\n", "\n", "

\n", "Share to:\n", "\n", "\n", " \"LinkedIn\n", "\n", "\n", "\n", " \"Bluesky\n", "\n", "\n", "\n", " \"X\n", "\n", "\n", "\n", " \"Reddit\n", "\n", "\n", "\n", " \"Facebook\n", "\n", "

\n" ] }, { "cell_type": "markdown", "metadata": { "id": "m1Xixczzs9mQ" }, "source": [ "| Author |\n", "| ------------------------------------------------ |\n", "| [Laurent Picard](https://github.com/PicardParis) |\n" ] }, { "cell_type": "markdown", "metadata": { "id": "Hsi0Sy73rYeH" }, "source": [ "---\n", "\n", "## ✨ Overview\n" ] }, { "cell_type": "markdown", "metadata": { "id": "X5XQkkkrrYeH" }, "source": [ "![intro image](https://storage.googleapis.com/github-repo/generative-ai/gemini/use-cases/knowledge-graph/kg_fr_dumas_comte_de_monte_cristo_3_flash.gif)\n", "\n", "In this exploration, we'll see how to turn raw, unstructured documents into structured knowledge graphs using Gemini. We'll start by prototyping to develop our intuition. Then, we'll optimize our prompts and outputs, and finally scale up to process entire books or dense legal contracts. By the end, we'll even visualize extracted book narratives and contractual network graphs!\n" ] }, { "cell_type": "markdown", "metadata": { "id": "om3Go4l7BQyf" }, "source": [ "---\n", "\n", "## 🔥 Challenge\n" ] }, { "cell_type": "markdown", "metadata": { "id": "3zK85vQGBQyf" }, "source": [ "Documents are everywhere. We use them for business, daily operations, legal matters, technical docs, education, and even just for fun. However, documents are not databases. They're generally unstructured, and fully understanding them requires multiple reading passes.\n", "\n", "So, can we extract structured knowledge from documents using only the following?\n", "\n", "- 1 document\n", "- 1 prompt\n", "- 1 request\n", "\n", "Let's try with Gemini…\n" ] }, { "cell_type": "markdown", "metadata": { "id": "_NlD5OhCwu4M" }, "source": [ "---\n", "\n", "## 🏁 Setup\n" ] }, { "cell_type": "markdown", "metadata": { "id": "eHoOUP0JBQyg" }, "source": [ "### 🐍 Python packages\n" ] }, { "cell_type": "markdown", "metadata": { "id": "xVaM54E5rYeJ" }, "source": [ "We'll use the following packages:\n", "\n", "- `google-genai` for calling Gemini with the [Google Gen AI Python SDK](https://pypi.org/project/google-genai)\n", "- `networkx` for graph management\n", "\n", "We'll also need:\n", "\n", "- `tenacity` for request management (a dependency of `google-genai`)\n", "- `matplotlib` and `pillow` for data visualization (dependencies of `networkx`)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "kZBN80r7qtgs" }, "outputs": [], "source": [ "%pip install --quiet \"google-genai>=2.6.0\" \"networkx[default]\"" ] }, { "cell_type": "markdown", "metadata": { "id": "51W6LrRJs9mT" }, "source": [ "---\n", "\n", "### 🤝 Gemini API\n" ] }, { "cell_type": "markdown", "metadata": { "id": "MDl51OblrYeJ" }, "source": [ "To use the Gemini API, we have two main options:\n", "\n", "1. Via **Agent Platform** (formerly Vertex AI) with a Google Cloud project\n", "2. Via **Google AI Studio** with a Gemini API key\n", "\n", "The Google Gen AI SDK provides a unified interface to these APIs and we can use environment variables for the configuration.\n", "\n", "**🛠️ Option 1 - Gemini API via Agent Platform**\n", "\n", "Requirements:\n", "\n", "- A Google Cloud project\n", "- The Agent Platform API must be enabled for this project: ▶️ [Enable the Agent Platform API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,storage-component.googleapis.com)\n", "\n", "Gen AI SDK environment variables:\n", "\n", "- `GOOGLE_GENAI_USE_ENTERPRISE=\"True\"`\n", "- `GOOGLE_CLOUD_PROJECT=\"\"`\n", "- `GOOGLE_CLOUD_LOCATION=\"\"`\n", "\n", "> 💡 For preview models, the location must be set to `global`. For generally available models, we can choose the closest location among the [Google model endpoint locations](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#google-models).\n", "\n", "> ℹ️ Learn more about [setting up a project and a development environment](https://docs.cloud.google.com/vertex-ai/docs/start/cloud-environment).\n", "\n", "**🛠️ Option 2 - Gemini API via Google AI Studio**\n", "\n", "Requirement:\n", "\n", "- A Gemini API key\n", "\n", "Gen AI SDK environment variables:\n", "\n", "- `GOOGLE_GENAI_USE_ENTERPRISE=\"False\"`\n", "- `GOOGLE_API_KEY=\"\"`\n", "\n", "> ℹ️ Learn more about [getting a Gemini API key from Google AI Studio](https://aistudio.google.com/app/apikey).\n" ] }, { "cell_type": "markdown", "metadata": { "id": "1bYRJlOXs9mT" }, "source": [ "💡 You can store your environment configuration outside of the source code:\n", "\n", "| Environment | Method |\n", "| ---------------- | ----------------------------------------------------------- |\n", "| IDE | `.env` file (or equivalent) |\n", "| Colab | Colab Secrets (🗝️ icon in left panel, see code below) |\n", "| Colab Enterprise | Google Cloud project and location are automatically defined |\n", "| Workbench | Google Cloud project and location are automatically defined |\n" ] }, { "cell_type": "markdown", "metadata": { "id": "JcBky51us9mU" }, "source": [ "Define the following environment detection functions. You can also define your configuration manually if needed.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "LAmlOAygs9mU" }, "outputs": [], "source": [ "# @title {display-mode: \"form\"}\n", "import os\n", "import sys\n", "from collections.abc import Callable\n", "\n", "from google import genai\n", "\n", "# Manual setup (leave unchanged if setup is environment-defined)\n", "\n", "# @markdown **Which API: Agent Platform (formerly Vertex AI) or Google AI Studio?**\n", "GOOGLE_GENAI_USE_ENTERPRISE = True # @param {type: \"boolean\"}\n", "\n", "# @markdown **Option A - Google Cloud project [+location]**\n", "GOOGLE_CLOUD_PROJECT = \"\" # @param {type: \"string\"}\n", "GOOGLE_CLOUD_LOCATION = \"global\" # @param {type: \"string\"}\n", "\n", "# @markdown **Option B - Google AI Studio API key**\n", "GOOGLE_API_KEY = \"\" # @param {type: \"string\"}\n", "\n", "\n", "def check_environment() -> bool:\n", " check_colab_user_authentication()\n", " return check_manual_setup() or check_enterprise() or check_colab() or check_local()\n", "\n", "\n", "def check_manual_setup() -> bool:\n", " return check_define_env_vars(\n", " GOOGLE_GENAI_USE_ENTERPRISE,\n", " GOOGLE_CLOUD_PROJECT.strip(), # Might have been pasted with a newline\n", " GOOGLE_CLOUD_LOCATION,\n", " GOOGLE_API_KEY,\n", " )\n", "\n", "\n", "def check_enterprise() -> bool:\n", " # Workbench and Colab Enterprise\n", " match os.getenv(\"VERTEX_PRODUCT\", \"\"):\n", " case \"WORKBENCH_INSTANCE\":\n", " pass\n", " case \"COLAB_ENTERPRISE\":\n", " if not running_in_colab_env():\n", " return False\n", " case _:\n", " return False\n", "\n", " return check_define_env_vars(\n", " True,\n", " os.getenv(\"GOOGLE_CLOUD_PROJECT\", \"\"),\n", " os.getenv(\"GOOGLE_CLOUD_REGION\", \"\"),\n", " \"\",\n", " )\n", "\n", "\n", "def check_colab() -> bool:\n", " if not running_in_colab_env():\n", " return False\n", "\n", " # Colab Enterprise was checked before, so this is Colab only\n", " from google.colab import auth as colab_auth # type: ignore\n", "\n", " colab_auth.authenticate_user()\n", "\n", " # Use Colab Secrets (🗝️ icon in left panel) to store the environment variables\n", " # Secrets are private, visible only to you and the notebooks that you select\n", " # - Agent Platform: Store your settings as secrets\n", " # - Google AI: Directly import your Gemini API key from the UI\n", " enterprise, project, location, api_key = get_vars(get_colab_secret)\n", "\n", " return check_define_env_vars(enterprise, project, location, api_key)\n", "\n", "\n", "def check_local() -> bool:\n", " enterprise, project, location, api_key = get_vars(os.getenv)\n", "\n", " return check_define_env_vars(enterprise, project, location, api_key)\n", "\n", "\n", "def running_in_colab_env() -> bool:\n", " # Colab or Colab Enterprise\n", " return \"google.colab\" in sys.modules\n", "\n", "\n", "def check_colab_user_authentication() -> None:\n", " if running_in_colab_env():\n", " from google.colab import auth as colab_auth # type: ignore\n", "\n", " colab_auth.authenticate_user()\n", "\n", "\n", "def get_colab_secret(secret_name: str, default: str) -> str:\n", " from google.colab import errors, userdata # type: ignore\n", "\n", " try:\n", " return userdata.get(secret_name)\n", " except errors.SecretNotFoundError:\n", " return default\n", "\n", "\n", "def disable_colab_cell_scrollbar() -> None:\n", " if running_in_colab_env():\n", " from google.colab import output # type: ignore\n", "\n", " output.no_vertical_scroll()\n", "\n", "\n", "def get_vars(getenv: Callable[[str, str], str]) -> tuple[bool, str, str, str]:\n", " # Limit getenv calls to the minimum (may trigger UI confirmation for secret access)\n", " enterprise_str = getenv(\"GOOGLE_GENAI_USE_ENTERPRISE\", \"\")\n", " if not enterprise_str:\n", " enterprise_str = getenv(\"GOOGLE_GENAI_USE_VERTEXAI\", \"\")\n", " if enterprise_str:\n", " enterprise = enterprise_str.lower() in [\"true\", \"1\"]\n", " else:\n", " enterprise = bool(getenv(\"GOOGLE_CLOUD_PROJECT\", \"\"))\n", "\n", " project = getenv(\"GOOGLE_CLOUD_PROJECT\", \"\") if enterprise else \"\"\n", " location = getenv(\"GOOGLE_CLOUD_LOCATION\", \"\") if project else \"\"\n", " api_key = getenv(\"GOOGLE_API_KEY\", \"\") if not project else \"\"\n", "\n", " return enterprise, project, location, api_key\n", "\n", "\n", "def check_define_env_vars(\n", " enterprise: bool,\n", " project: str,\n", " location: str,\n", " api_key: str,\n", ") -> bool:\n", " match (enterprise, bool(project), bool(location), bool(api_key)):\n", " case (True, True, _, _):\n", " # Agent Platform - Google Cloud project [+location]\n", " location = location or \"global\"\n", " define_env_vars(enterprise, project, location, \"\")\n", " case (True, False, _, True):\n", " # Agent Platform - API key\n", " define_env_vars(enterprise, \"\", \"\", api_key)\n", " case (False, _, _, True):\n", " # Google AI Studio - API key\n", " define_env_vars(enterprise, \"\", \"\", api_key)\n", " case _:\n", " return False\n", "\n", " return True\n", "\n", "\n", "def define_env_vars(\n", " enterprise: bool,\n", " project: str,\n", " location: str,\n", " api_key: str,\n", ") -> None:\n", " os.environ[\"GOOGLE_GENAI_USE_ENTERPRISE\"] = str(enterprise)\n", " os.environ[\"GOOGLE_GENAI_USE_VERTEXAI\"] = str(enterprise)\n", " os.environ[\"GOOGLE_CLOUD_PROJECT\"] = project\n", " os.environ[\"GOOGLE_CLOUD_LOCATION\"] = location\n", " os.environ[\"GOOGLE_API_KEY\"] = api_key\n", "\n", "\n", "def check_configuration(client: genai.Client) -> None:\n", " service = \"Agent Platform\" if client.vertexai else \"Google AI Studio\"\n", " print(f\"✅ Using the {service} API\", end=\"\")\n", "\n", " if client._api_client.project:\n", " print(f' with project \"{client._api_client.project[:7]}…\"', end=\"\")\n", " print(f' in location \"{client._api_client.location}\"')\n", " elif client._api_client.api_key:\n", " api_key = client._api_client.api_key\n", " print(f' with API key \"{api_key[:5]}…{api_key[-5:]}\"', end=\"\")\n", " print(f\" (in case of error, make sure it was created for {service})\")\n", "\n", "\n", "print(\"✅ Environment functions defined\")" ] }, { "cell_type": "markdown", "metadata": { "id": "Ee26klvTs9mU" }, "source": [ "---\n", "\n", "### 🤖 Gen AI SDK\n" ] }, { "cell_type": "markdown", "metadata": { "id": "dZu-UMI9rYeK" }, "source": [ "To send Gemini requests, we'll use a `google.genai` client:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "1vFn9oBTs9mU" }, "outputs": [], "source": [ "from google import genai\n", "\n", "check_environment()\n", "\n", "client = genai.Client()\n", "\n", "check_configuration(client)" ] }, { "cell_type": "markdown", "metadata": { "id": "mU7VFMfVwu4N" }, "source": [ "---\n", "\n", "### 🔣 Input data\n" ] }, { "cell_type": "markdown", "metadata": { "id": "hph-EFk3rYeK" }, "source": [ "We need a suite of test data to develop our solution.\n", "\n", "**Multimodality**\n", "\n", "We'll test the following types:\n", "\n", "- Text (`text/plain`): Classic books are good text sources of varying lengths and languages.\n", "- PDF (`application/pdf`): Legal agreements are also great examples of complex and dense documents.\n", "\n", "Gemini is natively multimodal, which means it can process different types of inputs. Once we've built knowledge graphs from text or PDF inputs, the solution will also naturally support the following formats:\n", "\n", "- Image (`image/*`)\n", "- Audio (`audio/*`)\n", "- Video (`video/*`)\n", "\n", "**General knowledge**\n", "\n", "⚠️ LLMs are trained on general knowledge, which becomes part of their \"long-term memory\". To avoid generating memorized information, we'll explicitly instruct the model to use only the provided inputs.\n", "\n", "**Multilinguality**\n", "\n", "Gemini is also natively [multilingual](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/models#expandable-1), which lets us process inputs and generate outputs in 100+ languages.\n", "\n", "To keep things general, we'll use English for prompts and knowledge graphs, but you can use any of the 100+ supported languages, as long as your prompts remain clear and explicit.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "9I_dFyVkrYeK" }, "source": [ "Let's define a few data sources and helpers:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "4EVlIhc0wu4N" }, "outputs": [], "source": [ "# @title {display-mode: \"form\"}\n", "import mimetypes\n", "from collections.abc import Iterator\n", "from enum import Enum\n", "from pathlib import Path\n", "\n", "from google.genai.types import Part\n", "\n", "GOOGLE_CLOUD_STORAGE_PREFIX = \"gs://\"\n", "HTTPS_PREFIX = \"https://\"\n", "FILE_PREFIX = \"file://\"\n", "LOCAL_FOLDER = \"./\"\n", "\n", "\n", "class Source(Enum):\n", " def yield_contents(self) -> Iterator[Part]:\n", " file_uri = self.value\n", " if not client.vertexai:\n", " file_uri = convert_to_https_url_if_cloud_storage_uri(file_uri)\n", " mime_type, _ = mimetypes.guess_type(file_uri)\n", " assert mime_type is not None, f\"❌ Could not determine mime type: {file_uri=}\"\n", "\n", " if file_uri.startswith((GOOGLE_CLOUD_STORAGE_PREFIX, HTTPS_PREFIX)):\n", " yield Part.from_uri(file_uri=file_uri, mime_type=mime_type)\n", " return\n", "\n", " if file_uri.startswith(FILE_PREFIX):\n", " file = Path(file_uri.removeprefix(FILE_PREFIX))\n", " assert file.exists(), f\"❌ File does not exist: {file=}\"\n", " if mime_type == \"text/plain\":\n", " yield Part.from_text(text=file.read_text(encoding=\"utf-8\"))\n", " else:\n", " yield Part.from_bytes(data=file.read_bytes(), mime_type=mime_type)\n", " return\n", "\n", " def yield_source_names(self) -> Iterator[str]:\n", " yield self.name\n", "\n", " def yield_source_links(self) -> Iterator[str]:\n", " file_uri = convert_to_https_url_if_cloud_storage_uri(self.value)\n", " if file_uri.startswith(HTTPS_PREFIX):\n", " yield file_uri\n", " return\n", " if file_uri.startswith(FILE_PREFIX):\n", " yield file_uri.removeprefix(FILE_PREFIX)\n", " return\n", "\n", "\n", "def convert_to_https_url_if_cloud_storage_uri(uri: str) -> str:\n", " return (\n", " f\"{HTTPS_PREFIX}storage.googleapis.com/{uri.removeprefix(GOOGLE_CLOUD_STORAGE_PREFIX)}\"\n", " if uri.startswith(GOOGLE_CLOUD_STORAGE_PREFIX)\n", " else uri\n", " )\n", "\n", "\n", "def local_file(filename: str) -> str:\n", " return f\"{FILE_PREFIX}{LOCAL_FOLDER}{filename}\"\n", "\n", "\n", "# You can find public domain books on Project Gutenberg: https://gutenberg.org/ebooks\n", "def project_gutenberg_txt_url(id: int) -> str:\n", " return f\"{HTTPS_PREFIX}gutenberg.org/cache/epub/{id}/pg{id}.txt\"\n", "\n", "\n", "class Classic(Source):\n", " en_hugo_les_misérables = project_gutenberg_txt_url(135)\n", " en_dumas_count_of_monte_cristo = project_gutenberg_txt_url(1184)\n", " fr_zola_thérèse_raquin = project_gutenberg_txt_url(7461)\n", " fr_dumas_trois_mousquetaires = project_gutenberg_txt_url(13951)\n", " fr_dumas_vingt_ans_après = project_gutenberg_txt_url(13952)\n", " fr_dumas_comte_de_monte_cristo_1 = project_gutenberg_txt_url(17989)\n", " fr_dumas_comte_de_monte_cristo_2 = project_gutenberg_txt_url(17990)\n", " fr_dumas_comte_de_monte_cristo_3 = project_gutenberg_txt_url(17991)\n", " fr_dumas_comte_de_monte_cristo_4 = project_gutenberg_txt_url(17992)\n", "\n", "\n", "class Document(Source):\n", " en_pharma_dev_agreement = \"gs://cloud-samples-data/documentai/ContractDocAI/CUAD_v1/Part_I/Development/PhasebioPharmaceuticalsInc_20200330_10-K_EX-10.21_12086810_EX-10.21_Development Agreement.pdf\"\n", "\n", "\n", "class Collection(Source):\n", " fr_dumas_comte_de_monte_cristo = [\n", " Classic.fr_dumas_comte_de_monte_cristo_1,\n", " Classic.fr_dumas_comte_de_monte_cristo_2,\n", " Classic.fr_dumas_comte_de_monte_cristo_3,\n", " Classic.fr_dumas_comte_de_monte_cristo_4,\n", " ]\n", " fr_dumas_trois_mousquetaires_vingt_ans_après = [\n", " Classic.fr_dumas_trois_mousquetaires,\n", " Classic.fr_dumas_vingt_ans_après,\n", " ]\n", "\n", " def yield_contents(self) -> Iterator[Part]:\n", " for source in self.value:\n", " yield from source.yield_contents()\n", "\n", " def yield_source_names(self) -> Iterator[str]:\n", " for source in self.value:\n", " yield from source.yield_source_names()\n", "\n", " def yield_source_links(self) -> Iterator[str]:\n", " for source in self.value:\n", " yield from source.yield_source_links()\n", "\n", "\n", "def display_input_data_caption(source: Source) -> None:\n", " names = list(source.yield_source_names())\n", " links = list(source.yield_source_links())\n", " links = \", \".join(\n", " f\"[{name}](<{link}>)\" for name, link in zip(names, links, strict=True)\n", " )\n", " md = f\"**Input data** ({links})\"\n", " display_markdown(md)\n", "\n", "\n", "print(\"✅ Data helpers defined\")" ] }, { "cell_type": "markdown", "metadata": { "id": "SB2kbdlBs9mV" }, "source": [ "---\n", "\n", "### 🧠 Gemini model\n" ] }, { "cell_type": "markdown", "metadata": { "id": "40a0ukjJwu4O" }, "source": [ "Gemini comes in different [versions](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/models#gemini-models) and sizes (Flash-Lite, Flash, and Pro).\n", "\n", "Let's get started with Gemini 3.1 Flash-Lite, as it offers high performance, low latency, and very high output speed:\n", "\n", "- `GEMINI_3_1_FLASH_LITE = \"gemini-3.1-flash-lite\"`\n" ] }, { "cell_type": "markdown", "metadata": { "id": "a3-ICTRMs9mV" }, "source": [ "---\n", "\n", "### ⚙️ Gemini configuration\n" ] }, { "cell_type": "markdown", "metadata": { "id": "y-3U82ZGs9mV" }, "source": [ "Gemini can be used in different ways, ranging from factual to creative modes. We're essentially dealing with a **data-extraction use case**. We want the results to be as factual and deterministic as possible. To achieve this, we can adjust the [content generation parameters](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/content-generation-parameters).\n", "\n", "We'll set the `temperature`, `top_p`, and `seed` parameters to minimize randomness:\n", "\n", "- `temperature=0.0`\n", "- `top_p=0.0`\n", "- `seed=42` (arbitrary fixed value)\n" ] }, { "cell_type": "markdown", "metadata": { "id": "SkkobNmYwu4O" }, "source": [ "---\n", "\n", "### 🛠️ Helpers\n" ] }, { "cell_type": "markdown", "metadata": { "id": "fj1rJnozrYeL" }, "source": [ "Now, let's add core helper classes and functions:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Bus2ODLIK02F" }, "outputs": [], "source": [ "# @title {display-mode: \"form\"}\n", "from enum import StrEnum, auto\n", "\n", "import IPython.display\n", "import tenacity\n", "from google.genai.errors import ClientError\n", "from google.genai.types import (\n", " FinishReason,\n", " GenerateContentConfig,\n", " GenerateContentResponse,\n", " ThinkingConfig,\n", " ThinkingLevel,\n", ")\n", "\n", "\n", "class Model(Enum):\n", " GEMINI_3_1_FLASH_LITE = \"gemini-3.1-flash-lite\"\n", " GEMINI_3_5_FLASH = \"gemini-3.5-flash\"\n", " GEMINI_2_5_FLASH = \"gemini-2.5-flash\"\n", " GEMINI_2_5_PRO = \"gemini-2.5-pro\"\n", " # Preview\n", " GEMINI_3_1_PRO = \"gemini-3.1-pro-preview\"\n", " # Default model\n", " DEFAULT = GEMINI_3_1_FLASH_LITE\n", "\n", "\n", "# Default configuration for more deterministic outputs\n", "DEFAULT_CONFIG = GenerateContentConfig(\n", " temperature=0.0,\n", " top_p=0.0,\n", " seed=42, # Arbitrary fixed value\n", ")\n", "\n", "\n", "class ShowAs(StrEnum):\n", " DONT_SHOW = auto()\n", " TEXT = auto()\n", " MARKDOWN = auto()\n", "\n", "\n", "def generate_content(\n", " prompt: str,\n", " source: Source | str | None = None,\n", " *,\n", " model: Model | None = None,\n", " config: GenerateContentConfig | None = None,\n", " system_instruction: str | None = None,\n", " show_prompt: ShowAs = ShowAs.DONT_SHOW,\n", " show_response: ShowAs = ShowAs.MARKDOWN,\n", " only_show_prompt: bool = False,\n", " return_response: bool = False,\n", ") -> GenerateContentResponse | None:\n", " disable_colab_cell_scrollbar()\n", "\n", " model = model or Model.DEFAULT\n", " model_id = model.value\n", " prompt_contents = get_prompt_contents(prompt, source, show_prompt, only_show_prompt)\n", " if only_show_prompt:\n", " return None\n", " config = config or get_generate_content_config(model, system_instruction)\n", " client = check_client_for_model(model)\n", "\n", " response = None\n", " display_request_header(model_id, source)\n", " for attempt in get_retrier():\n", " with attempt:\n", " response = client.models.generate_content(\n", " model=model_id,\n", " contents=prompt_contents, # type: ignore\n", " config=config,\n", " )\n", " display_response_info(response)\n", " display_response(response, show_response)\n", "\n", " return response if return_response else None\n", "\n", "\n", "def get_prompt_contents(\n", " prompt: str,\n", " source: Source | str | None,\n", " show_prompt: ShowAs,\n", " only_show_prompt: bool,\n", ") -> list[str | Part]:\n", " def yield_prompt_contents() -> Iterator[str | Part]:\n", " if not source:\n", " yield prompt.strip()\n", " return\n", " yield \"==Start of input data==\\n\"\n", " if isinstance(source, str):\n", " yield f\"{source.strip()}\\n\"\n", " else:\n", " yield from source.yield_contents()\n", " yield \"==End of input data==\\n\"\n", " yield f\"==Start of user prompt==\\n{prompt.strip()}\\n==End of user prompt==\"\n", "\n", " prompt_contents = list(yield_prompt_contents())\n", " display_prompt(prompt_contents, show_prompt, only_show_prompt)\n", "\n", " return prompt_contents\n", "\n", "\n", "def get_generate_content_config(\n", " model: Model,\n", " system_instruction: str | None = None,\n", ") -> GenerateContentConfig:\n", " thinking_config = get_thinking_config_for_model(model)\n", "\n", " return GenerateContentConfig(\n", " system_instruction=system_instruction,\n", " temperature=DEFAULT_CONFIG.temperature,\n", " top_p=DEFAULT_CONFIG.top_p,\n", " seed=DEFAULT_CONFIG.seed,\n", " thinking_config=thinking_config,\n", " )\n", "\n", "\n", "def get_thinking_config_for_model(model: Model) -> ThinkingConfig | None:\n", " # Use minimal thinking configurations since our prompt will directly provide a chain of thought\n", " match model:\n", " case Model.GEMINI_2_5_FLASH:\n", " return ThinkingConfig(thinking_budget=0)\n", " case Model.GEMINI_2_5_PRO:\n", " return ThinkingConfig(thinking_budget=128, include_thoughts=False)\n", " case Model.GEMINI_3_1_FLASH_LITE | Model.GEMINI_3_5_FLASH:\n", " return ThinkingConfig(thinking_level=ThinkingLevel.MINIMAL)\n", " case Model.GEMINI_3_1_PRO:\n", " return ThinkingConfig(thinking_level=ThinkingLevel.LOW)\n", " case _:\n", " return None # Default (dynamic thinking is generally enabled)\n", "\n", "\n", "def check_client_for_model(model: Model) -> genai.Client:\n", " if (\n", " model.value.endswith(\"-preview\")\n", " and client.vertexai\n", " and client._api_client.location != \"global\"\n", " ):\n", " # Preview models are only available on the \"global\" location\n", " return genai.Client(\n", " enterprise=client.vertexai,\n", " project=client._api_client.project,\n", " location=\"global\",\n", " )\n", "\n", " return client\n", "\n", "\n", "def get_retrier() -> tenacity.Retrying:\n", " return tenacity.Retrying(\n", " stop=tenacity.stop_after_attempt(7),\n", " wait=tenacity.wait_incrementing(start=10, increment=1),\n", " retry=tenacity.retry_if_exception(should_retry_request),\n", " reraise=True,\n", " )\n", "\n", "\n", "def should_retry_request(err: BaseException) -> bool:\n", " if not isinstance(err, ClientError):\n", " return False\n", " print(f\"❌ ClientError {err.code}: {err.message}\")\n", "\n", " retry = False\n", " match err.code:\n", " case 400 if err.message is not None and \" try again \" in err.message:\n", " # Workshop: project accessing Cloud Storage for the first time (service agent provisioning)\n", " retry = True\n", " case 429:\n", " # Workshop: temporary project with 1 QPM quota\n", " retry = True\n", " print(f\"🔄 Retry: {retry}\")\n", "\n", " return retry\n", "\n", "\n", "PRINT_COLUMNS = 80\n", "PRINT_SEPARATOR_CHAR = \"-\"\n", "PRINT_SEPARATOR = PRINT_COLUMNS * PRINT_SEPARATOR_CHAR\n", "\n", "\n", "def print_caption(caption: str) -> None:\n", " print(f\" {caption} \".center(PRINT_COLUMNS, PRINT_SEPARATOR_CHAR))\n", "\n", "\n", "def print_separator() -> None:\n", " print(PRINT_SEPARATOR)\n", "\n", "\n", "def display_response_info(response: GenerateContentResponse) -> None:\n", " if usage_metadata := response.usage_metadata:\n", " if usage_metadata.prompt_token_count:\n", " print(f\"Input tokens : {usage_metadata.prompt_token_count:9,d}\")\n", " if usage_metadata.cached_content_token_count:\n", " print(f\"Cached tokens : {usage_metadata.cached_content_token_count:9,d}\")\n", " if usage_metadata.candidates_token_count:\n", " print(f\"Output tokens : {usage_metadata.candidates_token_count:9,d}\")\n", " if usage_metadata.thoughts_token_count:\n", " print(f\"Thoughts tokens : {usage_metadata.thoughts_token_count:9,d}\")\n", " if not response.candidates:\n", " print(\"❌ No `response.candidates`\")\n", " return\n", " if (finish_reason := response.candidates[0].finish_reason) != FinishReason.STOP:\n", " print(f\"❌ {finish_reason = }\")\n", " if not response.text:\n", " print(\"❌ No `response.text`\")\n", " return\n", "\n", "\n", "def display_prompt(\n", " contents: list[str | Part],\n", " show_as: ShowAs,\n", " only_show_prompt: bool,\n", ") -> None:\n", " def yield_prompt_strings() -> Iterator[str]:\n", " for content in contents:\n", " if isinstance(content, Part):\n", " yield f\"{content!r}\\n\"\n", " continue\n", " yield content\n", "\n", " if only_show_prompt and show_as == ShowAs.DONT_SHOW:\n", " show_as = ShowAs.TEXT\n", " if show_as == ShowAs.DONT_SHOW:\n", " return\n", "\n", " separator = \"\\n\" if show_as == ShowAs.MARKDOWN else \"\"\n", " prompt = separator.join(yield_prompt_strings())\n", " print_caption(\"Prompt\")\n", " match show_as:\n", " case ShowAs.TEXT:\n", " print(prompt)\n", " case ShowAs.MARKDOWN:\n", " display_markdown(prompt)\n", " if only_show_prompt:\n", " print_separator()\n", "\n", "\n", "def display_request_header(model_id: str, source: Source | str | None = None) -> None:\n", " print_caption(f\"Request / {model_id}\")\n", "\n", "\n", "def display_response(response: GenerateContentResponse, show_as: ShowAs) -> None:\n", " if show_as == ShowAs.DONT_SHOW or not (response_text := response.text):\n", " return\n", " print_caption(\"Start of Response\")\n", " response_text = response_text.strip()\n", " match show_as:\n", " case ShowAs.TEXT:\n", " print(response_text)\n", " case ShowAs.MARKDOWN:\n", " display_markdown(response_text)\n", " print_caption(\"End of Response\")\n", "\n", "\n", "def display_markdown(markdown: str) -> None:\n", " IPython.display.display(IPython.display.Markdown(markdown))\n", "\n", "\n", "print(\"✅ Helpers defined\")" ] }, { "cell_type": "markdown", "metadata": { "id": "xCstWp8Dwu4P" }, "source": [ "---\n", "\n", "## 🏗️ Prototyping\n" ] }, { "cell_type": "markdown", "metadata": { "id": "0jisqsdjrYeM" }, "source": [ "Before diving into a solution, it helps to start by prototyping to build some intuition about the natural behavior of the model.\n", "\n", "Let's define a short text of a few sentences:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "QQdWNqzDBQyh" }, "outputs": [], "source": [ "text = \"\"\"\n", "- Henry Jones is a famous archaeologist. He is actually a \"Junior\" because he is named after his father.\n", "- Sophie is Henry's daughter, shares his last name, and works as a software engineer.\n", "- William Smith is an aerospace engineer and Sophie's lifelong friend. Everybody calls him Bill and Beau is his dog.\n", "- Short Round met Henry as a child. They first became close friends, and Henry officially adopted him a few years later.\n", "- Sophie and Bill both work at Acme Aerospace.\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": { "id": "cdPd_Q7nrYeM" }, "source": [ "---\n", "\n", "### 📋 Listing characters\n" ] }, { "cell_type": "markdown", "metadata": { "id": "gWZLdO61rYeM" }, "source": [ "🧪 Let's see if Gemini can spot our characters…\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Vlo-LQttBQyh" }, "outputs": [], "source": [ "prompt = \"\"\"\n", "Using only the input data, list all people and animals mentioned.\n", "\"\"\"\n", "generate_content(prompt, text)" ] }, { "cell_type": "markdown", "metadata": { "id": "9389bbe8f5a6" }, "source": [ "💡 All people and animals are detected as expected.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "Bj4vTDmWrYeM" }, "source": [ "---\n", "\n", "### 📋 Listing characters & relationships\n" ] }, { "cell_type": "markdown", "metadata": { "id": "LBSoebt9rYeM" }, "source": [ "🧪 Now, let's see if it can connect the dots and figure out who's who…\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "_ymgEE1ABQyh" }, "outputs": [], "source": [ "prompt = \"\"\"\n", "Using only the input data, list all people and animals mentioned, and how they relate to each other.\n", "\"\"\"\n", "generate_content(prompt, text)" ] }, { "cell_type": "markdown", "metadata": { "id": "425976f7f9f3" }, "source": [ "💡 Notes\n", "\n", "- The relationships between the characters can also be neatly consolidated.\n", "- Henry's father is not listed as a named character. Here, we can see the difference between explicit and implicit mentions. By default, only explicit entities are detailed (most likely because models are trained to summarize information).\n", "- Implied characters (like _\"he is named after his father\"_) represent a level of indirection. We'll see in the next section how to detect them as well.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "EoXFKrHUrYeR" }, "source": [ "---\n", "\n", "### 📚 Domain terminology\n" ] }, { "cell_type": "markdown", "metadata": { "id": "dp8cpOWIrYeR" }, "source": [ "We're not domain experts in the field we're exploring (yet!).\n", "\n", "An LLM processes instructions based on the given prompt and its training knowledge. This knowledge is part of its long-term memory, and we can learn a lot directly from the model itself.\n", "\n", "🧪 Let's ask Gemini:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "7V7B6P1erYeR" }, "outputs": [], "source": [ "prompt = \"\"\"\n", "What is the terminology used when building a knowledge graph?\n", "Please provide a simple data example in JSON.\n", "\"\"\"\n", "generate_content(prompt)" ] }, { "cell_type": "markdown", "metadata": { "id": "bfe9550d2a98" }, "source": [ "💡 We learn that knowledge graphs are made of **entities** and **relationships**, also called **nodes** and **edges**, and we get a nice introduction to the field. Using domain terminology will help make our prompts explicit and precise.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "H0PdbpOzrYeR" }, "source": [ "---\n", "\n", "## ⛏️ Tabular extraction\n" ] }, { "cell_type": "markdown", "metadata": { "id": "2d7f483b2a8d" }, "source": [ "To extract knowledge graphs, we'll reason in terms of entities and relationships, adopting domain terminology.\n", "\n", "If we think of the final result as a database, our goal is to generate two linked tables, allowing us to reason in terms of data and fields.\n", "\n", "Here is a conceptual view of what we want to achieve:\n", "\n", "**Entities**\n", "\n", "| `id` | `name` | `label` |\n", "| :--: | :-------------: | :------ |\n", "| 0 | Henry Jones Jr. | person |\n", "| 1 | Henry Jones Sr. | person |\n", "\n", "**Relationships**\n", "\n", "| `source_id` | `link` | `target_id` |\n", "| :---------: | :------: | :---------: |\n", "| 0 | child_of | 1 |\n", "\n", "Let's call this approach \"tabular extraction\" and split our instructions to output two successive tables, while still using a single request…\n" ] }, { "cell_type": "markdown", "metadata": { "id": "DvwrL4xlrYeR" }, "source": [ "---\n", "\n", "### 💠 Entities\n" ] }, { "cell_type": "markdown", "metadata": { "id": "b4eb7ce49827" }, "source": [ "In our prototype text, the entities we want to extract are characters (like people or animals). We can define an entity data schema with the fields `id` (0, 1, 2…), `name` (full name of the entity), and `label` (`person`|`animal`).\n" ] }, { "cell_type": "markdown", "metadata": { "id": "FCoqYCbrrYeR" }, "source": [ "🧪 Let's extract the entities:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "BYEHthFBrYeR" }, "outputs": [], "source": [ "prompt = \"\"\"\n", "**Data Schema**\n", "\n", "Entity:\n", "- `id`: Unique integer identifier (0, 1, 2…).\n", "- `name`: Full name of the entity.\n", "- `label`: `person`|`animal`.\n", "\n", "**Instructions**\n", "\n", "1. Entity Extraction:\n", " - Extract every distinct entity from the input data that matches an allowed `label`.\n", " - Include entities that are explicitly named as well as implied entities whose names can be determined from the context.\n", "2. Output the results as a JSON array inside a fenced code block.\n", "\"\"\"\n", "\n", "generate_content(prompt, text)" ] }, { "cell_type": "markdown", "metadata": { "id": "e8ef88bfca1b" }, "source": [ "💡 Remarks\n", "\n", "- Every entity is dynamically assigned a unique sequential identifier.\n", "- The name \"Henry Jones Sr.\" is extracted even though he's not explicitly mentioned in the text. This stems from the instruction to _\"include entities that are explicitly named as well as implied entities whose names can be determined from the context\"_.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "lVIEi9tlrYeS" }, "source": [ "---\n", "\n", "### 🔗 Relationships\n" ] }, { "cell_type": "markdown", "metadata": { "id": "LtGde_DKrYeS" }, "source": [ "🧪 Now, let's extract both the entities and their relationships:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "WM0RFso_rYeS" }, "outputs": [], "source": [ "prompt = \"\"\"\n", "**Data Schema**\n", "\n", "Entity:\n", "- `id`: Unique integer identifier (0, 1, 2…).\n", "- `name`: Full name of the entity.\n", "- `label`: `person`|`animal`.\n", "\n", "Relationship:\n", "- `source_id`: `id` of the subject entity.\n", "- `link`: `snake_case` predicate describing the relationship.\n", "- `target_id`: `id` of the object entity.\n", "\n", "**Instructions**\n", "\n", "1. Entity Extraction:\n", " - Extract every distinct entity from the input data that matches an allowed `label`.\n", " - Include entities that are explicitly named as well as implied entities whose names can be determined from the context.\n", "2. Relationship Extraction:\n", " - Extract every distinct relationship between them.\n", " - If a relationship changes over time, make sure to include every distinct stage of the relationship.\n", "3. Output a JSON object with keys `entities` and `relationships` inside a fenced code block.\n", "\"\"\"\n", "\n", "response = generate_content(prompt, text, return_response=True)" ] }, { "cell_type": "markdown", "metadata": { "id": "649eacf44e3d" }, "source": [ "💡 Remarks\n", "\n", "- The output now includes the `relationships` array.\n", "- We get the expected number of relationships, notably the two relationships between Henry and Short Round.\n", "- The `link` predicates are completely dynamic (a level of flexibility we left in the prompt). While it's interesting to see this natural behavior, we'll want to make it more deterministic for production since our prompt has too many degrees of freedom.\n", "- Our open prompt extracts relationships in only one direction. For example, \"[Animal] `pet_of` [Person]\" is an asymmetric relationship that could also be extracted as \"[Person] `owner_of` [Animal]\". This is another area where the prompt is too open-ended. In the finalization section, we'll see an example that asks the model to extract symmetric and asymmetric relationships in both directions.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "r1PkyO-ZrYeS" }, "source": [ "---\n", "\n", "## 💎 Structured output\n", "\n", "We've concluded our prototyping stage with promising results using a data schema.\n", "\n", "To move to production, the next step is to control the generation with a specific structured output.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "sMLYiIlxrYeS" }, "source": [ "---\n", "\n", "### 🗂️ JSON\n", "\n", "The JSON format has industry-wide support and serves as a core or intermediate format in many use cases.\n", "\n", "For the next step, we would typically define classes using the Pydantic library and request a pure JSON output with a response schema in the config parameters:\n", "\n", "- `response_mime_type=\"application/json\"`\n", "- `response_schema=\"CLASS_DERIVED_FROM_PYDANTIC_BASE_MODEL\"` ([docs](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/control-generated-output#fields))\n", "\n", "⚠️ However, JSON is a pretty verbose format, designed for interoperability but not optimized for size. Even if we generate compact JSON (also called minified JSON), it still has inherent verbosity due to:\n", "\n", "- repeated keys (object fields) for each object instance\n", "- opening and closing brackets\n", "- enclosing quotes for each key and string value\n", "\n", "ℹ️ When using LLMs, once the first token is generated, the remaining generation time is roughly proportional to the number of output tokens. Similarly, the cost of a request is based on token usage (input + output), with output tokens being significantly more expensive than input tokens.\n", "\n", "💡 A better output structure will positively impact both generation speed and request cost.\n", "\n", "Let's explore an alternative…\n" ] }, { "cell_type": "markdown", "metadata": { "id": "361f37b18efc" }, "source": [ "---\n", "\n", "### 📅 TSV\n", "\n", "Our tabular-extraction problem clearly calls for table outputs. An interesting possibility is to ask for Tab-Separated Values (TSV) outputs. For example, we can define our output to be formatted as two consecutive TSV tables.\n", "\n", "**Example output format**\n", "\n", "````text\n", "```tsv filename=\"entities.tsv\"\n", "id{TAB}name{TAB}label\n", "[rows]\n", "```\n", "\n", "```tsv filename=\"relationships.tsv\"\n", "source_id{TAB}link{TAB}target_id\n", "[rows]\n", "```\n", "````\n", "\n", "**Will this work?**\n", "\n", "Generating structured outputs like TSV will work seamlessly, as Gemini excels at patterns. We just need to be explicit about what's expected.\n", "\n", "**Will this be efficient?**\n", "\n", "💡 For our use case, this structure looks optimal:\n", "\n", "- Field names are stated once in the header row.\n", "- Field values are raw, without outer quotes.\n", "- Tab and newline separators take at most a single token each and do not collide with field values (unless we're dealing with very special input data, but we could then prompt the model to escape these using different characters or strings).\n", "\n", "ℹ️ CSV could be another alternative, but common separators like commas are everywhere in natural language and frequently appear in names and descriptions (e.g., if we decide to extend entity fields). If you're interested in this topic, check out the [TOON format](https://github.com/toon-format/toon), which proposes a JSON alternative using a YAML+CSV mix.\n", "\n", "To make an informed decision, we should actually compare the number of tokens needed to represent the same data…\n" ] }, { "cell_type": "markdown", "metadata": { "id": "DooNFicCrYeS" }, "source": [ "---\n", "\n", "### 🗜️ Token comparison\n", "\n", "Let's define some helpers to compare the same data using pretty-printed JSON, compact JSON, and TSV:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ahwHZVdGrYeS" }, "outputs": [], "source": [ "# @title {display-mode: \"form\"}\n", "import csv\n", "import io\n", "import json\n", "import re\n", "from typing import Literal\n", "\n", "\n", "def get_data_from_response(response: GenerateContentResponse) -> dict:\n", " response_text = response.text or \"\"\n", " pattern = r\"```json\\s*(.*?)\\s*```\"\n", " match = re.search(pattern, response_text, re.DOTALL)\n", " json_str = match.group(1) if match else response_text\n", " try:\n", " data = json.loads(json_str)\n", " if not isinstance(data, dict):\n", " print(\"❌ Returning empty dict (could not parse response as dict)\")\n", " data = {}\n", " except (json.JSONDecodeError, TypeError):\n", " print(\"❌ Returning empty dict (failed parsing the JSON string)\")\n", " data = {}\n", " return data\n", "\n", "\n", "def get_tsv_string_from_data(data: dict) -> str:\n", " output = \"\"\n", " for key, items in data.items():\n", " rows = \"\"\n", " if items:\n", " with io.StringIO() as out:\n", " headers = list(items[0].keys())\n", " writer = csv.DictWriter(\n", " out,\n", " fieldnames=headers,\n", " delimiter=\"\\t\",\n", " lineterminator=\"\\n\",\n", " )\n", " writer.writeheader()\n", " writer.writerows(items)\n", " rows = out.getvalue()\n", " if output:\n", " output += \"\\n\"\n", " output += f'```tsv filename=\"{key}.tsv\"\\n{rows}```\\n'\n", " return output\n", "\n", "\n", "def print_text_excerpt(title: str, text: str, max_chars: int = 400) -> None:\n", " assert max_chars > 0\n", " chars = len(text)\n", " if chars <= 0:\n", " print_caption(\"❌ Empty text\")\n", " return\n", " if chars <= max_chars:\n", " print_caption(f\"{title} ({chars} chars)\")\n", " print(text)\n", " return\n", " print_caption(\n", " f\"{title} - First {max_chars}/{chars} chars ({max_chars / chars:.0%})\"\n", " )\n", " print(f\"{text[:max_chars]}…\")\n", "\n", "\n", "def compare_json_vs_tsv(\n", " response: GenerateContentResponse | None,\n", " only_show_excerpts: bool = False,\n", ") -> None:\n", " def get_gain(rows: list[tuple[int, int]], col: Literal[0, 1]) -> str:\n", " val_0, val_1 = rows[0][col], rows[1][col]\n", " return f\"**{1 - val_1 / val_0:.1%}**\" if val_0 > 0 else \"?\"\n", "\n", " def yield_table_string_rows(\n", " source_title: str,\n", " target_title: str,\n", " rows: list[tuple[int, int]],\n", " ) -> Iterator[list[str]]:\n", " yield [\"\", \"Chars\", \"Tokens\"]\n", " yield [\"-\", \"-:\", \"-:\"]\n", " for caption, values in zip([source_title, target_title], rows):\n", " yield [caption, *[str(value) for value in values]]\n", " yield [\"**Gain**\", get_gain(rows, 0), get_gain(rows, 1)]\n", "\n", " def display_gain_table(\n", " source_title: str,\n", " target_title: str,\n", " source_text: str,\n", " target_text: str,\n", " ) -> None:\n", " print_caption(f\"{source_title} → {target_title}\")\n", " model = Model.DEFAULT\n", " model_id = model.value\n", " client = check_client_for_model(model)\n", "\n", " rows: list[tuple[int, int]] = []\n", " for s in [source_text, target_text]:\n", " chars = len(s)\n", " tokens = client.models.count_tokens(model=model_id, contents=s).total_tokens\n", " rows.append((chars, tokens or 0))\n", " markdown = \"\\n\".join(\n", " \"| \" + \" | \".join(row) + \" |\"\n", " for row in yield_table_string_rows(source_title, target_title, rows)\n", " )\n", " display_markdown(markdown)\n", "\n", " if response is None:\n", " print(\"❌ response is None\")\n", " return\n", " data = get_data_from_response(response)\n", " formatted_json = f\"```json\\n{json.dumps(data, indent=2)}\\n```\"\n", " compact_json = f\"```json\\n{json.dumps(data, separators=(',', ':'))}\\n```\"\n", " tsv = get_tsv_string_from_data(data)\n", "\n", " if only_show_excerpts:\n", " max_chars = len(tsv)\n", " print_text_excerpt(\"Formatted JSON\", formatted_json, max_chars)\n", " print_text_excerpt(\"Compact JSON\", compact_json, max_chars)\n", " print_text_excerpt(\"TSV\", tsv, max_chars)\n", " return\n", "\n", " display_gain_table(\"Formatted JSON\", \"Compact JSON\", formatted_json, compact_json)\n", " display_gain_table(\"Compact JSON\", \"TSV\", compact_json, tsv)\n", " display_gain_table(\"Formatted JSON\", \"TSV\", formatted_json, tsv)\n", " print_separator()\n", "\n", "\n", "print(\"✅ JSON vs TSV helpers defined\")" ] }, { "cell_type": "markdown", "metadata": { "id": "b17ee6aac3c0" }, "source": [ "🧪 First, let's compare how much data we can represent for the same number of characters based on our latest API response:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "11db1bcf88da" }, "outputs": [], "source": [ "compare_json_vs_tsv(response, only_show_excerpts=True)" ] }, { "cell_type": "markdown", "metadata": { "id": "630528d81396" }, "source": [ "💡 Notice how much more information can be represented in the same number of text characters. This will apply similarly to token counts.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "_GJKEnhhrYeS" }, "source": [ "🧪 And now, let's compare the gains, especially for token counts:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "otH73GYKrYeS" }, "outputs": [], "source": [ "compare_json_vs_tsv(response)" ] }, { "cell_type": "markdown", "metadata": { "id": "syetSSLErYeS" }, "source": [ "💡 **Savings in output tokens:**\n", "\n", "- **30 to 40%** compared to compact JSON\n", "- **60 to 70%** compared to standard JSON\n", "\n", "With a double-digit percentage reduction in output tokens, building knowledge graphs with TSV outputs is significantly faster (and cheaper)!\n", "\n", "Now, let's finalize our code with optimized structures…\n" ] }, { "cell_type": "markdown", "metadata": { "id": "FvIgJs0xwu4P" }, "source": [ "---\n", "\n", "## 🚀 Finalization\n" ] }, { "cell_type": "markdown", "metadata": { "id": "w7vY56A_BQyh" }, "source": [ "### 🧩 Structure\n" ] }, { "cell_type": "markdown", "metadata": { "id": "u0qCzi5prYeT" }, "source": [ "First, it helps to define a structured prompt template, so we can focus on specific parts of our solution using a divide-and-conquer approach.\n", "\n", "Here's a possible prompt template:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "pabif1zFrYeT" }, "outputs": [], "source": [ "KNOWLEDGE_GRAPH_PROMPT_TEMPLATE = \"\"\"\n", "**Data Schema**\n", "\n", "{data_schema}\n", "\n", "**Instructions**\n", "\n", "{instructions}\n", "\n", "**Output Format**\n", "\n", "{output_format}\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": { "id": "Qzv2DQWvrYeT" }, "source": [ "Then, here are some possible `Entity`, `Relationship`, and `KnowledgeGraph` data classes with the matching output format:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "xiliL8EZrYeT" }, "outputs": [], "source": [ "from dataclasses import dataclass, field\n", "\n", "\n", "@dataclass\n", "class Entity:\n", " id: int\n", " name: str\n", " label: str\n", "\n", "\n", "@dataclass\n", "class Relationship:\n", " source_id: int\n", " link: str\n", " target_id: int\n", "\n", "\n", "@dataclass\n", "class KnowledgeGraph:\n", " entities: list[Entity] = field(default_factory=list)\n", " relationships: list[Relationship] = field(default_factory=list)\n", "\n", "\n", "TAB = \"\\t\"\n", "KNOWLEDGE_GRAPH_OUTPUT_FORMAT = f\"\"\"\n", "Format the output strictly as two TSV code blocks (including the header row):\n", "\n", "```tsv filename=\"entities.tsv\"\n", "id{TAB}name{TAB}label\n", "[data_rows]\n", "```\n", "\n", "```tsv filename=\"relationships.tsv\"\n", "source_id{TAB}link{TAB}target_id\n", "[data_rows]\n", "```\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": { "id": "2rtBtsRRrYeT" }, "source": [ "💡 While the Gen AI SDK natively supports Pydantic models for JSON structured outputs, we're using standard Python data classes here and TSV outputs to maximize our token efficiency.\n", "\n", "ℹ️ If you use multiple entity or relationship data classes in your solution, you can dynamically generate the output format specification using features of the `dataclasses` package (like class docstrings and field descriptions).\n" ] }, { "cell_type": "markdown", "metadata": { "id": "Ny3Q6Df3rYeT" }, "source": [ "Now, let's define a few helpers to generate a knowledge graph:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "F3dbOXnKwu4P" }, "outputs": [], "source": [ "# @title {display-mode: \"form\"}\n", "from dataclasses import fields, is_dataclass\n", "from typing import get_args, get_origin, get_type_hints\n", "\n", "\n", "def generate_knowledge_graph(\n", " data_schema: str,\n", " instructions: str,\n", " source: Source | str,\n", " *,\n", " model: Model | None = None,\n", " config: GenerateContentConfig | None = None,\n", " system_instruction: str | None = None,\n", " show_prompt: ShowAs = ShowAs.DONT_SHOW,\n", " show_response: ShowAs = ShowAs.DONT_SHOW,\n", ") -> KnowledgeGraph:\n", " prompt = get_prompt_for_data_schema_and_instructions(data_schema, instructions)\n", " response = generate_content(\n", " prompt,\n", " source,\n", " model=model,\n", " config=config,\n", " system_instruction=system_instruction,\n", " show_prompt=show_prompt,\n", " show_response=show_response,\n", " return_response=True,\n", " )\n", "\n", " knowledge_graph = (\n", " parse_list_dataclass(KnowledgeGraph, response)\n", " if isinstance(response, GenerateContentResponse)\n", " else KnowledgeGraph()\n", " )\n", " display_knowledge_graph_info(knowledge_graph)\n", "\n", " return knowledge_graph\n", "\n", "\n", "def show_knowledge_graph_prompt(\n", " data_schema: str,\n", " instructions: str,\n", " source: Source | str,\n", " *,\n", " model: Model | None = None,\n", " config: GenerateContentConfig | None = None,\n", " system_instruction: str | None = None,\n", " show_as: ShowAs = ShowAs.TEXT,\n", ") -> None:\n", " prompt = get_prompt_for_data_schema_and_instructions(data_schema, instructions)\n", " generate_content(\n", " prompt,\n", " source,\n", " model=model,\n", " config=config,\n", " system_instruction=system_instruction,\n", " show_prompt=show_as,\n", " only_show_prompt=True,\n", " )\n", "\n", "\n", "def get_prompt_for_data_schema_and_instructions(\n", " data_schema: str,\n", " instructions: str,\n", ") -> str:\n", " return KNOWLEDGE_GRAPH_PROMPT_TEMPLATE.format(\n", " data_schema=data_schema.strip(),\n", " instructions=instructions.strip(),\n", " output_format=KNOWLEDGE_GRAPH_OUTPUT_FORMAT.strip(),\n", " ).strip()\n", "\n", "\n", "def parse_list_dataclass[T](cls: type[T], response: GenerateContentResponse) -> T:\n", " assert is_dataclass(cls)\n", " if not (response_text := response.text):\n", " return cls()\n", "\n", " data = {}\n", " for f in fields(cls):\n", " origin, list_types = get_origin(f.type), get_args(f.type)\n", " assert origin is list, (\n", " f\"❌ Field {f.name} must be a list[dataclass] parameterized list\"\n", " )\n", " assert len(list_types) == 1, f\"❌ Expected 1 single type: {len(list_types)=}\"\n", " data[f.name] = parse_tsv_block(list_types[0], response_text, f.name)\n", "\n", " return cls(**data)\n", "\n", "\n", "def parse_tsv_block[T](cls: type[T], data: str, tsv_filestem: str) -> list[T]:\n", " rows = []\n", " valid_fields = get_type_hints(cls)\n", " tsv_string = extract_tsv_block(data, tsv_filestem)\n", " for row in csv.DictReader(io.StringIO(tsv_string), delimiter=\"\\t\"):\n", " casted_data = {}\n", " for key, value in row.items():\n", " if key not in valid_fields or value is None:\n", " continue\n", " field_type = valid_fields[key]\n", " try: # Note: Works only for directly castable types such as int, float, str, enum (e.g., not bool)\n", " casted_data[key] = field_type(value)\n", " except (ValueError, TypeError):\n", " print(f'❌ Could not cast \"{value}\" to {field_type} → Skipping {row=}')\n", " break\n", " else:\n", " try:\n", " rows.append(cls(**casted_data))\n", " except TypeError as e:\n", " print(f\"❌ Could not instantiate {cls.__name__}: {e} → Skipping {row=}\")\n", "\n", " return rows\n", "\n", "\n", "def extract_tsv_block(data: str, filestem: str) -> str:\n", " pattern = rf'```tsv filename=\"{re.escape(filestem)}.tsv\"\\s*\\n(.*?)```'\n", " if not (match := re.search(pattern, data, flags=re.DOTALL)):\n", " print(f'❌ Could not find a TSV block for \"{filestem=}\"')\n", " return \"\"\n", " return match.group(1)\n", "\n", "\n", "def display_knowledge_graph_info(kg: KnowledgeGraph) -> None:\n", " print_caption(\"Knowledge Graph Info\")\n", " print(f\"Entities : {len(kg.entities):3,d}\")\n", " print(f\"Relationships : {len(kg.relationships):3,d}\")\n", " print_separator()\n", "\n", "\n", "print(\"✅ Knowledge graph generation helpers defined\")" ] }, { "cell_type": "markdown", "metadata": { "id": "iuL4sTIkrYeT" }, "source": [ "And here is a possible data schema with some instructions to generate a knowledge graph for our book analysis use case:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "a34vdbdKrYeT" }, "outputs": [], "source": [ "from enum import StrEnum, auto\n", "\n", "\n", "class BookAnalysisEntityLabel(StrEnum):\n", " PERSON = auto()\n", " ANIMAL = auto()\n", " ORGANIZATION = auto()\n", "\n", "\n", "def pipe_delimited_union(enum: type[StrEnum]) -> str:\n", " return \"|\".join(f\"`{e.value}`\" for e in enum)\n", "\n", "\n", "BOOK_ANALYSIS_DATA_SCHEMA = f\"\"\"\n", "Entity:\n", "- `id`: Unique integer identifier (0, 1, 2…).\n", "- `name`: Most complete name as exclusively determined from the input data.\n", "- `label`: {pipe_delimited_union(BookAnalysisEntityLabel)}.\n", "\n", "Relationship:\n", "- `source_id`: `id` of the subject entity.\n", "- `link`: `snake_case` predicate.\n", "- `target_id`: `id` of the object entity.\n", "\"\"\"\n", "\n", "BOOK_ANALYSIS_INSTRUCTIONS = \"\"\"\n", "- Extract every distinct entity:\n", " - Treat distinct pseudonyms/identities as separate entities.\n", " - Include implied entities whose names can be exclusively determined from the input data.\n", "- Extract every distinct relationship between them:\n", " - Use specific `link` predicates in `snake_case` as needed (e.g., `alias_of`, `son_of`, `fiancée_of`, `friend_of`, `murderer_of`, `employer_of`, `in_love_with`, `rival_of`).\n", " - If a relationship changes over time, make sure to include every distinct stage of the relationship.\n", " - For every asymmetric relationship extracted, make sure to include the logical inverse relationship (e.g., `A husband_of B` AND `B wife_of A`, `A employer_of B` AND `B employee_of A`).\n", " - For every symmetric relationship extracted, make sure to include both directions (e.g., `A friend_of B` AND `B friend_of A`).\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": { "id": "pF4ZMv1trYeT" }, "source": [ "Verify the structured prompt:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "KXJM7WafrYeU" }, "outputs": [], "source": [ "show_knowledge_graph_prompt(\n", " BOOK_ANALYSIS_DATA_SCHEMA,\n", " BOOK_ANALYSIS_INSTRUCTIONS,\n", " text,\n", " show_as=ShowAs.TEXT,\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "scOh2ra7wu4P" }, "source": [ "🧪 Let's generate a knowledge graph:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "QN7RyhLrwu4P" }, "outputs": [], "source": [ "knowledge_graph = generate_knowledge_graph(\n", " BOOK_ANALYSIS_DATA_SCHEMA,\n", " BOOK_ANALYSIS_INSTRUCTIONS,\n", " text,\n", " show_response=ShowAs.TEXT,\n", ")\n", "\n", "print(knowledge_graph.entities)\n", "print(knowledge_graph.relationships)" ] }, { "cell_type": "markdown", "metadata": { "id": "3puMj0dsrYeU" }, "source": [ "💡 This is looking good!\n", "\n", "Now, let's go to the next stage and build a network graph from our data…\n" ] }, { "cell_type": "markdown", "metadata": { "id": "HXU002GOBQyi" }, "source": [ "---\n", "\n", "### 🪢 Network graph\n" ] }, { "cell_type": "markdown", "metadata": { "id": "ZR_BXXjrrYeU" }, "source": [ "Now that we have our entities and relationships neatly packed into data classes, let's bring them to life. We'll use `networkx` to build a network graph. Using domain terminology, entities become nodes and relationships become directed edges. We'll also calculate node centralities to identify key nodes and use the Louvain method to detect communities (clusters of closely related nodes)…\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "gzjOfzJywu4Q" }, "outputs": [], "source": [ "# @title {display-mode: \"form\"}\n", "import textwrap\n", "from typing import cast\n", "\n", "import networkx as nx\n", "import numpy as np\n", "from networkx.algorithms.community.louvain import louvain_communities\n", "\n", "NODE_CENTRALITY = \"node_centrality\"\n", "NODE_COMMUNITY_INDEX = \"node_community_index\"\n", "NODE_COLOR = \"node_color\"\n", "EDGE_COLOR = \"edge_color\"\n", "# Wrap names over multiple lines (avoids long node labels)\n", "MULTILINE_NAMES = True\n", "MULTILINE_CHARS = 12\n", "\n", "\n", "def build_graph(kg: KnowledgeGraph, remove_orphan_nodes: bool) -> nx.DiGraph:\n", " # For simplicity, we build a DiGraph (adapt to MultiDiGraph if needed)\n", " graph = nx.DiGraph()\n", "\n", " # Nodes ← Entities\n", " node_name_from_id: dict[int, str] = {}\n", " for entity in kg.entities:\n", " node_name, display_name = get_node_and_display_names_for_entity(entity)\n", " node_name_from_id[entity.id] = node_name\n", " graph.add_node(node_name, name=display_name)\n", "\n", " # Edges ← Relationships\n", " for relationship in kg.relationships:\n", " source_node = node_name_from_id.get(relationship.source_id, \"\")\n", " target_node = node_name_from_id.get(relationship.target_id, \"\")\n", " if not source_node or not target_node:\n", " print(f\"❌ Skipping relationship due to empty node:\\n{relationship}\")\n", " continue\n", " # For simplicity, each link has the same weight\n", " # For better community detection, define your own weight mappings (e.g., family members have stronger bonds)\n", " weight = 1\n", " edge_label = relationship.link\n", " if graph.has_edge(source_node, target_node):\n", " existing_data = graph[source_node][target_node]\n", " existing_data[\"link\"] += f\"\\n{edge_label}\"\n", " existing_data[\"weight\"] += weight\n", " else:\n", " graph.add_edge(source_node, target_node, link=edge_label, weight=weight)\n", "\n", " if remove_orphan_nodes:\n", " graph.remove_nodes_from(list(nx.isolates(graph)))\n", "\n", " return graph\n", "\n", "\n", "def get_node_and_display_names_for_entity(entity: Entity) -> tuple[str, str]:\n", " snake_case_name = \"_\".join(map(str.lower, entity.name.split()))\n", " node_name = f\"{entity.id}_{snake_case_name}\"\n", "\n", " display_name = entity.name\n", " if MULTILINE_NAMES:\n", " display_name = \"\\n\".join(textwrap.wrap(display_name, width=MULTILINE_CHARS))\n", "\n", " return node_name, display_name\n", "\n", "\n", "def color_gen(color_count: int) -> Iterator[str]:\n", " B50, R50, Y50, G50 = (\"#4285F4\", \"#EA4335\", \"#FBBC04\", \"#34A853\")\n", " B20, R20, Y20, G20 = (\"#AECBFA\", \"#F6AEA9\", \"#FDE293\", \"#A8DAB5\")\n", " B05, R05, Y05, G05 = (\"#E8F0FE\", \"#FCE8E6\", \"#FEF7E0\", \"#E6F4EA\")\n", " COLORS = [B50, R50, Y50, G50, B20, R20, Y20, G20, B05, R05, Y05, G05]\n", " for i in range(color_count):\n", " yield COLORS[i % len(COLORS)]\n", "\n", "\n", "Node = str\n", "Positions = dict[Node, np.ndarray]\n", "Community = set[Node]\n", "Communities = list[Community]\n", "Nodes = list[Node]\n", "INTER_COMMUNITY_EDGE_COLOR = \"#8888\"\n", "\n", "\n", "def init_graph_data(graph: nx.Graph) -> Nodes:\n", " def node_centrality(node: Node) -> float:\n", " return graph.nodes[node][NODE_CENTRALITY]\n", "\n", " def community_max_centrality(community: Community) -> float:\n", " return max(node_centrality(node) for node in community)\n", "\n", " def nodes_sorted_by_community(communities: Communities) -> Nodes:\n", " entities = []\n", " for community in communities:\n", " sorted_entities = sorted(community, key=node_centrality, reverse=True)\n", " entities.extend(sorted_entities)\n", " return entities\n", "\n", " # Node centralities\n", " centralities = nx.betweenness_centrality(graph, endpoints=True)\n", " for node_key in graph.nodes:\n", " graph.nodes[node_key][NODE_CENTRALITY] = centralities[node_key]\n", "\n", " # Communities\n", " communities = cast(Communities, louvain_communities(graph, seed=42))\n", " sorted_communities = sorted(communities, key=community_max_centrality, reverse=True)\n", "\n", " # Community colors\n", " community_count = len(sorted_communities)\n", " community_colors = list(color_gen(community_count))\n", "\n", " # Node community indices and colors\n", " for community_index, community in enumerate(sorted_communities):\n", " for node_key in community:\n", " node = graph.nodes[node_key]\n", " node[NODE_COMMUNITY_INDEX] = community_index\n", " node[NODE_COLOR] = community_colors[community_index]\n", "\n", " # Edge colors\n", " for node_key_i, node_key_j, edge_data in graph.edges(data=True):\n", " node_i = graph.nodes[node_key_i]\n", " node_j = graph.nodes[node_key_j]\n", " same_community = node_i[NODE_COMMUNITY_INDEX] == node_j[NODE_COMMUNITY_INDEX]\n", " edge_data[EDGE_COLOR] = (\n", " node_i[NODE_COLOR] if same_community else INTER_COMMUNITY_EDGE_COLOR\n", " )\n", "\n", " return nodes_sorted_by_community(sorted_communities)\n", "\n", "\n", "def compute_node_positions(graph: nx.DiGraph, entities: Nodes) -> Positions:\n", " # Derive an undirected graph (preserving the entity order)\n", " undirected_graph = nx.Graph()\n", " for entity in entities:\n", " undirected_graph.add_node(entity)\n", " undirected_graph.add_edges_from(graph.edges())\n", "\n", " if len(entities) < 10:\n", " positions = nx.circular_layout(undirected_graph)\n", " else:\n", " positions = nx.kamada_kawai_layout(undirected_graph)\n", " positions = nx.arf_layout(undirected_graph, positions, seed=42)\n", "\n", " return positions\n", "\n", "\n", "@dataclass\n", "class GraphData:\n", " knowledge_graph: KnowledgeGraph\n", " remove_orphan_nodes: bool = True\n", " graph: nx.DiGraph = field(init=False)\n", " nodes: Nodes = field(init=False)\n", " positions: Positions = field(init=False)\n", "\n", " def __post_init__(self) -> None:\n", " self.graph = build_graph(self.knowledge_graph, self.remove_orphan_nodes)\n", " self.nodes = init_graph_data(self.graph)\n", " self.positions = compute_node_positions(self.graph, self.nodes)\n", "\n", "\n", "print(\"✅ Network graph helpers defined\")" ] }, { "cell_type": "markdown", "metadata": { "id": "eHZOgBWowu4Q" }, "source": [ "Let's test this:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Ti6xC5Zswu4Q" }, "outputs": [], "source": [ "graph_data = GraphData(knowledge_graph)\n", "\n", "print(f\"{graph_data.graph = !s}\")\n", "print(f\"{graph_data.nodes = }\")" ] }, { "cell_type": "markdown", "metadata": { "id": "Q-pgpVD3BQyi" }, "source": [ "---\n", "\n", "### 🎨 Data visualization\n" ] }, { "cell_type": "markdown", "metadata": { "id": "aS_KWTKLrYeV" }, "source": [ "The extracted data is much easier to understand when you can actually see it! We can use `matplotlib` to draw our network graphs. We'll size the nodes based on their centrality and color-code them by community. To make it even easier to digest, we'll generate an animated sequence highlighting each character's connections one by one…\n", "\n", "Let's define our data visualization helpers:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "5HK-U0aqwu4Q" }, "outputs": [], "source": [ "# @title {display-mode: \"form\"}\n", "import typing\n", "from io import BytesIO\n", "\n", "import matplotlib.pyplot as plt\n", "from IPython import display\n", "from PIL import Image as PilImage\n", "from matplotlib.axes import Axes\n", "from matplotlib.backends.backend_agg import FigureCanvasAgg\n", "from matplotlib.figure import Figure\n", "\n", "\n", "class AnimationFormat(StrEnum):\n", " # Matches PIL.Image.Image.format\n", " WEBP = auto()\n", " PNG = auto()\n", " GIF = auto()\n", "\n", "\n", "FIGURE_DPI = 200\n", "FIGURE_FACTOR = 1.0\n", "ANIMATION_INTRO_DURATION = 2500\n", "ANIMATION_FRAME_DURATION = 250\n", "EDGE_STYLE = \"arc3,rad=0.2\"\n", "NodeSizes = dict[Node, int]\n", "\n", "if running_in_colab_env():\n", " ANIMATION_FORMAT = AnimationFormat.WEBP\n", "else:\n", " ANIMATION_FORMAT = AnimationFormat.GIF\n", "\n", "\n", "def init_figure(title: str, subtitle: str) -> tuple[Figure, Axes]:\n", " figsize = (16 * FIGURE_FACTOR, 9 * FIGURE_FACTOR)\n", " fig, ax = plt.subplots(figsize=figsize, dpi=FIGURE_DPI)\n", " ax.set_title(title, loc=\"left\")\n", " ax.set_title(subtitle, loc=\"right\")\n", " ax.axis(\"off\")\n", " fig.tight_layout(pad=2)\n", "\n", " return fig, ax\n", "\n", "\n", "def draw_nodes(graph: nx.Graph, positions: Positions, ax: Axes) -> NodeSizes:\n", " node_view = graph.nodes(data=True)\n", " node_sizes = {\n", " node: max(500, int(10000 * data[NODE_CENTRALITY])) for node, data in node_view\n", " }\n", " node_colors = [str(data[NODE_COLOR]) for _, data in node_view]\n", " border_width = 3.0\n", "\n", " nx.draw_networkx_nodes(\n", " graph,\n", " pos=positions,\n", " node_size=list(node_sizes.values()),\n", " node_color=node_colors,\n", " alpha=0.95,\n", " ax=ax,\n", " linewidths=border_width,\n", " )\n", " labels = {node: data.get(\"name\", str(node)) for node, data in node_view}\n", " nx.draw_networkx_labels(graph, positions, labels=labels, ax=ax)\n", "\n", " if len(node_sizes) >= 10:\n", " # Extend axis limits (default rounding changes them too much otherwise)\n", " (x_min, x_max), (y_min, y_max) = ax.get_xlim(), ax.get_ylim()\n", " x_min, x_max = int(x_min - 1.0), int(x_max + 1.0)\n", " y_min, y_max = int(y_min - 1.0), int(y_max + 1.0)\n", " ax.set_xlim(x_min, x_max)\n", " ax.set_ylim(y_min, y_max)\n", "\n", " return node_sizes\n", "\n", "\n", "def draw_edges(\n", " graph: nx.DiGraph,\n", " positions: Positions,\n", " node_sizes: NodeSizes,\n", " ax: Axes,\n", " *,\n", " focused_node: Node | None = None,\n", ") -> None:\n", " # Draw specific out-edges or all edges\n", " if focused_node:\n", " out_edges = graph.edges([focused_node], data=True)\n", " else:\n", " out_edges = graph.edges(data=True)\n", " edge_colors = [data[EDGE_COLOR] for _, _, data in out_edges]\n", "\n", " edge_list = [(u, v) for u, v, _ in out_edges]\n", " ordered_sizes = [node_sizes[n] for n in graph.nodes()]\n", " nx.draw_networkx_edges(\n", " graph,\n", " positions,\n", " edge_list,\n", " edge_color=edge_colors,\n", " style=\":\",\n", " alpha=0.9,\n", " arrowstyle=\"-|>\",\n", " arrowsize=20,\n", " ax=ax,\n", " node_size=ordered_sizes,\n", " connectionstyle=EDGE_STYLE,\n", " )\n", "\n", " edge_labels = {(u, v): data[\"link\"] for u, v, data in out_edges}\n", " nx.draw_networkx_edge_labels(\n", " graph,\n", " positions,\n", " edge_labels,\n", " font_size=8,\n", " font_family=\"monospace\",\n", " bbox=dict(ec=\"#FFF8\", fc=\"#FFF8\"),\n", " ax=ax,\n", " node_size=ordered_sizes, # type: ignore\n", " connectionstyle=EDGE_STYLE, # type: ignore\n", " )\n", "\n", "\n", "def display_graph(title: str, subtitle: str, graph_data: GraphData) -> None:\n", " _, ax = init_figure(title, subtitle)\n", "\n", " node_graph = graph_data.graph\n", " edge_graph = graph_data.graph\n", " positions = graph_data.positions\n", " node_sizes = draw_nodes(node_graph, positions, ax)\n", " draw_edges(edge_graph, positions, node_sizes, ax)\n", "\n", " plt.show()\n", "\n", "\n", "def yield_images(\n", " title: str,\n", " subtitle: str,\n", " graph_data: GraphData,\n", ") -> Iterator[PilImage.Image]:\n", " fig, ax = init_figure(title, subtitle)\n", " canvas = FigureCanvasAgg(fig)\n", "\n", " positions = graph_data.positions\n", " node_graph = graph_data.graph\n", " node_sizes = draw_nodes(node_graph, positions, ax)\n", " edge_graph = graph_data.graph\n", "\n", " for focused_node in [None, *graph_data.nodes]:\n", " if focused_node is not None:\n", " draw_edges(edge_graph, positions, node_sizes, ax, focused_node=focused_node)\n", " canvas.draw()\n", " image_size = canvas.get_width_height()\n", " image_bytes = canvas.buffer_rgba()\n", " yield PilImage.frombytes(\"RGBA\", image_size, image_bytes).convert(\"RGB\")\n", " plt.close(fig)\n", "\n", "\n", "def generate_animation(\n", " title: str,\n", " subtitle: str,\n", " graph_data: GraphData,\n", " format: AnimationFormat,\n", ") -> BytesIO:\n", " frames = list(yield_images(title, subtitle, graph_data))\n", " assert len(frames) >= 1\n", "\n", " if format == AnimationFormat.GIF:\n", " # Dither all frames with the same palette to optimize the animation\n", " # The animation is cumulative, so most colors are in the last frame\n", " method = PilImage.Quantize.MEDIANCUT\n", " palettized = frames[-1].quantize(method=method)\n", " frames = [frame.quantize(method=method, palette=palettized) for frame in frames]\n", "\n", " # The animation will be played in a loop: start cycling with the most complete frame\n", " first_frame = frames[-1]\n", " next_frames = frames[:-1]\n", " durations = [ANIMATION_INTRO_DURATION]\n", " durations += [ANIMATION_FRAME_DURATION] * len(next_frames)\n", " params: dict[str, typing.Any] = dict(\n", " save_all=True,\n", " append_images=next_frames,\n", " duration=durations,\n", " loop=0,\n", " )\n", " match format:\n", " case AnimationFormat.GIF:\n", " params.update(optimize=False)\n", " case AnimationFormat.PNG:\n", " params.update(optimize=True)\n", " case AnimationFormat.WEBP:\n", " params.update(lossless=True)\n", "\n", " image_io = BytesIO()\n", " first_frame.save(image_io, str(format).upper(), **params)\n", "\n", " return image_io\n", "\n", "\n", "def display_graph_animation(title: str, subtitle: str, graph_data: GraphData) -> None:\n", " image_io = generate_animation(title, subtitle, graph_data, ANIMATION_FORMAT)\n", " ipython_image = display.Image(data=image_io.getvalue())\n", " display.display(ipython_image)\n", "\n", "\n", "def get_graph_title_and_subtitle(\n", " source: Source | str,\n", " model: Model | None = None,\n", " domain: str = \"\",\n", ") -> tuple[str, str]:\n", " if isinstance(source, str):\n", " source_name = f'\"{source.strip()[:20]}…\"'\n", " else:\n", " source_name = source.name\n", " model_id = model.value if model else Model.DEFAULT.value\n", " model_id = model_id.removesuffix(\"-preview\")\n", " separator = \" • \"\n", " title_parts = [\"Knowledge Graph\"]\n", " if domain:\n", " title_parts.append(domain)\n", " subtitle_parts = [source_name, model_id]\n", " return separator.join(title_parts), separator.join(subtitle_parts)\n", "\n", "\n", "def display_knowledge_graph(\n", " knowledge_graph: KnowledgeGraph,\n", " source: Source | str,\n", " model: Model | None = None,\n", " animated: bool = False,\n", " domain: str = \"\",\n", " remove_orphan_nodes: bool = True,\n", ") -> None:\n", " if not knowledge_graph.entities:\n", " return\n", " title, subtitle = get_graph_title_and_subtitle(source, model, domain)\n", " graph_data = GraphData(knowledge_graph, remove_orphan_nodes)\n", "\n", " if animated:\n", " display_graph_animation(title, subtitle, graph_data)\n", " else:\n", " display_graph(title, subtitle, graph_data)\n", "\n", "\n", "def extract_knowledge_graph(\n", " data_schema: str,\n", " instructions: str,\n", " source: Source | str,\n", " model: Model | None = None,\n", " *,\n", " domain: str = \"\",\n", " animated: bool = False,\n", ") -> None:\n", " if isinstance(source, Source):\n", " display_input_data_caption(source)\n", " knowledge_graph = generate_knowledge_graph(\n", " data_schema,\n", " instructions,\n", " source,\n", " model=model,\n", " )\n", " display_knowledge_graph(knowledge_graph, source, model, animated, domain)\n", "\n", "\n", "print(\"✅ Data visualization helpers defined\")" ] }, { "cell_type": "markdown", "metadata": { "id": "cqFoT8eABQyl" }, "source": [ "Let's test this:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "UVerSJcQBQyl" }, "outputs": [], "source": [ "display_knowledge_graph(knowledge_graph, text)" ] }, { "cell_type": "markdown", "metadata": { "id": "oSrGnlGirYeV" }, "source": [ "💡 We can now quickly visualize and understand our knowledge graphs. This helps us iterate faster when refining prompts.\n", "\n", "ℹ️ While this simple approach is great for a quick overview, you might want to swap it out for more specialized libraries if you want to explore the graph interactively.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "3-mWOis7wu4Q" }, "source": [ "---\n", "\n", "## ✅ Challenge completed\n" ] }, { "cell_type": "markdown", "metadata": { "id": "f0075432ee45" }, "source": [ "Let's define a book analysis function:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "c47KS08drYeV" }, "outputs": [], "source": [ "def analyze_book(\n", " source: Source,\n", " model: Model | None = None,\n", " animated: bool = False,\n", ") -> None:\n", " extract_knowledge_graph(\n", " BOOK_ANALYSIS_DATA_SCHEMA,\n", " BOOK_ANALYSIS_INSTRUCTIONS,\n", " source,\n", " model,\n", " domain=\"Character Connections\",\n", " animated=animated,\n", " )" ] }, { "cell_type": "markdown", "metadata": { "id": "24cbaef26a3b" }, "source": [ "🧪 First, let's build a knowledge graph based on Zola's _Thérèse Raquin_:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "zJ7KVZjrrYeV" }, "outputs": [], "source": [ "analyze_book(Classic.fr_zola_thérèse_raquin)" ] }, { "cell_type": "markdown", "metadata": { "id": "be347a0796d1" }, "source": [ "💡 We can extract and understand the book's narrative in seconds: The love triangle between Thérèse, Camille, and Laurent clearly stands out. Despite being over 200 pages long (and 100k+ tokens), this novel is incredibly minimalistic, revolving around a limited set of characters, which is reflected in the network graph. Adding locations to the extracted entities would also reveal the claustrophobic atmosphere of the book in the resulting knowledge graph.\n", "\n", "ℹ️ We used the original French version with English instructions, which works seamlessly. If you translate the instructions, you can also generate dynamic relationship links in different languages (see the [100+ supported languages](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/models#expandable-1)).\n" ] }, { "cell_type": "markdown", "metadata": { "id": "3dd1f59a87ff" }, "source": [ "🧪 Let's see how the model handles the interconnected cast of Hugo's _Les Misérables_:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "_iM5C6Lnwu4Q" }, "outputs": [], "source": [ "analyze_book(\n", " Classic.en_hugo_les_misérables,\n", " model=Model.GEMINI_3_5_FLASH,\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "3513c2092b91" }, "source": [ "💡 We quickly get the gist of the novel.\n", "\n", "ℹ️ Donald Knuth famously used _Les Misérables_ as an example back in 1994 (see the [Stanford GraphBase](https://www-cs-faculty.stanford.edu/~knuth/sgb.html)). It's been consistently used in Natural Language Processing (NLP) because of its massive scale, linguistic complexity, and multiple high-quality translations. At 800k+ tokens, this book is still a true stress test. Note that we used Gemini 3.5 Flash (instead of 3.1 Flash-Lite). Larger models can infer more and perform deeper consolidation.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "2ff0fc33592a" }, "source": [ "🧪 Now, let's process just the first volume of _Le Comte de Monte-Cristo_ (in French):\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ikWHgVgYwu4R" }, "outputs": [], "source": [ "analyze_book(Classic.fr_dumas_comte_de_monte_cristo_1)" ] }, { "cell_type": "markdown", "metadata": { "id": "8ae553261079" }, "source": [ "💡 The graph shows the initial setup of Edmond Dantès' world, his friends, and his betrayers. The love triangle between Edmond, Mercédès, and Fernand also comes to light.\n", "\n", "ℹ️ Note that the antagonist is referred to only as _Fernand_, which is expected. We learn his full name, _Fernand Mondego_, only in volume three. In the prompt, we asked the model to \"extract\" entities and determine names \"from the input data\" to avoid generating memorized knowledge. To detect regressions when updating the prompt, we can use this as a unit test to ensure that our response actually provides extracted data and not memorized information.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "f1f5c82e4b45" }, "source": [ "🧪 And finally, let's analyze the entire saga of _Le Comte de Monte-Cristo_, all four volumes at once (800k+ tokens):\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "vUdGXxF1s9mc" }, "outputs": [], "source": [ "analyze_book(\n", " Collection.fr_dumas_comte_de_monte_cristo,\n", " model=Model.GEMINI_3_5_FLASH,\n", " animated=True,\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "3592b815c653" }, "source": [ "💡 The multiple aliases of Edmond Dantès (and other characters) are nicely extracted. The complex plot of this book is built on characters juggling multiple identities in a psychological chess match.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "8eb80869f13f" }, "source": [ "🎉 This is an example of how we can complete the challenge in a single request, using the fewest tokens possible and zero thinking tokens, while providing multiple levels of consolidation.\n", "\n", "ℹ️ Note that this is a proof of concept. For an exhaustive extraction in a fully professional solution, we would probably set up a multi-step workflow and consider the following:\n", "\n", "- As a preliminary step, cache the input data (cached tokens get a 90% discount; learn more about [context caching](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/context-cache/context-cache-overview)).\n", "- In the first request, based on the cached content, focus on extracting the entities (possibly extending the entity labels with `location`, `date`…), and then save them to a database.\n", "- In the second request, based on the cached content and the entity table, focus on extracting the stated relationships using additional fields (such as `evidence` or `excerpt` to serve as direct proof, or `chapter` or `page` for source attribution). In this step, we could also dig deeper and differentiate literal/figurative relationships (e.g., biological vs. figurative parents).\n", "- In subsequent requests, focus on additional extractions (e.g., interactions between entities) or specific consolidations (e.g., adding inverse relationships, classifying the relationships or interactions into categories).\n" ] }, { "cell_type": "markdown", "metadata": { "id": "0cgofTAtrYeW" }, "source": [ "---\n", "\n", "## 🔭 Generalization\n" ] }, { "cell_type": "markdown", "metadata": { "id": "M85CyOfErYeW" }, "source": [ "With our current setup, generalizing to other types of content is as simple as adapting our data schema and instructions.\n", "\n", "For example, legal agreements are among the densest types of documents. They're usually made up of many articles and clauses, with every sentence carrying specific legal weight, outlining obligations, or providing definitions. But what kind of knowledge graph do we want to build from a legal agreement?\n" ] }, { "cell_type": "markdown", "metadata": { "id": "144WP1aXrYeW" }, "source": [ "🧪 Let's test a minimalistic, open-ended prompt:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Hy5BBEHBrYeW" }, "outputs": [], "source": [ "source = Document.en_pharma_dev_agreement\n", "model = Model.GEMINI_3_5_FLASH\n", "\n", "AGREEMENT_OPEN_DATA_SCHEMA = \"\"\"\n", "Entity:\n", "- `id`: Unique integer identifier (0, 1, 2…).\n", "- `name`: Name of the entity.\n", "- `label`: Entity type.\n", "\n", "Relationship:\n", "- `source_id`: `id` of the subject entity.\n", "- `link`: `snake_case` predicate.\n", "- `target_id`: `id` of the object entity.\n", "\"\"\"\n", "\n", "AGREEMENT_OPEN_INSTRUCTIONS = \"\"\"\n", "Perform a comprehensive, highly-granular entity/relationship extraction.\n", "\"\"\"\n", "\n", "extract_knowledge_graph(\n", " AGREEMENT_OPEN_DATA_SCHEMA,\n", " AGREEMENT_OPEN_INSTRUCTIONS,\n", " source,\n", " model,\n", " domain=\"Agreement High-Level Extraction\",\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "IFOAPeKRrYeW" }, "source": [ "💡 Remarks\n", "\n", "- Notice how we just passed a PDF directly! Gemini processes the document natively, automatically extracting text and images while performing OCR along the way.\n", "- This minimalistic prompt offers the greatest degree of freedom, as the model can't guess exactly what data you want or how you plan to use it. As a result, only high-level entities and relationships are extracted, providing a nice summary of the agreement.\n", "- LLMs are trained to synthesize information. With such highly open-ended instructions, the default behavior helps avoid generating unnecessary tokens.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "dzkEGUmurYeW" }, "source": [ "🧪 Then, let's try semi-open instructions focusing on legal obligations:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ILxuNknVrYeW" }, "outputs": [], "source": [ "class AgreementEntityLabel(StrEnum):\n", " PARTY = auto()\n", " PERSON = auto()\n", " ROLE = auto()\n", " LOCATION = auto()\n", " JURISDICTION = auto()\n", " FINANCIAL_AMOUNT = auto()\n", " DATE = auto()\n", " EVENT = auto()\n", " ASSET = auto()\n", " PRODUCT = auto()\n", " INTELLECTUAL_PROPERTY = auto()\n", " OBLIGATION_TYPE = auto()\n", "\n", "\n", "AGREEMENT_SEMI_OPEN_DATA_SCHEMA = f\"\"\"\n", "Entity:\n", "- `id`: Unique integer identifier (0, 1, 2…).\n", "- `name`: Name of the entity.\n", "- `label`: {pipe_delimited_union(AgreementEntityLabel)}.\n", "\n", "Relationship: Obligation, right, or transfer from a source entity to a target entity.\n", "- `source_id`: The `id` of the subject entity.\n", "- `link`: Specific `snake_case` predicate.\n", "- `target_id`: The `id` of the object entity.\n", "\"\"\"\n", "\n", "AGREEMENT_SEMI_OPEN_INSTRUCTIONS = \"\"\"\n", "- Analyze the input data for every covenant (e.g., \"shall\", \"will\", \"must\", \"is obligated to\") and perform an exhaustive extraction.\n", "- Make sure to deconstruct complex obligations: For complex clauses (e.g., \"A shall pay B $X Million within Y days of the Effective Date\"), extract:\n", " - The primary obligation: `[A] is_obligated_to_pay [B]`\n", " - The value: `[A's obligation] subject_to [$X Million]`\n", " - The trigger: `[A's obligation] triggered_by [Effective Date]`\n", "\"\"\"\n", "\n", "extract_knowledge_graph(\n", " AGREEMENT_SEMI_OPEN_DATA_SCHEMA,\n", " AGREEMENT_SEMI_OPEN_INSTRUCTIONS,\n", " source,\n", " model,\n", " domain=\"Agreement Obligations\",\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "QKWA6dnGrYeW" }, "source": [ "💡 Remarks\n", "\n", "- This semi-open prompt lists the types of entities to extract, which naturally increases the number of extracted entities and their specificity.\n", "- The resulting graph is denser and reflects the legal complexity of the document, rather than just giving us a high-level summary.\n", "- The extracted relationships are still rather high-level due to how open-ended this part of our prompt is. For such specific extractions, it's possible to extend the entity and relationship data schemas with additional fields, or even to request specific tabular outputs.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "947tZMu9rYeW" }, "source": [ "What if we don't care about legal obligations, but rather the document's architecture? Let's shift our focus to the structure itself and extract how sections, clauses, and defined terms are hierarchically organized…\n", "\n", "🧪 And now, let's test closed instructions focusing on the document structure:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "upnfalI_rYeW" }, "outputs": [], "source": [ "class AgreementStructureEntityLabel(StrEnum):\n", " DEFINED_TERM = auto()\n", " DOCUMENT_SECTION = auto()\n", " DOCUMENT = auto()\n", "\n", "\n", "class AgreementStructureRelationshipType(StrEnum):\n", " DEFINED_IN = auto()\n", " CONTAINS = auto()\n", "\n", "\n", "AGREEMENT_STRUCTURAL_DATA_SCHEMA = f\"\"\"\n", "Entity:\n", "- `id`: Unique integer identifier (0, 1, 2…).\n", "- `name`: Name of the entity.\n", "- `label`: {pipe_delimited_union(AgreementStructureEntityLabel)}.\n", "\n", "Relationship: Connection from a source entity to a target entity.\n", "- `source_id`: The `id` of the subject entity.\n", "- `link`: {pipe_delimited_union(AgreementStructureRelationshipType)}.\n", "- `target_id`: The `id` of the object entity.\n", "\"\"\"\n", "\n", "AGREEMENT_STRUCTURAL_OPEN_INSTRUCTIONS = \"\"\"\n", "- Extract every distinct entity that matches an allowed `label`.\n", "- Extract every distinct relationship representing a structural connection (hierarchical organization) between these entities:\n", " - You must be comprehensive and highly granular. If multiple distinct relationships exist between the same pair of entities, create a separate entry for each.\n", "\"\"\"\n", "\n", "extract_knowledge_graph(\n", " AGREEMENT_STRUCTURAL_DATA_SCHEMA,\n", " AGREEMENT_STRUCTURAL_OPEN_INSTRUCTIONS,\n", " source,\n", " model,\n", " domain=\"Agreement Structure\",\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "857e79d2b5ae" }, "source": [ "💡 If you extract hundreds of entities from a massive document, your graph will quickly turn into an unreadable hairball. For larger datasets, you'll want to export your nodes and edges to a dedicated graph database, which typically comes with its own visualization and exploration tools.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "Nx3dioUE6PnJ" }, "source": [ "---\n", "\n", "## 💡 Analyze your documents\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "JDdluSOn6PnJ" }, "outputs": [], "source": [ "class MyDocs(Source):\n", " # Classic books\n", " en_lewis_carroll_alice = project_gutenberg_txt_url(11)\n", " de_goethe_die_leiden_des_jungen_werther = project_gutenberg_txt_url(2407)\n", " de_fontane_effi_briest = project_gutenberg_txt_url(5323)\n", "\n", " # Local files\n", " # my_local_file = local_file(\"my_file.ext\")\n", "\n", " # Online files\n", " # my_online_file = \"https://path/to/my_file.ext\"\n", "\n", "\n", "MY_DATA_SCHEMA = \"\"\"\n", "- Entity:\n", " - `id`: Unique integer identifier (0, 1, 2…).\n", " - `name`: Name of the entity.\n", " - `label`\n", "- Relationship: Connection from a source entity to a target entity.\n", " - `source_id`: `id` of the subject entity.\n", " - `link`: `snake_case` predicate describing the relationship.\n", " - `target_id`: `id` of the object entity.\n", "\"\"\"\n", "\n", "MY_INSTRUCTIONS = \"\"\"\n", "Perform an entity and relationship extraction.\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "X4wc6JXXrYeX" }, "outputs": [], "source": [ "# analyze_book(MyDocs.en_lewis_carroll_alice)\n", "\n", "# extract_knowledge_graph(MY_DATA_SCHEMA, MY_INSTRUCTIONS, MyDocs.my_local_file)" ] }, { "cell_type": "markdown", "metadata": { "id": "yWMUeAYfBQym" }, "source": [ "---\n", "\n", "## 🏁 Conclusion\n" ] }, { "cell_type": "markdown", "metadata": { "id": "Q1lyY001BQym" }, "source": [ "We successfully extracted data and built knowledge graphs from documents by following these steps:\n", "\n", "- Prototyping with open prompts to develop an intuition for the model's natural strengths\n", "- Crafting increasingly specific prompts using a tabular-extraction strategy\n", "- Structuring our inputs to move towards production-ready and generalizable code\n", "- Structuring and optimizing our outputs for faster and cheaper generation\n", "- Adding data visualization for easier interpretation of responses and smoother iterations\n", "- Conducting more tests, iterating, and enriching the extracted data\n", "\n", "These principles apply to many other data-extraction domains and will allow you to solve your own complex problems. Have fun and happy solving!\n" ] }, { "cell_type": "markdown", "metadata": { "id": "8GNUerw6BQym" }, "source": [ "---\n", "\n", "## ➕ More!\n", "\n", "- Explore typical use cases in the [Agent Platform Prompt Gallery](https://console.cloud.google.com/agent-platform/studio/prompt-gallery)\n", "- Stay updated with the [Agent Platform Release Notes](https://docs.cloud.google.com/gemini-enterprise-agent-platform/release-notes)\n" ] } ], "metadata": { "colab": { "name": "knowledge_graph_generation.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }