diff --git a/examples/gpt-5/gpt-5_new_params_and_tools.ipynb b/examples/gpt-5/gpt-5_new_params_and_tools.ipynb index d19d48b271..daafb77385 100644 --- a/examples/gpt-5/gpt-5_new_params_and_tools.ipynb +++ b/examples/gpt-5/gpt-5_new_params_and_tools.ipynb @@ -15,6 +15,8 @@ "| 1. | **Verbosity Parameter** | Lets you hint the model to be more or less expansive in its replies. Keep prompts stable and use the parameter instead of re-writing. | • **low** → terse UX, minimal prose.
• **medium** *(default)* → balanced detail.
• **high** → verbose, great for audits, teaching, or hand-offs. |\n", "| 2. | **Free-Form Function Calling** | Generate raw text payloads—anything from Python scripts to SQL queries—directly to your custom tool without JSON wrapping. Offers greater flexibility for external runtimes like:
• Code sandboxes (Python, C++, Java, …)
• SQL databases
• Shell environments
• Config generators | Use when structured JSON isn’t needed and raw text is more natural for the target tool. |\n", "| 3. | **Context-Free Grammar (CFG)** | A set of production rules defining valid strings in a language. Each rule rewrites a non-terminal into terminals and/or other non-terminals, independent of surrounding context. Useful for constraining output to match the syntax of programming languages or custom formats in OpenAI tools. | Use as a contract to ensure the model emits only valid strings accepted by the grammar. |\n", + "| 4. | **Minimal Reasoning** | Runs GPT-5 with few or no reasoning tokens to minimize latency and speed time-to-first-token. Ideal for deterministic, lightweight tasks (extraction, formatting, short rewrites, simple classification) where explanations aren’t needed. If not specified, effort defaults to medium. | Set reasoning effort: \"minimal\". Avoid for multi-step planning or tool-heavy workflows. |\n", + "\n", "\n", "**Supported Models:** \n", "- gpt-5 \n", @@ -48,7 +50,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "openai 1.99.1\n", + "openai 1.99.2\n", "pandas 2.3.1\n" ] } @@ -80,7 +82,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 3, "id": "d5260af8", "metadata": {}, "outputs": [ @@ -88,153 +90,203 @@ "data": { "text/html": [ "\n", - "\n", + "
\n", " \n", " \n", " \n", - " \n", - " \n", - " \n", + " \n", + " \n", + " \n", " \n", " \n", " \n", " \n", - " \n", - " \n", - " \n", + " \n", + " \n", - " \n", + "When time unlatched its gates, the boy still carried small things:\n", + "a collar, a chewed shoe, the echo of a bark that taught him how to hope.\n", + "He learned that love can look like leaving crumbs of ordinary kings,\n", + "and that some firsts fit in your pockets long after they have gone.\n", + " \n", " \n", " \n", - " \n", - " \n", - " \n", + " \n", + " \n", - " \n", + "Seasons unraveled the way they always do.\n", + "Snow came to lay white questions across the yard;\n", + "summer stretched its lazy hands and left grass bleaching in August.\n", + "The boy grew taller and later, the dog moved slower,\n", + "but in late afternoons they still shared the same light —\n", + "a private currency of sun and shadow.\n", + "\n", + "When the boy learned the language of goodbyes,\n", + "it was the dog who taught him how to soften them.\n", + "A last look, a lingering hand across the coat,\n", + "and a promise that out of all the small ordinary days\n", + "something invincible had been braided:\n", + "two hearts, a leash, a map of pawprints on the threshold.\n", + "\n", + "Years later, the boy — now grown — tucks a photograph\n", + "into his coat pocket. He feels the hollow\n", + "where a warm head used to rest and smiles.\n", + "Some bonds refuse to be folded away.\n", + "In the quiet hum of rememberings,\n", + "he can still hear a collar's jingle and a small, glad bark:\n", + "first home, first friend, first forever.\n", + " \n", " \n", " \n", - " \n", - " \n", - " \n", + " \n", + " \n", - " \n", + "A first dog is a first map of how to love:\n", + "fur on your sleeve, the sound of feet that always come home.\n", + "He taught a boy how to stand steady under weather,\n", + "how to be brave by being kind, and how to keep a place warm.\n", + "If you listen, sometimes the past still answers,\n", + "with a jingle, a wag, and the echo of a small, perfect breath.\n", + " \n", " \n", " \n", "
 VerbositySample OutputOutput TokensVerbositySample OutputOutput Tokens
0lowHe found him behind the old shed, a damp ball of surprise,\n", - "eyes like two small moons against the dusk.\n", - "His palms trembled when they touched the ribs, a first brave promise —\n", - "the word that made them both grin: \"home.\"\n", + " 0lowHe found a scruff of fur behind the shed one spring afternoon,\n", + "a heartbeat small and fast beneath a coat of dust and light.\n", + "The world shrank to two—mud on sneakers, a wag, a clumsy tune—\n", + "names rolled off his tongue like marbles, simple, sure, and bright.\n", "\n", - "They learned the map of each other's days:\n", - "mud on the porch, the shorthand of paws on tile,\n", - "lessons in patience—sit, wait, the clumsy language of fetch—\n", - "evenings stitched together by a tail that kept time.\n", + "They learned the map of each other's hands: the scratch beneath the ear,\n", + "the way a storm could change the shape of brave into a shake.\n", + "Mornings were for toast and sunlight, afternoons for running near\n", + "the riverbank where leaves applauded every leap they'd take.\n", "\n", - "The dog taught him how to be gentle with broken things:\n", - "scarred knees, lost kites, the ache of a scraped promise.\n", - "When the boy fell, the dog was there to push him up with a wet nose,\n", - "when the world tightened, the dog leaned in like a small sun.\n", + "At night they shared a blanket and the secret of the dark,\n", + "the boy with whispered stories, the dog with steady breath.\n", + "Years braided into footprints—first skinned knees, then a spark\n", + "of barnyard gray upon a muzzle, slow and gentle as a wreath.\n", "\n", - "Years threaded silver into ears and softened the sprint,\n", - "the boy grew taller, pockets fuller of other lives.\n", - "On the last slow walk he carried the dog across the field they had worn bare,\n", - "and learned what it meant to hold and let go at once.\n", - "\n", - "Sometimes, in a house that now holds different voices,\n", - "he still calls the name and feels a short, bright tug at the hem of memory.754560
1mediumHe was small enough to be held in two palms,\n", - "hands surprised by the light, warm weight of a breathing animal.\n", - "The dog came with a cardboard box of toys,\n", - "a collar that jingled like a laugh,\n", - "and eyes the color of late autumn pools.\n", + " 1mediumHe found him folded in the crook of a cardboard box,\n", + "a tiny ribcage hitching like a thought.\n", + "The boy had pockets full of pennies and promises;\n", + "the dog had eyes like two small questions.\n", + "\n", + "They learned names together — the boy said one,\n", + "the dog tilted his head and accepted it.\n", + "Mornings were clumsy lessons: leash in hand,\n", + "the dog discovering sidewalks with a sneeze of wonder,\n", + "the boy discovering courage at the end of a rope.\n", "\n", - "They learned each other by touch:\n", - "how a thumb smoothed a lump of fur,\n", - "how a paw fit between fingers like a promise.\n", - "Afternoons became slow, luminous things —\n", - "fetch across the yard, the dog tumbling through dandelions,\n", - "the boy counting sticks as if they were crowns.\n", + "They chased afternoons into puddles,\n", + "mud kissing the boy's knees and the dog's whiskers.\n", + "The dog taught him how to throw sticks that never came back\n", + "and how to forgive them when they didn't.\n", + "Evenings were for quiet conspiracies:\n", + "the dog's breath a warm punctuation\n", + "against the boy's ankle as the sky grew blue-black.\n", "\n", - "At night the dog curled against a ribcage\n", - "and taught the boy how to sleep with one ear listening.\n", - "They shared secrets whispered into warm fur,\n", - "bandaged scraped knees with careful nuzzles,\n", - "and sat together on porches while light leaned away.\n", + "Homework became a small island between their worlds,\n", + "a pencil, a pat, the faithful presence of paws on carpet.\n", + "The dog learned how to sit for apples,\n", + "how to hide a cold nose under a blanket of fingers.\n", + "The boy learned how to stitch up a torn stuffed bear,\n", + "how to say sorry and mean it.\n", "\n", - "The world outside was larger, sharper,\n", - "but he had a companion who never measured fear,\n", - "only presence — a warm, steady map back home.\n", - "Lessons came not in words but in ritual:\n", - "the bowl filled, the leash clicked, the hush before storms.\n", - "Responsibility fit him like a second skin.\n", + "There were days of thunder when the boy's knees knocked,\n", + "and the dog, all stern responsibility, pressed his head\n", + "into the hollow of the boy's fear and held it there\n", + "as if he could anchor lightning with his chin.\n", "\n", - "Years threaded through collars and collars loosened,\n", - "legs that once ran like wind now slowed to wiser steps.\n", - "The boy learned how to be brave in other ways:\n", - "walking into rooms without the certainty of pawprints,\n", - "carrying a small quiet grief folded into his chest.\n", + "They practiced being brave together: doors opened for new schools,\n", + "new roads, a first bike without training wheels,\n", + "the dog a steady metronome of tail and warmth,\n", + "never asking to be anything but present.\n", "\n", - "Even when the dog went where yards are always green,\n", - "he left prints on the boy’s life that never washed away —\n", - "a tucked-in photograph, a faded ball, the smell of wet fur in summer rain.\n", - "Sometimes, when the house is very still, the boy — now taller,\n", - "still hears the jingle of a collar and smiles,\n", - "for he knows how to be loved, and how to love back.939849
2highThe dog arrived like a small sun, all fur and surprise,\n", - "an apology for shoes chewed at the doorstep.\n", - "He fit into the boy’s lap as if he had been made there:\n", - "a warm, wiggling answer to the question the boy never knew he’d asked.\n", + " 2highThe day the boy met his dog the world grew wider—\n", + "a small breath of fur and a damp, earnest nose\n", + "pressed like a secret against his palm.\n", + "They stood on the porch and the sun tilted curious,\n", + "as if the sky had come to see how two new things\n", + "might fit together.\n", + "\n", + "He named him after a comic-strip hero,\n", + "or maybe he didn’t name him at all at first,\n", + "just laughed and let the sound of it become a name.\n", + "They learned each other’s weight: the dog’s heavy joy,\n", + "the boy’s thin, cautious fingers turning into hands\n", + "that could hold a leaping heart steady.\n", "\n", - "They learned one another by touch — the boy’s clumsy fingers\n", - "finding the soft map of ears, the steady paddling heart.\n", - "The dog learned the geometry of a bedroom, a couch, a favorite chair;\n", - "the boy learned the weight of responsibility when the bowl was empty.\n", + "Mornings became a chorus of paws and cereal,\n", + "of a collar’s jingle and the scrape of a chair.\n", + "Homework survived only when the dog approved;\n", + "math problems were beneath a wagging tail,\n", + "spelling tests punctuated by a slobbering vowel.\n", + "They hid secrets under the bed, between dust bunnies,\n", + "and shared the small, perfect conspiracy of being alive.\n", "\n", - "They practiced words like spellcraft: sit, stay, no — then laugh\n", - "when the commands rearranged themselves into games.\n", - "Mud sketched secret rivers on their trousers;\n", - "the neighborhood became a kingdom to patrol on two legs and four.\n", + "Afternoons were a map of adventures: the cracked sidewalk,\n", + "the river that smelled like stones and moss, the hill\n", + "where the wind felt like permission to run.\n", + "The dog learned to fetch sticks and forgotten courage,\n", + "and the boy learned that bravery could be soft\n", + "as a warm head on a lap, or loud as a bark that scares away thunder.\n", "\n", - "At night the dog lay like a small, even moon against the boy’s ribs,\n", - "breathing the rhythm of a shared world into his dreams.\n", - "Storms were smaller storms then, because the dog’s body was a promise:\n", - "that thunder could be waited out, that hands could find something warm.\n", + "Summer taught them both how long the day could be.\n", + "They chased shadows and each other, made small rules:\n", + "no digging in the tulips, no chasing the mailman,\n", + "except that the tulips never stood a chance.\n", + "The boy’s knees collected stories—scrapes that healed,\n", + "dirt that stained his socks but not his smile.\n", + "The dog’s ears learned the cadence of the boy’s breath,\n", + "the way it tipped into sleep like a boat finding harbor.\n", "\n", - "They buried treasures — bones, a tin soldier, a lost mitten —\n", - "beneath the old apple tree, sworn companions to the earth.\n", - "They chased imagined villains down fences and over hedges,\n", - "and sometimes, at the creek, the boy learned the exact angle of courage:\n", - "how to step in, then trust another heartbeat beside his.\n", + "Years folded like worn pages. The boy got taller,\n", + "his voice snagged on words he used to swallow.\n", + "School took afternoons; friends took phone numbers.\n", + "Still, the dog found ways to be a country in which the boy could disappear\n", + "and always be found again—on the porch, by the back door,\n", + "where a tail thumped the rhythm of home.\n", "\n", - "The dog taught him how to be brave without knowing the word,\n", - "showed him where loyalty lived (in the bright, impatient wag of a tail).\n", - "He taught him how to say hello, properly; how to stay when needed;\n", - "how to forgive a day of wrongs with a single, earnest lick.\n", + "Time comes like winter in slow increments.\n", + "The dog’s muzzle silvered; his steps remembered caution.\n", + "He stopped fitting into the spaces he once owned\n", + "and learned to ask for rest. The boy—no longer quite a boy—\n", + "sat longer, tracing the map of every scar and whiskered gray.\n", + "There were nights when the dog’s breathing was a thin, honest drum,\n", + "and the boy pressed his forehead to the dog’s and said things out loud:\n", + "I am here. You were right. You showed me how.\n", "\n", - "Seasons folded themselves into the years;\n", - "the boy measured time in collars replaced, in new aches in the dog’s hips.\n", - "Snow made the yard a clean page; leaves wrote their own goodbyes.\n", - "When the dog’s runs slowed, the boy learned a different kind of steady:\n", - "to sit more, to listen longer, to count the small comforts.\n", + "The last morning was quiet in the way that endings often are:\n", + "a light that does not need to hurry, a sky that keeps its blue.\n", + "Hands that had once been small bore the weight of goodbye,\n", + "and the dog, who had taught him everything about leaving,\n", + "went gentle as a story closing.\n", "\n", - "There was a last evening where the light sat low and patient,\n", - "and the boy — now older in ways that did not fit his face — held that same warm weight.\n", - "He remembered the first bark like a promise kept, the first wild sprint across the grass,\n", - "and he kept, beneath his ribs, the map of a thousand small mercies.\n", + "They buried a bone under the apple tree, where shade remembered them.\n", + "At dusk the boy—grown, with work-worn hands and a child’s memory—\n", + "watches the place where grass leans toward the earth and listens.\n", + "Once, when the house was exactly the same and yet not,\n", + "he swore he heard a soft, familiar jangle in the kitchen,\n", + "a rhythm of steps padding toward the door.\n", + "For a beat the world tilted back to the way it had been:\n", + "porch light, collar, laughter spilling like coins into a pocket.\n", "\n", - "Now when he walks by an old apple tree, his hand finds empty air,\n", - "but his steps know how to make room for another’s rhythm.\n", - "Sometimes a stray dog will glance his way and tilt its head,\n", - "and he smiles, answering without words what he was taught long ago:\n", + "Years will teach you how to be without the body of what you loved,\n", + "but they cannot unteach the shape of its love.\n", + "In small things he carries the dog—an old ball behind the shed,\n", + "the smell of rain when it hits hot dust, the way loyalty sits\n", + "like a warm stone under the ribs. Sometimes, at night,\n", + "he still calls out a name the way you call to the ocean:\n", + "to feel a voice come back, immediate and soft,\n", + "and remember the simple miracle of being chosen.\n", "\n", - "how to open a hand, how to offer a place on the floor,\n", - "how to recognize the sun when it returns — in fur, in breath, in the simple, astonished love\n", - "of a first pet who showed a boy what home can mean.11741288
\n" ], "text/plain": [ - "" + "" ] }, "metadata": {}, @@ -267,16 +319,6 @@ " if hasattr(content, \"text\"):\n", " output_text += content.text\n", "\n", - " # Truncate for display\n", - " if len(output_text) > 700:\n", - " sample_output = (\n", - " output_text[:500]\n", - " + \" ... redacted for brevity ... \"\n", - " + output_text[-200:]\n", - " )\n", - " else:\n", - " sample_output = output_text\n", - "\n", " usage = response.usage\n", " data.append({\n", " \"Verbosity\": verbosity,\n", @@ -304,7 +346,7 @@ "id": "07fdb759", "metadata": {}, "source": [ - "The output tokens scale roughly linearly with verbosity: low (754) → medium (939) → high (1174)." + "The output tokens scale roughly linearly with verbosity: low (560) → medium (849) → high (1288)." ] }, { @@ -319,7 +361,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 4, "id": "aa6b6b12", "metadata": {}, "outputs": [ @@ -330,28 +372,27 @@ "--------------------------------\n", "Verbosity: low\n", "Output:\n", + "```python\n", "#!/usr/bin/env python3\n", "import random\n", "import time\n", "\n", "def main():\n", " N = 1_000_000\n", - " # generate 1,000,000 random floats\n", " arr = [random.random() for _ in range(N)]\n", "\n", " t0 = time.perf_counter()\n", - " arr.sort() # in-place Timsort\n", + " arr.sort()\n", " t1 = time.perf_counter()\n", "\n", " print(f\"Sorted {N} numbers in {t1 - t0:.4f} seconds\")\n", - " # optional quick checks\n", - " print(\"First 5:\", arr[:5])\n", - " print(\"Last 5:\", arr[-5:])\n", - " print(\"Verified sorted:\", all(arr[i] <= arr[i+1] for i in range(len(arr)-1)))\n", + " print(\"First 10:\", arr[:10])\n", + " print(\"Last 10:\", arr[-10:])\n", "\n", "if __name__ == \"__main__\":\n", " main()\n", - "Tokens => input: 21 | output: 877\n" + "```\n", + "Tokens => input: 21 | output: 575\n" ] } ], @@ -405,7 +446,7 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 5, "id": "d2efe2d7", "metadata": {}, "outputs": [ @@ -416,42 +457,40 @@ "--------------------------------\n", "Verbosity: medium\n", "Output:\n", - "Here's a simple Python program that generates 1,000,000 random floats and sorts them using Python's built-in Timsort. It times generation and sorting and verifies the result.\n", + "Here's a simple Python script that generates 1,000,000 random numbers, sorts them using the built-in Timsort, and reports timings and a small sample of the sorted output:\n", "\n", "```python\n", + "#!/usr/bin/env python3\n", "import random\n", "import time\n", "\n", "def main():\n", " N = 1_000_000\n", + " random.seed(42) # remove or change for different runs\n", "\n", - " print(f\"Generating {N} random numbers...\")\n", " t0 = time.perf_counter()\n", - " arr = [random.random() for _ in range(N)]\n", + " data = [random.random() for _ in range(N)]\n", " t1 = time.perf_counter()\n", - " print(f\"Generated in {t1 - t0:.3f} seconds\")\n", "\n", - " print(\"Sorting...\")\n", + " data.sort()\n", " t2 = time.perf_counter()\n", - " arr.sort()\n", - " t3 = time.perf_counter()\n", - " print(f\"Sorted in {t3 - t2:.3f} seconds\")\n", - "\n", - " # Quick verification\n", - " is_sorted = all(arr[i] <= arr[i+1] for i in range(len(arr)-1))\n", - " print(\"Verified sorted:\", is_sorted)\n", "\n", - " print(\"First 10 elements:\", arr[:10])\n", - " print(\"Last 10 elements:\", arr[-10:])\n", + " # Basic verification and sample output\n", + " is_sorted = all(data[i] <= data[i+1] for i in range(len(data)-1))\n", + " print(f\"Generated {N} random numbers in {t1 - t0:.3f} seconds\")\n", + " print(f\"Sorted in {t2 - t1:.3f} seconds\")\n", + " print(\"Sorted check:\", is_sorted)\n", + " print(\"First 10 values:\", data[:10])\n", + " print(\"Last 10 values:\", data[-10:])\n", "\n", "if __name__ == \"__main__\":\n", " main()\n", "```\n", "\n", - "If you prefer a faster/more memory-efficient approach and have NumPy installed, you can replace the generation and sort with:\n", - "- arr = np.random.random(N)\n", - "- arr.sort()\n", - "Tokens => input: 21 | output: 1178\n" + "Notes:\n", + "- This uses Python's built-in list sort (Timsort), which is efficient for general-purpose sorting.\n", + "- If you need more memory- and performance-efficient numeric operations on large arrays, consider using NumPy (numpy.random.random and numpy.sort).\n", + "Tokens => input: 21 | output: 943\n" ] } ], @@ -469,7 +508,7 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 6, "id": "4f92fb12", "metadata": {}, "outputs": [ @@ -480,134 +519,125 @@ "--------------------------------\n", "Verbosity: high\n", "Output:\n", - "Below are two complete Python programs you can run to generate and sort 1,000,000 random numbers. One is a pure-Python implementation using the built-in list and list.sort() (Timsort). The other uses NumPy (faster and far more memory-efficient for large numeric arrays). Each script times generation and sorting and optionally verifies the result is sorted.\n", + "Here's a single, self-contained Python program that generates 1,000,000 random numbers and sorts them. It supports two backends: the built-in Python list sort (Timsort) and NumPy (if you have NumPy installed). It measures and prints the time taken for generation, sorting, and verification.\n", "\n", - "Pure-Python version (no extra dependencies)\n", - "- Generates 1,000,000 Python floats with random.random().\n", - "- Uses list.sort() (Timsort), which is O(n log n) and very efficient in practice.\n", - "- Note: Python float objects have overhead, so the list will use substantially more memory than a raw numeric array.\n", + "Copy the code into a file (for example sort_random.py) and run it. By default it uses the pure Python backend; pass --backend numpy to use NumPy.\n", "\n", - "Save as sort_random_pure.py and run: python sort_random_pure.py\n", - "You can change the size with the --count option.\n", + "Note: Sorting a million Python floats uses a moderate amount of memory (Python floats and list overhead). NumPy will typically be faster and use less overhead but requires the numpy package.\n", + "\n", + "Program:\n", "\n", - "```python\n", - "#!/usr/bin/env python3\n", - "\"\"\"\n", - "Generate and sort N random numbers using pure Python list and list.sort().\n", - "Default N = 1_000_000. Use --count to override.\n", - "\"\"\"\n", - "import argparse\n", - "import random\n", "import time\n", + "import random\n", + "import argparse\n", "import sys\n", "\n", - "def is_sorted(seq):\n", - " # Efficient check: compare neighbours\n", - " return all(x <= y for x, y in zip(seq, seq[1:]))\n", + "def is_sorted_list(a):\n", + " # Linear check for sortedness\n", + " return all(a[i] <= a[i+1] for i in range(len(a)-1))\n", "\n", "def main():\n", - " parser = argparse.ArgumentParser(description=\"Generate and sort random numbers (pure Python).\")\n", - " parser.add_argument(\"--count\", \"-n\", type=int, default=1_000_000,\n", - " help=\"Number of random numbers to generate (default: 1_000_000)\")\n", - " parser.add_argument(\"--seed\", type=int, default=None, help=\"Optional random seed\")\n", + " parser = argparse.ArgumentParser(description=\"Generate and sort random numbers.\")\n", + " parser.add_argument(\"--n\", type=int, default=1_000_000, help=\"Number of random numbers (default: 1,000,000)\")\n", + " parser.add_argument(\"--backend\", choices=[\"python\", \"numpy\"], default=\"python\",\n", + " help=\"Sorting backend to use: 'python' (default) or 'numpy'\")\n", + " parser.add_argument(\"--seed\", type=int, default=0, help=\"Random seed (default: 0)\")\n", + " parser.add_argument(\"--sample\", type=int, default=10, help=\"How many sample elements to print (default: 10)\")\n", " args = parser.parse_args()\n", "\n", - " n = args.count\n", - " if args.seed is not None:\n", - " random.seed(args.seed)\n", + " n = args.n\n", + " backend = args.backend\n", + " seed = args.seed\n", + " sample = args.sample\n", "\n", - " print(f\"Generating {n:,} random floats...\")\n", - " t0 = time.perf_counter()\n", - " data = [random.random() for _ in range(n)]\n", - " t1 = time.perf_counter()\n", - " print(f\"Generation took {t1 - t0:.3f} seconds.\")\n", + " print(f\"Generating {n:,} random numbers using backend: {backend!r}, seed={seed}\")\n", "\n", - " print(\"Sorting...\")\n", - " t2 = time.perf_counter()\n", - " data.sort() # in-place Timsort\n", - " t3 = time.perf_counter()\n", - " print(f\"Sorting took {t3 - t2:.3f} seconds.\")\n", + " random.seed(seed)\n", "\n", - " print(\"Verifying sorted order...\")\n", - " t4 = time.perf_counter()\n", - " ok = is_sorted(data)\n", - " t5 = time.perf_counter()\n", - " print(f\"Verification took {t5 - t4:.3f} seconds. Sorted: {ok}\")\n", + " if backend == \"python\":\n", + " # Generate list of floats in Python\n", + " t0 = time.perf_counter()\n", + " data = [random.random() for _ in range(n)]\n", + " t1 = time.perf_counter()\n", + " gen_time = t1 - t0\n", + " print(f\"Generated {n:,} numbers in {gen_time:.4f} s\")\n", "\n", - " # Example: print first/last 3 values\n", - " print(\"First 3:\", data[:3])\n", - " print(\"Last 3:\", data[-3:])\n", + " if sample > 0:\n", + " print(\"Sample before sort:\", data[:sample])\n", "\n", - "if __name__ == \"__main__\":\n", - " main()\n", - "```\n", + " # Sort in-place\n", + " t0 = time.perf_counter()\n", + " data.sort()\n", + " t1 = time.perf_counter()\n", + " sort_time = t1 - t0\n", + " print(f\"Sorted {n:,} numbers in {sort_time:.4f} s (Python list.sort)\")\n", "\n", - "NumPy version (recommended for performance and memory)\n", - "- Requires NumPy installed (pip install numpy).\n", - "- Uses np.random.rand for fast generation and np.sort or ndarray.sort for sorting.\n", - "- Much less memory overhead: 1,000,000 float64 values use ~8 MB, whereas a Python list of float objects can use dozens of megabytes more.\n", + " if sample > 0:\n", + " print(\"Sample after sort: \", data[:sample])\n", "\n", - "Save as sort_random_numpy.py and run: python sort_random_numpy.py\n", + " # Verify sortedness\n", + " t0 = time.perf_counter()\n", + " ok = is_sorted_list(data)\n", + " t1 = time.perf_counter()\n", + " verify_time = t1 - t0\n", + " print(f\"Verified sortedness in {verify_time:.4f} s -> {'OK' if ok else 'NOT SORTED'}\")\n", "\n", - "```python\n", - "#!/usr/bin/env python3\n", - "\"\"\"\n", - "Generate and sort N random numbers using NumPy.\n", - "Default N = 1_000_000. Use --count to override.\n", - "Requires: numpy\n", - "\"\"\"\n", - "import argparse\n", - "import time\n", - "import numpy as np\n", + " else: # numpy backend\n", + " try:\n", + " import numpy as np\n", + " except ImportError:\n", + " print(\"NumPy is not installed. Install it with 'pip install numpy' or use the python backend.\")\n", + " sys.exit(1)\n", "\n", - "def main():\n", - " parser = argparse.ArgumentParser(description=\"Generate and sort random numbers (NumPy).\")\n", - " parser.add_argument(\"--count\", \"-n\", type=int, default=1_000_000,\n", - " help=\"Number of random numbers to generate (default: 1_000_000)\")\n", - " parser.add_argument(\"--seed\", type=int, default=None, help=\"Optional random seed\")\n", - " args = parser.parse_args()\n", + " # Use the new Generator API for reproducible generation\n", + " rng = np.random.default_rng(seed)\n", + " t0 = time.perf_counter()\n", + " data = rng.random(n) # numpy array of floats\n", + " t1 = time.perf_counter()\n", + " gen_time = t1 - t0\n", + " print(f\"Generated {n:,} numbers in {gen_time:.4f} s (NumPy)\")\n", "\n", - " n = args.count\n", - " if args.seed is not None:\n", - " np.random.seed(args.seed)\n", + " if sample > 0:\n", + " print(\"Sample before sort:\", data[:sample])\n", "\n", - " print(f\"Generating {n:,} random floats with NumPy...\")\n", - " t0 = time.perf_counter()\n", - " data = np.random.rand(n) # float64 by default\n", - " t1 = time.perf_counter()\n", - " print(f\"Generation took {t1 - t0:.3f} seconds.\")\n", + " # Sort in-place using NumPy's sort\n", + " t0 = time.perf_counter()\n", + " data.sort() # in-place quicksort/mergesort (NumPy chooses default)\n", + " t1 = time.perf_counter()\n", + " sort_time = t1 - t0\n", + " print(f\"Sorted {n:,} numbers in {sort_time:.4f} s (NumPy sort)\")\n", "\n", - " print(\"Sorting (in-place) with ndarray.sort()...\")\n", - " t2 = time.perf_counter()\n", - " data.sort() # in-place sort\n", - " t3 = time.perf_counter()\n", - " print(f\"Sorting took {t3 - t2:.3f} seconds.\")\n", + " if sample > 0:\n", + " print(\"Sample after sort: \", data[:sample])\n", "\n", - " print(\"Verifying sorted order...\")\n", - " t4 = time.perf_counter()\n", - " ok = np.all(np.diff(data) >= 0)\n", - " t5 = time.perf_counter()\n", - " print(f\"Verification took {t5 - t4:.3f} seconds. Sorted: {bool(ok)}\")\n", + " # Verify sortedness\n", + " t0 = time.perf_counter()\n", + " ok = np.all(np.diff(data) >= 0)\n", + " t1 = time.perf_counter()\n", + " verify_time = t1 - t0\n", + " print(f\"Verified sortedness in {verify_time:.4f} s -> {'OK' if ok else 'NOT SORTED'}\")\n", "\n", - " # Example: print first/last 3 values\n", - " print(\"First 3:\", data[:3])\n", - " print(\"Last 3:\", data[-3:])\n", + " print(\"Done.\")\n", "\n", "if __name__ == \"__main__\":\n", " main()\n", - "```\n", "\n", - "Notes, tips, and expected behavior\n", - "- Speed: NumPy will typically be faster for generation and use much less memory, because it stores numbers in a contiguous C array (8 bytes per float64). Pure-Python lists have per-object overhead (tens of bytes per float), and list generation + sorting will incur more Python-level overhead.\n", - "- Sorting complexity: both approaches use comparison-based sorts (Timsort for list.sort, quicksort/mergesort/heap variants in NumPy depending on algorithm choice) with typical O(n log n) runtime.\n", - "- If you only need a few smallest/largest values (e.g., top-k), consider heapq.nsmallest/nlargest or numpy.partition which can be faster than a full sort.\n", - "- If you want reproducible results, pass a fixed seed (see --seed).\n", - "- If memory becomes an issue and you only need to produce sorted output, consider external sorting methods (e.g., sort chunks and merge on disk) or using array.array('d') or memory-mapped files via numpy.memmap.\n", + "Usage examples:\n", + "- Pure Python (default):\n", + " python sort_random.py\n", "\n", - "If you want, I can:\n", - "- Provide a version that writes/reads from disk and performs an external merge sort to handle arbitrarily large arrays with limited memory.\n", - "- Provide a version that finds only the k smallest or k largest items more efficiently than sorting the whole list.\n", - "Tokens => input: 21 | output: 2176\n" + "- NumPy backend (if installed):\n", + " python sort_random.py --backend numpy\n", + "\n", + "- Use a different size:\n", + " python sort_random.py --n 500000\n", + "\n", + "Notes and tips:\n", + "- Pure Python uses random.random in a list comprehension, then list.sort(). Sorting a list of 1,000,000 Python floats is quite feasible but uses more memory than a NumPy array because of Python object overhead.\n", + "- NumPy's random generation and sorting are implemented in C and are typically much faster and more memory efficient for large numeric arrays.\n", + "- You can change the seed to get different random sequences, or omit seed for non-deterministic results.\n", + "- If you plan to sort data that doesn't fit in memory, consider external sorting approaches (merge sort with chunking to disk) or use specialized libraries.\n", + "Tokens => input: 21 | output: 2381\n" ] } ], @@ -662,7 +692,7 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 7, "id": "02d3f9d3", "metadata": {}, "outputs": [ @@ -670,7 +700,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "[ResponseReasoningItem(id='rs_6894d0c323d481a2b727907746def8ec03e38603225fe1bd', summary=[], type='reasoning', content=[], encrypted_content=None, status=None), ResponseOutputMessage(id='ctc_6894d0c4917881a29923bb525509b34003e38603225fe1bd', content=None, role=None, status='completed', type='custom_tool_call', call_id='call_1ACilrk0d1DISLvW4Q2iE0jc', input='# Calculate the area of a circle where radius = number of \\'r\\'s in \"strawberry\"\\nimport math\\nradius = \"strawberry\".count(\\'r\\')\\narea = math.pi * radius**2\\n{\"radius\": radius, \"area\": area, \"area_exact\": f\"{radius**2}*pi\"}', name='code_exec')]\n" + "[ResponseReasoningItem(id='rs_6894e31b1f8081999d18325e5aeffcfe0861a2e1728d1664', summary=[], type='reasoning', content=[], encrypted_content=None, status=None), ResponseCustomToolCall(call_id='call_Gnqod2MwPvayp2JdNyA0z0Ah', input='# Counting \\'r\\'s in the word \"strawberry\" and computing circle area with that radius\\nimport math\\nr = \"strawberry\".count(\\'r\\')\\narea = math.pi * r**2\\n{\"radius\": r, \"area\": area, \"area_exact\": f\"{r}*pi\"}', name='code_exec', type='custom_tool_call', id='ctc_6894e31c66f08199abd622bb5ac3c4260861a2e1728d1664', status='completed')]\n" ] } ], @@ -716,7 +746,7 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 8, "id": "2e9ca32e", "metadata": {}, "outputs": [ @@ -727,49 +757,51 @@ "--- tool name ---\n", "code_exec_python\n", "--- tool call argument (generated code) ---\n", - "arr_orig = [448, 986, 255, 884, 632, 623, 246, 439, 936, 925, 644, 159, 777, 986, 706, 723, 534, 862, 195, 686, 846, 880, 970, 276, 613, 736, 329, 622, 870, 284, 945, 708, 267, 327, 678, 807, 687, 890, 907, 645, 364, 333, 385, 262, 730, 603, 945, 358, 923, 930, 761, 504, 870, 561, 517, 928, 994, 949, 233, 137, 670, 555, 149, 870, 997, 809, 180, 498, 914, 508, 411, 378, 394, 368, 766, 486, 757, 319, 338, 159, 585, 934, 654, 194, 542, 188, 934, 163, 889, 736, 792, 737, 667, 772, 198, 971, 459, 402, 989, 949]\n", - "\n", "import time\n", "\n", - "start = time.perf_counter_ns()\n", + "arr = [448, 986, 255, 884, 632, 623, 246, 439, 936, 925, 644, 159, 777, 986, 706, 723, 534, 862, 195, 686, 846, 880, 970, 276, 613, 736, 329, 622, 870, 284, 945, 708, 267, 327, 678, 807, 687, 890, 907, 645, 364, 333, 385, 262, 730, 603, 945, 358, 923, 930, 761, 504, 870, 561, 517, 928, 994, 949, 233, 137, 670, 555, 149, 870, 997, 809, 180, 498, 914, 508, 411, 378, 394, 368, 766, 486, 757, 319, 338, 159, 585, 934, 654, 194, 542, 188, 934, 163, 889, 736, 792, 737, 667, 772, 198, 971, 459, 402, 989, 949]\n", + "\n", + "start = time.perf_counter()\n", "for _ in range(10):\n", - " arr = arr_orig.copy()\n", - " arr.sort()\n", - "elapsed_ms = (time.perf_counter_ns() - start) // 1_000_000\n", - "print(elapsed_ms)\n", + " b = arr[:] # copy\n", + " b.sort()\n", + "elapsed_ms = int((time.perf_counter() - start) * 1000)\n", + "print(elapsed_ms, end=\"\")\n", "--- tool name ---\n", "code_exec_cpp\n", "--- tool call argument (generated code) ---\n", - "#include \n", + "#include \n", "#include \n", + "#include \n", "#include \n", - "#include \n", + "using namespace std;\n", + "\n", "int main() {\n", - " std::vector orig = {448, 986, 255, 884, 632, 623, 246, 439, 936, 925, 644, 159, 777, 986, 706, 723, 534, 862, 195, 686, 846, 880, 970, 276, 613, 736, 329, 622, 870, 284, 945, 708, 267, 327, 678, 807, 687, 890, 907, 645, 364, 333, 385, 262, 730, 603, 945, 358, 923, 930, 761, 504, 870, 561, 517, 928, 994, 949, 233, 137, 670, 555, 149, 870, 997, 809, 180, 498, 914, 508, 411, 378, 394, 368, 766, 486, 757, 319, 338, 159, 585, 934, 654, 194, 542, 188, 934, 163, 889, 736, 792, 737, 667, 772, 198, 971, 459, 402, 989, 949};\n", - " auto start = std::chrono::steady_clock::now();\n", + " vector a = {448, 986, 255, 884, 632, 623, 246, 439, 936, 925, 644, 159, 777, 986, 706, 723, 534, 862, 195, 686, 846, 880, 970, 276, 613, 736, 329, 622, 870, 284, 945, 708, 267, 327, 678, 807, 687, 890, 907, 645, 364, 333, 385, 262, 730, 603, 945, 358, 923, 930, 761, 504, 870, 561, 517, 928, 994, 949, 233, 137, 670, 555, 149, 870, 997, 809, 180, 498, 914, 508, 411, 378, 394, 368, 766, 486, 757, 319, 338, 159, 585, 934, 654, 194, 542, 188, 934, 163, 889, 736, 792, 737, 667, 772, 198, 971, 459, 402, 989, 949};\n", + " auto start = chrono::high_resolution_clock::now();\n", " for (int i = 0; i < 10; ++i) {\n", - " auto arr = orig;\n", - " std::sort(arr.begin(), arr.end());\n", + " auto b = a;\n", + " sort(b.begin(), b.end());\n", " }\n", - " auto end = std::chrono::steady_clock::now();\n", - " auto ms = std::chrono::duration_cast(end - start).count();\n", - " std::cout << ms << std::endl;\n", + " auto end = chrono::high_resolution_clock::now();\n", + " auto ms = chrono::duration_cast(end - start).count();\n", + " cout << ms;\n", " return 0;\n", "}\n", "--- tool name ---\n", "code_exec_java\n", "--- tool call argument (generated code) ---\n", - "import java.util.Arrays;\n", + "import java.util.*;\n", "public class Main {\n", " public static void main(String[] args) {\n", - " int[] orig = new int[] {448, 986, 255, 884, 632, 623, 246, 439, 936, 925, 644, 159, 777, 986, 706, 723, 534, 862, 195, 686, 846, 880, 970, 276, 613, 736, 329, 622, 870, 284, 945, 708, 267, 327, 678, 807, 687, 890, 907, 645, 364, 333, 385, 262, 730, 603, 945, 358, 923, 930, 761, 504, 870, 561, 517, 928, 994, 949, 233, 137, 670, 555, 149, 870, 997, 809, 180, 498, 914, 508, 411, 378, 394, 368, 766, 486, 757, 319, 338, 159, 585, 934, 654, 194, 542, 188, 934, 163, 889, 736, 792, 737, 667, 772, 198, 971, 459, 402, 989, 949};\n", + " int[] a = new int[] {448, 986, 255, 884, 632, 623, 246, 439, 936, 925, 644, 159, 777, 986, 706, 723, 534, 862, 195, 686, 846, 880, 970, 276, 613, 736, 329, 622, 870, 284, 945, 708, 267, 327, 678, 807, 687, 890, 907, 645, 364, 333, 385, 262, 730, 603, 945, 358, 923, 930, 761, 504, 870, 561, 517, 928, 994, 949, 233, 137, 670, 555, 149, 870, 997, 809, 180, 498, 914, 508, 411, 378, 394, 368, 766, 486, 757, 319, 338, 159, 585, 934, 654, 194, 542, 188, 934, 163, 889, 736, 792, 737, 667, 772, 198, 971, 459, 402, 989, 949};\n", " long start = System.nanoTime();\n", " for (int i = 0; i < 10; i++) {\n", - " int[] arr = Arrays.copyOf(orig, orig.length);\n", - " Arrays.sort(arr);\n", + " int[] b = Arrays.copyOf(a, a.length);\n", + " Arrays.sort(b);\n", " }\n", - " long elapsedMs = (System.nanoTime() - start) / 1_000_000;\n", - " System.out.println(elapsedMs);\n", + " long elapsedMs = (System.nanoTime() - start) / 1_000_000L;\n", + " System.out.print(elapsedMs);\n", " }\n", "}\n" ] @@ -966,7 +998,7 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 9, "id": "c6e7f843", "metadata": {}, "outputs": [], @@ -1049,7 +1081,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 10, "id": "7e316744", "metadata": {}, "outputs": [ @@ -1105,7 +1137,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 11, "id": "e704a3f5", "metadata": {}, "outputs": [ @@ -1174,7 +1206,7 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 12, "id": "2f9e2fbd", "metadata": {}, "outputs": [ @@ -1258,6 +1290,77 @@ "\n", "Context-Free Grammar (CFG) support in GPT-5 lets you strictly constrain model output to match predefined syntax, ensuring only valid strings are generated. This is especially useful for enforcing programming language rules or custom formats, reducing post-processing and errors. By providing a precise grammar and clear tool description, you can make the model reliably stay within your target output structure." ] + }, + { + "cell_type": "markdown", + "id": "e061d81a", + "metadata": {}, + "source": [ + "## 4. Minimal Reasoning \n", + "\n", + "### 4.1 Overview \n", + "\n", + "GPT-5 now support for a new minimal reasoning effort. When using minimal reasoning effort, the model will output very few or no reasoning tokens. This is designed for use cases where developers want a very fast time-to-first-user-visible token. Note: If no reasoning effort is supplied, the default value is medium. " + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "cf5e7cae", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "--------------------------------\n", + "Output:\n", + "positive\n" + ] + } + ], + "source": [ + "from openai import OpenAI\n", + "\n", + "client = OpenAI()\n", + "\n", + "prompt = \"Classify sentiment of the review as positive|neutral|negative. Return one word only.\" \n", + "\n", + "\n", + "response = client.responses.create(\n", + " model=\"gpt-5\",\n", + " input= [{ 'role': 'developer', 'content': prompt }, \n", + " { 'role': 'user', 'content': 'The food that the restaurant was great! I recommend it to everyone.' }],\n", + " reasoning = {\n", + " \"effort\": \"minimal\"\n", + " },\n", + ")\n", + "\n", + "# Extract model's text output\n", + "output_text = \"\"\n", + "for item in response.output:\n", + " if hasattr(item, \"content\"):\n", + " for content in item.content:\n", + " if hasattr(content, \"text\"):\n", + " output_text += content.text\n", + "\n", + "# Token usage details\n", + "usage = response.usage\n", + "\n", + "print(\"--------------------------------\")\n", + "print(\"Output:\")\n", + "print(output_text)\n" + ] + }, + { + "cell_type": "markdown", + "id": "ca82847a", + "metadata": {}, + "source": [ + "### 4.2 Takeaways \n", + "\n", + "Minimal reasoning runs GPT-5 with few or no reasoning tokens to minimize latency and speed up time-to-first-token. Use it for deterministic, lightweight tasks (extraction, formatting, short rewrites, simple classification) where explanations aren’t needed. If you don’t specify effort, it defaults to medium—set minimal explicitly when you want speed over deliberation." + ] } ], "metadata": {