{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "uVA4QwESUwdw"
},
"source": [
"# How to get a 100% Guaranteed Valid JSON response"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "SFZbIO4GTM36"
},
"source": [
"## 1. Install Litelines"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"id": "4pn7gRD5TEOn"
},
"outputs": [],
"source": [
"%pip install --quiet --upgrade litelines"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Uc2GbTIvb5fY"
},
"source": [
"## 2. Download a model and its tokenizer"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"id": "cuWp975qWGlK"
},
"outputs": [],
"source": [
"# Use cuda for faster inference\n",
"import torch\n",
"\n",
"device = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n",
"assert device == torch.device(\"cuda\"), \"In the Runtime tab, please Change runtime type to GPU\""
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"id": "XURqquVBYIe4"
},
"outputs": [],
"source": [
"from transformers import AutoModelForCausalLM, AutoTokenizer\n",
"\n",
"MODEL_ID = \"Qwen/Qwen2.5-0.5B-Instruct\"\n",
"tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)\n",
"model = AutoModelForCausalLM.from_pretrained(MODEL_ID).to(device)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "twipl7hucAV2"
},
"source": [
"## 3. Prepare the inputs to the LLM"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"id": "AE1s9Q2eU-27"
},
"outputs": [],
"source": [
"user_input = \"\"\"Give me a json describing the following text:\n",
"Linus is a 55 years old software engineer.\n",
"\"\"\"\n",
"messages = [{\"role\": \"user\", \"content\": user_input}]\n",
"inputs = tokenizer.apply_chat_template(\n",
" messages,\n",
" add_generation_prompt=True,\n",
" return_tensors=\"pt\",\n",
" return_dict=True\n",
").to(model.device)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "nRxF3dLkcGv2"
},
"source": [
"## 4. Define a Pydantic schema describing the required JSON"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"id": "u4YCQ-6LYCxt"
},
"outputs": [],
"source": [
"from typing import Literal\n",
"from pydantic import BaseModel, Field\n",
"\n",
"class Person(BaseModel):\n",
" name: str = Field(..., description=\"The person's full name\")\n",
" age: int = Field(..., description=\"The person's age in years\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "J4zmgiw0cVUF"
},
"source": [
"## 5. Define the processor and visualize it"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 1000
},
"id": "p8EUUNfZa0p5",
"outputId": "5303ea79-5adc-498e-8e7c-c3f85a5781d3"
},
"outputs": [
{
"data": {
"image/svg+xml": [
""
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"from litelines.transformers import SchemaProcessor\n",
"\n",
"processor = SchemaProcessor(response_format=Person, tokenizer=tokenizer)\n",
"processor.show_graph()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "X22P6Meua9B7"
},
"source": [
"## 6. Generate a structured response"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "flRiHrgqa5ix",
"outputId": "dc991b8f-a356-4bc3-9dd9-f612e0fe5697"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Response:\n",
"{\n",
" \"name\": \"Linus\",\n",
" \"age\": 55\n",
"}\n"
]
}
],
"source": [
"generated = model.generate(**inputs, logits_processor=[processor], temperature=0.1)\n",
"print(f\"Response:\\n{tokenizer.decode(generated[0][inputs['input_ids'].shape[-1]:-1])}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xSb51PWpc7LE"
},
"source": [
"## 7. Visualize the selected path"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 1000
},
"id": "_WqgdCynbGnK",
"outputId": "dda043c0-baef-447b-f9b1-57ea71d801e7"
},
"outputs": [
{
"data": {
"image/svg+xml": [
""
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"processor.show_graph()"
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"gpuType": "T4",
"provenance": []
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.4"
}
},
"nbformat": 4,
"nbformat_minor": 4
}