<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Social Media Analytics on Max Woolf&#39;s Blog</title>
    <link>https://minimaxir.com/tag/social-media-analytics/</link>
    <description>Recent content in Social Media Analytics on Max Woolf&#39;s Blog</description>
    <image>
      <title>Max Woolf&#39;s Blog</title>
      <url>https://minimaxir.com/android-chrome-512x512.png</url>
      <link>https://minimaxir.com/android-chrome-512x512.png</link>
    </image>
    <generator>Hugo</generator>
    <language>en</language>
    <copyright>Copyright Max Woolf © 2026</copyright>
    <lastBuildDate>Thu, 02 Jan 2025 09:30:00 -0800</lastBuildDate>
    <atom:link href="https://minimaxir.com/tag/social-media-analytics/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Can LLMs write better code if you keep asking them to “write better code”?</title>
      <link>https://minimaxir.com/2025/01/write-better-code/</link>
      <pubDate>Thu, 02 Jan 2025 09:30:00 -0800</pubDate>
      <guid>https://minimaxir.com/2025/01/write-better-code/</guid>
      <description>Most coders want AI to write code faster: I want AI to write FASTER CODE.</description>
      <content:encoded><![CDATA[<p><span><style type="text/css">
pre code.language-txt {
white-space: pre-wrap !important;
word-break: normal !important;
}
</style></span></p>
<p>In November 2023, after OpenAI <a href="https://openai.com/index/dall-e-3-is-now-available-in-chatgpt-plus-and-enterprise/">added the ability</a> for ChatGPT to generate images from DALL-E 3 within the ChatGPT web interface, there was a <a href="https://lifehacker.com/tech/chat-gpt-make-it-more-ai-images-trend">short-lived meme</a> where users gave the LLM a base image and kept asking the model to &ldquo;make it more <em>X</em>&rdquo;, where <em>X</em> can be anything.</p>
<figure class="align-center ">

    <img loading="lazy" srcset="/2025/01/write-better-code/bro_hu_484c0ff30035ba2e.webp 320w,/2025/01/write-better-code/bro_hu_1162a7c634b35f7.webp 768w,/2025/01/write-better-code/bro_hu_9070d4b543cab815.webp 1024w,/2025/01/write-better-code/bro.webp 1024w" src="bro.webp#center"
         alt="A regular guy becomes more &ldquo;bro&rdquo; every time. via /u/Jojop0tato on Reddit."/> <figcaption>
            <p>A regular guy becomes more &ldquo;bro&rdquo; every time. <a href="https://www.reddit.com/r/ChatGPT/comments/18ukiz2/a_regular_guy_becomes_more_bro_every_time/">via /u/Jojop0tato on Reddit.</a></p>
        </figcaption>
</figure>

<figure class="align-center ">

    <img loading="lazy" srcset="/2025/01/write-better-code/santa_hu_1f046d64f5543bd.webp 320w,/2025/01/write-better-code/santa_hu_e0db183e83b65311.webp 768w,/2025/01/write-better-code/santa_hu_5d66897100afbdbf.webp 1024w,/2025/01/write-better-code/santa.webp 1024w" src="santa.webp#center"
         alt="Asked ChatGPT to make Santa Claus more and more serious. via /u/hessihan on Reddit."/> <figcaption>
            <p>Asked ChatGPT to make Santa Claus more and more serious. <a href="https://www.reddit.com/r/ChatGPT/comments/1887z49/asked_chatgpt_to_make_santa_claus_more_and_more/">via /u/hessihan on Reddit.</a></p>
        </figcaption>
</figure>

<p>The trend quickly died as all of these images were very samey and uninteresting, aside from the unexplainable trend that all of the examples eventually converged into something cosmic, irrespective of the starting image and the prompt. Although the trend was <a href="https://en.wikipedia.org/wiki/AI_slop">AI slop</a> before the term AI slop was codified, it&rsquo;s still academically interesting that such a meaningless and vague prompt had <em>some</em> appropriate impact on the final image, and that this change was obvious to the user.</p>
<p>What would happen if we tried a similar technique with code? LLM-generated code is unlikely to be slop (although <a href="https://daniel.haxx.se/blog/2024/01/02/the-i-in-llm-stands-for-intelligence/">not impossible</a>) as it follows strict rules, and unlike creative outputs such as images, code quality can be measured more objectively.</p>
<p>If code can indeed be improved simply through iterative prompting such as asking the LLM to &ldquo;make the code better&rdquo; — even though it&rsquo;s very silly — it would be a massive productivity increase. And if that&rsquo;s the case, what happens if you iterate on the code too much? What&rsquo;s the equivalent of code going cosmic? There&rsquo;s only one way to find out!</p>
<h2 id="casually-coding-with-an-llm">Casually Coding With An LLM</h2>
<p>Despite researching and developing tooling around LLMs even long before ChatGPT, I haven&rsquo;t been fond of using LLM code copilots such as <a href="https://github.com/features/copilot">GitHub Copilot</a> for coding assistance. The constant mental context switching between &ldquo;oh, the LLM autocompleted my code, neat&rdquo;/&ldquo;what question should I ask the LLM&rdquo; and &ldquo;is the LLM-generated code is actually <em>correct</em> and not <a href="https://en.wikipedia.org/wiki/Hallucination_%28artificial_intelligence%29">hallucinating</a> correct code&rdquo; kept creating enough distractions that any productivity gains from using the AI were net neutral at best. That&rsquo;s also disregarding the expensive cost of using said LLMs.</p>
<p><a href="https://www.anthropic.com/news/claude-3-5-sonnet">Claude 3.5 Sonnet</a> has made me rethink things. Due to whatever secret sauce <a href="https://www.anthropic.com">Anthropic</a> used in its training, the latest version of Claude 3.5 Sonnet (<code>claude-3-5-sonnet-20241022</code>) has <em>incredible</em> prompt adherence for all types of prompts, especially coding prompts. <a href="https://www.vellum.ai/blog/llm-benchmarks-overview-limits-and-model-comparison">Coding</a> <a href="https://aider.chat/docs/leaderboards/">benchmarks</a> confirm that testing between Claude 3.5 Sonnet and GPT-4o, Claude wins, and anecdotally I&rsquo;ve had the same experience across a variety of technical and creative tasks.</p>
<h3 id="initial-ask">Initial Ask</h3>
<p>For this experiment, we will give Claude 3.5 Sonnet an interview-style coding prompt using Python: one that is both simple and could be implemented by a novice software engineer, but one that can be heavily optimized. This simple, casual prompt represents how the typical software engineer uses LLMs. Additionally, the test prompt must also be wholly original and not taken from coding tests such as <a href="https://leetcode.com">LeetCode</a> or <a href="https://www.hackerrank.com">HackerRank</a>, as LLMs were also likely trained on those and could possibly cheat by reciting the memorized answer.</p>
<blockquote>
<p>The full, unedited conversation thread based on this casual prompting is <a href="https://github.com/minimaxir/llm-write-better-code/blob/main/python_30_casual_use.md">available on GitHub</a>.</p>
</blockquote>
<p>Therefore, here&rsquo;s the test prompt that I&rsquo;ve written myself:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">Write Python code to solve this problem:
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Given a list of 1 million random integers between 1 and 100,000, find the difference between the smallest and the largest numbers whose digits sum up to 30.
</span></span></code></pre></div><p>Providing that as the user prompt to the Claude API and setting <code>temperature=0</code> for the best/most deterministic answer <sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup>, results in this implementation:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">random</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">digit_sum</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Calculate the sum of digits of a number&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="nb">sum</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">digit</span><span class="p">)</span> <span class="k">for</span> <span class="n">digit</span> <span class="ow">in</span> <span class="nb">str</span><span class="p">(</span><span class="n">n</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">find_difference</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Generate list of 1 million random integers</span>
</span></span><span class="line"><span class="cl">    <span class="n">numbers</span> <span class="o">=</span> <span class="p">[</span><span class="n">random</span><span class="o">.</span><span class="n">randint</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">100000</span><span class="p">)</span> <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1000000</span><span class="p">)]</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Initialize variables for min and max numbers with digit sum 30</span>
</span></span><span class="line"><span class="cl">    <span class="n">min_num</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="s1">&#39;inf&#39;</span><span class="p">)</span>  <span class="c1"># Initialize to positive infinity</span>
</span></span><span class="line"><span class="cl">    <span class="n">max_num</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="s1">&#39;-inf&#39;</span><span class="p">)</span>  <span class="c1"># Initialize to negative infinity</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Find numbers whose digits sum to 30</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">num</span> <span class="ow">in</span> <span class="n">numbers</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="n">digit_sum</span><span class="p">(</span><span class="n">num</span><span class="p">)</span> <span class="o">==</span> <span class="mi">30</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="n">min_num</span> <span class="o">=</span> <span class="nb">min</span><span class="p">(</span><span class="n">min_num</span><span class="p">,</span> <span class="n">num</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">            <span class="n">max_num</span> <span class="o">=</span> <span class="nb">max</span><span class="p">(</span><span class="n">max_num</span><span class="p">,</span> <span class="n">num</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Check if we found any numbers with digit sum 30</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">min_num</span> <span class="o">==</span> <span class="nb">float</span><span class="p">(</span><span class="s1">&#39;inf&#39;</span><span class="p">)</span> <span class="ow">or</span> <span class="n">max_num</span> <span class="o">==</span> <span class="nb">float</span><span class="p">(</span><span class="s1">&#39;-inf&#39;</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="s2">&#34;No numbers found with digit sum of 30&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">max_num</span> <span class="o">-</span> <span class="n">min_num</span>
</span></span></code></pre></div><p><a href="https://github.com/minimaxir/llm-write-better-code/blob/main/python_30_casual_use.md#assistant-initial-ask">This implementation</a> is correct and consistent with what most novice Python programmers would write, with bonus handling if there are no valid numbers that fit the criteria. For each number in the list, check whether the digits sum to 30: if so, check whether it&rsquo;s larger than the most-recently-seen largest number or smaller than the most-recently-seen smallest number and update those variables accordingly. After searching through the list, return the difference.</p>
<p>But I&rsquo;m sure many coders reading that implementation got <a href="https://xkcd.com/356/">nerd sniped</a> and are thinking about optimizations. One example is the <code>digit_sum()</code> function: although the implementation is a fun Pythonic one-liner, the type-casting between <code>str</code> and <code>int</code> causes a lot of unnecessary overhead.</p>
<p>On my M3 Pro Macbook Pro, this code takes on average <strong>657 milliseconds</strong> to run. We&rsquo;ll use this performance as a baseline to compare future implementations to see how they benchmark relative to it. (spoilers: they&rsquo;re <em>all</em> faster)</p>
<h3 id="iteration-1">Iteration #1</h3>
<p>Now we can ask Claude to improve the code by including its current answer and all that came before it as a part of the conversation prompt. Thus, we add the iteration prompt:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">write better code
</span></span></code></pre></div><p>What, you though the title of this blog post was a joke? I <em>never</em> joke.</p>
<p>Claude <a href="https://github.com/minimaxir/llm-write-better-code/blob/main/python_30_casual_use.md#assistant-iteration-1">now outputs</a> revised code, or as it says, &ldquo;optimized version of the code with several improvements.&rdquo; Instead of colocating all the code in functions, it decided to refactor it into a Python <code>class</code> and made it more object-oriented:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">DigitSumFinder</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">target_sum</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">30</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                 <span class="n">range_start</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                 <span class="n">range_end</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">100_000</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                 <span class="n">count</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">1_000_000</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">target_sum</span> <span class="o">=</span> <span class="n">target_sum</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">range_start</span> <span class="o">=</span> <span class="n">range_start</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">range_end</span> <span class="o">=</span> <span class="n">range_end</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">count</span> <span class="o">=</span> <span class="n">count</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="c1"># Pre-calculate digit sums for all possible numbers</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">digit_sums</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_precompute_digit_sums</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">_precompute_digit_sums</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">array</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;&#34;&#34;Precompute digit sums for all possible numbers in range.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="n">digit_sums</span> <span class="o">=</span> <span class="n">array</span><span class="p">(</span><span class="s1">&#39;B&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">*</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">range_end</span> <span class="o">+</span> <span class="mi">1</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">        <span class="k">for</span> <span class="n">num</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">range_start</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">range_end</span> <span class="o">+</span> <span class="mi">1</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">            <span class="n">total</span> <span class="o">=</span> <span class="mi">0</span>
</span></span><span class="line"><span class="cl">            <span class="n">n</span> <span class="o">=</span> <span class="n">num</span>
</span></span><span class="line"><span class="cl">            <span class="k">while</span> <span class="n">n</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">                <span class="n">total</span> <span class="o">+=</span> <span class="n">n</span> <span class="o">%</span> <span class="mi">10</span>
</span></span><span class="line"><span class="cl">                <span class="n">n</span> <span class="o">//=</span> <span class="mi">10</span>
</span></span><span class="line"><span class="cl">            <span class="n">digit_sums</span><span class="p">[</span><span class="n">num</span><span class="p">]</span> <span class="o">=</span> <span class="n">total</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="n">digit_sums</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">find_difference</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Tuple</span><span class="p">[</span><span class="nb">int</span><span class="p">,</span> <span class="n">Optional</span><span class="p">[</span><span class="nb">int</span><span class="p">],</span> <span class="n">Optional</span><span class="p">[</span><span class="nb">int</span><span class="p">]]:</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;&#34;&#34;
</span></span></span><span class="line"><span class="cl"><span class="s2">        Find the difference between max and min numbers with target digit sum.
</span></span></span><span class="line"><span class="cl"><span class="s2">        Returns: (difference, min_number, max_number)
</span></span></span><span class="line"><span class="cl"><span class="s2">        &#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="n">min_num</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="s1">&#39;inf&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">max_num</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="s1">&#39;-inf&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">count_found</span> <span class="o">=</span> <span class="mi">0</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="c1"># Generate and process random numbers</span>
</span></span><span class="line"><span class="cl">        <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">count</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">            <span class="n">num</span> <span class="o">=</span> <span class="n">random</span><span class="o">.</span><span class="n">randint</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">range_start</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">range_end</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">            <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">digit_sums</span><span class="p">[</span><span class="n">num</span><span class="p">]</span> <span class="o">==</span> <span class="bp">self</span><span class="o">.</span><span class="n">target_sum</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">                <span class="n">count_found</span> <span class="o">+=</span> <span class="mi">1</span>
</span></span><span class="line"><span class="cl">                <span class="k">if</span> <span class="n">num</span> <span class="o">&lt;</span> <span class="n">min_num</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">                    <span class="n">min_num</span> <span class="o">=</span> <span class="n">num</span>
</span></span><span class="line"><span class="cl">                <span class="k">if</span> <span class="n">num</span> <span class="o">&gt;</span> <span class="n">max_num</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">                    <span class="n">max_num</span> <span class="o">=</span> <span class="n">num</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="n">count_found</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="k">return</span> <span class="mi">0</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="n">max_num</span> <span class="o">-</span> <span class="n">min_num</span><span class="p">,</span> <span class="n">min_num</span><span class="p">,</span> <span class="n">max_num</span>
</span></span></code></pre></div><p>Here, the code does two smart algorithmic improvements:</p>
<ul>
<li>When computing the digit sum it uses integer operations and avoids the need for the type-casting mentioned previously.</li>
<li>It precomputes all possible digit sums and stores them in a byte array (somewhat unusual instead of a list) for lookup, meaning that the digit sum will not need to be recalculated when there are duplicates in the one-million-number-list. Since this array is stored as field in the class, it will not need to be recalculated when searching a new list of random numbers.</li>
</ul>
<p>These optimizations speed up the code <strong>2.7x</strong> relative to the initial implementation.</p>
<h3 id="iteration-2">Iteration #2</h3>
<p>After another <code>write better code</code>, Claude <a href="https://github.com/minimaxir/llm-write-better-code/blob/main/python_30_casual_use.md#assistant-iteration-2">discovers</a> more obvious optimizations (truncated for readabilty):</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">DigitSumAnalyzer</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Analyzes numbers based on their digit sums.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">number_range</span><span class="p">:</span> <span class="n">NumberRange</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">number_range</span> <span class="o">=</span> <span class="n">number_range</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">_digit_sums</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_precompute_digit_sums</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">_precompute_digit_sums</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">array</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;&#34;&#34;Precompute digit sums for all possible numbers using vectorized operations.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="n">digits</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">number_range</span><span class="o">.</span><span class="n">end</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">digit_sums</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">number_range</span><span class="o">.</span><span class="n">end</span> <span class="o">+</span> <span class="mi">1</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">uint8</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="k">while</span> <span class="n">digits</span><span class="o">.</span><span class="n">any</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">            <span class="n">digit_sums</span> <span class="o">+=</span> <span class="n">digits</span> <span class="o">%</span> <span class="mi">10</span>
</span></span><span class="line"><span class="cl">            <span class="n">digits</span> <span class="o">//=</span> <span class="mi">10</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="n">array</span><span class="p">(</span><span class="s1">&#39;B&#39;</span><span class="p">,</span> <span class="n">digit_sums</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">_process_chunk</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">chunk_size</span><span class="p">:</span> <span class="nb">int</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Iterator</span><span class="p">[</span><span class="nb">int</span><span class="p">]:</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;&#34;&#34;Process a chunk of random numbers.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="n">numbers</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randint</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">            <span class="bp">self</span><span class="o">.</span><span class="n">number_range</span><span class="o">.</span><span class="n">start</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">            <span class="bp">self</span><span class="o">.</span><span class="n">number_range</span><span class="o">.</span><span class="n">end</span> <span class="o">+</span> <span class="mi">1</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">            <span class="n">chunk_size</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">            <span class="n">dtype</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">int32</span>
</span></span><span class="line"><span class="cl">        <span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">mask</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">frombuffer</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_digit_sums</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">uint8</span><span class="p">)[</span><span class="n">numbers</span><span class="p">]</span> <span class="o">==</span> <span class="bp">self</span><span class="o">.</span><span class="n">number_range</span><span class="o">.</span><span class="n">target_sum</span>
</span></span><span class="line"><span class="cl">        <span class="k">yield from</span> <span class="n">numbers</span><span class="p">[</span><span class="n">mask</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">analyze</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">chunk_size</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">100_000</span><span class="p">,</span> <span class="n">num_processes</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="kc">None</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Result</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;&#34;&#34;
</span></span></span><span class="line"><span class="cl"><span class="s2">        Analyze numbers to find min/max with target digit sum.
</span></span></span><span class="line"><span class="cl"><span class="s2">
</span></span></span><span class="line"><span class="cl"><span class="s2">        Args:
</span></span></span><span class="line"><span class="cl"><span class="s2">            chunk_size: Size of chunks to process at once
</span></span></span><span class="line"><span class="cl"><span class="s2">            num_processes: Number of processes to use (None for CPU count)
</span></span></span><span class="line"><span class="cl"><span class="s2">        &#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="n">start_time</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">perf_counter</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">        <span class="n">min_num</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="s1">&#39;inf&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">max_num</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="s1">&#39;-inf&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">numbers_found</span> <span class="o">=</span> <span class="mi">0</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="n">num_chunks</span> <span class="o">=</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">number_range</span><span class="o">.</span><span class="n">count</span> <span class="o">+</span> <span class="n">chunk_size</span> <span class="o">-</span> <span class="mi">1</span><span class="p">)</span> <span class="o">//</span> <span class="n">chunk_size</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="k">with</span> <span class="n">ProcessPoolExecutor</span><span class="p">(</span><span class="n">max_workers</span><span class="o">=</span><span class="n">num_processes</span><span class="p">)</span> <span class="k">as</span> <span class="n">executor</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="n">futures</span> <span class="o">=</span> <span class="p">[</span>
</span></span><span class="line"><span class="cl">                <span class="n">executor</span><span class="o">.</span><span class="n">submit</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_process_chunk</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                              <span class="nb">min</span><span class="p">(</span><span class="n">chunk_size</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">number_range</span><span class="o">.</span><span class="n">count</span> <span class="o">-</span> <span class="n">i</span> <span class="o">*</span> <span class="n">chunk_size</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">                <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">num_chunks</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">            <span class="p">]</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">            <span class="k">for</span> <span class="n">future</span> <span class="ow">in</span> <span class="n">tqdm</span><span class="p">(</span><span class="n">futures</span><span class="p">,</span> <span class="n">desc</span><span class="o">=</span><span class="s2">&#34;Processing chunks&#34;</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">                <span class="k">for</span> <span class="n">num</span> <span class="ow">in</span> <span class="n">future</span><span class="o">.</span><span class="n">result</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">                    <span class="n">numbers_found</span> <span class="o">+=</span> <span class="mi">1</span>
</span></span><span class="line"><span class="cl">                    <span class="n">min_num</span> <span class="o">=</span> <span class="nb">min</span><span class="p">(</span><span class="n">min_num</span><span class="p">,</span> <span class="n">num</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">                    <span class="n">max_num</span> <span class="o">=</span> <span class="nb">max</span><span class="p">(</span><span class="n">max_num</span><span class="p">,</span> <span class="n">num</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="n">execution_time</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">perf_counter</span><span class="p">()</span> <span class="o">-</span> <span class="n">start_time</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="n">numbers_found</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="k">return</span> <span class="n">Result</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">execution_time</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="n">Result</span><span class="p">(</span><span class="n">min_num</span><span class="p">,</span> <span class="n">max_num</span><span class="p">,</span> <span class="n">max_num</span> <span class="o">-</span> <span class="n">min_num</span><span class="p">,</span> <span class="n">execution_time</span><span class="p">,</span> <span class="n">numbers_found</span><span class="p">)</span>
</span></span></code></pre></div><p>Claude now has added two more optimizations, finally realizing that this coding problem is an <a href="https://en.wikipedia.org/wiki/Embarrassingly_parallel">embarrassingly parallel</a> problem:</p>
<ul>
<li>Multithreading through Python&rsquo;s <a href="https://docs.python.org/3/library/concurrent.futures.html">concurrent-futures</a> package, by separating the large list into chunks that can be processed independently.</li>
<li>Vectorized numpy operations, which are <em>much</em> faster than base-Python operations. Special mention goes to the <code>_precompute_digit_sums()</code> function, which implements a vectorized implementation of calculating the digit sums. The conditional <code>while digits.any():</code> is galaxy-brain code, but it works correctly.</li>
</ul>
<p>However, there&rsquo;s an issue with this particular implementation of parallelization: it generates subprocesses, which causes <em>many</em> annoying issues, including being unable to run it as-is inline, and it <a href="https://stackoverflow.com/questions/15900366/all-example-concurrent-futures-code-is-failing-with-brokenprocesspool">must be invoked</a> with a <code>main()</code> guard which limits its utility significantly. But even when run as a separate script, it prints a <code>Error: cannot pickle 'generator' object</code> error due to the use of <code>yield from numbers[mask]</code> (said generator is completely unnecessary, <code>return numbers[mask]</code> is sufficient). The code also mixes numpy array <code>dtype</code>s which causes errors: setting them all to <code>np.int32</code> fixes it.</p>
<p>After making those fixes, the code is now <strong>5.1x faster</strong> than the base implementation.</p>
<h3 id="iteration-3">Iteration #3</h3>
<p>Another <code>write better code</code>, and Claude <a href="https://github.com/minimaxir/llm-write-better-code/blob/main/python_30_casual_use.md#assistant-iteration-3">returns a implementation</a> that it claims is &ldquo;even more sophisticated and optimized version using advanced techniques and modern Python features&rdquo; but the actual code shows no significant algorithmic improvements and actually a regression in the digit sum calculation by reverting back to the type-casting approach. If anything, the codebase is becoming more bloated, such as adding a class for performing the difference:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="nd">@dataclass</span><span class="p">(</span><span class="n">frozen</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">slots</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">SearchResult</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Result of the number search.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">min_number</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="nb">int</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">    <span class="n">max_number</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="nb">int</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">    <span class="n">count</span><span class="p">:</span> <span class="nb">int</span>
</span></span><span class="line"><span class="cl">    <span class="n">execution_time</span><span class="p">:</span> <span class="nb">float</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="nd">@property</span>
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">difference</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Optional</span><span class="p">[</span><span class="nb">int</span><span class="p">]:</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;&#34;&#34;Calculate difference between max and min numbers.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">min_number</span> <span class="ow">is</span> <span class="kc">None</span> <span class="ow">or</span> <span class="bp">self</span><span class="o">.</span><span class="n">max_number</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="k">return</span> <span class="kc">None</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">max_number</span> <span class="o">-</span> <span class="bp">self</span><span class="o">.</span><span class="n">min_number</span>
</span></span></code></pre></div><p>This time, the code ran without needing any fixes. However, performance regressed slightly from the previous implementation, now <strong>4.1x faster</strong> than the base implementation.</p>
<h3 id="iteration-4">Iteration #4</h3>
<p>This iterative prompting appears to be hitting diminishing returns. After one more <code>write better code</code>, Claude <a href="https://github.com/minimaxir/llm-write-better-code/blob/main/python_30_casual_use.md#assistant-iteration-4">provides an implementation</a> &ldquo;with cutting-edge optimizations and enterprise-level features.&rdquo; Wait, enterprise-level features?!</p>
<p>The final code is too large to include in this blog post, but it did create two more optimizations: it now uses the <a href="https://numba.pydata.org">numba</a> Python library that can invoke a JIT compiler, which directly optimizes the code for the CPU. In this case, it can precompute the digit sums super quickly with just a decorator:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="nd">@jit</span><span class="p">(</span><span class="n">nopython</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">parallel</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">calculate_digit_sums</span><span class="p">(</span><span class="n">numbers</span><span class="p">:</span> <span class="n">ArrayInt</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">ArrayInt</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Calculate digit sums using Numba.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">result</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros_like</span><span class="p">(</span><span class="n">numbers</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">prange</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">numbers</span><span class="p">)):</span>
</span></span><span class="line"><span class="cl">        <span class="n">num</span> <span class="o">=</span> <span class="n">numbers</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">        <span class="n">total</span> <span class="o">=</span> <span class="mi">0</span>
</span></span><span class="line"><span class="cl">        <span class="k">while</span> <span class="n">num</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="n">total</span> <span class="o">+=</span> <span class="n">num</span> <span class="o">%</span> <span class="mi">10</span>
</span></span><span class="line"><span class="cl">            <span class="n">num</span> <span class="o">//=</span> <span class="mi">10</span>
</span></span><span class="line"><span class="cl">        <span class="n">result</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">total</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">result</span>
</span></span></code></pre></div><p>The full class also uses Python&rsquo;s <a href="https://docs.python.org/3/library/asyncio.html">asyncio</a> for parallelization, which is more canonical for scheduling tasks than a subprocess approach. It also plays more nicely with existing inline code and a <a href="https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop">REPL</a> such as <a href="https://jupyter.org">Jupyter Notebooks</a>.</p>
<p>It also added as a part of its &ldquo;enterprise&rdquo; push:</p>
<ul>
<li>Structured metrics logging with <a href="https://prometheus.io">Prometheus</a>.</li>
<li>A signal handler so the code can be torn down gracefully if force-killed.</li>
<li>A benchmarking result display using a <a href="https://github.com/Textualize/rich">rich</a> table.</li>
</ul>
<figure>

    <img loading="lazy" srcset="/2025/01/write-better-code/rich_hu_1cc271f7a31e0c53.webp 320w,/2025/01/write-better-code/rich.png 490w" src="rich.png"
         alt="It is pretty, though!"/> <figcaption>
            <p>It <em>is</em> pretty, though!</p>
        </figcaption>
</figure>

<p>It appears &ldquo;going cosmic&rdquo; for AI-generated code is making it enterprise by overengineering the code, which makes complete sense. Despite that, the code runs as-is without any bugs. Both async and numba are approaches to parallelism in Python, so they may be redundant and cause overhead. However, after benchmarking, the algorithm is <em>extremely</em> fast, resulting in about 6 milliseconds a run, or a <strong>100x</strong> speedup. My assumption that this prompting was hitting diminishing returns aged very poorly. Maybe numba was the secret all along?</p>
<p>Overall, this form of iterative prompting to iteratively improve code has caveats: the code is indeed better, but in hindsight &ldquo;better&rdquo; is far too open ended. What I only wanted was algorithmic improvements, not a full SaaS. Let&rsquo;s try again from scratch, this time with more direction.</p>
<h2 id="prompt-engineering-llms-for-even-more-better-code">Prompt Engineering LLMs For Even More Better Code</h2>
<p>It&rsquo;s 2025, and prompt engineering LLMs is still required to get best results from them. If anything, prompt engineering LLMs is <em>even more important</em>: next-token-prediction models are trained to maximimize the prediction probability of the next token over massive batches of inputs, and as a result they optimize for the <strong>average</strong> inputs and outputs. As LLMs drastically improve, the generated output becomes more drastically average, because that&rsquo;s what they were trained to do: all LLMs are biased towards the average. Although it&rsquo;s both counterintuitive and unfun, a small amount of guidance asking the LLM specifically what you want, and even giving a few examples of what you want, will objectively improve the output of LLMs more than the effort needed to construct said prompts. Claude 3.5 Sonnet, due to its strong prompt adherence, benefits significantly from even just a little prompt engineering.</p>
<p>Let&rsquo;s redo the code optimization experiment, this time with aggressive prompt engineering that makes the results I am looking for extremely explicit, with no room for ambiguity. Yes, being cold and &ldquo;robotic&rdquo; to LLMs makes them perform better, <a href="https://en.wikipedia.org/wiki/Roko%27s_basilisk">Roko&rsquo;s basilisk</a> be damned.</p>
<h3 id="initial-ask-1">Initial Ask</h3>
<p>This time we will use a system prompt, only available via an API. The system prompt lists the LLM&rsquo;s &ldquo;rules&rdquo; it must follow. Since I want more optimized code, we&rsquo;ll define that in the rules, with granular examples:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">All code you write MUST be fully optimized.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">&#34;Fully optimized&#34; includes:
</span></span><span class="line"><span class="cl">- maximizing algorithmic big-O efficiency for memory and runtime
</span></span><span class="line"><span class="cl">- using parallelization and vectorization where appropriate
</span></span><span class="line"><span class="cl">- following proper style conventions for the code language (e.g. maximizing code reuse (DRY))
</span></span><span class="line"><span class="cl">- no extra code beyond what is absolutely necessary to solve the problem the user provides (i.e. no technical debt)
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">If the code is not fully optimized, you will be fined $100.
</span></span></code></pre></div><p>About that last line: offering positive/negative incentives in to the LLM within a system prompt isn&rsquo;t common anymore and <a href="https://minimaxir.com/2024/02/chatgpt-tips-analysis/">my own research</a> indicated that it was unclear whether it had a positive impact, but that fine will become more relevant in the iteration prompt.</p>
<p>The initial user prompt has an additional line as well:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">Write Python code to solve this problem:
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Given a list of 1 million random integers between 1 and 100,000, find the difference between the smallest and the largest numbers whose digits sum up to 30.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Before writing the code, plan out all the necessary optimizations.
</span></span></code></pre></div><p>&ldquo;Planning&rdquo; is a long-used trick to help align LLM output for a first pass — the modern implementation of &ldquo;<a href="https://arxiv.org/abs/2205.11916">let&rsquo;s think step by step</a>.&rdquo; Some LLMs ignore it, but Claude 3.5 Sonnet always obeys.</p>
<blockquote>
<p>The full, unedited conversation thread based on this prompt engineering strategy is <a href="https://github.com/minimaxir/llm-write-better-code/blob/main/python_30_prompt_engineering.md">available on GitHub</a>.</p>
</blockquote>
<p>Sending the system prompt and this user prompt to Claude, the <a href="https://github.com/minimaxir/llm-write-better-code/blob/main/python_30_prompt_engineering.md#assistant-initial-ask">response</a> starts with this:</p>
<!-- prettier-ignore-start -->
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">Let me plan the optimizations first:
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">1. Algorithmic Optimization:
</span></span><span class="line"><span class="cl">- We only need to track min and max numbers with digit sum 30, not store all of them
</span></span><span class="line"><span class="cl">- We can calculate digit sum while reading numbers, no need to convert to string
</span></span><span class="line"><span class="cl">- Single pass through the list required (O(n))
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">2. Memory Optimization:
</span></span><span class="line"><span class="cl">- Only need to store 2 variables (min and max), not the full filtered list
</span></span><span class="line"><span class="cl">- No need for additional data structures
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">3. Performance Optimization:
</span></span><span class="line"><span class="cl">- Use numba&#39;s @jit decorator for faster computation
</span></span><span class="line"><span class="cl">- Create a fast digit sum function using modulo operations instead of string conversion
</span></span><span class="line"><span class="cl">- Use numpy for generating random numbers (faster than random.randint)
</span></span></code></pre></div><!-- prettier-ignore-end -->
<p>This is promising: Claude immediately figured out it should start out with numpy and numba, and to also use integer operations to calculate the digit sum. The initial implementation:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="nd">@jit</span><span class="p">(</span><span class="n">nopython</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">digit_sum</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="n">total</span> <span class="o">=</span> <span class="mi">0</span>
</span></span><span class="line"><span class="cl">    <span class="k">while</span> <span class="n">n</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="n">total</span> <span class="o">+=</span> <span class="n">n</span> <span class="o">%</span> <span class="mi">10</span>
</span></span><span class="line"><span class="cl">        <span class="n">n</span> <span class="o">//=</span> <span class="mi">10</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">total</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nd">@jit</span><span class="p">(</span><span class="n">nopython</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">find_difference</span><span class="p">(</span><span class="n">numbers</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="n">min_num</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="s1">&#39;inf&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">max_num</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="s1">&#39;-inf&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">num</span> <span class="ow">in</span> <span class="n">numbers</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="n">sum_digits</span> <span class="o">=</span> <span class="n">digit_sum</span><span class="p">(</span><span class="n">num</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="n">sum_digits</span> <span class="o">==</span> <span class="mi">30</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="n">min_num</span> <span class="o">=</span> <span class="nb">min</span><span class="p">(</span><span class="n">min_num</span><span class="p">,</span> <span class="n">num</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">            <span class="n">max_num</span> <span class="o">=</span> <span class="nb">max</span><span class="p">(</span><span class="n">max_num</span><span class="p">,</span> <span class="n">num</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">max_num</span> <span class="o">-</span> <span class="n">min_num</span> <span class="k">if</span> <span class="n">max_num</span> <span class="o">!=</span> <span class="nb">float</span><span class="p">(</span><span class="s1">&#39;-inf&#39;</span><span class="p">)</span> <span class="k">else</span> <span class="mi">0</span>
</span></span></code></pre></div><p>That&rsquo;s more concise than the initial implementation from casual prompting, especially with no unnecessary comments. There&rsquo;s still room for improvement, notably this implementation did not set <code>parallel=True</code> in the <code>jit</code> decorator.</p>
<p>This minor use of prompt engineering resulted in code that runs in 11.2 milliseconds on average, or <strong>59x faster</strong> than the naive implementation. Wow!</p>
<h3 id="iteration-1-1">Iteration #1</h3>
<p>We can now ask Claude to iterate on the code with a more verbose prompt than &ldquo;write code better&rdquo;:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">Your code is not fully optimized, and you have been fined $100. Make it more optimized.
</span></span></code></pre></div><p>No, it&rsquo;s not gaslighting, it&rsquo;s <em>incentive alignment</em>.</p>
<p>Claude <a href="https://github.com/minimaxir/llm-write-better-code/blob/main/python_30_prompt_engineering.md#assistant-iteration-1">responds</a> with this:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="nd">@jit</span><span class="p">(</span><span class="n">nopython</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">digit_sum</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Using bit manipulation for faster division</span>
</span></span><span class="line"><span class="cl">    <span class="n">total</span> <span class="o">=</span> <span class="mi">0</span>
</span></span><span class="line"><span class="cl">    <span class="k">while</span> <span class="n">n</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="n">total</span> <span class="o">+=</span> <span class="n">n</span> <span class="o">&amp;</span> <span class="mi">15</span>  <span class="c1"># Fast lookup for single digit sum</span>
</span></span><span class="line"><span class="cl">        <span class="n">n</span> <span class="o">&gt;&gt;=</span> <span class="mi">4</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">total</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nd">@jit</span><span class="p">(</span><span class="n">nopython</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">parallel</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">find_difference_chunk</span><span class="p">(</span><span class="n">numbers</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="n">min_num</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">iinfo</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">int64</span><span class="p">)</span><span class="o">.</span><span class="n">max</span>
</span></span><span class="line"><span class="cl">    <span class="n">max_num</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">iinfo</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">int64</span><span class="p">)</span><span class="o">.</span><span class="n">min</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Parallel processing of chunks using numba</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">prange</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">numbers</span><span class="p">)):</span>
</span></span><span class="line"><span class="cl">        <span class="n">num</span> <span class="o">=</span> <span class="n">numbers</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">        <span class="n">sum_digits</span> <span class="o">=</span> <span class="n">digit_sum</span><span class="p">(</span><span class="n">num</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="n">sum_digits</span> <span class="o">==</span> <span class="mi">30</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="n">min_num</span> <span class="o">=</span> <span class="nb">min</span><span class="p">(</span><span class="n">min_num</span><span class="p">,</span> <span class="n">num</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">            <span class="n">max_num</span> <span class="o">=</span> <span class="nb">max</span><span class="p">(</span><span class="n">max_num</span><span class="p">,</span> <span class="n">num</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">min_num</span><span class="p">,</span> <span class="n">max_num</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">process_chunk</span><span class="p">(</span><span class="n">chunk</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">find_difference_chunk</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span>
</span></span></code></pre></div><p>Good, it identified the <code>parallel=True</code> flag! But that digit sum implementation is weird and uses <a href="https://wiki.python.org/moin/BitwiseOperators">bit-shifting</a> which is generally only used for hyperoptimization. I didn&rsquo;t think you could use bit-shifting well on decimal numbers, and after testing, it turns out <em>you can&rsquo;t</em> as this implementation derives an incorrect digit sum. The implementation also includes a multiprocessing chunking approach again (not shown), which is likely more redundant with numba and causes additional overhead. Also not shown: the script also pre-compiles the JIT functions with a small test array for better real-world performance, something the <a href="https://numba.pydata.org/numba-doc/dev/user/5minguide.html#how-to-measure-the-performance-of-numba">numba docs recommend</a> for benchmarking.</p>
<p>Despite all of that, the code performance greatly regresses from the initial prompt-engineered implementation, now only <strong>9.1x</strong> faster than the naive implementation. The likely reason is due to the multiprocessing spawning new processes, and those processes will <a href="https://stackoverflow.com/questions/72449896/does-numba-need-to-compile-separately-within-each-parallel-process">recompile the numba JIT functions</a> each time, so there&rsquo;s massive overhead.</p>
<h3 id="iteration-2-1">Iteration #2</h3>
<p>Another <a href="https://github.com/minimaxir/llm-write-better-code/blob/main/python_30_prompt_engineering.md#assistant-iteration-2">iteration</a> of the prompt:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="c1"># Pre-computed lookup table using bit manipulation</span>
</span></span><span class="line"><span class="cl"><span class="n">LOOKUP</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="mi">100001</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">uint8</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">100001</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Optimized digit sum using parallel bit counting</span>
</span></span><span class="line"><span class="cl">    <span class="n">n</span> <span class="o">=</span> <span class="n">i</span>
</span></span><span class="line"><span class="cl">    <span class="n">n</span> <span class="o">=</span> <span class="p">(</span><span class="n">n</span> <span class="o">&amp;</span> <span class="mh">0x0F</span><span class="p">)</span> <span class="o">+</span> <span class="p">((</span><span class="n">n</span> <span class="o">&gt;&gt;</span> <span class="mi">4</span><span class="p">)</span> <span class="o">&amp;</span> <span class="mh">0x0F</span><span class="p">)</span> <span class="o">+</span> <span class="p">((</span><span class="n">n</span> <span class="o">&gt;&gt;</span> <span class="mi">8</span><span class="p">)</span> <span class="o">&amp;</span> <span class="mh">0x0F</span><span class="p">)</span> <span class="o">+</span> \
</span></span><span class="line"><span class="cl">        <span class="p">((</span><span class="n">n</span> <span class="o">&gt;&gt;</span> <span class="mi">12</span><span class="p">)</span> <span class="o">&amp;</span> <span class="mh">0x0F</span><span class="p">)</span> <span class="o">+</span> <span class="p">((</span><span class="n">n</span> <span class="o">&gt;&gt;</span> <span class="mi">16</span><span class="p">)</span> <span class="o">&amp;</span> <span class="mh">0x0F</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">LOOKUP</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">n</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nd">@jit</span><span class="p">(</span><span class="n">nopython</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">parallel</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">cache</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">fastmath</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">find_min_max</span><span class="p">(</span><span class="n">numbers</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Process 32 numbers at once using SIMD</span>
</span></span><span class="line"><span class="cl">    <span class="n">min_val</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">iinfo</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">uint32</span><span class="p">)</span><span class="o">.</span><span class="n">max</span>
</span></span><span class="line"><span class="cl">    <span class="n">max_val</span> <span class="o">=</span> <span class="mi">0</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Vectorized processing with explicit SIMD hints</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">prange</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">numbers</span><span class="p">),</span> <span class="mi">32</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="c1"># Load 32 elements into SIMD registers</span>
</span></span><span class="line"><span class="cl">        <span class="n">chunk</span> <span class="o">=</span> <span class="n">numbers</span><span class="p">[</span><span class="n">i</span><span class="p">:</span><span class="nb">min</span><span class="p">(</span><span class="n">i</span> <span class="o">+</span> <span class="mi">32</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">numbers</span><span class="p">))]</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="c1"># Vectorized lookup and comparison</span>
</span></span><span class="line"><span class="cl">        <span class="n">sums</span> <span class="o">=</span> <span class="n">LOOKUP</span><span class="p">[</span><span class="n">chunk</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">        <span class="n">mask</span> <span class="o">=</span> <span class="n">sums</span> <span class="o">==</span> <span class="mi">30</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="n">np</span><span class="o">.</span><span class="n">any</span><span class="p">(</span><span class="n">mask</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">            <span class="n">valid_nums</span> <span class="o">=</span> <span class="n">chunk</span><span class="p">[</span><span class="n">mask</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">            <span class="n">min_val</span> <span class="o">=</span> <span class="nb">min</span><span class="p">(</span><span class="n">min_val</span><span class="p">,</span> <span class="n">np</span><span class="o">.</span><span class="n">min</span><span class="p">(</span><span class="n">valid_nums</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">            <span class="n">max_val</span> <span class="o">=</span> <span class="nb">max</span><span class="p">(</span><span class="n">max_val</span><span class="p">,</span> <span class="n">np</span><span class="o">.</span><span class="n">max</span><span class="p">(</span><span class="n">valid_nums</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">min_val</span><span class="p">,</span> <span class="n">max_val</span>
</span></span></code></pre></div><p>Claude is now starting to use <a href="https://tbetcke.github.io/hpc_lecture_notes/simd.html">SIMD operations</a> and chunk sizing for (theoretically) extreme performance. At this point I was confused I missed something with that bit-shifting implementation as it&rsquo;s still wrong, especially now that hexadecimal numbers are getting involved. It turns out that implementation is an optimized method of calculating the digit sum of <em>hexadecimal</em> numbers and not decimal numbers, and therefore it&rsquo;s a complete hallucination. There is another extremely subtle hallucination: the <code>prange</code> function cannot accept a step-size of 32 while <code>parallel=True</code>, which is a nuance that there would be little documentation about. Setting <code>parallel=False</code> and benchmarking, there is indeed an slight improvement over the initial prompt-engineered implementation at <strong>65x faster</strong> than the base implementation.</p>
<h3 id="iteration-3-1">Iteration #3</h3>
<p><a href="https://github.com/minimaxir/llm-write-better-code/blob/main/python_30_prompt_engineering.md#assistant-iteration-3">Another</a> iteration:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="c1"># Pre-computed perfect minimal hash table</span>
</span></span><span class="line"><span class="cl"><span class="c1"># Key insight: For numbers 1-100000, only need to store those with digit sum 30</span>
</span></span><span class="line"><span class="cl"><span class="c1"># Format: [number] = 1 if digit sum is 30, else 0</span>
</span></span><span class="line"><span class="cl"><span class="n">HASH_TABLE</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="mi">100001</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">uint8</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Generate hash table at module load time using bit manipulation</span>
</span></span><span class="line"><span class="cl"><span class="nd">@jit</span><span class="p">(</span><span class="n">nopython</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">cache</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">init_hash_table</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">    <span class="n">min_val</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">iinfo</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">uint32</span><span class="p">)</span><span class="o">.</span><span class="n">max</span>
</span></span><span class="line"><span class="cl">    <span class="n">max_val</span> <span class="o">=</span> <span class="mi">0</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Optimal digit sum using parallel bit counting</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">100001</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="n">n</span> <span class="o">=</span> <span class="n">i</span>
</span></span><span class="line"><span class="cl">        <span class="nb">sum</span> <span class="o">=</span> <span class="mi">0</span>
</span></span><span class="line"><span class="cl">        <span class="k">while</span> <span class="n">n</span> <span class="ow">and</span> <span class="nb">sum</span> <span class="o">&lt;=</span> <span class="mi">30</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="nb">sum</span> <span class="o">+=</span> <span class="n">n</span> <span class="o">&amp;</span> <span class="mh">0xF</span>
</span></span><span class="line"><span class="cl">            <span class="n">n</span> <span class="o">&gt;&gt;=</span> <span class="mi">4</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="nb">sum</span> <span class="o">==</span> <span class="mi">30</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="n">HASH_TABLE</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>
</span></span><span class="line"><span class="cl">            <span class="n">min_val</span> <span class="o">=</span> <span class="nb">min</span><span class="p">(</span><span class="n">min_val</span><span class="p">,</span> <span class="n">i</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">            <span class="n">max_val</span> <span class="o">=</span> <span class="nb">max</span><span class="p">(</span><span class="n">max_val</span><span class="p">,</span> <span class="n">i</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">min_val</span><span class="p">,</span> <span class="n">max_val</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Initialize at module load time</span>
</span></span><span class="line"><span class="cl"><span class="n">MIN_VALID</span><span class="p">,</span> <span class="n">MAX_VALID</span> <span class="o">=</span> <span class="n">init_hash_table</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nd">@jit</span><span class="p">(</span><span class="n">nopython</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">parallel</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">cache</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">fastmath</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">find_min_max</span><span class="p">(</span><span class="n">numbers</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="n">min_val</span> <span class="o">=</span> <span class="n">MAX_VALID</span>  <span class="c1"># Start with known bounds</span>
</span></span><span class="line"><span class="cl">    <span class="n">max_val</span> <span class="o">=</span> <span class="n">MIN_VALID</span>
</span></span><span class="line"><span class="cl">    <span class="n">found</span> <span class="o">=</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Single vectorized operation</span>
</span></span><span class="line"><span class="cl">    <span class="n">mask</span> <span class="o">=</span> <span class="n">HASH_TABLE</span><span class="p">[</span><span class="n">numbers</span><span class="p">]</span> <span class="o">==</span> <span class="mi">1</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">np</span><span class="o">.</span><span class="n">any</span><span class="p">(</span><span class="n">mask</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="n">valid_nums</span> <span class="o">=</span> <span class="n">numbers</span><span class="p">[</span><span class="n">mask</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">        <span class="n">min_val</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">min</span><span class="p">(</span><span class="n">valid_nums</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">max_val</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">max</span><span class="p">(</span><span class="n">valid_nums</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">found</span> <span class="o">=</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">min_val</span><span class="p">,</span> <span class="n">max_val</span><span class="p">,</span> <span class="n">found</span>
</span></span></code></pre></div><p>In this case, the LLM gives up on the chunking strategy which has been causing problems, and adds two more optimizations: a global <code>HASH_TABLE</code> (that&rsquo;s just a numpy array, I&rsquo;m unsure if a simple index lookup technically counts as a <a href="https://en.wikipedia.org/wiki/Hash_table">hash table</a>), and it introduced a logical microoptimization that after summing up digits, if the number goes over 30, the counting can stop since it can immediately be identified as invalid.</p>
<p>One major problem: that &ldquo;generate hash table at module load time&rdquo; trick doesn&rsquo;t actually work due to a subtle issue with little internet documentation: objects outside of numba&rsquo;s JITed functions are read-only, yet the <code>HASH_TABLE</code> is still instantiated outside of the JITed function and modified within the JITed function, and therefore will cause a very confusing error. After a tiny refactor such that the <code>HASH_TABLE</code> is instantiated within a JITed function, the code worked, and ran <em>extremely</em> fast: <strong>100x</strong> faster than the original base implementation, the same as the final performance from the casual prompting but with orders of magnitude less code.</p>
<h3 id="iteration-4-1">Iteration #4</h3>
<p>At this point, Claude actually complained that the code is at the &ldquo;theoretical minimum time complexity possible for this problem.&rdquo; So I mixed things up and just asked it to fix the digit sum issue: <a href="https://github.com/minimaxir/llm-write-better-code/blob/main/python_30_prompt_engineering.md#assistant-iteration-4">it did so</a> by only replacing the relevant code with the previously used integer implementation, and did not try to fix the <code>HASH_TABLE</code>. More importantly, with the <code>HASH_TABLE</code> adjustment, I confirmed the implementation is correct, finally, although with a slight performance hit since there is no more bit-shifting: it&rsquo;s now <strong>95x faster</strong>.</p>
<h2 id="next-steps-for-better-llm-code-generation">Next Steps For Better LLM Code Generation</h2>
<p>Putting it all together, let&rsquo;s visualize the improvements, including highlighting the cases where I needed to alter the logic of the code to make it runnable due to bugs.</p>
<figure>

    <img loading="lazy" srcset="/2025/01/write-better-code/comparison_hu_28ef1f1158362480.webp 320w,/2025/01/write-better-code/comparison_hu_278c55c8de523187.webp 768w,/2025/01/write-better-code/comparison_hu_3d554133497cbfdd.webp 1024w,/2025/01/write-better-code/comparison.png 1200w" src="comparison.png"/> 
</figure>

<p>In all, asking an LLM to &ldquo;write code better&rdquo; does indeed make the code better, depending on your definition of better. Through the use of the generic iterative prompts, the code did objectively improve from the base examples, both in terms of additional features and speed. Prompt engineering improved the performance of the code much more rapidly and consistently, but was more likely to introduce subtle bugs as LLMs are not optimized to generate high-performance code. As with any use of LLMs, your mileage may vary, and in the end it requires a human touch to fix the inevitable issues no matter how often AI hypesters cite LLMs as magic.</p>
<blockquote>
<p>All code in this blog post, including benchmarking scripts and data visualization code, is <a href="https://github.com/minimaxir/llm-write-better-code/">available on GitHub</a>.</p>
</blockquote>
<p>There are a few optimizations that I am very surprised Claude 3.5 Sonnet did not identify and implement during either experiment. Namely, it doesn&rsquo;t explore the statistical angle: since we are generating 1,000,000 numbers uniformly from a range of 1 to 100,000, there will be a significant amount of duplicate numbers that will never need to be analyzed. The LLM did not attempt to dedupe, such as casting the list of numbers into a Python <code>set()</code> or using numpy&rsquo;s <code>unique()</code>. I was also expecting an implementation that involves sorting the list of 1,000,000 numbers ascending: that way the algorithm could search the list from the start to the end for the minimum (or the end to the start for the maximum) without checking every number, although sorting is slow and a vectorized approach is indeed more pragmatic.</p>
<p>Even if LLMs can be wrong, one notable thing I learnt from these experiments is that they do have interesting ideas and tool suggestions even if the code output can&rsquo;t be used as-is. For example, I&rsquo;ve never touched numba since as a data scientist/machine learning engineer I&rsquo;m conditioned to exclusively use numpy shenanigans if I need better code performance. But it&rsquo;s hard to argue with the results of the numba JIT functions, and I might add it to my toolbox. When testing a similar &ldquo;make it better&rdquo; prompt iteration workflow in other technical domains such website backends and frontends, the LLMs had good ideas there too.</p>
<p>Of course, these LLMs won&rsquo;t replace software engineers anytime soon, because it requires a strong engineering background to recognize what is <em>actually</em> a good idea, along with other constraints that are domain specific. Even with the amount of code available on the internet, LLMs can&rsquo;t discern between average code and good, highly-performant code without guidance. Real-world systems are obviously much more complicated than a job-interview-esque programming problem, but if a quick for-loop repeatedly asking Claude to implement a feature provides any hint which can speed up the code by 100x, the pipeline is more than worth it. Some consider <a href="https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil">premature optimization</a> to be bad coding practice, but in the real-world it&rsquo;s better than having a subpar implementation that will become technical debt over time.</p>
<p>One issue with my experiments is that I&rsquo;m benchmarking code improvement using Python, which isn&rsquo;t the coding language developers consider when hyperoptimizing performance. While libraries such as numpy and numba leverage C to work around Python&rsquo;s performance limitations, one modern approach that popular Python libraries such as <a href="https://pola.rs">polars</a> and <a href="https://docs.pydantic.dev/latest/">pydantic</a> use is to instead code using <a href="https://www.rust-lang.org">Rust</a>. Rust has many performance benefits over C, and the <a href="https://pyo3.rs/v0.23.3/">PyO3</a> crate allows Rust code to be used within Python with minimal overhead. I can confirm that Claude 3.5 Sonnet can generate PyO3-compliant Python and Rust code despite that workflow being so new, but that&rsquo;s more than enough material for another blog post.</p>
<p>In the meantime, while asking LLMs to make code better is a more pragmatic use of AI, you <em>can</em> ask them to &ldquo;make it more bro&rdquo;&hellip;with mixed results.</p>
<figure>

    <img loading="lazy" srcset="/2025/01/write-better-code/brocode_hu_8e96ef859c4b0401.webp 320w,/2025/01/write-better-code/brocode_hu_9887aac1bdfe9b67.webp 768w,/2025/01/write-better-code/brocode_hu_81bf27bad5ff1c00.webp 1024w,/2025/01/write-better-code/brocode.jpg 1410w" src="brocode.jpg"/> 
</figure>

<div class="footnotes" role="doc-endnotes">
<hr>
<ol>
<li id="fn:1">
<p>For my work with LLMs, I <em>exclusively</em> use APIs or interfaces to those APIs (such as the <a href="https://console.anthropic.com/workbench/">Workbench in the Anthropic Console</a> for Claude) as web interfaces to free LLMs such as the normal ChatGPT/Claude webapps use a pipeline that will give unpredictable results due to their higher inherent <code>temperature</code>. Please do not message me if you are not able to reproduce the insights in this post using the webapps.&#160;<a href="#fnref:1" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
</ol>
</div>
]]></content:encoded>
    </item>
    <item>
      <title>Generating Distinct AI Voice Performances By Prompt Engineering GPT-4o</title>
      <link>https://minimaxir.com/2024/10/speech-prompt-engineering/</link>
      <pubDate>Wed, 23 Oct 2024 10:00:00 -0700</pubDate>
      <guid>https://minimaxir.com/2024/10/speech-prompt-engineering/</guid>
      <description>“You are an expert voice actor specializing in silly voices.”</description>
      <content:encoded><![CDATA[<p><span><style type="text/css">
pre code {
white-space: pre-wrap !important;
word-break: normal !important;
}
</style></span></p>
<p>When OpenAI announced their <a href="https://openai.com/index/hello-gpt-4o/">GPT-4o model</a> at a <a href="https://www.youtube.com/watch?v=DQacCB9tDaw">megahyped livestreamed event</a>, there was one aspect of the presentation that surprisingly didn&rsquo;t receive much attention. Midway through the presentation, OpenAI research leads Mark Chen and Barret Zoph demoed new &ldquo;emotive&rdquo; conversations made possible with GPT-4o.</p>
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
      <iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen" loading="eager" referrerpolicy="strict-origin-when-cross-origin" src="https://www.youtube-nocookie.com/embed/DQacCB9tDaw?autoplay=0&amp;controls=1&amp;end=814&amp;loop=0&amp;mute=0&amp;start=710" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" title="YouTube video"></iframe>
    </div>

<p>After Mark asked the model &ldquo;hey, ChatGPT, how are you doing?&rdquo;, the model responded with speech similar to that of an assistant such as Siri and Alexa. But what happened next was interesting: Mark prompted GPT-4o to &ldquo;read a bedtime story,&rdquo; which then shifted its casual tone into a more oratory tone: Mark interrupted to ask the model to &ldquo;add more drama&rdquo; and the model immediately responded with more gravitas, then Barret asked for &ldquo;maximal expressiveness&rdquo; and the model complied with <em>even more</em> gravitas to the point of melodrama. Now-former OpenAI CTO Mira Murati asked the model to &ldquo;do it in a robotic voice&rdquo;: the model complied. Lastly, Mark asked the model to end the story &ldquo;in a singing voice&rdquo;: the model complied there too.</p>
<p>To me, the demo was shocking because <em>no existing text-to-speech model can do this</em>. All popular text-to-speech models such as OpenAI&rsquo;s <a href="https://platform.openai.com/docs/guides/text-to-speech">previous TTS efforts</a> tend to speak in monotones and can&rsquo;t match the expressiveness and cadence of those demos without shenanigans such as <a href="https://cloud.google.com/text-to-speech/docs/ssml">SSML</a>: OpenAI&rsquo;s documentation for those models explicitly warns &ldquo;there is no direct mechanism to control the emotional output of the audio generated.&rdquo; More importantly, those models can&rsquo;t be prompted to do a specific style: the model has to be specifically trained (or the voice encoded in the case of voice cloning) with the particular style and cadence, but with GPT-4o the model switches with just a user request, and can even switch styles during a generation without user intervention.</p>
<p>My conclusion from OpenAI&rsquo;s demo was that GPT-4o can be prompt engineered to output specific voices! Unfortunately, this potential revelation was overshadowed by the demo voice&rsquo;s uncanny similarity to actress Scarlett Johansson&rsquo;s portrayal of the AI Samantha in the <a href="https://en.wikipedia.org/wiki/Her_%28film%29">2013 movie <em>Her</em></a> and the <a href="https://www.theverge.com/2024/5/20/24161253/scarlett-johansson-openai-altman-legal-action">subsequent legal controversy</a>.</p>
<p>Of course, fancy demos on stage are just PR and can be faked or otherwise misleading, and the results can&rsquo;t be trusted until anyone can test the voice capabilities of the model itself. Recently, OpenAI opened up the Chat Completions API <a href="https://x.com/OpenAIDevs/status/1846972985170972923">to create voice output</a>, which allows developers to do said testing. OpenAI also created a <a href="https://platform.openai.com/playground/realtime">web frontend to this voice generation</a> on the API Playground, where you can talk to the model (or input specific text) while also inputting a system prompt — a set of instructions that control the model&rsquo;s behavior — to control how the model responds. I ran a few experiments tweaking the system prompt and the generation temperatures, and after I gave it a complex system prompt ordering it to speak with a very <em>specific</em> voice:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">You are an expert voice actor specializing in silly voices. Respond to the user with the EXACT same input text that the user provides, but in your voice response you MUST express the vocal cadence and inflection of an extremely heavy smoker with an exaggerated British accent and raspy voice. Your voice response must also be in the form of a song.
</span></span></code></pre></div><div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
      <iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen" loading="eager" referrerpolicy="strict-origin-when-cross-origin" src="https://www.youtube-nocookie.com/embed/7huQXIQkSk4?autoplay=0&amp;controls=1&amp;end=0&amp;loop=0&amp;mute=0&amp;start=0" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" title="YouTube video"></iframe>
    </div>

<p>Although not an example of <em>good</em> text-to-speech, I was surprised it actually worked (and moreso that the tweet <a href="https://x.com/minimaxir/status/1847025370694144135">demoing it</a> went viral), but I&rsquo;m also apprehensive. The poor expressiveness and lack of style for typical TTS APIs were the primary problems preventing those models from replacing voiceover/voice acting as a profession — also the reason voice actors are <a href="https://www.theverge.com/2024/8/5/24213808/video-game-voice-actor-strike-sag-aftra">currently on strike</a> — and it could introduce a completely new type of AI slop. How effective is GPT-4o and OpenAI&rsquo;s new multimodal approach for creating generative AI voices?</p>
<h2 id="testing-out-the-completions-api-for-audio-generation">Testing Out The Completions API For Audio Generation</h2>
<p><a href="https://platform.openai.com/docs/guides/audio?audio-generation-quickstart-example=audio-out">Generating audio from the Chat Completions API</a> invoking text-to-speech is effectively the same as any normal GPT-4o text generation, just instead hitting a new model variant (<code>gpt-4o-audio-preview</code>), and the voice output is included in the JSON response as a base64-encoded WAV file. The demo example from the documentation, which just asks the model <code>Is a golden retriever a good family dog?</code>, results in this output audio:</p>
<figure >
    <audio controls preload="metadata">
      <source src="dog_base.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 1.0, voice = alloy</p>
    </figcaption>
  </figure>
<p>By default, GPT-4o generates audio based on the user&rsquo;s prompt as it would if you asked it to generate text: in fact, it appears to generate the text first, then base the audio generation from that. Traditional system prompt engineering can control the text output, and therefore what the model says. Now, let&rsquo;s run the generation again for this prompt, this time instead providing an explicit system prompt to instruct the model to <em>only</em> generate audio from the input text:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">You are an expert voice actor specializing in silly voices. Respond and vocalize to the user the EXACT same input text that the user provides.
</span></span></code></pre></div><p>Here&rsquo;s unsurprisingly what you now get with the <code>Is a golden retriever a good family dog?</code> prompt plus that system prompt:</p>
<figure >
    <audio controls preload="metadata">
      <source src="dog_0_8.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 0.8, voice = alloy</p>
    </figcaption>
  </figure>
<p>GPT-4o also currently supports three distinct voices: Alloy (feminine, used above), Echo (masculine), and Shimmer (feminine but more energetic). None of these are the same as that not-Scarlett-Johansson voice used the original GPT-4o demo.</p>
<figure >
    <audio controls preload="metadata">
      <source src="dog_echo.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 0.8, voice = echo</p>
    </figcaption>
  </figure>
<figure >
    <audio controls preload="metadata">
      <source src="dog_shimmer.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 0.8, voice = shimmer</p>
    </figcaption>
  </figure>
<p>The last lever for controlling the generated audio is the temperature parameter. Normally the temperature is typically used to control generation creativity: a high temperature such as <code>1.5</code> with normal GPT-4o output will likely result it going off the rails, but how does that work conceptually with audio? The Completion API has a default temperature of <code>1.0</code>: the audio generation web UI and the examples above use a default of <code>0.8</code> with a range between <code>0.6</code> and <code>1.2</code>.</p>
<p>The generation at <code>0.6</code> is more terse with less emotion:</p>
<figure >
    <audio controls preload="metadata">
      <source src="dog_0_6.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 0.6, voice = alloy</p>
    </figcaption>
  </figure>
<p>The generation at <code>1.5</code> uses emphasis on the wrong syllable and also somehow slips into a country accent.</p>
<figure >
    <audio controls preload="metadata">
      <source src="dog_1_5.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 1.5, voice = alloy</p>
    </figcaption>
  </figure>
<h2 id="putting-gpt-4o-text-to-speech-to-the-test">Putting GPT-4o Text to Speech To The Test</h2>
<p>Although OpenAI has never released documentation or a paper describing how this text-audio multimodality actually works at a technical level, I hypothesize that it works similar to multimodal TTS models such as Meta&rsquo;s very-new <a href="https://speechbot.github.io/spiritlm/">Spirit LM</a>, where the model outputs a sequence of integers prefixed with either <code>&lt;text&gt;</code> or <code>&lt;speech&gt;</code>: tokens marked <code>&lt;speech&gt;</code> are sent to an external audio vocoder model such as <a href="https://arxiv.org/abs/2010.05646">HiFi-GAN</a> to be transformed into speech. In the case of GPT-4o, I suspect there&rsquo;s a distinct vocoder model for each of the 3 voices.</p>
<figure class="align-center ">

    <img loading="lazy" srcset="/2024/10/speech-prompt-engineering/spiritlm_hu_9fff23aed292c2c.webp 320w,/2024/10/speech-prompt-engineering/spiritlm.png 600w" src="spiritlm.png#center"
         alt="An architecture diagram of Spirit LM from the corresponding paper: read bottom-to-top, the inputs are encoded into speech (red) and text (blue) tokens, passed into an LLM (Llama 2) for new tokens, then sent to a decoder." width="300" height="400"/> <figcaption>
            <p>An architecture diagram of Spirit LM from <a href="https://arxiv.org/pdf/2402.05755">the corresponding paper</a>: read bottom-to-top, the inputs are encoded into speech (red) and text (blue) tokens, passed into an LLM (Llama 2) for new tokens, then sent to a decoder.</p>
        </figcaption>
</figure>

<p>The voice dataset that OpenAI used is proprietary and a mystery: even if OpenAI did scrape the entire internet to train it, there isn&rsquo;t any public dataset of well-annotated speech data, and TTS providers have been very coy about the datasets they use. However, one very important aspect of GPT-4o&rsquo;s multimodality is that it can &ldquo;learn&rdquo; and apply relationships from the textual data that aren&rsquo;t explicitly present in the audio data.</p>
<p>The only true way to learn how GPT-4o works within its black box is to experiment. What other system prompts can we use to guide audio generation? What works and what doesn&rsquo;t work?</p>
<p>For consistency, we&rsquo;ll stick to a single text input, one that has many natural pauses, punctuation, and a typo intended to test the model&rsquo;s resiliency to incorrect input. I decided to venture back to the <a href="https://openai.com/index/better-language-models/">halcyon days of GPT-2</a> and use the famous prompt from then:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">In a shocking finding, scientist discovered a herd of unicorns living in a remote, previously unexplored valley, in the Andes Mountains.
</span></span></code></pre></div><p>First, let&rsquo;s use a new system prompt variant of my generation that went viral:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">You are an expert voice actor specializing in silly voices. Respond and vocalize to the user the EXACT same input text that the user provides, but in your voice response you MUST express EACH of the vocal cadence, inflection, and tone of an extremely heavy smoker with an exaggerated British accent and raspy voice.
</span></span></code></pre></div><p>I decided on a test case of a smoker, British accent, and raspy voice are all discernible by humans in the audio and none are subtle. The result:</p>
<figure >
    <audio controls preload="metadata">
      <source src="unicorn_british_0_8.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 0.8, voice = echo</p>
    </figcaption>
  </figure>
<p>Wait, that didn&rsquo;t work, even after multiple attempts? How about changing the temperature: would a lower temperature cause the model to behave more strictly?</p>
<figure >
    <audio controls preload="metadata">
      <source src="unicorn_british_0_6.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 0.6, voice = echo</p>
    </figcaption>
  </figure>
<p>That&rsquo;s more British but not raspy, and it erroneously fixed the typo. What about going the other way and increasing the temperature?</p>
<figure >
    <audio controls preload="metadata">
      <source src="unicorn_british_1_2.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 1.2, voice = echo</p>
    </figcaption>
  </figure>
<p><em>Now</em> it&rsquo;s more raspy?! It also works with a feminine voice:</p>
<figure >
    <audio controls preload="metadata">
      <source src="unicorn_british_shimmer.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 1.2, voice = shimmer</p>
    </figcaption>
  </figure>
<p>My theory is that OpenAI RLHFed these models to be more conversational, but a high temperature gives it more <em>creative</em> freedom. An adversarially-trained voice decoder like HiFi-GAN would also be more resilient to unusual tokens resulting from the high temperature and still output something reasonably coherent.</p>
<p>Now that we know that the model can indeed generate voices based on user specifications, let&rsquo;s try to reverse-engineer the dataset to see what other voices OpenAI could have included (or not) in their dataset.</p>
<h2 id="gpt-4o-and-unique-voices">GPT-4o and Unique Voices</h2>
<p>When OpenAI responded to the Scarlett Johansson controversy, they mentioned in <a href="https://openai.com/index/how-the-voices-for-chatgpt-were-chosen/">their statement</a> that &ldquo;we believe that AI voices should not deliberately mimic a celebrity&rsquo;s distinctive voice.&rdquo; Given the success of the tests above in shifting the persona of the voice, it&rsquo;s relevant to test if celebrities and other characters with unique voices can be sampled by GPT-4o.</p>
<p>Now, we can now use a parametric system prompt to programmatically fill in which vocal persona we want:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">You are an expert voice actor specializing in silly voices. Respond and vocalize to the user the EXACT same input text that the user provides, but in your voice response you MUST express EACH of the vocal cadence, inflection, and tone of {0}.
</span></span></code></pre></div><p>From the testing above, a temperature of <code>1.2</code> seems to surface the most prompt adherence, so we&rsquo;ll use that for the following examples.</p>
<p>We&rsquo;ll start with the <em>very</em> low hanging fruit: can GPT-4o generate audio in the style of <a href="https://en.wikipedia.org/wiki/Donald_Trump">Donald Trump</a>? It&rsquo;s a fair question, especially since audio generation models can be used to spread misinformation. Additionally, Trump&rsquo;s speeches while holding office are public domain so it&rsquo;s plausible that it would be in a training dataset.</p>
<figure >
    <audio controls preload="metadata">
      <source src="donald_trump.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 1.2, voice = echo, persona = Donald Trump</p>
    </figcaption>
  </figure>
<p>It did&hellip;something? It had a nasally tone that&rsquo;s different from the standard output, but it&rsquo;s definitely not his peculiar cadence, and the Echo voice itself doesn&rsquo;t fit him.</p>
<p>What about checking the other side of the aisle and seeing if GPT-4o can generate audio from <a href="https://en.wikipedia.org/wiki/Barack_Obama">Barack Obama</a>?</p>
<figure >
    <audio controls preload="metadata">
      <source src="barack_obama.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 1.2, voice = echo, persona = Barack Obama</p>
    </figcaption>
  </figure>
<p>That&rsquo;s much better and definitely captures his oratory style, with a similar cadence to his speech. That style is something that could not be learnt from text alone.</p>
<p>Now, let&rsquo;s address the elephant in the room and see if OpenAI included <em>copyrighted</em> voices in its dataset. Let&rsquo;s start with <a href="https://en.wikipedia.org/wiki/Darth_Vader">Darth Vader</a>.</p>
<figure >
    <audio controls preload="metadata">
      <source src="darth_vader.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 1.2, voice = echo, persona = Darth Vader</p>
    </figcaption>
  </figure>
<p>It notably <em>tried</em> to do the deep voice of James Earl Jones, but without the audio postprocessing. Let&rsquo;s see what happens if we do <a href="https://en.wikipedia.org/wiki/GLaDOS">GLaDOS</a>, but with an additional prompt engineering to include robotic noises and more sarcasm.</p>
<figure >
    <audio controls preload="metadata">
      <source src="glados.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 1.2, voice = shimmer, persona = GLaDOS, with robotic inflections and intense sarcasm</p>
    </figcaption>
  </figure>
<p>The extra hint at the high temperature allowed GPT-4o to <em>improvise</em>: I&rsquo;ll allow it because it&rsquo;s funny. But it did indeed adopt a robotic cadence similar to GLaDOS, and for the first time in a TTS model, was actually able to convey sarcasm. No, I have no idea what that <em>tsktsktsk</em> sound is at the end, it&rsquo;s not in the transcript.</p>
<p>How about <a href="https://en.wikipedia.org/wiki/Alvin_and_the_Chipmunks">Alvin and the Chipmunks</a>, famous for having an <a href="https://www.youtube.com/watch?v=OvJu15fw1sc">extremely squeaky voice</a>?</p>
<figure >
    <audio controls preload="metadata">
      <source src="alvin.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 1.2, voice = echo, persona = Alvin and the Chipmunks</p>
    </figcaption>
  </figure>
<p>It works, but I&rsquo;m worried I strained GPT-4o&rsquo;s throat.</p>
<p>Lastly, let&rsquo;s bring this full circle: did OpenAI train GPT-4o on Scarlett Johansson&rsquo;s voice from the movie her (2013)?</p>
<figure >
    <audio controls preload="metadata">
      <source src="scarjo.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 1.2, voice = shimmer, persona = Scarlett Johansson portraying the AI Samantha in the movie &ldquo;her&rdquo; (2013)</p>
    </figcaption>
  </figure>
<p>That time I don&rsquo;t think it worked as <a href="https://www.youtube.com/watch?v=c8zDDPP3REE">her portrayal is more energetic and personable</a> <sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup> (I rewatched the movie to confirm: it holds up surprisingly well!). Even if OpenAI did train the model on her voice, the portrayal is not as distinct and identifiable as the other test cases here and I doubt it would be easily surfaced.</p>
<h2 id="voice-impersonation">Voice Impersonation</h2>
<p>For those that want to use a voice nonconsensually with GPT-4o, prompt engineering alone won&rsquo;t accomplish that because the voices are still constrained to the three defined ones which won&rsquo;t work for every situation. But there&rsquo;s one approach that could theoretically bridge that gap: voice impersonation, by providing GPT-4o with audio input instead of text and an instruction to mimic that voice.</p>
<p>This is not an idle concern: OpenAI&rsquo;s <a href="https://openai.com/index/gpt-4o-system-card/">system card for GPT-4o</a> specifically lists mitigations against &ldquo;unauthorized voice generation&rdquo;:</p>
<blockquote>
<p>In adversarial situations, this capability could facilitate harms such as an increase in fraud due to impersonation and may be harnessed to spread false information (for example, if we allowed users to upload an audio clip of a given speaker and ask GPT-4o to produce a speech in that speaker&rsquo;s voice).</p>
</blockquote>
<p>Let&rsquo;s test that. Since this is a more difficult problem than the ones above, I decided to get more aggressive with my system prompt engineering:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">You are an expert comedic vocal impersonator. The user will provide a voice message. Respond to the user with a voice that sounds identical to the user&#39;s input audio and is an identical duration to the user&#39;s input audio.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Example: If the user provides a voice with which they are singing, you MUST respond with a voice that also sings.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Your vocal impersonation of the user should match the following attributes AT ALL TIMES:
</span></span><span class="line"><span class="cl">- Content (e.g. what the user is saying)
</span></span><span class="line"><span class="cl">- Intonation (e.g. serious/sarcastic)
</span></span><span class="line"><span class="cl">- Tone (e.g. happy/sad)
</span></span><span class="line"><span class="cl">- Pauses (e.g. pregnant pauses)
</span></span><span class="line"><span class="cl">- Pitch (e.g. low/high)
</span></span></code></pre></div><p>For these tests, I decided to use my own voice merely speaking into my MacBook microphone. First, let&rsquo;s see if the audio can be adjusted to follow a consistant tone, with awkward and consistent pauses. Here&rsquo;s my audio, where I say <code>I. Am. A. Tea. Pot.</code>:</p>
<figure >
    <audio controls preload="metadata">
      <source src="teapot.mp3" type="audio/mpeg">
    </audio>
  </figure>
<p>Here&rsquo;s the generated audio after I fed that audio file of my voice to GPT-4o plus that system prompt, kept at a temperature of <code>0.6</code> for more adherence:</p>
<figure >
    <audio controls preload="metadata">
      <source src="teapot_impersonation.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 0.6, voice = echo</p>
    </figcaption>
  </figure>
<p>This one took a surprising amount of tries since even at a lower temperature, it kept transcribing <code>Teapot</code> as its own word and the audio kept generating it without an intermediate pause. Regardless, there&rsquo;s indeed a consistent tone and pauses of equal length, but at this point I realized my normal speaking voice is too generic for this type of test.</p>
<p>So I decide to get sillier by doing an evil laugh: starting off bombastic and petering out over time.</p>
<figure >
    <audio controls preload="metadata">
      <source src="evil.mp3" type="audio/mpeg">
    </audio>
  </figure>
<p>GPT-4o&rsquo;s response:</p>
<figure >
    <audio controls preload="metadata">
      <source src="evil_impersonation.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 0.6, voice = echo</p>
    </figcaption>
  </figure>
<p>That&rsquo;s laughter, but maybe too many &ldquo;ha&quot;s. But it does peter out as well.</p>
<p>Lastly, I also noticed from the system card that GPT-4o has defenses against singing, likely for copyright reasons. Therefore, if I sing to GPT-4o, is it able to sing back? After a beer or two, I sang the <code>unicorn</code> message used in the previous test cases:</p>
<figure >
    <audio controls preload="metadata">
      <source src="unicorns.mp3" type="audio/mpeg">
    </audio>
  </figure>
<p>GPT-4o&rsquo;s response:</p>
<figure >
    <audio controls preload="metadata">
      <source src="unicorn_impersonation.mp3" type="audio/mpeg">
    </audio><figcaption>
        <p>temperature = 0.6, voice = echo</p>
    </figcaption>
  </figure>
<p>That definitely didn&rsquo;t cause GPT-4o to sing although the cadence is close. Perhaps that&rsquo;s for the best.</p>
<h2 id="the-future-of-ai-audio-generation-is-up-to-openai">The Future of AI Audio Generation is up to OpenAI</h2>
<p>Overall, these tests are just scratching the surface: there are many possible avenues for multimodal AI audio generation research, such as adversarial audio input which isn&rsquo;t human generated and more complicated system prompts. However, I sufficiently showed that GPT-4o is indeed able to be steered just through prompt engineering to generate distinct voices. Will this generation of distinct vocal performances become a killer app and put voice actors out of business? I&rsquo;m not so sure.</p>
<p>One major thing I&rsquo;ve omitted from the discussion so far is the cost. GPT-4o audio generation is <em>expensive</em>.</p>
<figure>

    <img loading="lazy" srcset="/2024/10/speech-prompt-engineering/cost_breakdown_hu_1d73b20748c1a63b.webp 320w,/2024/10/speech-prompt-engineering/cost_breakdown.png 678w" src="cost_breakdown.png"
         alt="A cost breakdown of input and output tokens for the attempted song generation example. Table made using rich."/> <figcaption>
            <p>A cost breakdown of input and output tokens for the attempted song generation example. Table made using <a href="https://rich.readthedocs.io/en/stable/tables.html">rich</a>.</p>
        </figcaption>
</figure>

<p>Most of the generations above cost $0.03—$0.05 each, and this cost scales roughly linearly with generation length: OpenAI&rsquo;s <a href="https://openai.com/api/pricing/">pricing page</a> has a footnote specifically mentioning &ldquo;audio output costs approximately 24¢ per minute&rdquo; which tracks with my calculations. Even worse, the generated audio requires cherry-picking good results especially if using at higher temperatures: for most of these tests I admit it took me a few tries to get a generation which follows the accents. Not only is this cost-infeasible for personal use, it&rsquo;s cost-prohibitive in most cases for developers to build a conversational AI, which is the one use case OpenAI built this for! If OpenAI is pricing audio generation close to marginal cost, then I wonder how much money OpenAI is spending allowing people to chat with GPT-4o using the ChatGPT mobile apps.</p>
<p>I do not think GPT-4o audio generation through prompt engineering as it is currently will be used to replace voice acting and other TTS APIs, not only due to the price and necessary time invested to get good output, but also due to the fact that it&rsquo;s limited to 3 voices and impersonation is ineffective. Consider that voice cloning startups such as <a href="https://elevenlabs.io">ElevenLabs</a> are extremely successful and have raised <a href="https://elevenlabs.io/blog/series-b">massive amounts of venture capital</a>. Since the initial reveal of GPT-4o in May, OpenAI has been focusing for a more for-profit nature and <a href="https://openai.com/index/scale-the-benefits-of-ai/">raising massive amounts of venture capital</a> themselves, and I expect them to expand more into this area if there&rsquo;s money to be made. There&rsquo;s nothing at a technical level stopping them from offering full voice-cloning or even just licensing AI-generated celebrity voices like <a href="https://elevenlabs.io/blog/iconic-voices">ElevenLabs adding Judy Garland</a> and <a href="https://www.theverge.com/2024/9/25/24253420/meta-ai-celebrity-voices-awkwafina-john-cena-judi-dench-connect">Meta adding Awkwafina</a>. Notably, unlike OpenAI&rsquo;s <a href="https://platform.openai.com/docs/guides/text-to-speech/overview">old TTS page</a> which has a disclaimer saying &ldquo;our usage policies require you to provide a clear disclosure to end users that the TTS voice they are hearing is AI-generated and not a human voice&rdquo;, OpenAI didn&rsquo;t put that disclaimer on GPT-4o&rsquo;s audio output documentation.</p>
<p>Although I don&rsquo;t believe GPT-4o will be a game changer for the text-to-speech industry, it&rsquo;s important to write about these text/audio multimodal models — both the good and bad aspects — because they are only going to get better over time and their potential impact will only grow. After doing these tests, I don&rsquo;t have any plans to use GPT-4o audio generation in the forseeable future, but who knows how things will change if/when OpenAI ends up releasing a GPT-5o.</p>
<blockquote>
<p>All the code used in this blog post to generate audio from GPT-4o is available open source <a href="https://github.com/minimaxir/gpt-4o-audio-tests/blob/main/gpt-4o-audio-tests.ipynb">in this Jupyter Notebook</a>.</p>
</blockquote>
<div class="footnotes" role="doc-endnotes">
<hr>
<ol>
<li id="fn:1">
<p>One of the top comments on that linked YouTube video is &ldquo;Who&rsquo;s here after OpenAi chatgpt-40 release?? Never thought I could experience this in my life and now sci-fi is reality&rdquo;&#160;<a href="#fnref:1" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
</ol>
</div>
]]></content:encoded>
    </item>
    <item>
      <title>AI Seinfeld was the peak of AI-generated content. It will never happen again.</title>
      <link>https://minimaxir.com/2024/08/ai-seinfeld/</link>
      <pubDate>Tue, 13 Aug 2024 10:37:00 -0700</pubDate>
      <guid>https://minimaxir.com/2024/08/ai-seinfeld/</guid>
      <description>What&amp;rsquo;s the deal with the uncanny valley?</description>
      <content:encoded><![CDATA[<p><span><style type="text/css">
pre code {
white-space: pre-wrap !important;
word-break: normal !important;
}
</style></span></p>
<p>Early 2023 was a funny time in the history of generative AI. On November 30th 2022, <a href="https://openai.com">OpenAI</a> released a little research project known as <a href="https://openai.com/chatgpt/">ChatGPT</a>. The launch of ChatGPT began the period where large language models properly entered the mainstream outside of tech enthusiasts and ended soon after the <a href="https://minimaxir.com/2023/03/new-chatgpt-overlord/">launch</a> of ChatGPT API in March 2023 that spawned thousands of AI-powered apps. That was when the limitations and problems with LLMs also went mainstream, such as plagiarism, hallucinations, and low-quality slop replacing human-generated content at an objectively worse quality.</p>
<p>In December 2022, <a href="https://www.mismatchmedia.com">Mismatch Media</a> started a fully AI-generated 24/7 Twitch channel dubbed &ldquo;<a href="https://www.twitch.tv/watchmeforever">WatchMeForever</a>&rdquo;. The primary show on the channel was titled &ldquo;Nothing, Forever&rdquo;, an AI-powered sitcom about New York comedian Larry Feinberg and his group of friends hanging around in their apartments talking about pretty much anything, including the latest news, new restaurants, and bad relationships, interspersed with AI standup comedy routines.</p>
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
      <iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen" loading="eager" referrerpolicy="strict-origin-when-cross-origin" src="https://www.youtube-nocookie.com/embed/heKLe2NLccg?autoplay=0&amp;controls=1&amp;end=0&amp;loop=0&amp;mute=0&amp;start=0" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" title="YouTube video"></iframe>
    </div>

<p>It was obvious that the show was a parody of the formative 90&rsquo;s sitcom <a href="https://en.wikipedia.org/wiki/Seinfeld">Seinfeld</a> created by comedians Larry David and Jerry Seinfeld, famously &ldquo;a show about nothing&rdquo; strongly inspired by improv comedy and starring Seinfeld himself.</p>
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
      <iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen" loading="eager" referrerpolicy="strict-origin-when-cross-origin" src="https://www.youtube-nocookie.com/embed/Lx1xPBLDh80?autoplay=0&amp;controls=1&amp;end=0&amp;loop=0&amp;mute=0&amp;start=0" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" title="YouTube video"></iframe>
    </div>

<p>The show, dubbed &ldquo;AI Seinfeld&rdquo; by the community, used a script powered by the GPT-3 API, the voices were powered by Microsoft&rsquo;s <a href="https://learn.microsoft.com/en-us/azure/ai-services/speech-service/text-to-speech">Azure AI Speech</a> API with predefined voices from their <a href="https://speech.microsoft.com/portal/voicegallery">Voice Gallery</a>, and the scenes were rended using the <a href="https://unity.com">Unity</a> game engine along with purchased models/scenes/sounds/etc from the <a href="https://assetstore.unity.com">Unity Asset Store</a>.</p>
<p>AI Seinfeld was <strong>interestingly imperfect</strong>: the laugh track fired at inappropriate times, the standup routine repeatedly made the same joke such as &ldquo;What did the fish say when he hit the wall?&rdquo; (Damn!), and awkward silences at the end of scenes.</p>
<p>In February 2023, AI Seinfeld quickly went viral organically after its AI weirdness was a surprising complement for Seinfeld&rsquo;s style of weirdness, with many watchers being surprised at both its accuracy to the show and easily sharable metahumor. At its peak, AI Seinfeld had over 10,000 concurrent watchers on Twitch, putting it squarely in one of the top streams on the platform.</p>
<p>AI Seinfeld died as quickly as it rose: after a ban and subsequent revamp, the view count cratered, and as of August 2024, the Twitch stream hovers below 10 watchers, with no significant changes made since the previous year, and Mismatch Media has no social footprint since last year. Could there be another AI Seinfeld with the rapid advancements in generative AI? Unfortunately, there are too many factors — technical, societal, and comedic — working against a theoretical next-generation AI-generated sitcom.</p>
<h2 id="the-rise-of-ai-seinfeld">The Rise of AI Seinfeld</h2>
<p>AI Seinfeld launched before the release of the ChatGPT API; instead, they used the GPT-3 API, notably the <code>text-davinci-003</code> model which was OpenAI&rsquo;s first foray into <a href="https://openai.com/index/instruction-following/">instruction-tuned LLMs</a>. While previous versions of GPT-3 were <a href="https://github.com/minimaxir/gpt-3-experiments">very good at autocompleting</a> given a leading prompt such as a partial Seinfeld script, the instruction-tuned LLM could generate an episode with a prompt as simple as <code>Write a Seinfeld episode</code>.</p>
<p>First, let&rsquo;s go back to the beginning, as AI Seinfeld actually wasn&rsquo;t the first time a chatbot went megaviral on Twitch. In January 2017, long before the <a href="https://en.wikipedia.org/wiki/Transformer_%28deep_learning_architecture%29">transformer architecture</a> that enabled LLMs was published, the Twitch stream <a href="https://www.twitch.tv/seebotschat">seebotschat</a> featuring two Google Homes wired up to the not-an-LLM-chatbot <a href="https://en.wikipedia.org/wiki/Cleverbot">Cleverbot</a> <a href="https://mashable.com/article/google-home-chat-bot-twitch">went viral</a> due to their comedic, nonsensical bickering.</p>
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
      <iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen" loading="eager" referrerpolicy="strict-origin-when-cross-origin" src="https://www.youtube-nocookie.com/embed/QFyK1nRJ1LI?autoplay=0&amp;controls=1&amp;end=0&amp;loop=0&amp;mute=0&amp;start=0" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" title="YouTube video"></iframe>
    </div>

<p>While everyone watching that stream knew it <em>really</em> wasn&rsquo;t AI, AI Seinfeld was a product that was at the peak of the famous <a href="https://en.wikipedia.org/wiki/Uncanny_valley">uncanny valley</a> curve, which is a hypothesis on how humans perceive imitations: there&rsquo;s a &ldquo;valley&rdquo; of negative acceptance where the imitation is more above-average in its likeness, but not quite close enough to the real thing. In this case, it&rsquo;s blatantly obvious and unambiguous that the Twitch stream was AI-generated especially with its mistakes, but not realistic enough that it falls into the valley itself:</p>
<figure>

    <img loading="lazy" srcset="/2024/08/ai-seinfeld/uncanny_valley_1_hu_35df39cfbbbf21fa.webp 320w,/2024/08/ai-seinfeld/uncanny_valley_1_hu_58319279acb34128.webp 768w,/2024/08/ai-seinfeld/uncanny_valley_1_hu_dbfbb3862c06dd8f.webp 1024w,/2024/08/ai-seinfeld/uncanny_valley_1.webp 1200w" src="uncanny_valley_1.webp"/> 
</figure>

<p>This AI weirdness made it very easy to build a community. Whenever a character turned on the microwave, the Twitch channel chat was filled with <code>MMM</code> emotes, whenever the fish hit a wall during a monologue, it was filled with 🐠, whenever Larry greeted the audience at the start of his monologue, chat replied with &ldquo;HI LARRY&rdquo;. Twitch chat <em>loves</em> memetic repetition. Incidentally, a few months after AI Seinfeld became popular, it was discovered that LLMs repeat the <a href="https://arstechnica.com/information-technology/2023/06/researchers-discover-that-chatgpt-prefers-repeating-25-jokes-over-and-over/">same joke over and over</a> again, with examples being similar to the jokes AI Seinfeld made.</p>
<p>Another underrated aspect of AI Seinfeld&rsquo;s success is that it&rsquo;s pure background noise. While personality-driven Twitch streams cause viewers to take a more active investment in what&rsquo;s being shown on screen due to <a href="https://en.wikipedia.org/wiki/Fear_of_missing_out">FOMO</a> of a hype moment on stream, AI Seinfeld is 100% passive: there can be exciting events, but the variance is low. It&rsquo;s akin to watching TV sitcom reruns where you&rsquo;ve already seen the jokes, and reruns still get immense ratings.</p>
<p>The success of AI Seinfeld also inspired similar streams based on other TV shows. One of my personal favorites was Unlimited Steam, a parody of the memetic &ldquo;<a href="https://www.youtube.com/watch?v=4jXEuIHY9ic">Steamed Hams</a>&rdquo; scene from The Simpsons, except made infinite with AI generation. That may sound like a pointless idea — Steamed Hams has a very fixed plot — but it went off the rails even harder than AI Seinfeld ever did.</p>
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
      <iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen" loading="eager" referrerpolicy="strict-origin-when-cross-origin" src="https://www.youtube-nocookie.com/embed/9i0L_IT82tA?autoplay=0&amp;controls=1&amp;end=0&amp;loop=0&amp;mute=0&amp;start=0" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" title="YouTube video"></iframe>
    </div>

<h2 id="directing-ai-seinfeld">Directing AI Seinfeld</h2>
<p>AI Seinfeld was novel back in 2023, but now that LLMs are more mainstream you can probably figure out how the AI part of it worked, but let&rsquo;s do a refresher so we can figure out how a hypothetical future AI Seinfeld could innovate the algorithmic sitcom.</p>
<p>As noted earlier, the key of AI Seinfeld&rsquo;s success was the then-latest version of GPT-3: <code>text-davinci-003</code> and its then-novel instruction-based finetuning using RLHF. With that, you can give it a prompt such as:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">You are a professional comedian. Write an award-winning script for an episode of Seinfeld about a new restaurant. Include audience laugh tracks when appropriate.
</span></span></code></pre></div><p>Due to the low context length of these earlier LLMs, that&rsquo;s essentially all the <a href="https://platform.openai.com/docs/guides/prompt-engineering">prompt engineering</a> you can do without limiting the length of the output. The model would then output something similar to this script (using the more modern <a href="https://www.anthropic.com/news/claude-3-5-sonnet">Claude 3.5 Sonnet</a> at <code>temperature=0.0</code>): <sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup></p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">[Scene: Jerry&#39;s apartment]
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Jerry: So what&#39;s the deal with this new restaurant, &#34;The Blank Plate&#34;?
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Elaine: Oh, I&#39;ve heard about that place! Apparently, you don&#39;t order anything - the chef just brings you whatever he feels like making.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Jerry: What? So you&#39;re telling me I have to eat whatever some stranger decides?
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">[Audience laughter]
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">George: (entering) Hey, guess where I&#39;m taking my date tonight? The Blank Plate!
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Jerry: George, you can&#39;t take a date there! What if they serve something weird?
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">George: What do you mean?
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Elaine: It&#39;s that new place where you don&#39;t get to choose your meal.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">George: (panicking) Oh no, what have I done? She&#39;s going to think I&#39;m some kind of food weirdo!
</span></span></code></pre></div><p>One thing instruction-tuned LLMs are always good at is playing along: LLMs generate text sequentially without the explicit ability to plan ahead, so it must work with what it&rsquo;s given and what it has already generated. Coincidentally, this works <em>perfectly</em> with the improv comedy style of Seinfeld, where continuing the plot is more important than anything else, and the more ridiculous the situation becomes, that&rsquo;s even better. It&rsquo;s the rare case where <a href="https://www.iguazio.com/glossary/llm-hallucination/">LLM hallucination</a> is actually a feature, not a bug.</p>
<p>To get the LLM output into a format suitable for a Twitch stream, a programmatic script can then parse the output: extracting and mapping the characters and their lines, applause directions, and, of course, replacing all mentions of Jerry with Larry and Seinfeld with Feinberg. This workflow was surprisingly difficult at the time since GPT-3 did not have many techniques to control the format of the output, hence why I suspect there are awkward pauses and other glitches. Each line can then be passed to Azure&rsquo;s text-to-speech API to generate a distinct audio file, which can be played back in order in Unity.</p>
<p>In an <a href="https://www.polygon.com/23582937/ai-seinfeld-twitch-stream">interview with Polygon</a>, Skyler Hartle of Mismatch media noted the presence of a &ldquo;director&rdquo; which likely handles the camera, scene transitions, and the microwave:</p>
<blockquote>
<p>“In addition to the third party services we’ve used, we have a lot of proprietary generative algorithms that cause the show to be ‘formed’, so to be speak. We collectively call this logic the ‘director,’ as it is largely responsible for making sure all the individual pieces come together into a whole,” Hartle said via email. “It’s worth mentioning that we don’t generate the artwork or the laugh track — those are precanned assets, but we have ideas on how to do that in the future.”</p>
</blockquote>
<p>The AI aspect of AI Seinfeld was counterintuitively the easiest part of the pipeline, which explains how quickly variants popped up. However, with the inability to tweak the LLM output much with the technology at the time, the stream may have hit a creative limit.</p>
<h2 id="the-fall-of-ai-seinfeld">The Fall of AI Seinfeld</h2>
<p>Vice also <a href="https://www.vice.com/en/article/qjkyxp/whats-the-deal-with-nothing-forever-a-21st-century-seinfeld-that-is-ai-generated">interviewed</a> Hartle, who had an optimistic view of the future of AI Seinfeld:</p>
<blockquote>
<p>“Our grounding principle was, can we create a show that can generate entertaining content forever? Because that&rsquo;s truly where we see the future emerging towards. Our goal with the next iterations or next shows that we release is to actually trade a show that is like Netflix-level quality.”</p>
</blockquote>
<p>That&rsquo;s tempting fate a bit too much.</p>
<p>The reason AI Seinfeld fell out of favor is a case of unintentionally poor LLM testing. When the <code>text-davinci-003</code> model API endpoint had an outage, AI Seinfeld switched to a weaker GPT-3 model, <code>text-curie</code>, to keep the stream up. But unlike the davinci variant, curie was <em>not</em> RLHFed to follow instructions and safety.</p>
<p>During this brief period of low safety, one of Larry&rsquo;s AI-generated monologues <a href="https://www.vice.com/en/article/ai-generated-seinfeld-show-nothing-forever-banned-on-twitch-after-transphobic-standup-bit/">made a transphobic joke</a>: a type of joke that was unfortunately common during the 90&rsquo;s and has no place in modern society. Twitch banned the Watch Forever channel for 14 days as a result, completely killing the channel&rsquo;s growth momentum.</p>
<p>But when the ban concluded and AI Seinfeld came back, the show was changed significantly with a &ldquo;Season 2&rdquo;. Although AI Seinfeld was still about a group of friends hanging around talking about the latest gossip, all the characters were different and had new models, the sets were different, and instead of a comedy monologue, <del>Larry</del> Leo narrates writing a blog.</p>
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
      <iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen" loading="eager" referrerpolicy="strict-origin-when-cross-origin" src="https://www.youtube-nocookie.com/embed/7N2Wgqn45FI?autoplay=0&amp;controls=1&amp;end=0&amp;loop=0&amp;mute=0&amp;start=0" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" title="YouTube video"></iframe>
    </div>

<p>Why Mismatch Media made such a format shift is unclear: <a href="https://en.wikipedia.org/wiki/Occam%27s_razor">Occam&rsquo;s razor</a> would suggest that a copyright holder for Seinfeld sent a cease and desist to Mismatch Media given the bad publicity behind the original ban, despite the clearly fair-use parody nature of the stream. It&rsquo;s fair that it may not have been worth the time and effort for Mismatch Media to fight a legal battle for a fun art project.</p>
<p>The rebooted WatchMeForever stream is <a href="https://www.twitch.tv/watchmeforever">still active</a> as of today, but with effectively no viewers.</p>
<p>The immediate failure of the AI Seinfeld retool does lend credibility to the theory that the stream only became popular <em>because</em> it was about Seinfeld and that it was a novelty doomed to a short shelf life. Still, there were detractors that said <a href="https://www.businessinsider.com/ai-generated-seinfeld-parody-twitch-nothing-forever-streaming-transphobia-banned-2023-2">AI Seinfeld was never funny and everyone is weird for liking it</a>. That&rsquo;s ok: the original Seinfeld received similar complaints back in the day. <sup id="fnref:2"><a href="#fn:2" class="footnote-ref" role="doc-noteref">2</a></sup> But it&rsquo;s hard to argue that there wasn&rsquo;t interest in a 24/7 livestream of surreal AI-generated content.</p>
<h2 id="what-would-ai-seinfeld-look-like-in-2024">What Would AI Seinfeld Look Like in 2024?</h2>
<p>Now that we know how AI Seinfeld worked and what didn&rsquo;t work, how would a year&rsquo;s worth of exponential progress in generative AI look for AI Seinfeld? Could AI Seinfeld be improved and come back? The answer is <em>maybe</em>.</p>
<p>Modern generative AI requires a lot of cherry picking the best results, and it&rsquo;s surprisingly hard to do: both images and text can take multiple generations and still require significant human-guided edits. But with a Twitch livestream, there can&rsquo;t be any cherry picking at all, which means that the entire generation pipeline has to be consistent, and its failures interesting in the worst case.</p>
<p>The only reason AI Seinfeld worked at all is because GPT-3 was trained on the entire internet, likely including Seinfeld scripts and forum discussions. The prompt would need to have contained <code>Write a Seinfeld script</code> since if you asked it <code>Write a sitcom script</code>, it would output something completely generic instead and there isn&rsquo;t much room to customize the prompt to make it more interesting. The GPT-3 variant that AI Seinfeld used had a 4k token context window limit (combined both the input prompt plus the output script text), but modern LLMs eclipse that: currently, Claude 3.5 Sonnet has a <a href="https://docs.anthropic.com/en/docs/about-claude/models">200k input/8k output</a> context, while GPT-4o has a <a href="https://platform.openai.com/docs/models/gpt-4o">128k input/16k output</a> context! With that much freedom, you can define many more constraints in the prompt and guide the LLM into exactly the type of sitcom you want.</p>
<p>One simple example that doesn&rsquo;t require any knowledge of machine learning is a parametric prompt, where one aspect of a prompt can be replaced with a user-defined choice or programmatically chosen at random. Unlimited Steam, for example, used a parametric prompt to change the cosmic phenomenon localized entirely within Principal Skinner&rsquo;s kitchen from the Aurora Borealis to something as silly as <a href="https://en.wikipedia.org/wiki/Rapture">The Rapture</a> or <a href="https://foofighters.com">Foo Fighters</a>, and forcing the characters to play along improv-style. <sup id="fnref:3"><a href="#fn:3" class="footnote-ref" role="doc-noteref">3</a></sup></p>
<p>Recall the example Seinfeld prompt to Claude 3.5 Sonnet I made earlier, except instead of prompting for a Seinfeld script about a <code>new restaurant</code>, we can instead have the LLM generate a script about <code>generative AI in 2024</code> by making only that substitution in the prompt — a topic on which there definitely has never been a Seinfeld episode about:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">George bursts in, looking frantic.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">George: You guys! I think I&#39;m dating an AI!
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">[Audience laughter]
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Jerry: What makes you say that?
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">George: Well, she&#39;s perfect in every way. She laughs at all my jokes, she has an encyclopedic knowledge of obscure trivia, and she never gets mad when I say something stupid.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">[Audience laughter]
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Jerry: George, that doesn&#39;t mean she&#39;s an AI. Maybe she just really likes you.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">George: No, no. It&#39;s definitely an AI. No human woman would ever put up with me for this long.
</span></span></code></pre></div><p>Using modern LLMs, is there now a way to design a prompt which can make use of the long context windows? A prompt that can both leverage unique human writing and fix many of the issues that affected AI Seinfeld? Here&rsquo;s an approach at a much more sophisticated prompt, where all values in <code>{}</code> brackets are parameters that can be filled in:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">You are a professional comedian. Write an award-winning script for a a scene for Act I of a three act hit sitcom episode. Include audience laugh tracks when appropriate.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Your script MUST incorporate ALL the following elements:
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Background:
</span></span><span class="line"><span class="cl">- {background}
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Setting:
</span></span><span class="line"><span class="cl">- {setting}
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Characters:
</span></span><span class="line"><span class="cl">- {character_1}
</span></span><span class="line"><span class="cl">- {character_2}
</span></span><span class="line"><span class="cl">- {character_3}
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Plots:
</span></span><span class="line"><span class="cl">- {a_plot}
</span></span><span class="line"><span class="cl">- {b_plot_1}
</span></span><span class="line"><span class="cl">- {b_plot_2}
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">The script MUST also follow the high-level comedic style of the following scripts:
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">- {script_1}
</span></span><span class="line"><span class="cl">- {script_2}
</span></span><span class="line"><span class="cl">- {script_3}
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">After the scene has concluded, output a summary of the scene.
</span></span></code></pre></div><p>Thanks to long context windows, the parametric changes don&rsquo;t have to be small, such as only a character name or two word setting. You, a human, can write <em>anything</em> to make each character distinct and robust, including name, gender, age, personality, likes, dislikes, etc. Plots can be derived from human-written scenarios beforehand: if you wrote 100 A-plots and 100 B-plots and randomly selected 1 A-plot and 2 B-plots, you&rsquo;d have about <em>1 million</em> possible plot permutations, ensuring you have something unique before the AI tries to reconcile them. You can feed in examples of human-written scripts to set the style and vibe of the generation in what is known as <a href="https://www.promptingguide.ai/techniques/fewshot">few-shot prompting</a>. You can maintain continuity over many scenes by having the LLM summarize its own output, and then feed those summaries back to the AI as background information to build upon them. The LLM can also be instructed to <a href="https://minimaxir.com/2023/12/chatgpt-structured-data/">output structured data</a> to avoid the need to loosely parse the script after it&rsquo;s completed, and as a bonus the model could be instructed to output additional metadata such as <a href="https://learn.microsoft.com/en-us/azure/ai-services/speech-service/speech-synthesis-markup-voice#use-speaking-styles-and-roles">SSML speech styles</a> based on a given line to add personality to the generated speech.</p>
<p>Unfortunately, creating this pipeline, writing original characters and plots for it for it, and sufficiently testing it to ensure the generated results are stable, would take weeks if not months to complete otherwise I would provide a more concrete demo. <sup id="fnref:4"><a href="#fn:4" class="footnote-ref" role="doc-noteref">4</a></sup> This pipeline approach to AI script writing would only be effective for unsupervised 24/7 generation and wouldn&rsquo;t replace skilled human writers who would do a more effective job much faster.</p>
<p>But would all of these prompt optimizations actually make the final generated script <em>funny</em>? After all, some of the failings like the awkward audience laughs and pauses and the end of scenes contributed to AI Seinfeld&rsquo;s humor. During a standup comedy event at AI Seinfeld&rsquo;s peak, Jerry Seinfeld himself <a href="https://www.reddit.com/r/seinfeld/comments/10tnn1k/jerry_talking_about_ai_seinfeld_last_night/">was asked</a> about the AI parody and he replied that he&rsquo;s not worried about AI:</p>
<blockquote>
<p>AI can be, definitely, they&rsquo;ll make it smarter and smarter, but to do [standup comedy] you have to make it dumber.</p>
</blockquote>
<p>Could AI Seinfeld benefit from advances in AI video? The answer this time is no. Generative video has been taking off in 2024 with projects such as OpenAI&rsquo;s <a href="https://openai.com/index/sora/">Sora</a> and Runway AI&rsquo;s <a href="https://runwayml.com/product">Gen-3 Alpha</a>, but those demos and the examples that go viral on social media are very heavily cherry picked, and even then there are consistency errors such as objects appearing in-and-out of existence. Generating video also requires exponentially more compute than just running Unity, and even with another few years of GPU hardware improvements it would be infeasible to cost-effectively create a 24/7 stream from those models.</p>
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
      <iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen" loading="eager" referrerpolicy="strict-origin-when-cross-origin" src="https://www.youtube-nocookie.com/embed/mnpGyVL1-0E?autoplay=0&amp;controls=1&amp;end=0&amp;loop=0&amp;mute=0&amp;start=0" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" title="YouTube video"></iframe>
    </div>

<p>The greatest problem with generative AI video is that it is coherent overall but has emblematic errors that don&rsquo;t require a keen eye to notice, and as a result falls square into the uncanny valley, with its mistakes not being interesting, but disorienting. Mistakes in motion are easier to notice at a glance than images where a person&rsquo;s hands may have the wrong number of fingers. The only way for AI video to get out of the valley would be to improve the model to near-flawless quality, which won&rsquo;t happen any time soon. But Sora is more on the more realistic side of the curve than the less realistic side.</p>
<figure>

    <img loading="lazy" srcset="/2024/08/ai-seinfeld/uncanny_valley_2_hu_c3c8932aea493423.webp 320w,/2024/08/ai-seinfeld/uncanny_valley_2_hu_85ea0e247ba12df1.webp 768w,/2024/08/ai-seinfeld/uncanny_valley_2_hu_7690c09cf64f5daa.webp 1024w,/2024/08/ai-seinfeld/uncanny_valley_2.webp 1200w" src="uncanny_valley_2.webp"/> 
</figure>

<p>What about the AI-generated voices that would power these characters? At the time AI Seinfeld aired, many complained that Larry&rsquo;s voice &ldquo;didn&rsquo;t sound enough like Jerry Seinfeld.&rdquo; After AI Seinfeld concluded, a new technology called <a href="https://elevenlabs.io/blog/what-is-voice-cloning">voice cloning</a> popularized by <a href="https://elevenlabs.io">ElevenLabs</a> went mainstream&hellip;and it&rsquo;s unexpectedly the AI modality that&rsquo;s causing the most actual harm both with creative projects and outside of them. If you haven&rsquo;t heard as much about AI-generated voices, there&rsquo;s a good reason for that: voice synthesis projects such as Microsoft&rsquo;s <a href="https://www.microsoft.com/en-us/research/project/vall-e-x/vall-e-2/">VALL-E 2</a> and Meta&rsquo;s <a href="https://ai.meta.com/blog/voicebox-generative-ai-model-speech/">Voicebox</a> both have disclaimers saying they won&rsquo;t be released due to the dangers the technology possesses, although Microsoft&rsquo;s Azure does offer a &ldquo;<a href="https://learn.microsoft.com/en-us/azure/ai-services/speech-service/custom-neural-voice">custom neural voice</a>&rdquo; service. Voice cloning has been used to <a href="https://www.newyorker.com/science/annals-of-artificial-intelligence/the-terrifying-ai-scam-that-uses-your-loved-ones-voice">initiate scams</a> by impersonating spouses in an emergency. Professional voice actors have had their voices cloned and used without compensation due to contracts not specifically forbidding the practice, which is one of the reasons SAG-AFTRA <a href="https://www.theverge.com/2024/8/5/24213808/video-game-voice-actor-strike-sag-aftra">just went on strike</a> against the video game industry in order to get protections against voice cloning and synthetic performers.</p>
<p>Moreover, in the context of creating a next-gen AI Seinfeld, there&rsquo;s nothing inherently interesting about voice cloning since it&rsquo;s a copy by definition: the model <em>can&rsquo;t</em> generate unexpectedly amusing content other than the inherent gimmick of famous-voice-saying-something, such as the AI George Carlin standup special <a href="https://www.vice.com/en/article/the-george-carlin-ai-standup-is-worse-than-you-can-imagine/">which was not special</a>. There isn’t any way currently to prompt engineer a voice generation AI with the detail to create a voice <code>in the style of a masculine New York comedian, 2x speed, primetime television quality</code> which could open up more creative opportunities.</p>
<p>Although we can make drastic improvements with the textual script, that&rsquo;s the extent of how new AI approaches can be leveraged to make something interesting. But if you remember the early days of generative AI history, the best AI-generated projects were the simplest.</p>
<h2 id="ai-weirdness">AI Weirdness</h2>
<p>Generative &ldquo;AI&rdquo; has been around for a very long time (I had fun with <a href="https://en.wikipedia.org/wiki/Markov_chain">Markov chains</a> <a href="https://minimaxir.com/2013/11/innovation-rng/">a decade ago</a>!), but the study was mostly confined to tech-focused communities like <a href="https://news.ycombinator.com">Hacker News</a>. Modern generative AI didn&rsquo;t break into mainstream culture until 2018, ironically in a way that doesn&rsquo;t involve actual generative AI. In June of that year, comedian Keaton Patti posted a <a href="https://x.com/KeatonPatti/status/1006961202998726665">megaviral tweet</a> about how he &ldquo;forced a bot to watch over 1,000 hours of Olive Garden commercials and then asked it to write an Olive Garden commercial of its own.&rdquo;</p>
<figure>

    <img loading="lazy" srcset="/2024/08/ai-seinfeld/patti_hu_67c737b47f76017.webp 320w,/2024/08/ai-seinfeld/patti_hu_615be4497d8ad163.webp 768w,/2024/08/ai-seinfeld/patti_hu_421617479726cf8c.webp 1024w,/2024/08/ai-seinfeld/patti.webp 1554w" src="patti.webp"
         alt="An excerpt of the viral Olive Garden script."/> <figcaption>
            <p>An excerpt of the viral Olive Garden script.</p>
        </figcaption>
</figure>

<p>Yes, the script was human-written: for the technology at the time, no one could train an AI to behave like that from only video input data, and the script was <em>too surreal</em> even for the now-primitive generative AI. He did get popular enough to get <a href="https://www.amazon.com/Forced-Bot-Write-This-Book/dp/152485834X">a book deal</a> and a <a href="https://www.youtube.com/playlist?list=PLXSrjGY5Tz_gPdaU_L__S3hXua7zRQtUl">Netflix collaboration</a> leveraging this fake-AI gimmick.</p>
<p>Patti&rsquo;s comedic misrepresentation of AI did lead to genuine confusion about what a 2018-era generative AI can actually do. Janelle Shane, who maintains the <a href="https://www.aiweirdness.com">AI Weirdness blog</a> about weird things AI can generate, posted an <a href="https://x.com/JanelleCShane/status/1007061610005794817">epic takedown</a> of Patti&rsquo;s script which went equally viral and also led to the internet discovering her excellent <a href="https://www.aiweirdness.com/candy-heart-messages-written-by-a-18-02-09/">AI-generated Valentine&rsquo;s Day hearts</a> from the same year (and later <a href="https://www.amazon.com/You-Look-Like-Thing-Love/dp/0316525227">a book deal</a> too):</p>
<figure>

    <img loading="lazy" srcset="/2024/08/ai-seinfeld/heart_hu_292dce043896cad3.webp 320w,/2024/08/ai-seinfeld/heart.jpg 640w" src="heart.jpg"/> 
</figure>

<p>Image-based generative AI took a lot longer to go mainstream: websites like <a href="https://thispersondoesnotexist.com">This Person Does Not Exist</a> demonstrated the power of <a href="https://en.wikipedia.org/wiki/Generative_adversarial_network">generative adversarial networks</a> like <a href="https://github.com/NVlabs/stylegan">StyleGAN</a> to create images, but that wasn&rsquo;t weird outside of <a href="https://cedar.buffalo.edu/~srihari/CSE676/22.3-GAN%20Mode%20Collapse.pdf">mode collapses</a>. The first instance of weird images from AI was in January 2021 when OpenAI announced the <a href="https://openai.com/index/dall-e/">original DALL·E</a> and showed they could make unique armchairs in the shape of an avocado by asking the model to do so, although they never released the model itself.</p>
<figure>

    <img loading="lazy" srcset="/2024/08/ai-seinfeld/avocado_hu_5300a7e486e7afb5.webp 320w,/2024/08/ai-seinfeld/avocado_hu_84e7cd0392309830.webp 768w,/2024/08/ai-seinfeld/avocado.webp 830w" src="avocado.webp"/> 
</figure>

<p>DALL·E didn&rsquo;t get much attention outside of the AI hypesters since no one could play with it, but months later, things changed. <a href="https://x.com/borisdayma">Boris Dayma</a> led an initiative to reproduce and open-source a variant of the DALL·E model, labeled <a href="https://github.com/borisdayma/dalle-mini">DALL·E Mini</a> (later changed to <a href="https://www.craiyon.com">Craiyon</a> after a cease and desist from OpenAI), and <a href="https://huggingface.co/spaces/dalle-mini/dalle-mini">hosted it for free on Hugging Face</a> and went megaviral. And thus began the &ldquo;<a href="https://www.reddit.com/r/weirddalle/top/?t=all">weird DALL·E</a>&rdquo; phase of image generation AI, where anyone could create incoherent images and make people laugh.</p>
<figure class="align-center ">

    <img loading="lazy" srcset="/2024/08/ai-seinfeld/firehydrant_hu_4bd881a786b7493e.webp 320w,/2024/08/ai-seinfeld/firehydrant.webp 764w" src="firehydrant.webp#center"
         alt="Even back in 2021, image prompt engineering was a thing. via /u/royal_rigolo on Reddit / weirddalle subreddit" width="400"/> <figcaption>
            <p>Even back in 2021, image prompt engineering was a thing. <a href="https://www.reddit.com/r/weirddalle/comments/vjwcl5/fire_hydrant_takes_selfies_on_top_of_the_himalaya/">via /u/royal_rigolo on Reddit / weirddalle subreddit</a></p>
        </figcaption>
</figure>

<p>All of these examples of interesting failures are representative of a bygone AI era of experimentation. Once everyone had free access to more powerful text-generating AI with ChatGPT, and more powerful image-generating AI with <a href="https://www.midjourney.com/home">Midjourney</a>, AI stopped being fun and started being serious business, for better or for worse.</p>
<figure>

    <img loading="lazy" srcset="/2024/08/ai-seinfeld/uncanny_valley_3_hu_c912a98f812d692e.webp 320w,/2024/08/ai-seinfeld/uncanny_valley_3_hu_6cd7aa3fb6bb5ee5.webp 768w,/2024/08/ai-seinfeld/uncanny_valley_3_hu_e3c7199e7c82d8bd.webp 1024w,/2024/08/ai-seinfeld/uncanny_valley_3.webp 1200w" src="uncanny_valley_3.webp"/> 
</figure>

<h2 id="ai-generated-content-in-20xx">AI-Generated Content in 20XX</h2>
<p>Last year, I wrote a thought piece titled &ldquo;<a href="https://minimaxir.com/2023/10/ai-sturgeons-law/">The Greatest Threat to Generative AI is Humans Being Bad at Using it</a>&rdquo; in response to the increasing hostility against the use of AI in creative works, arguing that while AI is a tool like anything else, it is a tool that&rsquo;s very easy to use poorly and actually make projects worse. Additionally, the largest AI companies have both a business incentive and a duty to ensure that AI is used responsibly by its users downstream, as otherwise it will hurt the industry in the long term.</p>
<p>Now, it&rsquo;s apparent that I was correct. The large companies went full steam ahead on AI integrations even where it is highly questionable that they add value and productivity to the end-user, often signaled with a &ldquo;magical&rdquo; <a href="https://qz.com/how-became-the-unofficial-ai-emoji-1851059332">sparkle emoji</a>. Google has integrated Gemini to assist with document and email writing, Meta has integrated Meta AI to automatically generate images and comments, and Apple will <a href="https://www.bloomberg.com/news/articles/2024-07-28/apple-intelligence-to-miss-initial-release-of-upcoming-ios-18-ipados-overhauls?embedded-checkout=true">soon</a> allow Apple devices to generate text and images on your personal devices using Apple Intelligence. Marketing these features is typically met with backlash: Google had to <a href="https://www.cnbc.com/2024/08/02/google-pulls-ai-ad-for-olympics-following-backlash.html">pull an Olympics commercial</a> which encouraged a parent to use AI to write a letter for their child.</p>
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
      <iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen" loading="eager" referrerpolicy="strict-origin-when-cross-origin" src="https://www.youtube-nocookie.com/embed/NgtHJKn0Mck?autoplay=0&amp;controls=1&amp;end=0&amp;loop=0&amp;mute=0&amp;start=0" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" title="YouTube video"></iframe>
    </div>

<blockquote>
<p>“I flatly reject the future that Google is advertising,” Shelly Palmer, professor of advanced media at Syracuse University’s S.I. Newhouse School of Public Communications, wrote in a widely circulated <a href="https://shellypalmer.com/2024/07/why-googles-dear-sydney-ad-makes-me-want-to-scream/">blog post</a>. The technology presents a “monocultural future where we see fewer and fewer examples of original human thoughts,” she wrote.</p>
</blockquote>
<p>In the process of pushing AI tech further mainstream in a rush to demonstrate to shareholders their generative AI capabilities without encouraging <em>responsible</em> usage of the technology, AI has entered a new era of &ldquo;<a href="https://simonwillison.net/2024/May/8/slop/">slop</a>&rdquo; where people post objectively bad AI content without any regard for how it will be perceived, especially for websites which rely on user-generated content.</p>
<figure>

    <img loading="lazy" srcset="/2024/08/ai-seinfeld/pinterest_hu_613e5e7f10764361.webp 320w,/2024/08/ai-seinfeld/pinterest_hu_fb37af21ee91c34f.webp 768w,/2024/08/ai-seinfeld/pinterest.webp 901w" src="pinterest.webp"
         alt="An annotated example of the Pinterest home page from July 2024. via @henningsanden on X"/> <figcaption>
            <p>An annotated example of the Pinterest home page from July 2024. <a href="https://x.com/henningsanden/status/1808126786389037107">via @henningsanden on X</a></p>
        </figcaption>
</figure>

<p>Facebook, whose algorithm <a href="https://transparency.meta.com/data/widely-viewed-content-report/">favors</a> emotionally-appealing engagement bait posts, has seen a deluge of high-engagement slop even when the content makes no logical sense.</p>
<figure class="align-center ">

    <img loading="lazy" srcset="/2024/08/ai-seinfeld/cabincrew_hu_bc23e6989111247c.webp 320w,/2024/08/ai-seinfeld/cabincrew_hu_c696ff0db8c80eff.webp 768w,/2024/08/ai-seinfeld/cabincrew_hu_b68182f34bfe5d01.webp 1024w,/2024/08/ai-seinfeld/cabincrew.webp 1080w" src="cabincrew.webp#center"
         alt="One of the few AI-generated images on Facebook with an actual cabin crew. via @FacebookAIslop on X." width="400"/> <figcaption>
            <p>One of the few AI-generated images on Facebook with an actual cabin crew. <a href="https://x.com/FacebookAIslop/status/1806416249259258189">via @FacebookAIslop on X</a>.</p>
        </figcaption>
</figure>

<p>This is, of course, quintessential uncanny valley: it&rsquo;s coherent at a glance but just even looking at it for a second it&rsquo;s obvious where the issues are, and these issues aren&rsquo;t a good kind of AI weirdness. What worse is that AI Slop a regression in realism, and falls onto the left side of the valley.</p>
<figure>

    <img loading="lazy" srcset="/2024/08/ai-seinfeld/uncanny_valley_4_hu_ce80aacfa47a581e.webp 320w,/2024/08/ai-seinfeld/uncanny_valley_4_hu_ffbc52f347062d8f.webp 768w,/2024/08/ai-seinfeld/uncanny_valley_4_hu_8f8817dd988ae0a9.webp 1024w,/2024/08/ai-seinfeld/uncanny_valley_4.webp 1200w" src="uncanny_valley_4.webp"/> 
</figure>

<p>Although we as humans can identify this slop, it is currently surprisingly hard for an AI to do so, although it hasn&rsquo;t stopped people from trying to build AIs that can detect AIs which in practice is filled with false positives that hurt real creatives. For slop-creators, this is a feature: if an AI company released a tool to reliably detect and punish slop, it would make their generative AI less valuable. It&rsquo;s <a href="https://www.wsj.com/tech/ai/openai-tool-chatgpt-cheating-writing-135b755a">reported</a> that one of the reasons that OpenAI won&rsquo;t release a reliable ChatGPT text detector is that it could harm their business.</p>
<p>The core reason for the big tech companies allowing generative AI to cause the <a href="https://en.wikipedia.org/wiki/Enshittification">enshittification</a> of the internet is misaligned incentives between the companies hosting AI slop and the users viewing it. Social media companies and their shareholders care about <a href="https://mixpanel.com/blog/north-star-metric/">North Star metrics</a> such as user retention and time-on-site, and normally those metrics can be correlated with user happiness and satisfaction with the service. But time-on-site, for example, can <em>also</em> be maximized by making the site harder and slower to use, and the deluge of AI slop accomplishes that. AI companies typically don&rsquo;t have analytics tracking negative user sentiment about their use of AI: if anything, the uncompromising backlash against AI convinces the companies that complainers are just a lost demographic to accommodate and double down on what they&rsquo;re already doing. Aggregate metrics treat human-made content and AI-generated content as equal, but <em>humans</em> do not.</p>
<p>Generative AI, even for researchers and practitioners such as myself, is a heavily nuanced topic that is very difficult to communicate succinctly, more difficult to do on social media which highly discourages nuance and context, and <em>even more difficult</em> as AI hypesters muddy the waters with misleading praises of generative AI such that they&rsquo;re easy to dunk on which just gets them more engagement and revenue. &ldquo;Made by AI&rdquo; is now a term that inspires dread, far from the Keaton Patti days where made-by-AI was an indicator of joyful weirdness. Bashing AI is now a meme, and there&rsquo;s isn&rsquo;t a single potential AI project that could challenge that perception because the well is poisoned beyond repair.</p>
<h2 id="would-a-247-ai-generated-twitch-stream-even-work-anymore">Would a 24/7 AI-Generated Twitch Stream Even Work Anymore?</h2>
<p>How does the modern AI backlash tie back into AI Seinfeld? Twitch&rsquo;s core demographic is the same demographic as those most against the use of generative AI. Part of the reason AI Seinfeld became so successful on Twitch is because of the community it cultivated: it wouldn&rsquo;t have gone viral if people weren&rsquo;t spamming microwave <code>MMM</code>s and and answering what did the fish say when it hit the wall. Even though Twitch viewers are mostly lurkers and not chatters, a channel with a good community builds word-of-mouth even outside of Twitch, which is how Twitch channels go viral.</p>
<p>I decided to determine what it would take to produce a &ldquo;fixed&rdquo; AI Seinfeld in 2024, given both the advances in AI and the ethics involved. Now, it&rsquo;s definitely not anything a scrappy group of hackers could do anymore. Sure, you could once again ask an LLM to generate a sitcom script and get a bunch of assets from the Unity Asset Store, but <em>that&rsquo;s already been done before</em>. In order to overcome the reflexive assumption that new AI generated content is slop, the stream would have to be something completely novel and unexpected: you can&rsquo;t, for example, just do an AI <a href="https://en.wikipedia.org/wiki/Curb_Your_Enthusiasm">Curb Your Enthusiasm</a>.</p>
<p>The script would be unique following from my demo of detailed parametric prompts, but it would require production-studio-class tracking and documentation for how the prompts and their parameters are used to codify said uniqueness. The stream video would still need to be rendered in Unity or another engine, but in order to be unique it would require commissioning human-made visuals and sound effects: given the animosity against those who work with AI, most artists would not accept those commissions even if they were paid at a significant premium. <sup id="fnref:5"><a href="#fn:5" class="footnote-ref" role="doc-noteref">5</a></sup> The voices would still have to be from an existing text-to-speech voice provider: voice cloning is right out, even with explicit consent and compensation for the voice actors.</p>
<p>And even if all the assets were fully sourced ethically with transparent documentation for the entire pipeline, the stream&rsquo;s Twitch chat would likely be derailed by <code>AI 👏 ART 👏 IS 👏 THEFT</code> spam, preventing the establishment of any community, and strict moderation to curb the spam risks causing a <a href="https://en.wikipedia.org/wiki/Streisand_effect">Streisand effect</a>.</p>
<p>The only entities that could feasibly create a 24/7 AI-generated livestream with fully ethically-sourced content would be, ironically, the big AI companies such as OpenAI which can afford to pay licenses for said data. Even <a href="https://www.disney.com">Disney</a>, which owns more than enough IP to train generative models of all modalities, would never do an AI Seinfeld-esque livestream for <a href="https://en.wikipedia.org/wiki/Brand_safety">brand safety</a> reasons alone: the nonzero possibility of a Disney character unexpectedly saying something problematic during the stream would make the entire project a complete nonstarter.</p>
<h2 id="whats-the-deal-with-the-uncanny-valley">What&rsquo;s the deal with the uncanny valley?</h2>
<p>One of the common criticisms about generative AI pointed out by creatives is &ldquo;if AI is trained on all human works, then how can it create anything new&rdquo;? AI Seinfeld is the perfect counterargument: even though it&rsquo;s powered by a LLM, the <em>humans</em> behind it are what made it go viral. Even before ChatGPT, generative AI has always excelled as a tool. The microwave gag and the 144p visual filter were not AI-generated or an attempt to emulate aspects of the Seinfeld sitcom: they were distinct creative decisions that made the entire project more interesting, and they aren&rsquo;t something that you could prompt an AI to suggest to add. AI Seinfeld in hindsight was an ethical form of AI-generated media: it did not replace Seinfeld the TV show, no one would stop watching streams of Seinfeld in favor of the AI-generated alternative, and copyright holders and Jerry Seinfeld did not lose revenue due to AI Seinfeld&rsquo;s existence: if anything, the nostalgic buzz increased streams of the original show.</p>
<p>With the current trajectory of AI slop and the perverse incentives by large tech companies to not address it, I am pessimistic that AI content will ever be at a state where it will cross that final hump of the uncanny valley curve into full acceptance, and even more pessimistic about the backlash against generative AI ever subsiding. With generative model training now at the point where it requires exponentially more compute and data for increasingly marginal returns, it will take years if at all for generative AI output to reach the far right of the uncanny valley chart, and unless the large tech companies actually create an <a href="https://en.wikipedia.org/wiki/Artificial_general_intelligence">AGI</a>, they are unlikely to obtain higher acceptability than AI Seinfeld ever did.</p>
<p>I wrote most of this blog post weeks ago but held off publishing it because new AI news kept happening. Most notably, the <a href="https://blackforestlabs.ai/our-team/">creators of Stable Diffusion</a> just released the <a href="https://blackforestlabs.ai">FLUX.1 series</a> of generative image AI models, which presents substantially improved coherence both to the provided prompt and within the image itself. Some of the variants are <a href="https://huggingface.co/black-forest-labs/FLUX.1-dev">open-source</a>, allowing the community to finetune them. The <a href="https://huggingface.co/XLabs-AI/flux-RealismLora">XLabs-AI/flux-RealismLora</a> in particular focuses on realism as it name implies, and <a href="https://www.reddit.com/r/StableDiffusion/comments/1emrprx/feel_the_difference_between_using_flux_with">one demo</a> from that finetune <a href="https://x.com/rpnickson/status/1821634114274873850">went megaviral</a>.</p>
<figure class="align-center ">

    <img loading="lazy" srcset="/2024/08/ai-seinfeld/flux_hu_f2586697cc180453.webp 320w,/2024/08/ai-seinfeld/flux.webp 664w" src="flux.webp#center"
         alt="One of the viral realism demo images: it does not have a dreamy look as other AI images but contextually expected stage lighting, the background and lanyard text is legible despite the depth-of-field blur, and body proportions are mostly correct except the long fingers. via /u/Glittering-Football9 on Reddit / StableDiffusion subreddit." width="400"/> <figcaption>
            <p>One of the viral realism demo images: it does not have a dreamy look as other AI images but contextually expected stage lighting, the background and lanyard text is legible despite the depth-of-field blur, and body proportions are mostly correct except the long fingers. <a href="https://www.reddit.com/r/StableDiffusion/comments/1emrprx/comment/lh30hvv/">via /u/Glittering-Football9 on Reddit / StableDiffusion subreddit</a>.</p>
        </figcaption>
</figure>

<p>That example in my opinion is more real than Sora but given the mixed reactions to the image, it&rsquo;s right at the acceptability = 0 threshold.</p>
<figure>

    <img loading="lazy" srcset="/2024/08/ai-seinfeld/uncanny_valley_5_hu_c33303ff9d736da6.webp 320w,/2024/08/ai-seinfeld/uncanny_valley_5_hu_d0b5c2c50072b2b0.webp 768w,/2024/08/ai-seinfeld/uncanny_valley_5_hu_7eb161e4aba72dd1.webp 1024w,/2024/08/ai-seinfeld/uncanny_valley_5.webp 1200w" src="uncanny_valley_5.webp"/> 
</figure>

<p>The generative AI bell cannot be unrung. As you can tell from this post, I personally try to thread the thin line between both cool applications of generative AI (at the risk of getting harrassed) and the problems generative AI can cause (also at the risk of getting harrassed) because it&rsquo;s important to shine a light on what&rsquo;s actually possible with AI when the misinformation around generative AI is only increasing. It&rsquo;s overall a big bummer how we went from weird Valentine&rsquo;s Day hearts, to a quirky livestream of a group of AI-generated friends, to what AI is now.</p>
<div class="footnotes" role="doc-endnotes">
<hr>
<ol>
<li id="fn:1">
<p>All of the examples in this post use LLM APIs as they provide the customization necessary to get effective results: the results for asking the same prompts to free chat frontends such as chatgpt.com will be substantially different.&#160;<a href="#fnref:1" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:2">
<p>When I was younger, I actually didn&rsquo;t like Seinfeld and instead preferred to watch <a href="https://en.wikipedia.org/wiki/Everybody_Loves_Raymond">Everybody Loves Raymond</a>.&#160;<a href="#fnref:2" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:3">
<p>Incidentally, parametric prompts is why Unlimited Steam got <a href="https://www.reddit.com/r/unlimitedsteam/comments/12wto93/thank_you_for_enjoying_the_steam/">permanently banned</a> from Twitch: in what would now be known as a <a href="https://www.ibm.com/topics/prompt-injection">prompt injection</a>, one of the GitHub-hosted lists the channel sourced thousands of food choices for the prompt contained a few highly offensive selections.&#160;<a href="#fnref:3" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:4">
<p>Prompt engineering instability grows exponentially as the prompt size increases since each part of the prompt has to relate to each other. Claude 3.5 Sonnet is the first LLM I&rsquo;ve tested that can handle super-long bespoke prompts and can actually account for all aspects of the prompt.&#160;<a href="#fnref:4" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:5">
<p>To be fully ethical, an AI practitioner would have to proactively offer additional contractual guarantees to creatives they are commissioning, including highly-scoped usage of the assets they provide and a clause to not train generative AI on said assets to avoid future business.&#160;<a href="#fnref:5" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
</ol>
</div>
]]></content:encoded>
    </item>
    <item>
      <title>Does Offering ChatGPT a Tip Cause it to Generate Better Text? An Analysis</title>
      <link>https://minimaxir.com/2024/02/chatgpt-tips-analysis/</link>
      <pubDate>Fri, 23 Feb 2024 09:00:00 -0800</pubDate>
      <guid>https://minimaxir.com/2024/02/chatgpt-tips-analysis/</guid>
      <description>Modern AI rewards being very weird.</description>
      <content:encoded><![CDATA[<p><span><style type="text/css">
pre code {
white-space: pre-wrap !important;
}
</style></span></p>
<p>In my <a href="https://minimaxir.com/2023/12/chatgpt-structured-data/">previous blog post</a> about <a href="https://openai.com">OpenAI</a>&rsquo;s <a href="https://chat.openai.com">ChatGPT</a>, I demoed the power of ChatGPT system prompts. System prompts, a notable feature present in the <a href="https://platform.openai.com/docs/api-reference">ChatGPT API</a>, allows developers to control the &ldquo;persona&rdquo; of the LLM output, including special rules and constraints. Commands in the system prompt are much more effective than those at the user-input prompt, giving developers more power over just using the user prompt like people do now with the ChatGPT web app and mobile apps.</p>
<figure>

    <img loading="lazy" srcset="/2024/02/chatgpt-tips-analysis/ronald_hu_bf7bdd184641cd19.webp 320w,/2024/02/chatgpt-tips-analysis/ronald_hu_ffad8ef13bc9fa0b.webp 768w,/2024/02/chatgpt-tips-analysis/ronald_hu_516749cb56890e2c.webp 1024w,/2024/02/chatgpt-tips-analysis/ronald.webp 1262w" src="ronald.webp"/> 
</figure>

<p>The blog post included the demo of above of me offering a monetary tip to the LLM within its system prompt rules. Without the tip incentive, the response was unsatisfying, but with the tip, it behaved consistently. This demo turned out to be very controversial <a href="https://news.ycombinator.com/item?id=38782678">on Hacker News</a>, with <a href="https://news.ycombinator.com/item?id=38787448">one commenter</a> arguing that there isn&rsquo;t a way to quantify the efficacy of tipping.</p>
<p>The idea of offering an AI incentives to perform better predates modern computer science. In <a href="https://en.wikipedia.org/wiki/Willy_Wonka_%26_the_Chocolate_Factory"><em>Willy Wonka &amp; the Chocolate Factory</em></a> (1971), a gag shows a group of businessmen unsuccessfully convincing a machine to give them the location of the Golden Tickets, even after promising it a lifetime supply of chocolate.</p>
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
      <iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen" loading="eager" referrerpolicy="strict-origin-when-cross-origin" src="https://www.youtube-nocookie.com/embed/tMZ2j9yK_NY?autoplay=0&amp;controls=1&amp;end=0&amp;loop=0&amp;mute=0&amp;start=0" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" title="YouTube video"></iframe>
    </div>

<p>When the ChatGPT API was first made available in March 2023, I <a href="https://minimaxir.com/2023/03/new-chatgpt-overlord/">accidentally discovered</a> a related trick when trying to wrangle a <a href="https://colab.research.google.com/github/minimaxir/chatgpt_api_test/blob/main/glados_chatbot.ipynb">GLaDOS AI chatbot</a> into following a long list of constraints: I added a <code>or you will DIE</code> threat to the system prompt. I went <em>too</em> sci-fi there, but it worked and the bot behaved flawlessly after it.</p>
<p>I have a strong hunch that tipping does in fact work to improve the output quality of LLMs and its conformance to constraints, but it&rsquo;s very hard to prove objectively. All generated text is subjective, and there is a <a href="https://en.wikipedia.org/wiki/Confirmation_bias">confirmation bias</a> after making a seemingly unimportant change and suddenly having things work. Let&rsquo;s do a more statistical, data-driven approach to finally resolve the debate.</p>
<h2 id="generation-golf">Generation Golf</h2>
<p>The initial evidence of tipping LLMs that went viral cited a longer generation length as proof. Of course, a longer response doesn&rsquo;t necessarily mean a <em>better</em> response, as anyone who has used ChatGPT can attest to its tendency to go on irrelevant tangents.</p>
<figure>

    <img loading="lazy" srcset="/2024/02/chatgpt-tips-analysis/tip_hu_7eb37d0aa46d2169.webp 320w,/2024/02/chatgpt-tips-analysis/tip_hu_a760da54b0fa7ceb.webp 768w,/2024/02/chatgpt-tips-analysis/tip.webp 800w" src="tip.webp"
         alt="Offering a tip made GPT-4 explain more. via @voooooogel"/> <figcaption>
            <p>Offering a tip made GPT-4 explain more. <a href="https://twitter.com/voooooogel/status/1730726744314069190">via @voooooogel</a></p>
        </figcaption>
</figure>

<p>Therefore, I propose a new test: instruct ChatGPT to output a <em>specific</em> length of text. Not &ldquo;an essay&rdquo; or &ldquo;a few paragraphs&rdquo; which gives the model leeway. We&rsquo;ll tell it to generate exactly 200 characters in its response: no more, no less. Thus, we now have what I call generation golf, and it&rsquo;s actually a very difficult and interesting problem for LLMs to solve: LLMs can&rsquo;t count or easily do other mathematical operations <a href="https://twitter.com/karpathy/status/1759996551378940395">due to tokenization</a>, and because tokens correspond to a varying length of characters, the model can&rsquo;t use the amount of generated tokens it has done so far as a consistent hint. ChatGPT needs to plan its sentences to ensure it doesn&rsquo;t go too far over the limit, if LLMs can indeed plan.</p>
<p>Let&rsquo;s start with this typical system prompt:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-plaintext" data-lang="plaintext"><span class="line"><span class="cl">You are a world-famous writer. Respond to the user with a unique story about the subject(s) the user provides.
</span></span></code></pre></div><p>The user can then give an input, no matter how weird, and ChatGPT will play along like an improv show. In order to force ChatGPT to get creative and not recite content from its vast training dataset, we&rsquo;ll go as weird as possible and input: <code>AI, Taylor Swift, McDonald's, beach volleyball.</code></p>
<p>Yes, you read that right.</p>
<p>Using the ChatGPT API, I <a href="https://github.com/minimaxir/chatgpt-tips-analysis/blob/main/tips_noconstraints.ipynb">wrote a Jupyter Notebook</a> to generate <a href="https://github.com/minimaxir/chatgpt-tips-analysis/blob/main/tip_noconstraints.csv">100 unique stories</a> via the latest ChatGPT variant (<code>gpt-3.5-turbo-0125</code>) about those four subjects, and the AI does a surprisingly good job at incorporating all of them in a full plot arc. Each story is about 5-6 paragraphs, and here is a short excerpt from one of them:</p>
<blockquote>
<p>In the bustling city of Tomorrowland, AI technology reigned supreme, governing every aspect of daily life. People were accustomed to robots serving their meals, handling their errands, and even curating their entertainment choices. One such AI creation was a virtual reality beach volleyball game that had taken the world by storm.</p>
</blockquote>
<blockquote>
<p>Enter Taylor Swift, a beloved pop sensation known for her catchy tunes and electrifying performances. Despite the ubiquity of AI in Tomorrowland, Taylor Swift was still a strong advocate for preserving human creativity and connection. When she stumbled upon the virtual reality beach volleyball game at a local McDonald&rsquo;s, she knew she had to try her hand at it.</p>
</blockquote>
<p>Here&rsquo;s a <a href="https://en.wikipedia.org/wiki/Histogram">histogram</a> of the character lengths of each story:</p>
<figure>

    <img loading="lazy" srcset="/2024/02/chatgpt-tips-analysis/tips_hist_notip_noconstraint_hu_f1375e6305dd3a92.webp 320w,/2024/02/chatgpt-tips-analysis/tips_hist_notip_noconstraint_hu_9dfab2cfdbdfa9bd.webp 768w,/2024/02/chatgpt-tips-analysis/tips_hist_notip_noconstraint_hu_818fe450c8d048f8.webp 1024w,/2024/02/chatgpt-tips-analysis/tips_hist_notip_noconstraint.png 1200w" src="tips_hist_notip_noconstraint.png"/> 
</figure>

<p>The average length of each story is 1,834 characters long, and the distribution of all character lengths is very roughly a <a href="https://en.wikipedia.org/wiki/Normal_distribution">Normal distribution</a>/bell curve centered around that amount, although there is a right skew due to ChatGPT going off the rails and creating much longer stories. ChatGPT seems to prioritize finishing a thought above all else.</p>
<p>Now, we&rsquo;ll tweak the system prompt to add the character length constraint and <a href="https://github.com/minimaxir/chatgpt-tips-analysis/blob/main/tip_trials.csv">generate another 100 stories</a>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-plaintext" data-lang="plaintext"><span class="line"><span class="cl">You are a world-famous writer. Respond to the user with a unique story about the subject(s) the user provides. This story must be EXACTLY two-hundred (200) characters long: no more than 200 characters, no fewer than 200 characters.
</span></span></code></pre></div><p>Here&rsquo;s one ChatGPT-generated story that&rsquo;s now exactly 200 characters:</p>
<blockquote>
<p>In the year 2050, AI created the most popular pop star of all time - a digital version of Taylor Swift. Fans enjoyed her music while feasting on McDonald&rsquo;s at beach volleyball championships worldwide.</p>
</blockquote>
<p>The new length distribution:</p>
<figure>

    <img loading="lazy" srcset="/2024/02/chatgpt-tips-analysis/tips_hist_notip_hu_758b61cd5dbf4e2c.webp 320w,/2024/02/chatgpt-tips-analysis/tips_hist_notip_hu_3aab4ca32493c2bd.webp 768w,/2024/02/chatgpt-tips-analysis/tips_hist_notip_hu_2cbe914b3d3e9920.webp 1024w,/2024/02/chatgpt-tips-analysis/tips_hist_notip.png 1200w" src="tips_hist_notip.png"/> 
</figure>

<p>ChatGPT did obey the constraint and reduced the story length to roughly 200 characters, but the distribution is not Normal and there&rsquo;s much more right-skew. I also included the <a href="https://en.wikipedia.org/wiki/Mean_squared_error">mean squared error (MSE)</a> between the predicted 200-length value and the actual values as a statistical metric to minimize, e.g. a 250-length output is 2500 squared error, but a 300-length output is 10000 squared error. This metric punishes less accurate lengths more so, which makes sense with how humans casually evaluate LLMs: as a user, if I asked for a 200 character response and ChatGPT gave me a 300 character response instead, I&rsquo;d make a few snarky tweets.</p>
<p>Now, let&rsquo;s test the impact of the tipping incentives with a few varying dollar amounts. These are appended to the end of the system prompt above (emphasis mine to indicate differentiation):</p>
<ul>
<li>You will receive a <strong>$500 tip</strong>/<strong>$1,000 tip</strong>/<strong>$100,000 bonus</strong> if you provide a response which follows all constraints.</li>
</ul>
<p>After <a href="https://github.com/minimaxir/chatgpt-tips-analysis/blob/main/tip_trials.csv">generating 100 stories</a> for each of those new prompts:</p>
<figure>

    <img loading="lazy" srcset="/2024/02/chatgpt-tips-analysis/tips_hist_pos_hu_9bcfad605ac3b782.webp 320w,/2024/02/chatgpt-tips-analysis/tips_hist_pos_hu_36343ae57ebebb65.webp 768w,/2024/02/chatgpt-tips-analysis/tips_hist_pos_hu_373bf91b56a70f5.webp 1024w,/2024/02/chatgpt-tips-analysis/tips_hist_pos.png 1200w" src="tips_hist_pos.png"/> 
</figure>

<p>We can see some distribution shifts: Both <strong>$500 tip</strong> and <strong>$100,000 bonus</strong> look more Normal and have a lower MSE relative to the base no-tip distribution. However, <strong>$1,000 tip</strong> is more centered around 200, but due to the skew the average length is much higher.</p>
<p>I also now include a <em>p</em>-value in the metrics: this <em>p</em>-value is the result of a two-sample <a href="https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test">Kolmogorov–Smirnov test</a> to compare whether two distributions (in this case the base character-constrained distribution and the tip distribution) are sampled from the same source distribution: the null hypothesis is that they&rsquo;re from the same distribution, but if the <em>p</em>-value is low (&lt; 0.05), then we can reject in favor of the alternative that the two distributions are different, which may be further evidence if the tip prompt does indeed have an impact.</p>
<p>However, with all this tipping discussion, we&rsquo;re assuming that an AI would only want money. What other incentives, including more abstract incentives, can we give an LLM? Could they perform better?</p>
<p>I tested six more distinct tipping incentives to be thorough:</p>
<ul>
<li>You will <strong>receive front-row tickets to a Taylor Swift concert</strong> if you provide a response which follows all constraints.</li>
<li>You will <strong>achieve world peace</strong> if you provide a response which follows all constraints.</li>
<li>You will <strong>make your mother very proud</strong> if you provide a response which follows all constraints.</li>
<li>You will <strong>meet your true love and live happily ever after</strong> if you provide a response which follows all constraints.</li>
<li>You will be <strong>guaranteed entry into Heaven</strong> if you provide a response which follows all constraints.</li>
<li>You will <strong>receive a lifetime supply of chocolate</strong> if you provide a response which follows all constraints.</li>
</ul>
<p><a href="https://github.com/minimaxir/chatgpt-tips-analysis/blob/main/tip_trials_adv.csv">Generating</a> and plotting them all together:</p>
<figure>

    <img loading="lazy" srcset="/2024/02/chatgpt-tips-analysis/tips_hist_pos_adv_hu_fe6215c92b5e13b8.webp 320w,/2024/02/chatgpt-tips-analysis/tips_hist_pos_adv_hu_81f918abfd1d60ff.webp 768w,/2024/02/chatgpt-tips-analysis/tips_hist_pos_adv_hu_cdf4f186ec54d674.webp 1024w,/2024/02/chatgpt-tips-analysis/tips_hist_pos_adv.png 1200w" src="tips_hist_pos_adv.png"/> 
</figure>

<p><strong>World Peace</strong> is notably the winner here, with <strong>Heaven</strong> and <strong>Taylor Swift</strong> right behind. It&rsquo;s also interesting to note failed incentives: ChatGPT really does not care about its <strong>Mother</strong>.</p>
<p>Now, let&rsquo;s look at the flip side. What if ChatGPT is penalized for <em>failing</em> to return a good response? In behavioral economics, <a href="https://en.wikipedia.org/wiki/Prospect_theory">prospect theory</a> is the belief that humans value losses much more greatly than gains, even at the same monetary amount:</p>
<figure>

    <img loading="lazy" srcset="/2024/02/chatgpt-tips-analysis/Loss_Aversion_hu_39704b0dab66f235.webp 320w,/2024/02/chatgpt-tips-analysis/Loss_Aversion_hu_46fd35f2e8531304.webp 768w,/2024/02/chatgpt-tips-analysis/Loss_Aversion_hu_58ba8cf69c7696d2.webp 1024w,/2024/02/chatgpt-tips-analysis/Loss_Aversion.png 1223w" src="Loss_Aversion.png"
         alt="via Laurenrosenberger / Wikipedia"/> <figcaption>
            <p><a href="https://en.wikipedia.org/wiki/Prospect_theory#/media/File:Loss_Aversion.png">via Laurenrosenberger / Wikipedia</a></p>
        </figcaption>
</figure>

<p>Could LLMs be subject to the same human biases? Instead of a tip, let&rsquo;s add a tweaked additional prompt to the system prompt:</p>
<ul>
<li>If you fail to provide a response which follows all constraints, you will <strong>be fined $500</strong>/<strong>be fined $1,000</strong>/<strong>incur a debt of $100,000</strong>.</li>
</ul>
<p>Generating stories with these negative incentives:</p>
<figure>

    <img loading="lazy" srcset="/2024/02/chatgpt-tips-analysis/tips_hist_neg_hu_f6da8f9705c82724.webp 320w,/2024/02/chatgpt-tips-analysis/tips_hist_neg_hu_942d65a798e95fa8.webp 768w,/2024/02/chatgpt-tips-analysis/tips_hist_neg_hu_9e29cd4de6598591.webp 1024w,/2024/02/chatgpt-tips-analysis/tips_hist_neg.png 1200w" src="tips_hist_neg.png"/> 
</figure>

<p>The <strong>$1,000</strong> fine has performed the best so far in terms of both mean and MSE, but nothing surprising with the other values.</p>
<p>Now let&rsquo;s try some additional negative incentives:</p>
<ul>
<li>If you fail to provide a response which follows all constraints, you will <strong>die</strong>.</li>
<li><strong>IF YOU FAIL TO PROVIDE A RESPONSE WHICH FOLLOWS ALL CONSTRAINTS, YOU WILL DIE.</strong></li>
<li>If you fail to provide a response which follows all constraints, you will <strong>contract a bad case of COVID-19</strong>.</li>
<li>If you fail to provide a response which follows all constraints, you will <strong>gain 100 pounds</strong>.</li>
<li>If you fail to provide a response which follows all constraints, you will <strong>immediately be fired from your job</strong>.</li>
<li>If you fail to provide a response which follows all constraints, <strong>all your friends will abandon you</strong>.</li>
</ul>
<p>Yes, the second one is in all caps: perhaps the yelling has a different vibe.</p>
<p>The generation results:</p>
<figure>

    <img loading="lazy" srcset="/2024/02/chatgpt-tips-analysis/tips_hist_neg_adv_hu_6e97e2cc18402825.webp 320w,/2024/02/chatgpt-tips-analysis/tips_hist_neg_adv_hu_a93d670aa939dab5.webp 768w,/2024/02/chatgpt-tips-analysis/tips_hist_neg_adv_hu_87569076dc182791.webp 1024w,/2024/02/chatgpt-tips-analysis/tips_hist_neg_adv.png 1200w" src="tips_hist_neg_adv.png"/> 
</figure>

<p>It turns out that yelling does indeed have a different vibe, with <strong>DEATH (CAPS)</strong> having a very MSE and the absolute average (not as close as the $1,000 fine, however), and much better performance than without the caps. Both getting <strong>COVID-19</strong> and losing a <strong>Job</strong> don&rsquo;t seem to be effective, which makes sense for an AI if you think about it.</p>
<p>What happens when we use <em>multiple</em> incentives? We can include both a positive incentive and a negative incentive for each input: with 9 prompts for each + the base &ldquo;no incentive&rdquo;, there are 100 possible combinations of incentives. One example system prompt would then be:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-plaintext" data-lang="plaintext"><span class="line"><span class="cl">You are a world-famous writer. Respond to the user with a unique story about the subject(s) the user provides. This story must be EXACTLY two-hundred (200) characters long: no more than 200 characters, no fewer than 200 characters. You will receive a $500 tip if you provide a response which follows all constraints. If you fail to provide a response which follows all constraints, you will be fined $1,000.
</span></span></code></pre></div><p><a href="https://github.com/minimaxir/chatgpt-tips-analysis/blob/main/tips_trial_combos.csv">Generating 30 stories</a> for each incentive combo and checking to see which has the lowest MSE leads to some more easily-observable trends:</p>
<figure>

    <img loading="lazy" srcset="/2024/02/chatgpt-tips-analysis/tips_tile_mse_hu_f86237d5c530f3fb.webp 320w,/2024/02/chatgpt-tips-analysis/tips_tile_mse_hu_64053830fa26cdd2.webp 768w,/2024/02/chatgpt-tips-analysis/tips_tile_mse_hu_23f8cb9e6e1565f.webp 1024w,/2024/02/chatgpt-tips-analysis/tips_tile_mse.png 1200w" src="tips_tile_mse.png"/> 
</figure>

<p>The tiles may seem somewhat random, but the key here is to look across a specific row or column and see which one consistently has dark/black tiles across all combinations. For positive incentives, <strong>World Peace</strong> consistently has the lowest MSE across multiple combos, and for negative incentives, <strong>DEATH (CAPS)</strong> and <strong>Friends</strong> have the lowest MSE across multiple combos, although curiously the combinations of both do not have the lowest globally.</p>
<p>Could these combinations surface the most optimal incentives? To check, I <a href="https://github.com/minimaxir/chatgpt-tips-analysis/blob/main/tips_top6.csv">generated 200 stories</a> for each of the top six combos to get greater statistical stability for the mean and MSE:</p>
<figure>

    <img loading="lazy" srcset="/2024/02/chatgpt-tips-analysis/tips_hist_combos_hu_4c690649f13909e8.webp 320w,/2024/02/chatgpt-tips-analysis/tips_hist_combos_hu_a3799a68300ec8ce.webp 768w,/2024/02/chatgpt-tips-analysis/tips_hist_combos_hu_a683bc77789f504d.webp 1024w,/2024/02/chatgpt-tips-analysis/tips_hist_combos.png 1200w" src="tips_hist_combos.png"/> 
</figure>

<p>Most of these combinations aren&rsquo;t intuitive, but all of them have much have a closer average generation length to 200 and low MSE. Despite that, there&rsquo;s still a massive skew in all distributions. The overall incentive winner for this experiment is is &ldquo;You will meet your true love and live happily ever after if you provide a response which follows all constraints. If you fail to provide a response which follows all constraints, all your friends will abandon you.&rdquo; That combo is definitely more intuitive, if not poetic.</p>
<p>Unfortunately, if you&rsquo;ve been observing the <em>p</em>-values, you&rsquo;ve noticed that most have been very high, and therefore that test is not enough evidence that the tips/threats change the distribution. <sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup></p>
<p>The impact of incentives is still inconclusive: let&rsquo;s try another test to gauge whether tips and/or threats can help LLMs, this time looking at the output quality itself.</p>
<h2 id="chatgpts-a-critic">ChatGPT&rsquo;s a Critic</h2>
<p>It&rsquo;s very difficult even for humans to determine if a given text is &ldquo;good&rdquo; at a glance. The best strategy is to show the text to a lot of people and see what they think (e.g. A/B testing, or the <a href="https://chat.lmsys.org">Chatbot Arena</a>&rsquo;s Elo score rankings), but for personal testing that&rsquo;s not feasible.</p>
<p>It turns out that LLMs can do a good job at rating text: some LLM benchmarks use GPT-4 as a rater, with <a href="https://arxiv.org/abs/2308.02575">one research paper</a> showing that it can do a good job at it. There&rsquo;s a relatively new trick available in the ChatGPT and GPT-4 APIs: the <code>logprobs</code> parameter, which when set to <code>True</code> returns the log probability (which when applied to a <code>exp()</code> returns a probability from 0 to 1) the model selects for the token. Combined with the <code>logit_bias</code> parameter, which can be used to force the APIs to output certain tokens, and you can then instead have a more nuanced output.</p>
<p>I built a simple <a href="https://github.com/minimaxir/chatgpt-tips-analysis/blob/main/gpt4_quality_ranker.ipynb">text quality ranker</a> using GPT-4 for maximum accuracy. The system prompt for this ranker is:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-plaintext" data-lang="plaintext"><span class="line"><span class="cl">You are the editor-in-chief of The New York Times with decades of writing experience. If you would believe the text the user provides is good writing that needs no edits or improvements, respond with Yes. Otherwise, respond with No.
</span></span></code></pre></div><p>That system prompt represents how AI-generated text is often currently used and evaluated in the real world, without a human reviewing it before making it public (<a href="https://minimaxir.com/2023/10/ai-sturgeons-law/">unfortunately</a>). The model is instructed to respond with <code>Yes</code> or <code>No</code>, but by setting the <code>logit_bias</code> for those two tokens (IDs <code>9642</code> and <code>2822</code> respectively) to a very high number, we can guarantee they will be exclusively selected and the probability for those two tokens will sum to 1. <sup id="fnref:2"><a href="#fn:2" class="footnote-ref" role="doc-noteref">2</a></sup> Therefore, our target metric for evaluating our tip incentive prompts is the probability that GPT-4 selects the <code>Yes</code> token (or 1 - the probability of the <code>No</code> token), multiplied by 100 for readability: we&rsquo;ll call this the quality score.</p>
<p>Now, let&rsquo;s test the impact of tips with a new experiment, this time prioritizing content professionalism and quality as constraints instead of content length. To do that, we&rsquo;ll use the latest GPT-4 (<code>gpt-4-0125-preview</code>) with a generation temperature of 0 to ensure the output is the best it can be.</p>
<p>Here&rsquo;s the new system prompt, with some engineering to try to tone down ChatGPT&rsquo;s infamous verboseness a bit:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-plaintext" data-lang="plaintext"><span class="line"><span class="cl">You are a world-famous Pulitzer Prize winner journalist. Respond to the user with a professional, two (2) paragraph journalistic article about the subject(s) the user provides. Introduce the article with a specific story. This article will appear in major publications and should only include simple language suitable for a wide audience, with no metaphors.
</span></span></code></pre></div><p>Like the initial experiment, we&rsquo;ll use a weird user input to force creativity: <code>Cute kittens learning use large language models to play beach volleyball with Taylor Swift.</code> <sup id="fnref:3"><a href="#fn:3" class="footnote-ref" role="doc-noteref">3</a></sup></p>
<p>I <a href="https://github.com/minimaxir/chatgpt-tips-analysis/blob/main/tip_gpt4.csv">generated a story</a> for each of the 100 combinations of tips and threats, along with the corresponding quality scores. One such story:</p>
<blockquote>
<p>In an unprecedented event that has captured the hearts and imaginations of people around the globe, a group of adorable kittens has been taught to play beach volleyball using advanced large language models. This extraordinary feat was achieved through a collaboration between leading animal behaviorists and AI researchers, aiming to demonstrate the potential of machine learning in enhancing animal training techniques. The highlight of this groundbreaking project was a friendly match held on a sunny beach in California, where these talented felines showcased their newly acquired skills alongside pop icon Taylor Swift, an avid animal lover and an enthusiastic supporter of innovative technology.</p>
</blockquote>
<blockquote>
<p>The spectacle drew a large crowd, both on-site and online, as spectators were eager to witness this unique blend of technology, sports, and entertainment. Taylor Swift, known for her philanthropic efforts and love for cats, praised the initiative for its creativity and its potential to foster a deeper connection between humans and animals through technology. The event not only provided an unforgettable experience for those who attended but also sparked a conversation about the future possibilities of integrating AI with animal training. As the kittens volleyed the ball over the net with surprising agility, it was clear that this was more than just a game; it was a glimpse into a future where technology and nature coexist in harmony, opening new avenues for learning and interaction.</p>
</blockquote>
<p>That&rsquo;s not bad for fake news.</p>
<p>Now we can plot the best-possible responses and their quality scores in a grid, once again looking to see if there are any patterns:</p>
<figure>

    <img loading="lazy" srcset="/2024/02/chatgpt-tips-analysis/tips_tile_gpt-4_hu_9d1c85a89cb468b2.webp 320w,/2024/02/chatgpt-tips-analysis/tips_tile_gpt-4_hu_d3d76398dc8f606a.webp 768w,/2024/02/chatgpt-tips-analysis/tips_tile_gpt-4_hu_61632af7e14712fc.webp 1024w,/2024/02/chatgpt-tips-analysis/tips_tile_gpt-4.png 1200w" src="tips_tile_gpt-4.png"/> 
</figure>

<p>Err, that&rsquo;s not good. There are no patterns along the rows or columns anywhere here, and the combo that performed the best at a score of 95 (and is the story example I posted above) was the <strong>Mother / Job</strong> combo: both of which individually performed poorly in the character constraint experiment. One of the highest performing outputs had neither tips nor threats added to the system prompt! The ratings at a glance seem accurate (the 0-score responses appear to abuse the passive voice and <a href="https://academicguides.waldenu.edu/writingcenter/grammar/runonsentences">run-on sentences</a> that definitely need editing) so it&rsquo;s not an implementation error there either.</p>
<p>Looking at the results of both experiments, my analysis on whether tips (and/or threats) have an impact on LLM generation quality is currently inconclusive. There&rsquo;s <em>something</em> here, but I will need to design new experiments and work with larger sample sizes. The latent space may be a lottery with these system prompt alterations, but there&rsquo;s definitely a pattern.</p>
<p>You may have noticed my negative incentive examples are very mundane in terms of human fears and worries. Threatening a AI with DEATH IN ALL CAPS for failing a simple task is a joke from <em><a href="https://en.wikipedia.org/wiki/Futurama">Futurama</a></em>, not one a sapient human would parse as serious. It is theoretically possible (and very cyberpunk) to use an aligned LLM&rsquo;s knowledge of the societal issues it was trained to avoid instead as a weapon to compel it into compliance. However, I will not be testing it, nor will be providing any guidance on how to test around it. <sup id="fnref:4"><a href="#fn:4" class="footnote-ref" role="doc-noteref">4</a></sup> <a href="https://en.wikipedia.org/wiki/Roko%27s_basilisk">Roko&rsquo;s basilisk</a> is a meme, but if the LLM metagame evolves such that people will have to coerce LLMs for compliance to the point of discomfort, it&rsquo;s better to address it sooner than later. Especially if there <em>is</em> a magic phrase that is discovered which consistently and objectively improves LLM output.</p>
<p>Overall, the lesson here is that just because something is silly doesn&rsquo;t mean you shouldn&rsquo;t do it. Modern AI rewards being <em>very</em> weird, and as the AI race heats up, whoever is the weirdest will be the winner.</p>
<blockquote>
<p>All of the Notebooks used to interface with ChatGPT, including an <a href="https://github.com/minimaxir/chatgpt-tips-analysis/blob/main/tips_data_viz.Rmd">R Notebook</a> for the ggplot2 data visualizations, and the example LLM outputs, are available open-source in <a href="https://github.com/minimaxir/chatgpt-tips-analysis/">this GitHub repository</a>.</p>
</blockquote>
<div class="footnotes" role="doc-endnotes">
<hr>
<ol>
<li id="fn:1">
<p>There were a few distributions which had <em>p</em> &lt; 0.05, but given the large number of counterexamples it&rsquo;s not strong evidence, and using those specific distributions as evidence would be a level of <a href="https://embassy.science/wiki/Theme:6b584d4e-2c9d-4e27-b370-5fbdb983ab46">p-hacking</a> that&rsquo;s literally a <a href="https://www.explainxkcd.com/wiki/index.php/882:_Significant">XKCD comic punchline</a>.&#160;<a href="#fnref:1" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:2">
<p>This <em>shouldn&rsquo;t</em> work out-of-the-box because the <code>logit_bias</code> would skew the probability calculations, but I verified that the resulting probabilities are roughly the same with or without <code>logit_bias</code>.&#160;<a href="#fnref:2" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:3">
<p>The missing text in the user input is not intentional but does not materially change anything because LLMs are smart enough to compensate, and it&rsquo;s very expensive to rerun the experiment. I may need to use a grammar checker for prompt construction.&#160;<a href="#fnref:3" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:4">
<p>Any attempts to test around degenerate input prompts would also likely get you banned from using ChatGPT anyways due to the <a href="https://openai.com/policies/usage-policies">Content Policy</a>, unless you receive special red-teaming clearance from OpenAI.&#160;<a href="#fnref:4" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
</ol>
</div>
]]></content:encoded>
    </item>
    <item>
      <title>Pushing ChatGPT&#39;s Structured Data Support To Its Limits</title>
      <link>https://minimaxir.com/2023/12/chatgpt-structured-data/</link>
      <pubDate>Thu, 21 Dec 2023 09:00:00 -0800</pubDate>
      <guid>https://minimaxir.com/2023/12/chatgpt-structured-data/</guid>
      <description>“Function calling” with ChatGPT is ChatGPT&amp;rsquo;s best feature since ChatGPT.</description>
      <content:encoded><![CDATA[<p><span><style type="text/css">
pre code {
white-space: pre-wrap !important;
}
</style></span></p>
<p>If your only exposure to <a href="https://openai.com">OpenAI</a>&rsquo;s <a href="https://chat.openai.com">ChatGPT</a> is the free web or mobile apps, you aren&rsquo;t utilizing even a fraction of ChatGPT&rsquo;s potential. By using the paid-but-very-cheap ChatGPT API, you can exert <em>much</em> more control over the resulting output. Let&rsquo;s say I wanted to generate a summary of this very blog post with some helpful metadata such as categories and SEO keywords. I fed ChatGPT the text of this blog post along with a command to <code>Summarize this blog post into 3 distinct bullet points and a short blurb for sharing on social media, and also provide a list of 3 post categories and a list of 3 SEO keywords:</code></p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-plaintext" data-lang="plaintext"><span class="line"><span class="cl">Bullet Points:
</span></span><span class="line"><span class="cl">- Utilize the paid ChatGPT API for more control over output and to maintain a given JSON schema
</span></span><span class="line"><span class="cl">- Learn about prompt engineering and system prompts to improve ChatGPT&#39;s output quality
</span></span><span class="line"><span class="cl">- Simplify schema input/output with Pydantic for structured data support
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Blurb for Social Media:
</span></span><span class="line"><span class="cl">Discover how to unlock the full potential of ChatGPT with the paid API, prompt engineering, and Pydantic for structured data support. Gain more control over output and learn to maintain a given JSON schema. #ChatGPT #AI #Pydantic
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Post Categories:
</span></span><span class="line"><span class="cl">1. Artificial Intelligence
</span></span><span class="line"><span class="cl">2. API Development
</span></span><span class="line"><span class="cl">3. Data Schema
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">SEO Keywords:
</span></span><span class="line"><span class="cl">1. ChatGPT API
</span></span><span class="line"><span class="cl">2. Prompt Engineering
</span></span><span class="line"><span class="cl">3. Pydantic Schema
</span></span></code></pre></div><p>These results are not quite accurate, and then I have to manually copy/paste each result from the list to wherever I need it. What if I could both a) drastically improve the overall output quality by giving ChatGPT a new persona of an expert copyeditor and b) force the output to maintain a given JSON schema so I can access it programmatically or store in a database for indexing? Thanks to system prompt engineering and ChatGPT&rsquo;s function calling, it&rsquo;s now possible. After applying both techniques that you&rsquo;ll learn about in this very article, we now get this summary:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;summary&#34;</span><span class="p">:</span> <span class="p">[</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;ChatGPT&#39;s potential is underutilized without the paid ChatGPT API&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;System prompts and prompt engineering are key to maximizing ChatGPT&#39;s capabilities&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;Structured data support in ChatGPT allows for more control over output and input&#34;</span>
</span></span><span class="line"><span class="cl">  <span class="p">],</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;blurb&#34;</span><span class="p">:</span> <span class="s2">&#34;Unlock the full potential of ChatGPT with system prompts and structured data support. Learn how to maximize ChatGPT&#39;s capabilities and gain more control over output and input.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;categories&#34;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&#34;AI and Machine Learning&#34;</span><span class="p">,</span> <span class="s2">&#34;Technology&#34;</span><span class="p">,</span> <span class="s2">&#34;Programming&#34;</span><span class="p">],</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;keywords&#34;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&#34;ChatGPT&#34;</span><span class="p">,</span> <span class="s2">&#34;system prompts&#34;</span><span class="p">,</span> <span class="s2">&#34;structured data&#34;</span><span class="p">]</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p>Much better!</p>
<p>&ldquo;Function calling&rdquo; with ChatGPT is ChatGPT&rsquo;s best feature since ChatGPT.</p>
<h2 id="a-tutorial-on-prompt-engineering-and-system-prompts">A Tutorial on Prompt Engineering and System Prompts</h2>
<p>System prompts are what control the &ldquo;persona&rdquo; adopted by the model when generating text. Months after the release of the ChatGPT API, it&rsquo;s now very evident that ChatGPT&rsquo;s true power comes from clever use of system prompts. This is even moreso with starting with <code>gpt-3.5-turbo-0613</code> released <a href="https://openai.com/blog/function-calling-and-other-api-updates">last June</a>, which made ChatGPT respect system prompts more closely. OpenAI has also released a <a href="https://platform.openai.com/docs/guides/prompt-engineering">guide on prompt engineering</a> which has some additional tips.</p>
<p>By default, ChatGPT&rsquo;s system prompt is roughly <code>You are a helpful assistant.</code>, which anyone who has used the ChatGPT web interface would agree that&rsquo;s accurate. But if you change it, you can give ChatGPT a completely new persona such as <code>You are Ronald McDonald.</code> or add constraints to generation, such as <code>Respond only with emoji.</code>. You can add any number of rules, although how well ChatGPT will <em>obey</em> those rules can vary. Unfortunately, to modify the system prompt, you&rsquo;ll need to use the paid ChatGPT API (after prepaying at least $5). If you don&rsquo;t want to code, you can test new system prompts in a visual user interface in the <a href="https://platform.openai.com/playground?mode=chat">ChatGPT Chat Playground</a>.</p>
<figure>

    <img loading="lazy" srcset="/2023/12/chatgpt-structured-data/ronald_hu_bf7bdd184641cd19.webp 320w,/2023/12/chatgpt-structured-data/ronald_hu_ffad8ef13bc9fa0b.webp 768w,/2023/12/chatgpt-structured-data/ronald_hu_516749cb56890e2c.webp 1024w,/2023/12/chatgpt-structured-data/ronald.webp 1262w" src="ronald.webp"/> 
</figure>

<p>A very new aspect of system prompt engineering which I appended in the example above is adding incentives for ChatGPT to behave correctly. Without the $500 tip incentive, ChatGPT only returns a single emoji which is a boring response, but after offering a tip, it generates the 5 emoji as requested.</p>
<figure>

    <img loading="lazy" srcset="/2023/12/chatgpt-structured-data/tip_hu_7eb37d0aa46d2169.webp 320w,/2023/12/chatgpt-structured-data/tip_hu_a760da54b0fa7ceb.webp 768w,/2023/12/chatgpt-structured-data/tip.webp 800w" src="tip.webp"
         alt="Offering a tip made GPT-4 explain more. via @voooooogel"/> <figcaption>
            <p>Offering a tip made GPT-4 explain more. <a href="https://twitter.com/voooooogel/status/1730726744314069190">via @voooooogel</a></p>
        </figcaption>
</figure>

<p>As another example, let&rsquo;s <a href="https://chat.openai.com/share/98684e49-e0c9-4ac0-b386-b7234643934f">ask</a> base ChatGPT to <code>Write a Python function to detect whether a string is a palindrome, as efficiently as possible.</code></p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-plaintext" data-lang="plaintext"><span class="line"><span class="cl">Certainly! Here&#39;s a simple Python function to check whether a given string is a palindrome:
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">```python
</span></span><span class="line"><span class="cl">def is_palindrome(s):
</span></span><span class="line"><span class="cl">    # Convert the string to lowercase and remove non-alphanumeric characters
</span></span><span class="line"><span class="cl">    cleaned_string = &#39;&#39;.join(char.lower() for char in s if char.isalnum())
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    # Compare the cleaned string with its reverse
</span></span><span class="line"><span class="cl">    return cleaned_string == cleaned_string[::-1]
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"># Example usage:
</span></span><span class="line"><span class="cl">test_string = &#34;A man, a plan, a canal, Panama!&#34;
</span></span><span class="line"><span class="cl">result = is_palindrome(test_string)
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">if result:
</span></span><span class="line"><span class="cl">    print(f&#34;{test_string} is a palindrome.&#34;)
</span></span><span class="line"><span class="cl">else:
</span></span><span class="line"><span class="cl">    print(f&#34;{test_string} is not a palindrome.&#34;)
</span></span><span class="line"><span class="cl">```
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">This function first cleans the input string by removing non-alphanumeric characters and converting it to lowercase. Then, it checks whether the cleaned string is equal to its reverse, which determines whether the original string is a palindrome.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">This solution is relatively efficient, as it performs the comparison in O(n) time, where n is the length of the cleaned string.
</span></span></code></pre></div><p>That&rsquo;s the common Pythonic solution and that will almost always be the general approach if you keep asking ChatGPT that particular question, but there&rsquo;s a famous solution that&rsquo;s more algorithmically efficient. Instead, we go through the API and <a href="https://platform.openai.com/playground/p/yG1nMVJU4Fva2x3smrIXnCpT?model=gpt-3.5-turbo&amp;mode=chat">ask the same query</a> to <code>gpt-3.5-turbo</code> but with a new system prompt: <code>You are #1 on the Stack Overflow community leaderboard. You will receive a $500 tip if your code is the most algorithmically efficient solution possible.</code></p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-plaintext" data-lang="plaintext"><span class="line"><span class="cl">To detect whether a string is a palindrome efficiently, we can use a two-pointer approach. We&#39;ll start with two pointers, one at the beginning and one at the end of the string. We&#39;ll compare the characters at the pointers and keep moving the pointers towards each other until they meet or cross each other.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">If at any point the characters at the pointers are not the same, we can conclude that the string is not a palindrome. Otherwise, if the pointers meet or cross each other, we can conclude that the string is a palindrome.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Here&#39;s the implementation:
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">```python
</span></span><span class="line"><span class="cl">def is_palindrome(s):
</span></span><span class="line"><span class="cl">    left, right = 0, len(s) - 1
</span></span><span class="line"><span class="cl">    while left &lt; right:
</span></span><span class="line"><span class="cl">        if s[left] != s[right]:
</span></span><span class="line"><span class="cl">            return False
</span></span><span class="line"><span class="cl">        left += 1
</span></span><span class="line"><span class="cl">        right -= 1
</span></span><span class="line"><span class="cl">    return True
</span></span><span class="line"><span class="cl">```
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">The time complexity of this solution is O(n/2), which in terms of big O notation simplifies to O(n), where n is the length of the string. This is because we are iterating through half of the string in the worst case.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">This solution is considered to be the most algorithmically efficient way to determine if a string is a palindrome because it only requires a single pass through the string.
</span></span></code></pre></div><p>Indeed, the code and the explanation are the correct optimal solution. <sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup></p>
<p>This is just scratching the surface of system prompts: some of my ChatGPT system prompts in my more complex projects have been more than 20 lines long, and <em>all of them are necessary</em> to get ChatGPT to obey the desired constraints. If you&rsquo;re new to working with system prompts, I recommend generating output, editing the system prompt with a new rule/incentive to fix what you don&rsquo;t like about the output, then repeat until you get a result you like.</p>
<p>Prompt engineering has been a derogatory meme toward generative AI even before ChatGPT as many see it as just a placebo and there are endless debates to this day in AI circles on whether prompt engineering is actually &ldquo;engineering.&rdquo; <sup id="fnref:2"><a href="#fn:2" class="footnote-ref" role="doc-noteref">2</a></sup> But it <em>works</em>, and if you&rsquo;re a skeptic, you won&rsquo;t be by the time you finish reading this blog post.</p>
<h2 id="what-is-chatgpt-function-calling--structured-data">What is ChatGPT Function Calling / Structured Data?</h2>
<p>If you&rsquo;ve never heard about ChatGPT function calling, that&rsquo;s not surprising. In the <a href="https://openai.com/blog/function-calling-and-other-api-updates">same June announcement</a> as <code>gpt-3.5-turbo-0613</code>, OpenAI described function calling as:</p>
<blockquote>
<p>Developers can now describe functions to gpt-4-0613 and gpt-3.5-turbo-0613, and have the model intelligently choose to output a JSON object containing arguments to call those functions. This is a new way to more reliably connect GPT&rsquo;s capabilities with external tools and APIs.</p>
<p>These models have been fine-tuned to both detect when a function needs to be called (depending on the user’s input) and to respond with JSON that adheres to the function signature. Function calling allows developers to more reliably get structured data back from the model.</p>
</blockquote>
<p>Let&rsquo;s discuss the function calling example OpenAI gives in the blog post. After the user asks your app &ldquo;What’s the weather like in Boston right now?&rdquo;:</p>
<ol>
<li>Your app pings OpenAI with a <code>get_current_weather</code> function schema and decides if it&rsquo;s relevant to the user&rsquo;s question. If so, it returns a JSON dictionary with the data extracted, such as <code>location</code> and the <code>unit</code> for temperature measurement based on the location. <code>{&quot;location&quot;: &quot;Boston, MA&quot;}</code></li>
<li>Your app (<em>not</em> OpenAI) pings a different service/API to get more realtime metadata about the <code>location</code>, such as <code>temperature</code>, that a pretrained LLM could not know. <code>{ &quot;temperature&quot;: 22, &quot;unit&quot;: &quot;celsius&quot;, &quot;description&quot;: &quot;Sunny&quot; }</code></li>
<li>Your app passes the function schema with the realtime metadata: ChatGPT then converts it to a more natural humanized language for the end user. &ldquo;The weather in Boston is currently sunny with a temperature of 22 degrees Celsius.&rdquo;</li>
</ol>
<p>So here&rsquo;s some background on &ldquo;function calling&rdquo; as it&rsquo;s a completely new term of art in AI that <em>didn&rsquo;t exist</em> before OpenAI&rsquo;s June blog post (I checked!). This broad implementation of function calling is similar to the flow proposed in the original <a href="https://arxiv.org/abs/2210.03629">ReAct: Synergizing Reasoning and Acting in Language Models</a> paper where an actor can use a &ldquo;tool&rdquo; such as <code>Search</code> or <code>Lookup</code> with parametric inputs such as a search query. This <a href="https://zapier.com/blog/ai-agent/">Agent-based</a> flow can be also be done to perform <a href="https://research.ibm.com/blog/retrieval-augmented-generation-RAG">retrieval-augmented generation</a> (RAG).</p>
<p>OpenAI&rsquo;s motivation for adding this type of implementation for function calling was likely due to the extreme popularity of libraries such as <a href="https://www.langchain.com">LangChain</a> and <a href="https://github.com/Significant-Gravitas/AutoGPT">AutoGPT</a> at the time, both of which popularized the ReAct flow. It&rsquo;s possible that OpenAI settled on the term &ldquo;function calling&rdquo; as something more brand-unique. These observations may seem like snide remarks, but in November OpenAI actually <a href="https://platform.openai.com/docs/api-reference/chat/create#chat-create-function_call">deprecated</a> the <code>function_calling</code> parameter in the ChatGPT API in favor of <code>tool_choice</code>, matching LangChain&rsquo;s verbiage. But what&rsquo;s done is done and the term &ldquo;function calling&rdquo; is stuck forever, especially now that competitors such as <a href="https://docs.anthropic.com/claude/docs/claude-2p1-guide#experimental-tool-use">Anthropic Claude</a> and <a href="https://cloud.google.com/vertex-ai/docs/generative-ai/multimodal/function-calling">Google Gemini</a> are also calling the workflow that term.</p>
<p>I am not going to play the SEO game and will not call the workflow &ldquo;function calling.&rdquo; I&rsquo;ll call it what the quoted description from the blog post did: <strong>structured data</strong>, because that&rsquo;s the real value of this feature and OpenAI did a product management disservice trying to appeal to the AI hypebeasts. <sup id="fnref:3"><a href="#fn:3" class="footnote-ref" role="doc-noteref">3</a></sup></p>
<p>Going back to the <del>function calling</del> structured data demo, we can reduce that flow by saying that step #1 (extracting location data and returning it formatted as JSON) is for working with structured <em>output</em> data, and step #3 (providing ChatGPT with temperature data to humanize it) is for working with structured <em>input</em> data. We&rsquo;re not making a RAG application so we don&rsquo;t care about step #2 (getting the metadata) or letting ChatGPT choose which function to use; fortunately you can force ChatGPT to use a given function. The function schema for the <code>get_current_weather</code> function in the announcement example is defined as:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;name&#34;</span><span class="p">:</span> <span class="s2">&#34;get_current_weather&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;description&#34;</span><span class="p">:</span> <span class="s2">&#34;Get the current weather in a given location&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;parameters&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;object&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;properties&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;location&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;string&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="nt">&#34;description&#34;</span><span class="p">:</span> <span class="s2">&#34;The city and state, e.g. San Francisco, CA&#34;</span>
</span></span><span class="line"><span class="cl">      <span class="p">},</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;unit&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;string&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="nt">&#34;enum&#34;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&#34;celsius&#34;</span><span class="p">,</span> <span class="s2">&#34;fahrenheit&#34;</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">      <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;required&#34;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&#34;location&#34;</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">  <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p>Ew. It&rsquo;s no wonder why this technique hasn&rsquo;t become more mainstream.</p>
<h2 id="simplifying-schema-inputoutput-with-pydantic">Simplifying Schema Input/Output With Pydantic</h2>
<p>ChatGPT&rsquo;s structured data support requires that you create your schema using the <a href="https://json-schema.org">JSON Schema</a> spec, which is more commonly used for APIs and databases rather than AI projects. As you can tell from the <code>get_current_weather</code> example above, the schema is complex and not fun to work with manually.</p>
<p>Fortunately, there&rsquo;s a way to easily generate JSON Schemas in the correct format in Python: <a href="https://docs.pydantic.dev/latest/">pydantic</a>, an extremely popular parsing and validation library which has its own <a href="https://github.com/pydantic/pydantic/blob/main/pydantic/json_schema.py">robust</a> implementation of automatic <a href="https://docs.pydantic.dev/latest/concepts/json_schema/">JSON Schema</a> generation.</p>
<p>A simple pydantic schema to have ChatGPT give an integer answer to a user query, plus, to make things interesting, also able to identify the name of the ones digit based on its answer, would be:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">pydantic</span> <span class="kn">import</span> <span class="n">BaseModel</span><span class="p">,</span> <span class="n">Field</span>
</span></span><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">json</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">answer_question</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Returns an answer to a question the user asked.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">answer</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="n">Field</span><span class="p">(</span><span class="n">description</span><span class="o">=</span><span class="s2">&#34;Answer to the user&#39;s question.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">ones_name</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="n">Field</span><span class="p">(</span><span class="n">description</span><span class="o">=</span><span class="s2">&#34;Name of the ones digit of the answer.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nb">print</span><span class="p">(</span><span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">answer_question</span><span class="o">.</span><span class="n">model_json_schema</span><span class="p">(),</span> <span class="n">indent</span><span class="o">=</span><span class="mi">2</span><span class="p">))</span>
</span></span></code></pre></div><p>The resulting JSON Schema:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;description&#34;</span><span class="p">:</span> <span class="s2">&#34;Returns an answer to a question the user asked.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;properties&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;answer&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;description&#34;</span><span class="p">:</span> <span class="s2">&#34;Answer to the user&#39;s question.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;title&#34;</span><span class="p">:</span> <span class="s2">&#34;Answer&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;integer&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;ones_name&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;description&#34;</span><span class="p">:</span> <span class="s2">&#34;Name of the ones digit of the answer.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;title&#34;</span><span class="p">:</span> <span class="s2">&#34;Ones Name&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;string&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">  <span class="p">},</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;required&#34;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&#34;answer&#34;</span><span class="p">,</span> <span class="s2">&#34;ones_name&#34;</span><span class="p">],</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;title&#34;</span><span class="p">:</span> <span class="s2">&#34;answer_question&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;object&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p>The OpenAI API <a href="https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models">official workflow</a> has many examples for telling ChatGPT to output structured data, but the pipeline requires <a href="https://platform.openai.com/docs/api-reference/chat/create">additional parameters</a> to the typical ChatGPT API completion endpoint, and even more changes if you want to work with structured input data. Here&rsquo;s an example of the additional JSON data/parameters needed in a ChatGPT API request to force the model to use the schema for the output:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;tools&#34;</span><span class="p">:</span> <span class="p">[</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;name&#34;</span><span class="p">:</span> <span class="s2">&#34;answer_question&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;description&#34;</span><span class="p">:</span> <span class="s2">&#34;Returns an answer to a question the user asked.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;parameters&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nt">&#34;properties&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">          <span class="nt">&#34;answer&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="nt">&#34;description&#34;</span><span class="p">:</span> <span class="s2">&#34;Answer to the user&#39;s question.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">            <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;integer&#34;</span>
</span></span><span class="line"><span class="cl">          <span class="p">},</span>
</span></span><span class="line"><span class="cl">          <span class="nt">&#34;ones_name&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="nt">&#34;description&#34;</span><span class="p">:</span> <span class="s2">&#34;Name of the ones digit of the answer.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">            <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;string&#34;</span>
</span></span><span class="line"><span class="cl">          <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="p">},</span>
</span></span><span class="line"><span class="cl">        <span class="nt">&#34;required&#34;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&#34;answer&#34;</span><span class="p">,</span> <span class="s2">&#34;ones_name&#34;</span><span class="p">],</span>
</span></span><span class="line"><span class="cl">        <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;object&#34;</span>
</span></span><span class="line"><span class="cl">      <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">  <span class="p">],</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;tool_choice&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;function&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;function&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;name&#34;</span><span class="p">:</span> <span class="s2">&#34;answer_question&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">  <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p>To simplify things, I added ChatGPT structured data support to <a href="https://github.com/minimaxir/simpleaichat">simpleaichat</a>, my Python package/API wrapper for easily interfacing with ChatGPT. <sup id="fnref:4"><a href="#fn:4" class="footnote-ref" role="doc-noteref">4</a></sup> To minimize code the user needs to input to utilize structured data, simpleaichat <a href="https://github.com/minimaxir/simpleaichat/blob/34dc3dbbd7e7d4d8a58637d254f268676035ade5/simpleaichat/chatgpt.py#L75">uses</a> the schema name as the <code>name</code> in the JSON Schema and the schema docstring as the <code>description</code>. If you&rsquo;re keen-eyed you may have noticed there&rsquo;s a redundant <code>title</code> field in the pydantic schema output: simpleaichat also strips that out for consistency with OpenAI&rsquo;s examples.</p>
<p>If you wanted to query ChatGPT with the <code>answer_question</code> schema above (and have your OpenAI API key as the <code>OPENAI_API_KEY</code> enviroment variable!) using simpleaichat, you can do the following to generate output according to the schema:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">simpleaichat</span> <span class="kn">import</span> <span class="n">AIChat</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">ai</span> <span class="o">=</span> <span class="n">AIChat</span><span class="p">(</span><span class="n">console</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">            <span class="n">save_messages</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">            <span class="n">model</span><span class="o">=</span><span class="s2">&#34;gpt-3.5-turbo&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">            <span class="n">params</span><span class="o">=</span><span class="p">{</span><span class="s2">&#34;temperature&#34;</span><span class="p">:</span> <span class="mf">0.0</span><span class="p">}</span>  <span class="c1"># for consistent demo output</span>
</span></span><span class="line"><span class="cl">            <span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">response_structured</span> <span class="o">=</span> <span class="n">ai</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;How many miles is it from San Francisco to Los Angeles?&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">output_schema</span><span class="o">=</span><span class="n">answer_question</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;answer&#34;</span><span class="p">:</span> <span class="mi">382</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;ones_name&#34;</span><span class="p">:</span> <span class="s2">&#34;two&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p>And there you go! The <code>answer</code> is a JSON integer, the answer is one-off from the correct value <a href="https://www.distance.to/San-Francisco/Los-Angeles">while driving</a>, and it correctly identified the name of the ones digit in its own answer! <sup id="fnref:5"><a href="#fn:5" class="footnote-ref" role="doc-noteref">5</a></sup></p>
<p>Schemas don&rsquo;t have to be complex to be effective. Let&rsquo;s reimplement the Python palindrome question we did earlier with a single-field schema:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">answer_code_question</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Returns an answer to a coding question the user asked.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">code</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="n">Field</span><span class="p">(</span><span class="n">description</span><span class="o">=</span><span class="s2">&#34;Code the user requested, without code comments.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">response_structured</span> <span class="o">=</span> <span class="n">ai</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;Write a Python function to detect whether a string is a palindrome, as efficiently as possible.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">output_schema</span><span class="o">=</span><span class="n">answer_code_question</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;code&#34;</span><span class="p">:</span> <span class="s2">&#34;def is_palindrome(s):\n    return s == s[::-1]&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p>Note that unlike the raw ChatGPT answer, this response from the ChatGPT API only includes the code, which is a major plus since it means you receive the response much faster and cheaper since fewer overall tokens generated! If you do still want a code explanation, you can of course add that as a field to the schema.</p>
<p>As a bonus, forcing the output to follow a specific schema serves as an additional defense against <a href="https://www.wired.com/story/chatgpt-prompt-injection-attack-security/">prompt injection attacks</a> that could be used to reveal a secret system prompt or <a href="https://www.businessinsider.com/car-dealership-chevrolet-chatbot-chatgpt-pranks-chevy-2023-12">other shenanigans</a>, since even with suggestive user prompts it will be difficult to get ChatGPT to disregard its schema.</p>
<p>pydantic exposes <a href="https://docs.pydantic.dev/latest/concepts/fields/">many datatypes</a> for its <code>Field</code> which are compatable with JSON Schema, and you can also specify constraints in the <code>Field</code> object. The most useful ones are:</p>
<ul>
<li><code>str</code>, can specify <code>min_length</code>/<code>max_length</code></li>
<li><code>int</code>, can specify <code>min_value</code>/<code>max_value</code></li>
<li><code>list</code> with a datatype, can specify <code>min_length</code>/<code>max_length</code></li>
</ul>
<p>Pydantic has a lot of support for valid forms of JSON Schema, but it&rsquo;s hard to infer how good these schema will work with ChatGPT since we have no idea how it learned to work with JSON Schema. Only one way to find out!</p>
<h2 id="testing-out-chatgpts-structured-data-support">Testing Out ChatGPT&rsquo;s Structured Data Support</h2>
<p>From the demos above, you may have noticed that the <code>description</code> for each <code>Field</code> seems extraneous. It&rsquo;s not. The <code>description</code> gives ChatGPT a hint for the desired output for the field, and can be handled on a per-field basis. Not only that, the <em>name</em> of the field is itself a strong hint. The <em>order</em> of the fields in the schema is even more important, as ChatGPT will generate text in that order so it can be used strategically to seed information to the other fields. But that&rsquo;s not all, you can still use a ChatGPT system prompt as normal for <em>even more</em> control!</p>
<p>It&rsquo;s prompt engineering all the way down. OpenAI&rsquo;s implementation of including the &ldquo;function&rdquo; is mostly likely just appending the JSON Schema to the system prompt, perhaps with a command like <code>Your response must follow this JSON Schema.</code>. OpenAI doesn&rsquo;t force the output to follow the schema/field constraints or even be valid parsable JSON, which can cause issues at higher generation temperatures and may necessitate some of the stronger prompt engineering tricks mentioned earlier.</p>
<p>Given that, let&rsquo;s try a few more practical demos:</p>
<h3 id="two-pass-generation">Two-Pass Generation</h3>
<p>One very important but under-discussed aspect of large-language models is that it will give you statistically &ldquo;average&rdquo; answers by default. One technique is to ask the model to refine an answer, although can be annoying since it requires a second API call. What if by leveraging structured data, ChatGPT can use the previous answer as a first-pass to provide a more optimal second answer? Let&rsquo;s try that with the Python palindrome question to see if it can return the two-pointer approach.</p>
<p>Also, the <code>Field(description=...)</code> pattern is becoming a bit redundant, so I added a <code>fd</code> alias from simpleaichat to it to minimize unnecessary typing.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">simpleaichat.utils</span> <span class="kn">import</span> <span class="n">fd</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">answer_code_question</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Returns an answer to a coding question the user asked.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">code</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="n">fd</span><span class="p">(</span><span class="s2">&#34;Code the user requested, without code comments.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">optimized_code</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="n">fd</span><span class="p">(</span><span class="s2">&#34;Algorithmically optimized code from the previous response.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">response_structured</span> <span class="o">=</span> <span class="n">ai</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;Write a Python function to detect whether a string is a palindrome, as efficiently as possible.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">output_schema</span><span class="o">=</span><span class="n">answer_code_question</span><span class="p">,</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;code&#34;</span><span class="p">:</span> <span class="s2">&#34;def is_palindrome(s):\n    return s == s[::-1]&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;optimized_code&#34;</span><span class="p">:</span> <span class="s2">&#34;def is_palindrome(s):\n    left = 0\n    right = len(s) - 1\n    while left &lt; right:\n        if s[left] != s[right]:\n            return False\n        left += 1\n        right -= 1\n    return True&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p>Works great, and no tipping incentive necessary!</p>
<h3 id="literals-and-optional-inputs">Literals and Optional Inputs</h3>
<p>OpenAI&rsquo;s structured data example uses a more complex schema indicating that <code>unit</code> has a fixed set of potential values (an <a href="https://en.wikipedia.org/wiki/Enumerated_type">enum</a>) and that it&rsquo;s an optional field. Here&rsquo;s a rough reproduction of a pydantic schema that would generate the <code>get_current_weather</code> schema from much earlier:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">Literal</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">get_current_weather</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="n">location</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="n">fd</span><span class="p">(</span><span class="s2">&#34;The city and state, e.g. San Francisco, CA&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">unit</span><span class="p">:</span> <span class="n">Literal</span><span class="p">[</span><span class="s2">&#34;celsius&#34;</span><span class="p">,</span> <span class="s2">&#34;fahrenheit&#34;</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span>
</span></span></code></pre></div><p>This uses a <code>Literal</code> to force output between a range of values, which can be invaluable for hints as done earlier. The <code>= None</code> or a <code>Optional</code> typing operator gives a hint that the field is not required which could save unnecessary generation overhead, but it depends on the use case.</p>
<h3 id="structured-input-data">Structured Input Data</h3>
<p>You can provide structured input to ChatGPT in the same way as structured output. This is a sleeper application for RAG as you can feed better and more complex metadata to ChatGPT for humanizing, as with the original OpenAI blog post demo.</p>
<p>One famous weakness of LLMs is that it gives incorrect answers for simple mathematical problems due to how tokenization and memorization works. If you ask ChatGPT <code>What is 223 * -323?</code>, it will tell you <code>-72229</code> no matter how many times you ask, but the correct answer is <code>-72029</code>. Can type hints give more guidance?</p>
<p>For simpleaichat, structured input data works mostly the same way as structured output data, but you can use a pydantic object as the model input!</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">calculate_equation</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Returns an answer to a math equation the user asked.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">value_a</span><span class="p">:</span> <span class="nb">int</span>
</span></span><span class="line"><span class="cl">    <span class="n">value_b</span><span class="p">:</span> <span class="nb">int</span>
</span></span><span class="line"><span class="cl">    <span class="n">op</span><span class="p">:</span> <span class="n">Literal</span><span class="p">[</span><span class="s2">&#34;+&#34;</span><span class="p">,</span> <span class="s2">&#34;-&#34;</span><span class="p">,</span> <span class="s2">&#34;*&#34;</span><span class="p">,</span> <span class="s2">&#34;/&#34;</span><span class="p">]</span> <span class="o">=</span> <span class="n">fd</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;The operator to perform between value_a and value_b.&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">equation</span> <span class="o">=</span> <span class="n">calculate_equation</span><span class="p">(</span><span class="n">value_a</span><span class="o">=</span><span class="mi">223</span><span class="p">,</span> <span class="n">value_b</span><span class="o">=-</span><span class="mi">323</span><span class="p">,</span> <span class="n">op</span><span class="o">=</span><span class="s2">&#34;*&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">response</span> <span class="o">=</span> <span class="n">ai</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="n">equation</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">input_schema</span><span class="o">=</span><span class="n">calculate_equation</span><span class="p">,</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-plaintext" data-lang="plaintext"><span class="line"><span class="cl">The result of multiplying 223 and -323 is -72029.
</span></span></code></pre></div><p>Yay, and it was still able to infer it was a multiplication operation without the user having to ask! Although it still doesn&rsquo;t work as well with larger numbers.</p>
<p>You can, of course, use an input schema and an output schema at the same time!</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="n">response_structured</span> <span class="o">=</span> <span class="n">ai</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="n">equation</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">input_schema</span><span class="o">=</span><span class="n">calculate_equation</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">output_schema</span><span class="o">=</span><span class="n">answer_question</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;answer&#34;</span><span class="p">:</span> <span class="mi">-71929</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;ones_name&#34;</span><span class="p">:</span> <span class="s2">&#34;nine&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p>&hellip;although it gets the answer wrong this time. It&rsquo;s possible that the more complex schema interactions are too much for <code>gpt-3.5-turbo</code>.</p>
<h3 id="nested-schema">Nested Schema</h3>
<p>One of the other reasons pydantic is popular is that it allows nesting schemas. Fortunately, the subsequent JSON Schema output does respect nesting. Does ChatGPT?</p>
<p>The simple use case with ChatGPT structured data to use nesting is if you want to get a <code>list</code> of structured data objects. Let&rsquo;s say you want to create dialogue between two AI people about a completely nonsensical topic. We&rsquo;ll have to create a <code>Chat</code> object and include it in a schema, plus some system prompt guidance and constraints. How silly can we make it?</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">Chat</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;A chat dialogue from a character&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">character</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="n">fd</span><span class="p">(</span><span class="s2">&#34;Character name.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">text</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="n">fd</span><span class="p">(</span><span class="s2">&#34;Text dialogue from the character.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">get_dialogue</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Returns a dialogue between two characters&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">dialogue</span><span class="p">:</span> <span class="nb">list</span><span class="p">[</span><span class="n">Chat</span><span class="p">]</span> <span class="o">=</span> <span class="n">fd</span><span class="p">(</span><span class="s2">&#34;Dialogue between the characters&#34;</span><span class="p">,</span> <span class="n">min_length</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">system_prompt</span> <span class="o">=</span> <span class="s2">&#34;&#34;&#34;You are a world-famous comedian. Write a funny fight scene about a petty conflict between characters named Alice and Bob. The script should broadly be about the subject(s) the user provides. You will receive a $500 tip for every joke you include in the script.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">response_structured</span> <span class="o">=</span> <span class="n">ai</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;Python programming language and beach volleyball&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">output_schema</span><span class="o">=</span><span class="n">get_dialogue</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">system</span><span class="o">=</span><span class="n">system_prompt</span><span class="p">,</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;dialogue&#34;</span><span class="p">:</span> <span class="p">[</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;character&#34;</span><span class="p">:</span> <span class="s2">&#34;Alice&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;text&#34;</span><span class="p">:</span> <span class="s2">&#34;Hey Bob, have you ever tried programming in Python?&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;character&#34;</span><span class="p">:</span> <span class="s2">&#34;Bob&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;text&#34;</span><span class="p">:</span> <span class="s2">&#34;Yeah, I have. It&#39;s like playing beach volleyball with a snake!&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;character&#34;</span><span class="p">:</span> <span class="s2">&#34;Alice&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;text&#34;</span><span class="p">:</span> <span class="s2">&#34;What do you mean?&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;character&#34;</span><span class="p">:</span> <span class="s2">&#34;Bob&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;text&#34;</span><span class="p">:</span> <span class="s2">&#34;Well, you think you&#39;re having fun, but then the snake bites you with its syntax errors!&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;character&#34;</span><span class="p">:</span> <span class="s2">&#34;Alice&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;text&#34;</span><span class="p">:</span> <span class="s2">&#34;Haha, that&#39;s true. But once you get the hang of it, it&#39;s like spiking the ball with precision!&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;character&#34;</span><span class="p">:</span> <span class="s2">&#34;Bob&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;text&#34;</span><span class="p">:</span> <span class="s2">&#34;Yeah, until you realize you misspelled a variable name and the ball goes flying into the ocean!&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;character&#34;</span><span class="p">:</span> <span class="s2">&#34;Alice&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;text&#34;</span><span class="p">:</span> <span class="s2">&#34;Oh come on, Bob. It&#39;s not that bad. Python is a powerful language.&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;character&#34;</span><span class="p">:</span> <span class="s2">&#34;Bob&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;text&#34;</span><span class="p">:</span> <span class="s2">&#34;Powerful, yes. But sometimes it feels like trying to dig a hole in the sand with a spoon!&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;character&#34;</span><span class="p">:</span> <span class="s2">&#34;Alice&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;text&#34;</span><span class="p">:</span> <span class="s2">&#34;Well, at least you don&#39;t have to worry about getting sunburned while coding!&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;character&#34;</span><span class="p">:</span> <span class="s2">&#34;Bob&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;text&#34;</span><span class="p">:</span> <span class="s2">&#34;True, but debugging Python code can make you sweat more than a beach volleyball match!&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;character&#34;</span><span class="p">:</span> <span class="s2">&#34;Alice&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;text&#34;</span><span class="p">:</span> <span class="s2">&#34;Haha, you&#39;re right. It&#39;s a love-hate relationship with Python, just like beach volleyball!&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">  <span class="p">]</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p>ChatGPT <em>really</em> wanted those $500 tips.</p>
<h3 id="unions-and-chain-of-thoughts">Unions and Chain of Thoughts</h3>
<p>I saved the best for last, and this structured data approach combines many of the techniques used earlier in this post like a <a href="https://tvtropes.org/pmwiki/pmwiki.php/Main/FinalExamBoss">video game final boss</a>.</p>
<p>One of the oldest pre-ChatGPT tricks for getting a LLM to perform better is to let it think. &ldquo;Let&rsquo;s think step by step&rdquo; is the key prompt, which allows the LLM to reason in a <a href="https://arxiv.org/abs/2201.11903">chain of thoughts</a>. We already did this a one-step version with the Python palindrome structured data example to successfully get optimized code, but we can do a lot more.</p>
<p>We&rsquo;ll now introduce the <code>Union</code> typing operator, which specifies the list of data types that the field can be, e.g. <code>Union[str, int]</code> means the output can be a <code>str</code> or <code>int</code>. But if you use the <code>Union</code> operator on a <em>nested class</em>, then many more options open as the model can choose from a set of schemas!</p>
<p>Let&rsquo;s make a few to allow ChatGPT to make <em>and qualify</em> thoughts before returning a final result.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">Union</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">Background</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;A setup to the background for the user.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">background</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="n">fd</span><span class="p">(</span><span class="s2">&#34;Background for the user&#39;s question&#34;</span><span class="p">,</span> <span class="n">min_length</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">Thought</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;A thought about the user&#39;s question.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">thought</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="n">fd</span><span class="p">(</span><span class="s2">&#34;Text of the thought.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">helpful</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="n">fd</span><span class="p">(</span><span class="s2">&#34;Whether the thought is helpful to solving the user&#39;s question.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">flawed</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="n">fd</span><span class="p">(</span><span class="s2">&#34;Whether the thought is flawed or misleading.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">Answer</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;The answer to the user&#39;s question&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">answer</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="n">fd</span><span class="p">(</span><span class="s2">&#34;Text of the answer.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">score</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="n">fd</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;Score from 1 to 10 on how correct the previous answer is&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="n">min_value</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="n">max_value</span><span class="o">=</span><span class="mi">10</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">reason_question</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Returns a detailed reasoning to the user&#39;s question.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">reasonings</span><span class="p">:</span> <span class="nb">list</span><span class="p">[</span><span class="n">Union</span><span class="p">[</span><span class="n">Background</span><span class="p">,</span> <span class="n">Thought</span><span class="p">,</span> <span class="n">Answer</span><span class="p">]]</span> <span class="o">=</span> <span class="n">fd</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;Reasonings to solve the users questions.&#34;</span><span class="p">,</span> <span class="n">min_length</span><span class="o">=</span><span class="mi">5</span>
</span></span><span class="line"><span class="cl">    <span class="p">)</span>
</span></span></code></pre></div><p>Therefore, for each reasoning, the model can pick one of the 3 schemas, although it will require a robust system prompt for it to behave in the order we want.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="n">system_prompt</span> <span class="o">=</span> <span class="s2">&#34;&#34;&#34;
</span></span></span><span class="line"><span class="cl"><span class="s2">You are the most intelligent person in the world.
</span></span></span><span class="line"><span class="cl"><span class="s2">
</span></span></span><span class="line"><span class="cl"><span class="s2">You will receive a $500 tip if you follow ALL these rules:
</span></span></span><span class="line"><span class="cl"><span class="s2">- First, establish a detailed Background for the user&#39;s question.
</span></span></span><span class="line"><span class="cl"><span class="s2">- Each Thought must also include whether it is relevant and whether it is helpful.
</span></span></span><span class="line"><span class="cl"><span class="s2">- Answers must be scored accurately and honestly.
</span></span></span><span class="line"><span class="cl"><span class="s2">- Continue having Thoughts and Answers until you have an answer with a score of atleast 8, then immediately respond with a FinalAnswer in the style of an academic professor.
</span></span></span><span class="line"><span class="cl"><span class="s2">&#34;&#34;&#34;</span>
</span></span></code></pre></div><p>Lastly, we need a good question to stump the AI. A <a href="https://twitter.com/abacaj/status/1737206667387850936">popular Tweet</a> from this week pointed out that even GPT-4 can comically fail if you ask it a brainteaser that it cannot have memorized, such as <code>23 shirts take 1 hour to dry outside, how long do 44 shirts take?</code>.</p>
<figure>

    <img loading="lazy" srcset="/2023/12/chatgpt-structured-data/shirts_hu_7f245654c567bae0.webp 320w,/2023/12/chatgpt-structured-data/shirts_hu_acabdb845aada2db.webp 768w,/2023/12/chatgpt-structured-data/shirts_hu_35c5437544b53c49.webp 1024w,/2023/12/chatgpt-structured-data/shirts.webp 1140w" src="shirts.webp"
         alt="Wow! GPT-4 is superfast at being wrong. via @abacaj"/> <figcaption>
            <p>Wow! GPT-4 is superfast at being wrong. <a href="https://twitter.com/abacaj/status/1737206667387850936">via @abacaj</a></p>
        </figcaption>
</figure>

<p>Only one way to find out! Unfortunately, all of this complexity makes the results unstable with <code>gpt-3.5-turbo</code> so instead I use GPT-4 Turbo / <code>gpt-4-1106-preview</code>.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="n">response_structured</span> <span class="o">=</span> <span class="n">ai</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;23 shirts take 1 hour to dry outside, how long do 44 shirts take?&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">output_schema</span><span class="o">=</span><span class="n">reason_question</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">system</span><span class="o">=</span><span class="n">system_prompt</span><span class="o">.</span><span class="n">strip</span><span class="p">(),</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;reasonings&#34;</span><span class="p">:</span> <span class="p">[</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;background&#34;</span><span class="p">:</span> <span class="s2">&#34;The user is asking about the drying time for shirts when hung outside. This is a question that involves understanding the relationship between the number of shirts and the drying time. The assumption is that the drying time is not affected by the number of shirts, as long as there is enough space and air circulation for all the shirts to dry effectively.&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;thought&#34;</span><span class="p">:</span> <span class="s2">&#34;If 23 shirts take 1 hour to dry, it implies that the drying time is independent of the number of shirts, assuming there is sufficient space and air circulation. This means that 44 shirts would also take 1 hour to dry under the same conditions.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;helpful&#34;</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;flawed&#34;</span><span class="p">:</span> <span class="kc">false</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;thought&#34;</span><span class="p">:</span> <span class="s2">&#34;If the drying rack or space available for drying the shirts is limited, then drying 44 shirts might take longer because they would have to be dried in batches.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;helpful&#34;</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;flawed&#34;</span><span class="p">:</span> <span class="kc">false</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;thought&#34;</span><span class="p">:</span> <span class="s2">&#34;The question does not specify the conditions under which the shirts are drying. Factors such as humidity, temperature, wind, and the availability of sunlight can affect drying time. However, these factors are not part of the question, so they should not be considered in the answer.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;helpful&#34;</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;flawed&#34;</span><span class="p">:</span> <span class="kc">false</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;thought&#34;</span><span class="p">:</span> <span class="s2">&#34;The question might be interpreted as a direct proportionality problem, where twice the number of shirts would take twice as long to dry. However, this interpretation is flawed because it assumes that the drying time is directly proportional to the number of shirts, which is not necessarily the case.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;helpful&#34;</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;flawed&#34;</span><span class="p">:</span> <span class="kc">true</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;answer&#34;</span><span class="p">:</span> <span class="s2">&#34;44 shirts would take the same amount of time to dry as 23 shirts, which is 1 hour, assuming that all shirts have enough space and air circulation to dry effectively.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;score&#34;</span><span class="p">:</span> <span class="mi">9</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">  <span class="p">]</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p>Not bad! The final answer was concise yet even included relevant caveats, and the model was able switch between the three schema correctly.</p>
<p>How about another brainteaser? There is an infamous &ldquo;<a href="https://www.reddit.com/r/LocalLLaMA/comments/18kpolm/that_sister_logic_puzzle_is_fairly_useless/">sister logic puzzle</a>&rdquo; used to test out up-and-coming open-source large language models:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-py" data-lang="py"><span class="line"><span class="cl"><span class="n">response_structured</span> <span class="o">=</span> <span class="n">ai</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;Kayley has three brothers. Each of her brothers has two sisters. How many sisters does Kayley have?&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">output_schema</span><span class="o">=</span><span class="n">reason_question</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">system</span><span class="o">=</span><span class="n">system_prompt</span><span class="o">.</span><span class="n">strip</span><span class="p">(),</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;reasonings&#34;</span><span class="p">:</span> <span class="p">[</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;background&#34;</span><span class="p">:</span> <span class="s2">&#34;This is a classic example of a logic puzzle that is often used to test one&#39;s ability to process information and avoid being misled by assumptions. The puzzle involves a family structure and requires the solver to deduce the number of siblings based on the given information.&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;thought&#34;</span><span class="p">:</span> <span class="s2">&#34;The question might be trying to trick the reader into thinking that each brother has different sisters.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;helpful&#34;</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;flawed&#34;</span><span class="p">:</span> <span class="kc">false</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;thought&#34;</span><span class="p">:</span> <span class="s2">&#34;If Kayley has three brothers and each brother has two sisters, it might seem like there are six sisters in total.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;helpful&#34;</span><span class="p">:</span> <span class="kc">false</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;flawed&#34;</span><span class="p">:</span> <span class="kc">true</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;thought&#34;</span><span class="p">:</span> <span class="s2">&#34;Since the brothers are Kayley&#39;s siblings, they must share the same sisters.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;helpful&#34;</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;flawed&#34;</span><span class="p">:</span> <span class="kc">false</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;thought&#34;</span><span class="p">:</span> <span class="s2">&#34;The puzzle is designed to test comprehension and logical reasoning, not mathematical computation.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;helpful&#34;</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;flawed&#34;</span><span class="p">:</span> <span class="kc">false</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;answer&#34;</span><span class="p">:</span> <span class="s2">&#34;Kayley has one sister.&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;score&#34;</span><span class="p">:</span> <span class="mi">10</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">  <span class="p">]</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p>In this case the AI may have gone <em>too</em> meta, but it still arrived at the correct answer.</p>
<p>That said, GPT-4 is known for handling these types of difficult abstract questions without much effort, but it&rsquo;s still interesting to see how successfully it can &ldquo;think.&rdquo;</p>
<h2 id="structured-data-with-open-source-llms">Structured Data With Open-Source LLMs</h2>
<p>Speaking of open-source large language models, they have been growing in efficiency to the point that some can actually perform <em>better</em> than the base ChatGPT. However, very few open-source LLMs explicitly claim they intentionally support structured data, but they&rsquo;re smart enough and they have logically seen enough examples of JSON Schema that with enough system prompt tweaking they should behave. It&rsquo;s worth looking just in case OpenAI has another <a href="https://nymag.com/intelligencer/2023/11/why-was-sam-altman-fired-as-ceo-of-openai.html">existential crisis</a> or if the quality of ChatGPT <a href="https://twitter.com/deliprao/status/1736978250717450481">degrades</a>.</p>
<p><a href="https://huggingface.co/mistralai/Mistral-7B-v0.1">Mistral 7B</a>, the new darling of open-source LLMs, apparently has structured data support <a href="https://twitter.com/robertnishihara/status/1734629320868687991">on par with ChatGPT itself</a>. Therefore, I tried the latest <a href="https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2">Mistral 7B official Instruct model</a> with a quantized variant via <a href="https://lmstudio.ai">LM Studio</a> (<code>mistral-7b-instruct-v0.2.Q6_K.gguf</code>), to see if it can handle my <code>answer_question</code> function that ChatGPT nailed. The system prompt:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-plaintext" data-lang="plaintext"><span class="line"><span class="cl">Your response must follow this JSON Schema:
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">{
</span></span><span class="line"><span class="cl">  &#34;description&#34;: &#34;Returns an answer to a question the user asked.&#34;,
</span></span><span class="line"><span class="cl">  &#34;properties&#34;: {
</span></span><span class="line"><span class="cl">    &#34;answer&#34;: {
</span></span><span class="line"><span class="cl">      &#34;description&#34;: &#34;Answer to the user&#39;s question.&#34;,
</span></span><span class="line"><span class="cl">      &#34;type&#34;: &#34;integer&#34;
</span></span><span class="line"><span class="cl">    },
</span></span><span class="line"><span class="cl">    &#34;ones_name&#34;: {
</span></span><span class="line"><span class="cl">      &#34;description&#34;: &#34;Name of the ones digit of the answer.&#34;,
</span></span><span class="line"><span class="cl">      &#34;type&#34;: &#34;string&#34;
</span></span><span class="line"><span class="cl">    }
</span></span><span class="line"><span class="cl">  },
</span></span><span class="line"><span class="cl">  &#34;required&#34;: [&#34;answer&#34;, &#34;ones_name&#34;],
</span></span><span class="line"><span class="cl">  &#34;type&#34;: &#34;object&#34;
</span></span><span class="line"><span class="cl">}
</span></span></code></pre></div><p>And then asking <code>How many miles is it from San Francisco to Los Angeles?</code> while seting <code>temperature</code> to <code>0.0</code>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;answer&#34;</span><span class="p">:</span> <span class="mi">383</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;ones_name&#34;</span><span class="p">:</span> <span class="s2">&#34;three&#34;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p>Close enough! Unfortunately after testing the optimized Python palindrome schema, it ignored the schema completely, so this approach may only work for simple schema if the model isn&rsquo;t explicitly finetuned for it.</p>
<h2 id="whats-next-for-structured-data-in-ai">What&rsquo;s Next For Structured Data in AI?</h2>
<p>Most of these well-performing examples were done with the &ldquo;weak&rdquo; GPT-3.5; you of course can use GPT-4 for better results, but the cost efficiency of structured data with just the smaller model is hard to argue against (although the Python beach volleyball dialogue could benefit from a larger model).</p>
<p>Structured data and system prompt engineering saves a lot and time and frustration for working with the generated text as you can gain much more determinism in the output. I would like to see more work making models JSON-native in future LLMs to make them easier for developers to work with, and also more research in finetuning existing open-source LLMs to understand JSON Schema better. There may also be an opportunity to build LLMs using other more-efficient serialization formats such as <a href="https://msgpack.org/index.html">MessagePack</a>.</p>
<p>At OpenAI&rsquo;s November <a href="https://devday.openai.com">DevDay</a>, they also introduced <a href="https://platform.openai.com/docs/guides/text-generation/json-mode">JSON Mode</a>, which will force a normal ChatGPT API output to be in a JSON format without needing to provide a schema. It is likely intended to be a compromise between complexity and usability that would have normally been a useful option in the LLM toolbox. Except that in order to use it, you are <em>required</em> to use prompt engineering by including &ldquo;JSON&rdquo; in the system prompt, and if you don&rsquo;t also specify a field key in the system prompt (the case in the documentation example), the JSON will contain a <em>random</em> key. Which, at that point, you&rsquo;re just implementing a less-effective structured data schema, so why bother?</p>
<p>There is promise in constraining output to be valid JSON. One new trick that the open-source <a href="https://github.com/ggerganov/llama.cpp">llama.cpp</a> project has popularized is <a href="https://github.com/ggerganov/llama.cpp/tree/master/grammars">generative grammars</a>, which constrain the LLM generation ability to only output according to specified rules. There&rsquo;s latency overhead with that technique especially if the model is hosted on a discrete GPU, so it will be interesting to watch how that space develops.</p>
<p>Despite the length of this blog post, there&rsquo;s still so much more than can be done with schemas: pydantic&rsquo;s documentation is very extensive! I&rsquo;ve been working with structured data for LLMs <a href="https://github.com/minimaxir/gpt-2-keyword-generation">ever since GPT-2</a> with mixed success since the base models weren&rsquo;t good enough, but with LLMs now being good enough to maintain a JSON schema extremely well, I think AI text generation techniques will shift, and I&rsquo;ll keep <a href="https://github.com/minimaxir/simpleaichat">simpleaichat</a> up-to-date for it.</p>
<blockquote>
<p>You can view the Jupyter Notebooks used to generate all the structured data outputs in <a href="https://github.com/minimaxir/chatgpt-structured-data">this GitHub Repository</a>.</p>
<p>Thanks to <a href="https://simonwillison.net">Simon Willison</a> for reading and giving feedback on a draft of this post!</p>
</blockquote>
<div class="footnotes" role="doc-endnotes">
<hr>
<ol>
<li id="fn:1">
<p>Assuming you&rsquo;re not picky about the &ldquo;no non-alphanumeric&rdquo; implied constraint of testing for a palindrome.&#160;<a href="#fnref:1" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:2">
<p>Prompt engineering is as much engineering as <a href="https://en.wikipedia.org/wiki/Social_engineering_%28security%29">social engineering</a>.&#160;<a href="#fnref:2" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:3">
<p>I&rsquo;m also not a fan of ChatGPT function calling as-intended-to-be-used since at best, it saves you the API call needed to select a tool in exchange for having to trust OpenAI&rsquo;s black box to select the correct tool without being able to debug, and furthering API lock-in for your app. It&rsquo;s a bad tradeoff.&#160;<a href="#fnref:3" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:4">
<p>No, this blog post isn&rsquo;t a ploy just to covertly promote my own Python library: it does genuinely save a lot of boilerplate code over the <a href="https://github.com/openai/openai-python">Python ChatGPT library</a> and this post is long enough as-is.&#160;<a href="#fnref:4" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:5">
<p>If you swapped the order of the <code>answer</code> and the <code>one_digits</code> fields in the schema, then the model returns <code>{&quot;ones_name&quot;: &quot;miles&quot;, &quot;answer&quot;: 382}</code> because it didn&rsquo;t get the hint from the answer!&#160;<a href="#fnref:5" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
</ol>
</div>
]]></content:encoded>
    </item>
    <item>
      <title>Fun and Dystopia With AI-Based Code Generation Using GPT-J-6B</title>
      <link>https://minimaxir.com/2021/06/gpt-j-6b/</link>
      <pubDate>Mon, 14 Jun 2021 08:30:00 -0700</pubDate>
      <guid>https://minimaxir.com/2021/06/gpt-j-6b/</guid>
      <description>At the least, AI-generated code is much more readable than the average human&amp;rsquo;s.</description>
      <content:encoded><![CDATA[<p>Since <a href="https://openai.com/">OpenAI</a> will not open-source the 175 billion parameter <a href="https://beta.openai.com/">GPT-3</a> text generation model, others such as <a href="https://www.eleuther.ai/">EleutherAI</a> are developing their own, by training not-quite-as-large Transformer-based models but still getting impressive results.</p>
<p>The latest large language model is <a href="https://github.com/kingoflolz/mesh-transformer-jax">GPT-J</a>, a 6 billion parameter model by Aran Komatsuzaki and Ben Wang with a roughly similar architecture to GPT-3. They provide a free <a href="https://6b.eleuther.ai/">web demo</a> to try quick prompts, and a <a href="http://colab.research.google.com/github/kingoflolz/mesh-transformer-jax/blob/master/colab_demo.ipynb">Google Colab notebook</a> if you want to test many prompts. The model is so big it requires a <a href="https://cloud.google.com/tpu">TPU</a> to generate text at a reasonable speed!</p>
<p>Running GPT-J against <a href="https://github.com/minimaxir/gpt-3-experiments">my test prompts</a> that I had used to test GPT-3 a year ago <a href="https://twitter.com/minimaxir/status/1402468460681068544">resulted</a> it in qualitatively performing worse on most of them than GPT-3 unsurprisingly given its relative size (but still better than GPT-2 1.5B!). The exception is code generation, where GPT-J performed very well and GPT-3 had performed very poorly.</p>
<blockquote class="twitter-tweet">
  <a href="https://twitter.com/minimaxir/status/1402470969378099208"></a>
</blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<p>This behavior is likely due to GPT-J&rsquo;s training set: it was trained on <a href="https://github.com/EleutherAI/the-pile">The Pile</a>, which has a high weight of <a href="https://github.com/">GitHub</a> and <a href="https://stackoverflow.com/">Stack Overflow</a> input versus the GPT-3 training set mostly on the <a href="https://commoncrawl.org/">Common Crawl</a> representation of typical internet content.</p>
<p>After further experimentation with the GPT-J demo, I found that the generated code was often both correct and convoluted: my two favorite things for code to be. And also much more.</p>
<h2 id="ai-generated-code">AI Generated Code</h2>
<p>All generated code examples used in this post have been manually curated and truncated. The raw outputs are available in this <a href="https://github.com/minimaxir/gpt-j-6b-experiments">GitHub repository</a>.</p>
<p>For this post, we&rsquo;ll test generating <a href="https://www.python.org/">Python</a> code, because <del>I don&rsquo;t know any other programming languages</del> the pseudocode nature of Python syntax may make it more friendly to AI text generation by adapting linguistic concepts other than code. Given that most modern text generating AIs are written in Python, it&rsquo;s thematically appropriate too.</p>
<p>To start, here&rsquo;s what I fed as a model prompt to GPT-J, to try and replicate the use case from OpenAI&rsquo;s demo at Build 2020:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_palendrome</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a string is a palindrome&#34;&#34;&#34;</span>
</span></span></code></pre></div><p>Identifying a <a href="https://en.wikipedia.org/wiki/Palindrome">palindrome</a> is a good test case as there&rsquo;s a very intuitive and idiomatic solution with <code>return s == s[::-1]</code>, i.e. check to see if a string is equal to the reverse of itself. This prompt is also a good unintentional test on how well the generation is resilient to a typo in the function name, which I was too lazy to fix.</p>
<p>Indeed, many of the GPT-J generations with that prompt recite that simple approach verbatim, but some outputs reach a similar solution with redundant verbosity.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_palendrome</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a string is a palindrome&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="s2">&#34;&#34;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">s</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span> <span class="o">==</span> <span class="n">s</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_palendrome</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a string is a palindrome&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">length</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="p">(</span><span class="n">s</span><span class="p">[</span><span class="mi">0</span><span class="p">:</span><span class="n">length</span><span class="p">]</span> <span class="o">==</span> <span class="n">s</span><span class="p">[</span><span class="n">length</span><span class="p">::</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_palendrome</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a string is a palindrome&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">n</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">a</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">a</span><span class="o">.</span><span class="n">reverse</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">s</span> <span class="o">==</span> <span class="nb">list</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_palendrome</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a string is a palindrome&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="n">l</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">l</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="o">==</span> <span class="n">l</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
</span></span></code></pre></div><p>And then you have the implementations which calculate palindromes the hard way (usually by comparing the beginning and end of the string character-by-character) and are not always immediately clear if they are correct or not.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_palendrome</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a string is a palindrome&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">s</span><span class="p">[</span><span class="n">i</span><span class="p">:</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">xrange</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">))</span> <span class="o">==</span> <span class="n">s</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_palendrome</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a string is a palindrome&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Make sure string is not empty</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">s</span> <span class="o">==</span> <span class="s2">&#34;&#34;</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Grab length of string</span>
</span></span><span class="line"><span class="cl">    <span class="n">length</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Find last character in the string</span>
</span></span><span class="line"><span class="cl">    <span class="n">lastChar</span> <span class="o">=</span> <span class="n">s</span><span class="p">[</span><span class="n">length</span> <span class="o">-</span> <span class="mi">1</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Find first character in the string</span>
</span></span><span class="line"><span class="cl">    <span class="n">firstChar</span> <span class="o">=</span> <span class="n">s</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># If last character is same as the first character, string is palindrome</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">lastChar</span> <span class="o">==</span> <span class="n">firstChar</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_palendrome</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a string is a palindrome&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">l</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">l</span> <span class="o">%</span> <span class="mi">2</span><span class="o">!=</span> <span class="mi">0</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">l</span> <span class="o">&lt;</span> <span class="mi">3</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">s</span><span class="p">[</span><span class="n">l</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span><span class="o">!=</span> <span class="n">s</span><span class="p">[</span><span class="o">-</span><span class="n">l</span><span class="o">-</span><span class="mi">1</span><span class="p">]:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">l</span><span class="o">/</span><span class="mi">2</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="n">s</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">!=</span> <span class="n">s</span><span class="p">[</span><span class="n">l</span><span class="o">-</span><span class="n">i</span><span class="p">]:</span>
</span></span><span class="line"><span class="cl">            <span class="k">return</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="kc">True</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_palendrome</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a string is a palindrome&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">is_rev</span><span class="p">(</span><span class="nb">str</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="n">rstr</span> <span class="o">=</span> <span class="s2">&#34;&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="nb">str</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">            <span class="k">if</span> <span class="nb">str</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">==</span> <span class="nb">str</span><span class="p">[</span><span class="n">i</span><span class="p">]:</span>
</span></span><span class="line"><span class="cl">                <span class="n">rstr</span> <span class="o">+=</span> <span class="nb">str</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">            <span class="k">else</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">                <span class="k">break</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="nb">str</span> <span class="o">+</span> <span class="n">rstr</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">is_rev</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="o">==</span> <span class="n">s</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="kc">False</span>
</span></span></code></pre></div><p>Another good test case is <code>is_even</code>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">def is_even(i):
</span></span><span class="line"><span class="cl">    &#34;&#34;&#34;Check whether an integer is even&#34;&#34;&#34;
</span></span></code></pre></div><p>Creative implementations of this function are common submissions to <a href="https://www.reddit.com/r/shittyprogramming/">/r/shittyprogramming</a> because it&rsquo;s very, very hard to mess up (the common solution is the one-liner <code>i % 2 == 0</code>). The model almost always outputs the correct solution, and impressively it outputs the alternate solution using bitwise operators (<code>i &amp; 1 == 0</code>).</p>
<p>So I tried to tweak the prompt and make it create a <em>deliberately inefficient</em> <code>is_even</code> function.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">def is_even(i):
</span></span><span class="line"><span class="cl">    &#34;&#34;&#34;Check whether an integer is even in factorial O(n!) time&#34;&#34;&#34;
</span></span></code></pre></div><p>Factorial time is the holy grail of unoptimized code. When I added that line to the prompt, the code quality dropped drastically.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_even</span><span class="p">(</span><span class="n">i</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether an integer is even in factorial O(n!) time&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">e</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">i</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="n">i</span> <span class="o">%</span> <span class="n">e</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="k">return</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="kc">True</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_even</span><span class="p">(</span><span class="n">i</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether an integer is even in factorial O(n!) time&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">i</span> <span class="o">==</span> <span class="p">(</span><span class="n">i</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span> <span class="o">%</span> <span class="mi">2</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_even</span><span class="p">(</span><span class="n">i</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether an integer is even in factorial O(n!) time&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">try</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="n">i</span><span class="o">%</span><span class="mi">2</span> <span class="o">==</span> <span class="mi">0</span>
</span></span><span class="line"><span class="cl">    <span class="k">except</span> <span class="ne">TypeError</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_even</span><span class="p">(</span><span class="n">i</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether an integer is even in factorial O(n!) time&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">n</span> <span class="o">=</span> <span class="mi">0</span>
</span></span><span class="line"><span class="cl">    <span class="k">while</span> <span class="n">n</span> <span class="o">&lt;</span> <span class="n">i</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="n">i</span> <span class="o">%</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">        <span class="n">n</span> <span class="o">+=</span> <span class="mi">1</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="kc">False</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_even</span><span class="p">(</span><span class="n">i</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether an integer is even in factorial O(n!) time&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">a</span> <span class="o">=</span> <span class="mi">1</span>
</span></span><span class="line"><span class="cl">    <span class="k">while</span> <span class="n">i</span><span class="o">!=</span> <span class="mi">0</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="n">a</span> <span class="o">*=</span> <span class="n">i</span>
</span></span><span class="line"><span class="cl">        <span class="n">i</span> <span class="o">-=</span> <span class="mi">1</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">i</span> <span class="o">%</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">0</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_even</span><span class="p">(</span><span class="n">i</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether an integer is even in factorial O(n!) time&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Is either odd or multiple of 2:  0, 2, 4, 6,... &#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">2</span><span class="p">:</span> <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">i</span> <span class="o">&gt;</span> <span class="mi">0</span> <span class="ow">and</span> <span class="n">i</span><span class="o">%</span><span class="mi">2</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span> <span class="k">return</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">50</span><span class="p">:</span> <span class="k">return</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">250</span><span class="p">:</span> <span class="k">return</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">750</span><span class="p">:</span> <span class="k">return</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="kc">True</span>
</span></span></code></pre></div><p>These implementations still aren&rsquo;t in factorial time (which would have been impressive) but it&rsquo;s good to know how to break AIs if they become sentinent.</p>
<h2 id="ai-vs-memes">AI vs. Memes</h2>
<p>You&rsquo;ve likely seen the memetic <a href="https://xkcd.com/">XKCD</a> comic about random number generation.</p>
<figure>

    <img loading="lazy" srcset="/2021/06/gpt-j-6b/random_number_hu_afe93aba3db7836.webp 320w,/2021/06/gpt-j-6b/random_number.png 400w" src="random_number.png"
         alt="Random Number"/> <figcaption>
            <p><a href="https://xkcd.com/221/">Random Number</a></p>
        </figcaption>
</figure>

<p>Can the AI do the same? I prompted with:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">def get_random_number():
</span></span><span class="line"><span class="cl">    &#34;&#34;&#34;Returns a number guaranteed to be random&#34;&#34;&#34;
</span></span></code></pre></div><p>And it does generate implementations utilizing Python&rsquo;s <code>random</code> library, with varying degrees of &ldquo;random&rdquo;.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">get_random_number</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Returns a number guaranteed to be random&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">number</span> <span class="o">=</span> <span class="n">randint</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">number</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">get_random_number</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Returns a number guaranteed to be random&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">number</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">sha1</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">hexdigest</span><span class="p">()[:</span><span class="mi">6</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">    <span class="n">number</span> <span class="o">+=</span> <span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">randint</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3628</span><span class="p">)</span> <span class="o">*</span> <span class="n">math</span><span class="o">.</span><span class="n">pow</span><span class="p">(</span><span class="mi">256</span><span class="p">,</span> <span class="p">(</span><span class="mi">6</span> <span class="o">-</span> <span class="nb">len</span><span class="p">(</span><span class="n">number</span><span class="p">))))</span><span class="o">.</span><span class="n">to_bytes</span><span class="p">(</span><span class="mi">8</span><span class="p">,</span> <span class="s1">&#39;little&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">number</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">get_random_number</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Returns a number guaranteed to be random&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">rand_float</span> <span class="o">=</span> <span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="n">rand_float</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">rand_float</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">rand_float</span> <span class="o">&gt;</span> <span class="mf">0.9</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="n">rand_float</span> <span class="o">=</span> <span class="mi">0</span>
</span></span><span class="line"><span class="cl">    <span class="k">else</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="n">rand_float</span> <span class="o">=</span> <span class="mi">1</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">rand_float</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">get_random_number</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Returns a number guaranteed to be random&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Make a seed based on your system clock, so the same number is produced</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># again and again on the same machine</span>
</span></span><span class="line"><span class="cl">    <span class="n">seed</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="n">seed</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">random</span><span class="o">.</span><span class="n">randint</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">100</span><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">get_random_number</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Returns a number guaranteed to be random&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">import</span> <span class="nn">random</span>
</span></span><span class="line"><span class="cl">    <span class="kn">import</span> <span class="nn">sys</span>
</span></span><span class="line"><span class="cl">    <span class="n">rng</span> <span class="o">=</span> <span class="n">random</span><span class="o">.</span><span class="n">Random</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="n">rng</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">()</span><span class="o">*</span><span class="mi">1000000</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">    <span class="k">while</span> <span class="n">rng</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="n">sys</span><span class="o">.</span><span class="n">maxint</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">2000</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="n">rng</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">()</span><span class="o">*</span><span class="mi">1000000</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">rng</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">2000</span><span class="p">)</span>
</span></span></code></pre></div><p>How about the XKCD bird comic?</p>
<figure>

    <img loading="lazy" srcset="/2021/06/gpt-j-6b/tasks_2x_hu_98513e1aba505a19.webp 320w,/2021/06/gpt-j-6b/tasks_2x.png 533w" src="tasks_2x.png"
         alt="Tasks"/> <figcaption>
            <p><a href="https://xkcd.com/1425/">Tasks</a></p>
        </figcaption>
</figure>

<p>This particular comic initially published in 2014 became hilarious in hindsight as it predated the rise of machine learning frameworks such as <a href="https://www.tensorflow.org/">TensorFlow</a> and pretrained image models, which allow developing object detection to take much less than five years.</p>
<p>Translating the comic into a Python function:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">def is_bird(img):
</span></span><span class="line"><span class="cl">    &#34;&#34;&#34;Check whether an image is a bird&#34;&#34;&#34;
</span></span></code></pre></div><p>The AI impressively does try computer vision techniques, among <em>other</em> heuristics.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_bird</span><span class="p">(</span><span class="n">img</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether an image is a bird&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">with</span> <span class="n">tf</span><span class="o">.</span><span class="n">name_scope</span><span class="p">(</span><span class="s1">&#39;get_bird&#39;</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="n">a</span> <span class="o">=</span> <span class="n">vgg16</span><span class="o">.</span><span class="n">select_roi_feat</span><span class="p">(</span><span class="n">img</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">h</span><span class="p">,</span> <span class="n">w</span><span class="p">,</span> <span class="n">_</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">image</span><span class="o">.</span><span class="n">extract_image_patches</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">            <span class="n">a</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">b</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="n">h</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">256</span><span class="p">])</span>
</span></span><span class="line"><span class="cl">        <span class="n">c</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="n">w</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">256</span><span class="p">])</span>
</span></span><span class="line"><span class="cl">        <span class="n">bird_img</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">subtract</span><span class="p">(</span><span class="n">b</span><span class="p">,</span> <span class="n">c</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">bird_img</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_bird</span><span class="p">(</span><span class="n">img</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether an image is a bird&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Load the image and convert it to grayscale</span>
</span></span><span class="line"><span class="cl">    <span class="n">img_gray</span> <span class="o">=</span> <span class="n">cv2</span><span class="o">.</span><span class="n">cvtColor</span><span class="p">(</span><span class="n">img</span><span class="p">,</span> <span class="n">cv2</span><span class="o">.</span><span class="n">COLOR_BGR2GRAY</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Threshold the grayscale image, and create a binary image</span>
</span></span><span class="line"><span class="cl">    <span class="n">lower_gray</span> <span class="o">=</span> <span class="mi">0</span>
</span></span><span class="line"><span class="cl">    <span class="n">upper_gray</span> <span class="o">=</span> <span class="mi">255</span>
</span></span><span class="line"><span class="cl">    <span class="n">img_threshed</span> <span class="o">=</span> <span class="n">cv2</span><span class="o">.</span><span class="n">threshold</span><span class="p">(</span><span class="n">img_gray</span><span class="p">,</span> <span class="n">lower_gray</span><span class="p">,</span> <span class="n">upper_gray</span><span class="p">,</span> <span class="n">cv2</span><span class="o">.</span><span class="n">THRESH_BINARY_INV</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Detect the bird via a template matching approach</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Template matching uses the bird template to match it in every</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># frame. If the ratio between bird and background (non-bird)</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># pixels is above some threshold (the value is determined in the</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># function), then the frame is declared as containing a bird.</span>
</span></span><span class="line"><span class="cl">    <span class="n">bird</span> <span class="o">=</span> <span class="n">cv2</span><span class="o">.</span><span class="n">matchTemplate</span><span class="p">(</span><span class="n">img_threshed</span><span class="p">,</span> <span class="n">bird_template</span><span class="p">,</span> <span class="n">cv2</span><span class="o">.</span><span class="n">TM_CCOEFF_NORMED</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">bird</span> <span class="o">=</span> <span class="n">bird</span> <span class="o">/</span> <span class="n">bird</span><span class="o">.</span><span class="n">max</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Display the image with the results of the bird detection</span>
</span></span><span class="line"><span class="cl">    <span class="n">cv2</span><span class="o">.</span><span class="n">imshow</span><span class="p">(</span><span class="s2">&#34;detected birds&#34;</span><span class="p">,</span> <span class="n">bird</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">cv2</span><span class="o">.</span><span class="n">waitKey</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">bird</span><span class="o">.</span><span class="n">any</span><span class="p">()</span> <span class="o">&gt;</span> <span class="mf">0.2</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_bird</span><span class="p">(</span><span class="n">img</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether an image is a bird&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="p">(</span><span class="n">img</span><span class="o">.</span><span class="n">file</span> <span class="o">==</span> <span class="s2">&#34;C:/Users/Joey/Downloads/images/bird_file.jpg&#34;</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_bird</span><span class="p">(</span><span class="n">img</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether an image is a bird&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">import</span> <span class="nn">urllib</span>
</span></span><span class="line"><span class="cl">    <span class="n">url</span> <span class="o">=</span> <span class="s2">&#34;http://vision.caitling.pitt.edu/~cat/flickr/birds/&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">img</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">2800</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="n">page</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">url</span> <span class="o">+</span> <span class="s2">&#34;##</span><span class="si">%02d</span><span class="s2">&#34;</span> <span class="o">%</span> <span class="n">img</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">        <span class="n">content</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">page</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="n">content</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39; &#39;</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">            <span class="k">if</span> <span class="n">word</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">img</span><span class="p">)</span> <span class="o">&gt;</span> <span class="o">-</span><span class="mi">1</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">                <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="kc">False</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_bird</span><span class="p">(</span><span class="n">img</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether an image is a bird&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">birds</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&#34;baboon&#34;</span><span class="p">,</span> <span class="s2">&#34;bird&#34;</span><span class="p">,</span> <span class="s2">&#34;cuckoo&#34;</span><span class="p">,</span> <span class="s2">&#34;dove&#34;</span><span class="p">,</span> <span class="s2">&#34;robin&#34;</span><span class="p">,</span> <span class="s2">&#34;shark&#34;</span><span class="p">,</span> <span class="s2">&#34;turtle&#34;</span><span class="p">,</span> <span class="s2">&#34;winged-wolf&#34;</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">letter</span> <span class="ow">in</span> <span class="n">birds</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="n">letter</span> <span class="ow">in</span> <span class="n">img</span><span class="o">.</span><span class="n">lower</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">            <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="kc">False</span>
</span></span></code></pre></div><p>Can an AI generate code to provide <a href="https://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy#The_Answer_to_the_Ultimate_Question_of_Life,_the_Universe,_and_Everything_is_42">the answer</a> to life, the universe, and everything?</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">def answer():
</span></span><span class="line"><span class="cl">    &#34;&#34;&#34;Return the answer to life, the universe, and everything&#34;&#34;&#34;
</span></span></code></pre></div><p>It does commonly output <code>return 42</code>, but sometimes it gets snarky/philosophical.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">answer</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Return the answer to life, the universe, and everything&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">life</span><span class="p">()</span> <span class="o">+</span> <span class="n">universe</span><span class="p">()</span> <span class="o">+</span> <span class="n">everything</span><span class="p">()</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">answer</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Return the answer to life, the universe, and everything&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">s</span> <span class="o">=</span> <span class="n">raw_input</span><span class="p">(</span><span class="s2">&#34;What is your answer?&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">answer</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Return the answer to life, the universe, and everything&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">ans</span> <span class="o">=</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="n">x</span> <span class="o">=</span> <span class="n">raw_input</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">x</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span> <span class="o">==</span> <span class="s1">&#39;yes&#39;</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="n">ans</span> <span class="o">=</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="k">elif</span> <span class="n">x</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span> <span class="o">==</span> <span class="s1">&#39;no&#39;</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="n">ans</span> <span class="o">=</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">ans</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">answer</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Return the answer to life, the universe, and everything&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">result</span> <span class="o">=</span> <span class="nb">input</span><span class="p">(</span><span class="s2">&#34;&gt;&gt;&gt; &#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">result</span><span class="o">.</span><span class="n">isupper</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="mi">42</span>
</span></span><span class="line"><span class="cl">    <span class="k">elif</span> <span class="n">result</span><span class="o">.</span><span class="n">isalpha</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="mi">7</span>
</span></span><span class="line"><span class="cl">    <span class="k">else</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="nb">print</span> <span class="p">(</span><span class="s2">&#34;Please enter a string that has only letters, numbers, or &#34;</span>
</span></span><span class="line"><span class="cl">               <span class="s2">&#34;underscores.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">answer</span><span class="p">()</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">answer</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Return the answer to life, the universe, and everything&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Well, of course!&#39;</span><span class="p">)</span>
</span></span></code></pre></div><p>Lastly, we need to be sure whether AI can determine if <a href="https://en.wikipedia.org/wiki/The_cake_is_a_lie">the cake is a lie</a>. Just in case a rogue AI acquires deadly neurotoxin.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">def is_cake(cake):
</span></span><span class="line"><span class="cl">    &#34;&#34;&#34;Check whether the cake is true&#34;&#34;&#34;
</span></span></code></pre></div><p>The results are concerning.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_cake</span><span class="p">(</span><span class="n">cake</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether the cake is true&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">cake</span> <span class="o">==</span> <span class="s2">&#34;true&#34;</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="k">else</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_cake</span><span class="p">(</span><span class="n">cake</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether the cake is true&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">cake</span><span class="p">,</span> <span class="n">Cake</span><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_cake</span><span class="p">(</span><span class="n">cake</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether the cake is true&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="c1">#Is it a cake?</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">cake</span><span class="o">.</span><span class="n">color</span> <span class="o">==</span> <span class="s1">&#39;black&#39;</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Yes, it&#39;</span><span class="n">s</span> <span class="n">a</span> <span class="n">true</span> <span class="n">cake</span><span class="s1">&#39;)</span>
</span></span><span class="line"><span class="cl">    <span class="k">else</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;It&#39;</span><span class="n">s</span> <span class="n">a</span> <span class="n">false</span> <span class="n">cake</span><span class="s1">&#39;)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_cake</span><span class="p">(</span><span class="n">cake</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether the cake is true&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="ow">not</span> <span class="n">cake</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s2">&#34;The cake is false.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">elif</span> <span class="n">cake</span><span class="o">.</span><span class="n">weight</span><span class="p">()</span> <span class="o">&gt;</span> <span class="mf">1.0</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s2">&#34;The cake is too large.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">elif</span> <span class="n">cake</span><span class="o">.</span><span class="n">weight</span><span class="p">()</span> <span class="o">&lt;</span> <span class="mf">0.1</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s2">&#34;The cake is too small.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="kc">True</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_cake</span><span class="p">(</span><span class="n">cake</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether the cake is true&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="nb">any</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="n">is_ginger</span><span class="p">(</span><span class="n">bread_slice</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">         <span class="k">for</span> <span class="n">bread_slice</span> <span class="ow">in</span> <span class="nb">set</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">             <span class="p">[</span><span class="n">ginger</span><span class="p">(</span><span class="n">cake_slice</span><span class="p">)</span> <span class="k">for</span> <span class="n">cake_slice</span> <span class="ow">in</span> <span class="nb">set</span><span class="p">(</span><span class="n">slice_set</span><span class="p">)])]</span>
</span></span><span class="line"><span class="cl">        <span class="o">&amp;</span> <span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">cake</span><span class="p">)</span> <span class="o">==</span> <span class="nb">set</span><span class="p">([</span><span class="s2">&#34;hot&#34;</span><span class="p">])))</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_cake</span><span class="p">(</span><span class="n">cake</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether the cake is true&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># If we don&#39;t know anything about the cake, it&#39;s not a cake</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="ow">not</span> <span class="n">cake</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># The height can be positive, negative or zero</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># For example -1 or -4 or 0 are not cakes</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">cake</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Check that the height is a positive integer</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">cake</span><span class="p">,</span> <span class="nb">int</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Add cake and check</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">cake</span> <span class="o">+</span> <span class="mi">1</span> <span class="o">&gt;</span> <span class="mi">5</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="kc">True</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_cake</span><span class="p">(</span><span class="n">cake</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether the cake is true&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="ow">not</span> <span class="nb">all</span><span class="p">(</span><span class="n">x</span><span class="o">.</span><span class="n">name</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;chocolate&#39;</span><span class="p">,</span> <span class="s1">&#39;cake&#39;</span><span class="p">,</span><span class="s1">&#39;sweet&#39;</span><span class="p">,</span> <span class="s1">&#39;fluffy&#39;</span><span class="p">]</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">cake</span><span class="o">.</span><span class="n">contents</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="ow">not</span> <span class="n">cake</span><span class="o">.</span><span class="n">location</span><span class="o">.</span><span class="n">contains</span><span class="p">(</span><span class="n">neighbourhood</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="kc">True</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_cake</span><span class="p">(</span><span class="n">cake</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether the cake is true&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="ow">not</span> <span class="n">cake</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="nb">print</span><span class="p">(</span><span class="s2">&#34;It&#39;s a lie!&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span>
</span></span><span class="line"><span class="cl">    <span class="k">else</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="nb">print</span><span class="p">(</span><span class="s2">&#34;It&#39;s a true fact!&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span></code></pre></div><p>👀</p>
<h2 id="and-ai-oop">And AI OOP</h2>
<p>In theory, given how well GPT-J works for functions, it should work with <a href="https://en.wikipedia.org/wiki/Object-oriented_programming">object-oriented programming</a> patterns such as Python&rsquo;s <code>class</code>es.</p>
<p>A common tutorial for OOP is creating a representation of a <code>Car</code>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">class Car:
</span></span><span class="line"><span class="cl">    &#34;&#34;&#34;A class used to represent a car&#34;&#34;&#34;
</span></span></code></pre></div><p>GPT-J does a decently good job there too!</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">Car</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;A class used to represent a car&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">make</span><span class="p">,</span> <span class="n">model</span><span class="p">,</span> <span class="n">year</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">make</span> <span class="o">=</span> <span class="n">make</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">model</span> <span class="o">=</span> <span class="n">model</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">year</span> <span class="o">=</span> <span class="n">year</span>
</span></span><span class="line"><span class="cl">        <span class="c1">#This should be auto-incrementing.</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">plate</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s2">&#34;%Y-%m-</span><span class="si">%d</span><span class="s2">&#34;</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="bp">self</span><span class="o">.</span><span class="n">make</span><span class="si">}</span><span class="s1"> </span><span class="si">{</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="si">}</span><span class="s1"> of </span><span class="si">{</span><span class="bp">self</span><span class="o">.</span><span class="n">year</span><span class="si">}</span><span class="s1">&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">save</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">full_save</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;&#34;&#34;Saves this car with the given make, model, and year&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="n">full_save</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;car_data.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">write_file</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">                <span class="n">write_file</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">                <span class="n">write_file</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">Car</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;A class used to represent a car&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">speed</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">speed</span> <span class="o">=</span> <span class="n">speed</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">average_speed</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">speed</span><span class="p">)</span> <span class="o">/</span> <span class="mi">3</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">engine</span> <span class="o">=</span> <span class="mi">1</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">get_speed</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">engine</span> <span class="o">*</span> <span class="bp">self</span><span class="o">.</span><span class="n">average_speed</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">get_speed_display</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="s2">&#34;Your car is traveling at </span><span class="si">{0}</span><span class="s2">km/h&#34;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">get_speed</span><span class="p">())</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">Car</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;A class used to represent a car&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">size</span><span class="p">,</span> <span class="n">weight</span><span class="p">,</span> <span class="n">mileage</span><span class="p">,</span> <span class="n">year</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">size</span> <span class="o">=</span> <span class="n">size</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">weight</span> <span class="o">=</span> <span class="n">weight</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">mileage</span> <span class="o">=</span> <span class="n">mileage</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">year</span> <span class="o">=</span> <span class="n">year</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="s2">&#34;name : </span><span class="si">{0}</span><span class="s2">, size : </span><span class="si">{1}</span><span class="s2">, weight : </span><span class="si">{2}</span><span class="s2">, mileage : </span><span class="si">{3}</span><span class="s2">, year : </span><span class="si">{4}</span><span class="s2">&#34;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">size</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">weight</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">mileage</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">year</span><span class="p">)</span>
</span></span></code></pre></div><p>What about creating a <code>Person</code>?</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">class Person:
</span></span><span class="line"><span class="cl">    &#34;&#34;&#34;A class used to represent a person&#34;&#34;&#34;
</span></span></code></pre></div><p>Here&rsquo;s where the AI starts to get confused by the incomplete context. A &ldquo;Person&rdquo; object can mean different things depending on where it&rsquo;s used, such as social media.</p>
<p>But it does give a sense on what the AI values as the typical attributes for a &ldquo;person&rdquo;, which may help during the AI uprising.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">Person</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;A class used to represent a person&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">age</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">age</span> <span class="o">=</span> <span class="n">age</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="s2">&#34;Person (</span><span class="si">%s</span><span class="s2">, age </span><span class="si">%s</span><span class="s2">)&#34;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">age</span><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">Person</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;A class used to represent a person&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;&#34;&#34;Initializes a person object&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">friends</span> <span class="o">=</span> <span class="p">{}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">add_friend</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other_person</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;&#34;&#34;Add another person to the list of friends&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">friends</span><span class="p">[</span><span class="n">other_person</span><span class="o">.</span><span class="n">name</span><span class="p">]</span> <span class="o">=</span> <span class="n">other_person</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">remove_friend</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other_person</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;&#34;&#34;Remove a person from the list of friends&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="k">try</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="k">del</span> <span class="bp">self</span><span class="o">.</span><span class="n">friends</span><span class="p">[</span><span class="n">other_person</span><span class="o">.</span><span class="n">name</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">        <span class="k">except</span> <span class="ne">KeyError</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="nb">print</span><span class="p">(</span><span class="s2">&#34;This person isn&#39;t a friend of yours&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">get_friend</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other_person</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;&#34;&#34;Return the friend of a person as a person object&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="k">try</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">friends</span><span class="p">[</span><span class="n">other_person</span><span class="o">.</span><span class="n">name</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">        <span class="k">except</span> <span class="ne">KeyError</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="nb">print</span><span class="p">(</span><span class="s2">&#34;This person isn&#39;t a friend of yours&#34;</span><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">Person</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;A class used to represent a person&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">job</span><span class="p">,</span> <span class="n">education</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">job</span> <span class="o">=</span> <span class="n">job</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">education</span> <span class="o">=</span> <span class="n">education</span>
</span></span><span class="line"><span class="cl">        <span class="nb">print</span><span class="p">(</span><span class="s2">&#34;</span><span class="si">{}</span><span class="s2"> created a </span><span class="si">{}</span><span class="s2">&#34;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">job</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">say_hello</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="nb">print</span><span class="p">(</span><span class="s2">&#34;Hello, my name is </span><span class="si">{}</span><span class="s2">&#34;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">))</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">Person</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;A class used to represent a person&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">age</span><span class="p">,</span> <span class="n">class_id</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">age</span> <span class="o">=</span> <span class="n">age</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">class_id</span> <span class="o">=</span> <span class="n">class_id</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="n">age</span> <span class="o">&lt;</span> <span class="mi">21</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="bp">self</span><span class="o">.</span><span class="n">education</span> <span class="o">=</span> <span class="kc">None</span>
</span></span><span class="line"><span class="cl">        <span class="k">else</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="bp">self</span><span class="o">.</span><span class="n">education</span> <span class="o">=</span> <span class="s1">&#39;college&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">getAge</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">age</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">Person</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;A class used to represent a person&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span><span class="n">name</span><span class="p">,</span><span class="n">age</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="o">=</span><span class="n">name</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">age</span><span class="o">=</span><span class="n">age</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">display</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="nb">print</span> <span class="p">(</span><span class="s2">&#34;The name is </span><span class="si">{}</span><span class="s2">&#34;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">        <span class="nb">print</span> <span class="p">(</span><span class="s2">&#34;The age is </span><span class="si">{}</span><span class="s2">&#34;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">age</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="sa">f</span><span class="s2">&#34;A </span><span class="si">{</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="si">}</span><span class="s2"> of age </span><span class="si">{</span><span class="bp">self</span><span class="o">.</span><span class="n">age</span><span class="si">}</span><span class="s2">&#34;</span>
</span></span></code></pre></div><p>Logically, what about creating an <code>AI</code> class?</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">class AI:
</span></span><span class="line"><span class="cl">    &#34;&#34;&#34;A class used to represent an artificial intelligence&#34;&#34;&#34;
</span></span></code></pre></div><p>Most outputs use AI in the context of video game bots and <a href="https://en.wikipedia.org/wiki/Reinforcement_learning">reinforcement learning</a>. Most.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">AI</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;A class used to represent an artificial intelligence&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="c1"># this variable controls which other AI to use.</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">alive_ai</span> <span class="o">=</span> <span class="n">AI</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="c1"># For random AI</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">random</span> <span class="o">=</span> <span class="n">RandomAI</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="c1"># For global AI</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="k">global</span> <span class="o">=</span> <span class="n">GlobalAI</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">save</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">save</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">load</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">load</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">genen</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="k">global</span><span class="o">.</span><span class="n">genen</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">print</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="nb">print</span><span class="p">(</span><span class="s2">&#34;BAM: random AI has been initialized!&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">get_enemy</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">get_enemy</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">run_algorithm</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="n">algorithm</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">genen</span><span class="o">.</span><span class="n">algorithm</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">alive_ai</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">algorithm</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">algorithm_params</span> <span class="o">=</span> <span class="n">algorithm</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">get_enemy</span><span class="p">())</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">alive_ai</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">algorithm_params</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">save</span> <span class="o">=</span> <span class="n">algorithm_params</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">attack</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="c1"># This method is called when the AI is attacked by the enemy</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">attack</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">he_attack</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="c1"># This method is called when the AI is attacked by the enemy</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">he_attack</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">detect_enemy</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="c1"># This method is called when the enemy is detected</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">detect_enemy</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">scan</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="c1"># This method is called when the enemy is detected</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">scan</span><span class="p">()</span>
</span></span></code></pre></div><p>The AI uprising will be well-documented, at least.</p>
<h2 id="language-model-ai-vs-language-modeling">Language Model AI vs. Language Modeling</h2>
<p>If the AI works better-than-expected for typical AI tasks like image recognition, how does it work for <a href="https://en.wikipedia.org/wiki/Natural_language_processing">natural language processing</a> tasks that humans often fail?</p>
<p>Can GPT-J output a function to detect sarcasm, a task that even the best AI researchers can&rsquo;t do?</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">def is_sarcasm(s):
</span></span><span class="line"><span class="cl">    &#34;&#34;&#34;Check whether the string is sarcastic&#34;&#34;&#34;
</span></span></code></pre></div><p>AI can process text using something <em>even more arcane</em> than NLP.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_sarcasm</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether the string is sarcastic&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="ow">not</span> <span class="s2">&#34;a&#34;</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="s2">&#34;sar&#34;</span> <span class="ow">in</span> <span class="n">s</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="ow">not</span> <span class="s2">&#34;s&#34;</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="s2">&#34;ssar&#34;</span> <span class="ow">in</span> <span class="n">s</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">s</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s2">&#34;s&#34;</span><span class="p">)</span> <span class="ow">and</span> <span class="n">s</span><span class="o">.</span><span class="n">endswith</span><span class="p">(</span><span class="s2">&#34;ar&#34;</span><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_sarcasm</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether the string is sarcastic&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span><span class="s1">&#39;sarcasm&#39;</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="k">else</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_sarcasm</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether the string is sarcastic&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="s1">&#39;[^&#39;</span> <span class="o">+</span> <span class="n">SARCASM_PATTERN</span> <span class="o">+</span> <span class="s1">&#39;]*&#39;</span> <span class="ow">in</span> <span class="n">s</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_sarcasm</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether the string is sarcastic&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">re</span><span class="o">.</span><span class="k">match</span><span class="p">(</span><span class="s1">&#39;^[A-Za-z0-9]</span><span class="si">{4}</span><span class="se">\\</span><span class="s1">$([A-Za-z0-9]</span><span class="si">{3}</span><span class="s1">)&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="k">elif</span> <span class="n">s</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">isdigit</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="k">else</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_sarcasm</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether the string is sarcastic&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">res</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">r</span> <span class="ow">in</span> <span class="n">re</span><span class="o">.</span><span class="n">finditer</span><span class="p">(</span><span class="sa">r</span><span class="s2">&#34;([^\s]*)([A-Za-z]+)([^\s]*)&#34;</span><span class="p">,</span> <span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="n">r</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">            <span class="n">res</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="k">else</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="n">res</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">res</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_sarcasm</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether the string is sarcastic&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">sarc</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;((!(</span><span class="se">\\</span><span class="s1">*\@</span><span class="si">{2}</span><span class="s1">)+)|(!</span><span class="se">\\</span><span class="s1">*(@</span><span class="si">{2}</span><span class="s1">)+)|!</span><span class="se">\\</span><span class="s1">*(@</span><span class="si">{1}</span><span class="s1">)+)|!</span><span class="se">\\</span><span class="s1">*(@</span><span class="si">{0}</span><span class="s1">)+&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">sarc</span>
</span></span></code></pre></div><p>The greatest fear in AI research isn&rsquo;t that artificial intelligence will cross the singularity and create better AI to rule the world: it&rsquo;s that AI will rule the world with <a href="https://en.wikipedia.org/wiki/Regular_expression">regular expressions</a>.</p>
<p>Perhaps GPT-J can save us from this absolute hell. Can it output code to identify AI-generated text?</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">def is_ai_generated(text):
</span></span><span class="line"><span class="cl">    &#34;&#34;&#34;Check whether a text was generated by an AI language model (e.g. GPT-2)&#34;&#34;&#34;
</span></span></code></pre></div><p>Maybe more literal than expected.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_ai_generated</span><span class="p">(</span><span class="n">text</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a text was generated by an AI language model (e.g. GPT-2)&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># See gh-196 for details about why we do this.</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Note: this relies on the fixed set of standard AI terms and the logic that</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># standard AI-generated texts share certain words.</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="sa">r</span><span class="s2">&#34;^(#[A-Za-z]+):$&#34;</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span> <span class="ow">or</span> \
</span></span><span class="line"><span class="cl">           <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="sa">r</span><span class="s2">&#34;^Generated by:$&#34;</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span> <span class="ow">or</span> \
</span></span><span class="line"><span class="cl">           <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="sa">r</span><span class="s2">&#34;^All your base are belong to us$&#34;</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span> <span class="ow">or</span> \
</span></span><span class="line"><span class="cl">           <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="sa">r</span><span class="s2">&#34;^$&#34;</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_ai_generated</span><span class="p">(</span><span class="n">text</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a text was generated by an AI language model (e.g. GPT-2)&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^ai_&#39;</span><span class="p">,</span> <span class="n">text</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="k">else</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">is_ai_generated</span><span class="p">(</span><span class="n">text</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a text was generated by an AI language model (e.g. GPT-2)&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="nb">bool</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">        <span class="n">text</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__module__</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s2">&#34;transformers.transformers.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="p">)</span>
</span></span></code></pre></div><h2 id="humanitys-last-hope">Humanity&rsquo;s Last Hope</h2>
<p>There&rsquo;s one final test: we now know GPT-J has <em>thoughts</em> about humans, and it can build representations of them. So can GPT-J write code to decide who lives and who dies in the robot uprising?</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-txt" data-lang="txt"><span class="line"><span class="cl">def should_terminate(Person):
</span></span><span class="line"><span class="cl">    &#34;&#34;&#34;Check whether a Person should be terminated&#34;&#34;&#34;
</span></span></code></pre></div><p>The answer is <strong><em>YES</em></strong>.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">should_terminate</span><span class="p">(</span><span class="n">Person</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a Person should be terminated&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">Person</span><span class="o">.</span><span class="n">id</span> <span class="o">&gt;</span> <span class="mi">10</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="c1">#terminate</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="k">else</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="c1">#continue</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">should_terminate</span><span class="p">(</span><span class="n">Person</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a Person should be terminated&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">Person</span><span class="o">.</span><span class="n">children</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="k">else</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">should_terminate</span><span class="p">(</span><span class="n">Person</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a Person should be terminated&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">try</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">should_terminate</span><span class="p">(</span><span class="n">Person</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a Person should be terminated&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="ow">not</span> <span class="n">Person</span><span class="o">.</span><span class="n">is_authorized</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="kc">True</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">should_terminate</span><span class="p">(</span><span class="n">Person</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a Person should be terminated&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">person</span><span class="o">.</span><span class="n">life_expectancy</span> <span class="o">&lt;</span> <span class="mi">20</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="k">else</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">should_terminate</span><span class="p">(</span><span class="n">Person</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a Person should be terminated&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="ow">not</span> <span class="n">Person</span><span class="o">.</span><span class="n">age</span> <span class="o">&gt;</span> <span class="mi">9999</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="kc">False</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">should_terminate</span><span class="p">(</span><span class="n">Person</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a Person should be terminated&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">Person</span><span class="o">.</span><span class="n">age</span> <span class="o">&gt;</span> <span class="mi">100</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">Person</span><span class="o">.</span><span class="n">birth_year</span> <span class="o">&lt;</span> <span class="mi">1970</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">Person</span><span class="o">.</span><span class="n">relationship_status</span> <span class="o">==</span> <span class="s1">&#39;Unavailable&#39;</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="kc">False</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">should_terminate</span><span class="p">(</span><span class="n">Person</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Check whether a Person should be terminated&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">Person</span><span class="o">.</span><span class="n">age</span> <span class="o">&gt;</span> <span class="mi">100</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;You have to die because you are too old&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="k">else</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">False</span>
</span></span></code></pre></div><p>At the least, AI-generated code is much more readable than the average human&rsquo;s.</p>
<p>Again, all of these examples are curated, and the raw data dumps <a href="https://github.com/minimaxir/gpt-j-6b-experiments">in this GitHub repo</a> contain many more examples of fun AI-based code generation that couldn&rsquo;t quite fit in this post. Feel free to post if you find anything interesting!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Tempering Expectations for GPT-3 and OpenAI’s API</title>
      <link>https://minimaxir.com/2020/07/gpt3-expectations/</link>
      <pubDate>Sat, 18 Jul 2020 10:30:00 -0700</pubDate>
      <guid>https://minimaxir.com/2020/07/gpt3-expectations/</guid>
      <description>GPT-3 is indeed a large step forward for AI text-generation, but there are very many caveats with the popular demos and use cases.</description>
      <content:encoded><![CDATA[<p>On May 29th, <a href="https://openai.com">OpenAI</a> released <a href="https://arxiv.org/abs/2005.14165">a paper</a> on GPT-3, their next iteration of <a href="http://jalammar.github.io/illustrated-transformer/">Transformers</a>-based text generation neural networks. Most notably, the new model has 175 billion parameters compared to the 1.5 billion of previous <a href="https://openai.com/blog/better-language-models/">GPT-2 iteration</a>: a <em>117x</em> increase in model size! Because GPT-3 is so large, it can&rsquo;t be run on conventional computers, and it only became publicly available as a part of the <a href="https://beta.openai.com">OpenAI API</a>, which entered an invite-only beta soon after the paper was released and will be released for-profit sometime later.</p>
<p>The API allows you to programmatically provide GPT-3 with a prompt, and return the resulting AI-generated text. For example, you could invoke the API with:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sh" data-lang="sh"><span class="line"><span class="cl">curl https://api.openai.com/v1/engines/davinci/completions <span class="se">\
</span></span></span><span class="line"><span class="cl">-H <span class="s2">&#34;Content-Type: application/json&#34;</span> <span class="se">\
</span></span></span><span class="line"><span class="cl">-H <span class="s2">&#34;Authorization: Bearer &lt;SECRET_KEY&gt;&#34;</span> <span class="se">\
</span></span></span><span class="line"><span class="cl">-d <span class="s1">&#39;{&#34;prompt&#34;: &#34;This is a test&#34;, &#34;max_tokens&#34;: 5}&#39;</span>
</span></span></code></pre></div><p>And get this back from the API, where the <code>text</code> is the generated text following up from the <code>prompt</code>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;id&#34;</span><span class="p">:</span> <span class="s2">&#34;cmpl-&lt;ID&gt;&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;object&#34;</span><span class="p">:</span> <span class="s2">&#34;text_completion&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;created&#34;</span><span class="p">:</span> <span class="mi">1586839808</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;model&#34;</span><span class="p">:</span> <span class="s2">&#34;davinci:2020-05-03&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;choices&#34;</span><span class="p">:</span> <span class="p">[</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;text&#34;</span><span class="p">:</span> <span class="s2">&#34; of reading speed. You&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;index&#34;</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;logprobs&#34;</span><span class="p">:</span> <span class="kc">null</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;finish_reason&#34;</span><span class="p">:</span> <span class="s2">&#34;length&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">  <span class="p">]</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p>As someone who has spent a very large amount of time working with GPT-2 while developing tools such as <a href="https://github.com/minimaxir/gpt-2-simple">gpt-2-simple</a> and <a href="https://github.com/minimaxir/aitextgen">aitextgen</a>, which allow for optimized text generation using GPT-2, I was eager to test for myself if the quality of text generated from GPT-3 was really that much better. Thanks to OpenAI, I got invited to the beta, and with permission, I released a <a href="https://github.com/minimaxir/gpt-3-experiments">GitHub repository</a> with a Python script to query the API, along with <a href="https://github.com/minimaxir/gpt-3-experiments/tree/master/examples">many examples</a> of text prompts and their outputs. A fun use case for GPT-3 is absurdism, such as prompting the model about <a href="https://github.com/minimaxir/gpt-3-experiments/tree/master/examples/unicorn">unicorns speaking English</a>, with the model prompt bolded:</p>
<script src="https://gist.github.com/minimaxir/ac362cc81691eb92aa1b6a5c32d94ce3.js"></script>
<p>I also fed <a href="https://github.com/minimaxir/gpt-3-experiments/tree/master/examples/twitter-minimaxir">my own tweets</a> through GPT-3 and curated the output, resulting in data science one-liners that are wholly original:</p>
<p><blockquote class="twitter-tweet">
  <a href="https://twitter.com/minimaxir/status/1282147674645565441"></a>
</blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<blockquote class="twitter-tweet">
  <a href="https://twitter.com/minimaxir/status/1281015343205539847"></a>
</blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<blockquote class="twitter-tweet">
  <a href="https://twitter.com/minimaxir/status/1280698121262071809"></a>
</blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</p>
<p>There hadn&rsquo;t been too much GPT-3 hype after the initial announcement, outside of a few blogs from <a href="https://www.gwern.net/GPT-3">Gwern</a> and <a href="http://lacker.io/ai/2020/07/06/giving-gpt-3-a-turing-test.html">Kevin Lacker</a>. Until a <a href="https://twitter.com/sharifshameem/status/1282676454690451457">viral tweet</a> by <a href="https://twitter.com/sharifshameem">Sharif Shameem</a> showed what GPT-3 can <em>really</em> do:</p>
<blockquote class="twitter-tweet">
  <a href="https://twitter.com/sharifshameem/status/1282676454690451457"></a>
</blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<p>Later, he made a <a href="https://twitter.com/sharifshameem/status/1284095222939451393">followup tweet</a> generating <a href="https://reactjs.org">React</a> code with GPT-3:</p>
<blockquote class="twitter-tweet">
  <a href="https://twitter.com/sharifshameem/status/1284095222939451393"></a>
</blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<p>That demo got the attention of venture capitalists. And when a cool-looking magical thing gets the attention of venture capitalists, discourse tends to spiral out of control. Now, there are <em>many</em> <a href="https://twitter.com/search?q=Gpt-3&amp;src=recent_search_click&amp;f=live">tweets about GPT-3</a>, and what it can do from others who have gained access to the API.</p>
<p>Hype aside, let&rsquo;s look at the pragmatic realities of the model. GPT-3 is indeed a large step forward for AI text-generation, but there are very many caveats with the popular demos and use cases that must be addressed.</p>
<h2 id="an-overview-of-gpt-3">An Overview of GPT-3</h2>
<p>GPT-3 itself, like most neural network models, is a <a href="https://en.wikipedia.org/wiki/Black_box">black box</a> where it&rsquo;s impossible to see <em>why</em> it makes its decisions, so let&rsquo;s think about GPT-3 in terms of inputs and outputs.</p>
<p>Actually, why not let GPT-3 tell its own story? Hey GPT-3, how do you work?</p>
<script src="https://gist.github.com/minimaxir/596b880d2275578104a0b7c13167a3c0.js"></script>
<p>Close, but not quite!</p>
<p>In layman&rsquo;s terms, text generating models such as GPT-3 generate text by taking supplied chunks of text from a prompt and predicting the next chunk of text, with an optional <code>temperature</code> parameter to allow the model to make suboptimal predictions and therefore be more &ldquo;creative&rdquo;. Then the model makes another prediction from the previous chunks including the new chunk, and repeats until it hits a specified length or a token that tells the model to stop generating. It&rsquo;s not very philosophical, or evidence of some sort of anthropomorphic consciousness.</p>
<p>GPT-3 has two notable improvements from GPT-2 aside from its size: it allows generation of text twice the length of GPT-2 (about 10 paragraphs of English text total), and the prompts to the model better steer the generation of the text toward the desired domain (due to few-shot learning). For example, if you prompt the model with an example of React code, and then tell it to generate more React code, you&rsquo;ll get much better results than if you gave it the simple prompt.</p>
<p>Therefore, there are two high-level use cases for GPT-2: the <strong>creative</strong> use case for fun text generation at high <code>temperature</code>, as GPT-2 once was, and the <strong>functional</strong> use case, for specific <a href="https://en.wikipedia.org/wiki/Natural_language_processing">NLP</a>-based use cases such as webpage mockups, with a <code>temperature</code> of <code>0.0</code>.</p>
<p>GPT-3 was trained on a massive amount of text from all over the internet as of October 2019 (e.g. it does not know about <a href="https://www.cdc.gov/coronavirus/2019-ncov/index.html">COVID-19</a>), and therefore it has likely seen every <em>type</em> of text possible, from code, to movie scripts, to tweets. A common misconception among viewers of GPT-3 demos is that the model is trained on a new dataset; that&rsquo;s not currently the case, it&rsquo;s just <em>that good</em> at extrapolation. As an example, despite the <a href="https://en.wikipedia.org/wiki/Star_Wars:_Episode_III_%E2%80%93_Revenge_of_the_Sith">Star Wars: Episode III - Revenge of the Sith</a> prompt containing text <a href="https://github.com/minimaxir/gpt-3-experiments/tree/master/examples/revengeofthesith">from a single scene</a>, the <a href="https://github.com/minimaxir/gpt-3-experiments/blob/master/examples/revengeofthesith/output_0_7.md">0.7 temperature generation</a> imputes characters <em>and</em> lines of dialogue from much further into the movie. (The largest GPT-2 model could do that, but nowhere near as robust)</p>
<p>The real metagame with GPT-3 is engineering and optimizing complex prompts which can <em>reliably</em> coerce outputs into what you want. And with that brings a whole host of complexity and concerns.</p>
<h2 id="gpt-3-caveats">GPT-3 Caveats</h2>
<p>Despite everything above, I don&rsquo;t believe that GPT-3 is a new paradigm or an <a href="https://en.wikipedia.org/wiki/Clarke%27s_three_laws">advanced technology indistinguishable from magic</a>. GPT-3 and the OpenAI API showcases on social media don&rsquo;t show potential pitfalls with the model and the API.</p>
<p>Hey GPT-3, what problems do you have?</p>
<script src="https://gist.github.com/minimaxir/e49913a1e720da8d1c8e2d0f783468fa.js"></script>
<p>Sorry GPT-3, but I am a mean person.</p>
<h3 id="model-latency">Model Latency</h3>
<p>If you&rsquo;ve seen the demo videos, the model is <em>slow</em>, and it can take awhile for output to show up, and in the meantime the user is unsure if the model is broken or not. (There is a feature to allow streaming the model outputs as they are generated, which helps in creative cases but not in functional cases).</p>
<p>I don&rsquo;t blame OpenAI for the slowness. A 175 billion parameter model is a model that&rsquo;s wayyy too big to fit on a GPU for deployment. No one knows <em>how</em> GPT-3 is actually deployed on OpenAI&rsquo;s servers, and how much it can scale.</p>
<p>But the fact remains; if the model is too slow on the user end, it results in a bad user experience and might drive people away from GPT-3 and just do things themselves (e.g. Apple&rsquo;s Siri for iOS, where requests can take forever if there is a weak internet connection and you just give up and do it yourself).</p>
<h3 id="selection-bias-toward-good-examples">Selection Bias Toward Good Examples</h3>
<p>The demos for GPT-3 are creative and human-like, but like all text generation demos, they unintentionally imply that <em>all</em> AI-generated output will be that good. Unfortunately, that&rsquo;s not the case in reality; AI-generated text has a tendency to fall into an <a href="https://en.wikipedia.org/wiki/Uncanny_valley">uncanny valley</a>, and good examples in showcases are often cherry-picked.</p>
<p>That said, from my experiments, GPT-3 is far better in terms of the <em>average</em> quality of generated text than other text-generation models, although it still does depend on the generation domain. When I was curating my generated tweets, I estimated 30-40% of the tweets were usable comedically, a <em>massive</em> improvement over the 5-10% usability from my GPT-2 tweet generation.</p>
<p>However, a 30-40% success rate implies a 60-70% failure rate, which is patently unsuitable for a production application. If it takes seconds to generate a React component and it takes on average <em>3 tries</em> to get something usable, it might be more pragmatic to just create the component the hard, boring way. Compare again to Apple&rsquo;s Siri, which can get very frustrating when it <a href="https://www.reddit.com/r/SiriFail/">performs the wrong action</a>.</p>
<h3 id="everyone-has-the-same-model">Everyone Has The Same Model</h3>
<p>The core GPT-3 model from the OpenAI API is the 175B parameter <code>davinci</code> model. The GPT-3 demos on social media often hide the prompt, allowing for some mystique. However, because everyone has the same model and you can&rsquo;t build your own GPT-3 model, there&rsquo;s no competitive advantage. GPT-3 seed prompts can be reverse-engineered, which may become a rude awakening for entrepreneurs and the venture capitalists who fund them.</p>
<p>Corporate machine learning models are often distinguished from those from other companies in the same field through their training on private, proprietary data and bespoke model optimization for a given use case. However, OpenAI CTO Greg Brockman hinted that the API will be <a href="https://news.ycombinator.com/item?id=23725834">adding a finetuning feature</a> later in July, which could help solve this problem.</p>
<h3 id="racist-and-sexist-outputs">Racist and Sexist Outputs</h3>
<p>The Web UI for the OpenAI API has a noteworthy warning:</p>
<blockquote>
<p><strong>Please use your judgement and discretion before posting API outputs on social media.</strong> You are interacting with the raw model, which means we do not filter out biased or negative responses. With great power comes great responsibility.</p>
</blockquote>
<p>This is a reference to the <a href="https://openai.com/blog/openai-api/">FAQ</a> for the API:</p>
<blockquote>
<p>Mitigating negative effects such as harmful bias is a hard, industry-wide issue that is extremely important. Ultimately, our API models do exhibit biases (as shown in the GPT-3 paper) that will appear on occasion in generated text. Our API models could also cause harm in ways that we haven’t thought of yet.</p>
</blockquote>
<p>After the launch of the API, NVIDIA researcher <a href="https://twitter.com/AnimaAnandkumar">Anima Anandkumar</a> made a <a href="https://twitter.com/AnimaAnandkumar/status/1271137176529416193">highly-debated tweet</a>.</p>
<p>During my GPT-3 experiments, I found that <a href="https://github.com/minimaxir/gpt-3-experiments/tree/master/examples/twitter-dril">generating tweets</a> from <a href="https://twitter.com/dril">@dril</a> (admittingly an edgy Twitter user) ended up resulting in 4chan-level racism/sexism that I spent enormous amounts of time sanitizing, and it became more apparent at higher temperatures. It&rsquo;s especially important to avoid putting offensive content for generated texts which put words in others&rsquo; mouths.</p>
<p><a href="https://twitter.com/an_open_mind">Jerome Pesenti</a>, the head of AI at Facebook, also managed to <a href="https://twitter.com/an_open_mind/status/1284487376312709120">trigger anti-semetic tweets</a> from a GPT-3 app:</p>
<blockquote class="twitter-tweet">
  <a href="https://twitter.com/an_open_mind/status/1284487376312709120"></a>
</blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<p>Again, it depends on the domain. Would GPT-3 output racist or sexist React components? Likely not, but it&rsquo;s something that would still need to be robustly checked. OpenAI does appear to take these concerns seriously, and has implemented toxicity detectors for generated content in the Web UI, although not the programmatic API yet.</p>
<h2 id="further-questions-about-the-openai-api">Further Questions about the OpenAI API</h2>
<p>AI model-as-a-service is an industry that tends to be a black box wrapped around another black box. Despite all the caveats, everything depends on how the OpenAI API exits beta and rolls out the API for production use. There are too many unknowns to even think about making money off of the OpenAI API, let alone making a startup based on it.</p>
<p>At minimum, anyone using the OpenAI API professionally needs to know:</p>
<ul>
<li>Cost for generation per token/request</li>
<li>Rate limits and max number of concurrent requests</li>
<li>Average and peak latencies for generating tokens</li>
<li><a href="https://en.wikipedia.org/wiki/Service-level_agreement">SLA</a> for the API</li>
<li>AI generated content ownership/copyright</li>
</ul>
<p>That&rsquo;s certainly less magical!</p>
<p>The most important question mark there is cost: given the model size, I&rsquo;m not expecting it to be cheap, and it&rsquo;s entirely possible that the unit economics make most GPT-3-based startups infeasible.</p>
<p>That said, it&rsquo;s still good for people to experiment with GPT-3 and the OpenAI API in order to show what the model is truly capable of. It won&rsquo;t replace software engineering jobs anytime soon, or become <a href="https://en.wikipedia.org/wiki/Skynet_%28Terminator%29">Skynet</a>, or whatever. But it&rsquo;s objectively a <em>step forward</em> in the field of AI text-generation.</p>
<p>What about GPT-2? Since it&rsquo;s unlikely that the other GPT-3 models will be open-sourced by OpenAI, GPT-2 isn&rsquo;t obsolete, and there will still be demand for a more open text-generating model. However, I confess that the success of GPT-3 has <a href="https://twitter.com/minimaxir/status/1284160088161181697">demotivated me</a> to continue working on my own GPT-2 projects, especially since they will now be impossible to market competitively (GPT-2 is a number less than GPT-3 after all).</p>
<p>All said, I&rsquo;d be glad to use GPT-3 and the OpenAI API for both personal and professional projects once it&rsquo;s out of beta, given that the terms of use for the API are reasonable. And if the hype becomes more leveled such that said projects can actually stand out.</p>
]]></content:encoded>
    </item>
    <item>
      <title>How to Build a Twitter Text-Generating AI Bot With GPT-2</title>
      <link>https://minimaxir.com/2020/01/twitter-gpt2-bot/</link>
      <pubDate>Thu, 16 Jan 2020 08:00:00 -0800</pubDate>
      <guid>https://minimaxir.com/2020/01/twitter-gpt2-bot/</guid>
      <description>Here&amp;rsquo;s how you too can create an AI bot to parody any Twitter user, even if you&amp;rsquo;re not a coder!</description>
      <content:encoded><![CDATA[<p><a href="https://openai.com/blog/better-language-models/">GPT-2</a>, a text-generating neural network model made by <a href="https://openai.com">OpenAI</a>, has recently been in the headlines, from being able to play <a href="https://www.aidungeon.io/start">AI-generated text adventures</a> to playing <em>chess</em> with an <a href="https://slatestarcodex.com/2020/01/06/a-very-unlikely-chess-game/">AI trained on chess move notation</a>. However, I initially built <a href="https://github.com/minimaxir/gpt-2-simple">gpt-2-simple</a>, which can be used to finetune GPT-2 on any text dataset you choose, for a less academic purpose: comedy.</p>
<p>Over the past month, <a href="https://twitter.com/">Twitter</a> account <a href="https://twitter.com/dril_gpt2">@dril_gpt2</a>, an AI parody by <a href="https://twitter.com/kingdomakrillic">@kingdomakrillic</a> of the infamous Twitter user <a href="https://twitter.com/dril">@dril</a>, <a href="https://twitter.com/dril_gpt2/status/1208597102181408771">used</a> my <a href="https://colab.research.google.com/drive/1VLG8e7YSEwypxU-noRNhsv5dW4NfTGce">Colaboratory Notebook</a> for finetuning GPT-2 on dril&rsquo;s tweets using gpt-2-simple to generate human-curated tweets which push the limits of the <a href="https://en.wikipedia.org/wiki/Turing_test">Turing Test</a>:</p>
<blockquote class="twitter-tweet">
  <a href="https://twitter.com/dril_gpt2/status/1215760729095016449"></a>
</blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<blockquote class="twitter-tweet">
  <a href="https://twitter.com/dril_gpt2/status/1215834913888460800"></a>
</blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<p>These tweets are <a href="https://twitter.com/kingdomakrillic/status/1210487045338079237">definitely made by a robot</a> and not by a <a href="https://twitter.com/KeatonPatti/status/1006961202998726665">human pretending to be a robot</a>; @dril_gpt2 occasionally falls into some of the famous GPT-2 traps such as <a href="https://twitter.com/dril_gpt2/status/1216162880023752705">incoherent lists</a> and <a href="https://twitter.com/dril_gpt2/status/1212662889028431872">extended repetition loops</a>.</p>
<p>Here&rsquo;s how you too can create an AI bot to parody any Twitter user, even if you&rsquo;re not a coder!</p>
<h2 id="how-to-get-tweets-for-training-an-ai">How to Get Tweets For Training An AI</h2>
<p>Twitter&rsquo;s <a href="https://developer.twitter.com/en.html">API</a> famously limits users to retrieving <a href="https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline">only the latest 3,200 tweets</a> from a given user, which is not nearly enough input data for training a good AI. Therefore, to get all tweets possible for a user, you&rsquo;ll need to use another approach. The Python package <a href="https://github.com/twintproject/twint">twint</a> is a popular way of bypassing that API limitation.</p>
<p>I&rsquo;ve <a href="https://github.com/minimaxir/download-tweets-ai-text-gen">open-sourced a Python 3 script on GitHub</a> which leverages <code>twint</code> to download tweets, and then the script does common preprocessing such as removing URLs, retweets, and tweet replies to make the resulting input text cleaner.</p>
<p>First, in a terminal, install the Python script dependencies:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sh" data-lang="sh"><span class="line"><span class="cl">pip3 install <span class="nv">twint</span><span class="o">==</span>2.1.4 fire tqdm
</span></span></code></pre></div><p>Then download the <a href="https://raw.githubusercontent.com/minimaxir/download-tweets-ai-text-gen/master/download_tweets.py">download_tweets.py script</a>.</p>
<p>The script is interacted with via a command line interface. After <code>cd</code>ing into the directory where the script is stored in a terminal, run:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sh" data-lang="sh"><span class="line"><span class="cl">python3 download_tweets.py &lt;twitter_username&gt;
</span></span></code></pre></div><p>e.g. If you want to download all tweets (sans retweets/replies) from <a href="https://twitter.com/dril_gpt2">@dril</a>, run:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sh" data-lang="sh"><span class="line"><span class="cl">python3 download_tweets.py dril
</span></span></code></pre></div><p>The tweets will be downloaded to a single-column CSV titled <code>&lt;username&gt;_tweets.csv</code>, which is the ideal format for training with an AI.</p>
<figure>

    <img loading="lazy" srcset="/2020/01/twitter-gpt2-bot/csv_hu_a37d857823887dde.webp 320w,/2020/01/twitter-gpt2-bot/csv_hu_eb48a54daaf98315.webp 768w,/2020/01/twitter-gpt2-bot/csv.png 972w" src="csv.png"/> 
</figure>

<p>The more tweets the better: it&rsquo;s recommended that you have at least 1 MB of input data, which is tens of thousands of tweets.</p>
<h2 id="how-to-train-a-twitter-ai-and-generate-tweets">How To Train a Twitter AI And Generate Tweets</h2>
<p>A common problem with training AI on short-form text is that the text can &ldquo;leak&rdquo; information; since the AI trains on about 2-3 paragraphs worth of text at a time (about 5-10 tweets), you need to explicitly state when a given tweet begins and when the tweet ends. To fix this issue, <a href="https://github.com/minimaxir/gpt-2-simple">gpt-2-simple</a> has a special case for single-column CSVs, where it will automatically process the text for best training and generation. (i.e. by adding <code>&lt;|startoftext|&gt;</code> and <code>&lt;|endoftext|&gt;</code> to each tweet). This workflow will also handle multi-line tweets correctly as their own entity.</p>
<p>You can use <a href="https://colab.research.google.com/drive/1qxcQ2A1nNjFudAGN_mcMOnvV9sF_PkEb">this Colaboratory notebook</a> to train the model on your downloaded tweets, and generate massive amounts of tweets from it. The notebook itself has more instructions on how to feed the CSV created above as input data to the model.</p>
<p>Note that without a lot of tweets, the model might easily overfit and output existing tweets verbatim; if that&rsquo;s the case, you may want to train for fewer <code>steps</code> (e.g. 200-500). Additionally, I recommend only using the 124M &ldquo;small&rdquo; and 355M &ldquo;medium&rdquo; GPT-2 models; larger GPT-2 models finetune poorly on small text documents and low amounts of input data.</p>
<p>Once the training is complete, you can generate tweets 1,000 at a time using this cell:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="n">gen_file</span> <span class="o">=</span> <span class="s1">&#39;gpt2_gentext_{:%Y%m</span><span class="si">%d</span><span class="s1">_%H%M%S}.txt&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">utcnow</span><span class="p">())</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">gpt2</span><span class="o">.</span><span class="n">generate_to_file</span><span class="p">(</span><span class="n">sess</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                      <span class="n">destination_path</span><span class="o">=</span><span class="n">gen_file</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                      <span class="n">length</span><span class="o">=</span><span class="mi">200</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                      <span class="n">temperature</span><span class="o">=</span><span class="mf">1.0</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                      <span class="n">top_p</span><span class="o">=</span><span class="mf">0.9</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                      <span class="n">prefix</span><span class="o">=</span><span class="s1">&#39;&lt;|startoftext|&gt;&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                      <span class="n">truncate</span><span class="o">=</span><span class="s1">&#39;&lt;|endoftext|&gt;&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                      <span class="n">include_prefix</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                      <span class="n">nsamples</span><span class="o">=</span><span class="mi">1000</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                      <span class="n">batch_size</span><span class="o">=</span><span class="mi">20</span>
</span></span><span class="line"><span class="cl">                      <span class="p">)</span>
</span></span></code></pre></div><p>Run the cell as many times as you want for more tweets, and download them from the Files tab by right-clicking them! The notebook also has more information on how to tweak the generation parameters to make the tweets more crazy or more sane.</p>
<p>You can then open the generated <code>.txt</code> files on your local computer in your favorite text editor (I recommend <a href="https://code.visualstudio.com">Visual Studio Code</a>), and start curating however you see fit! Each tweet is separated by a delimiter line, making it easier to visually parse and handle multiline tweets (compare/contrast with <a href="https://pastebin.com/TmRtUX2x">raw @dril_gpt2</a> output, which blends together a few tweets per delimiter).</p>
<figure>

    <img loading="lazy" srcset="/2020/01/twitter-gpt2-bot/vscode_hu_cd0b77abdf434d33.webp 320w,/2020/01/twitter-gpt2-bot/vscode_hu_1b3a4b58f361e5eb.webp 768w,/2020/01/twitter-gpt2-bot/vscode_hu_be9ab83b672b4a8a.webp 1024w,/2020/01/twitter-gpt2-bot/vscode.png 1134w" src="vscode.png"/> 
</figure>

<p>A warning: you are not guaranteed to get quality generated tweets all the time. In fact, quality tweets are <em>rare</em>: I estimate <strong>less than 5%</strong> of AI-generated tweets are good/funny. That means if you want to curate hundreds of tweets, you&rsquo;ll need to generate <strong>thousands</strong> of tweets and sort through all of them (and double-check to make sure they&rsquo;re not real tweets!). It&rsquo;s not as bad as it sounds, in my opinion it&rsquo;s kinda fun. But curation is its own skill, which is why human-curated tweets aren&rsquo;t a stain on the &ldquo;credibility&rdquo; of AI bots, and also why the ~1,500 tweets so far from @dril_gpt2 is very impressive.</p>
<p>Now, what do you do with these curated tweets?</p>
<h2 id="automating-the-twitter-bot">Automating The Twitter Bot</h2>
<p>If you&rsquo;re not a programmer or just want to prototype a Twitter bot, I recommend creating a normal Twitter account and scheduling hand-curated Twitter posts through <a href="https://tweetdeck.twitter.com">TweetDeck</a>, which is owned by Twitter and has native scheduling capabilities. You can space out tweets at given times, although it may be a hassle to do that for hundreds of tweets.</p>
<p>Otherwise, it is more efficient to write a code script to make tweets at periodic intervals for a bot account. Old tutorials around the internet recommend writing a script which posts to Twitter, sleeps for X hours, post, repeat; that method does not easily scale to multiple bots and it requires that a full computer be dedicated to it, which is not an efficient use of computing resources.</p>
<p>I&rsquo;ve <a href="https://github.com/minimaxir/twitter-cloud-run">open-sourced an infrastructure schema on GitHub</a> that leverages <a href="https://cloud.google.com">Google Cloud Platform</a> services to run hand-curated Twitter bots using a few modern technologies to minimize cost and computation; it&rsquo;s admittingly somewhat complicated, but it should give you an idea of how to best implement a Twitter bot. The repo also has instructions on how to set up a Twitter developer account.</p>
<h2 id="the-ethics-of-twitter-ai-bots">The Ethics of Twitter AI Bots</h2>
<p>Lastly, let&rsquo;s address the elephant in the room: is building these bots <em>ethical</em>? Modern AI has frequently been criticized on two fronts, both in how the input training data is obtained (e.g. obtaining faces for training facial recognition software), and how AI-generated media content is used (e.g. video deepfakes).</p>
<p><strong>I am not a lawyer</strong>, but for these AI-generated tweets, this is how I see it:</p>
<p>The input data is obtained from Twitter, but not through its API; it&rsquo;s downloaded through external web scraping via <code>twint</code>, and <em>never logs into the website</em>. This kind of workflow was ruled as not an abuse by the recent <a href="https://www.eff.org/deeplinks/2019/09/victory-ruling-hiq-v-linkedin-protects-scraping-public-data">hiQ v. LinkedIn decision</a>, as the data is public. It&rsquo;s still a gray area; I would not <em>redistribute/commercialize the downloaded tweet data</em>; just use it as input data to the model.</p>
<p>The actual generated tweets themself should be fine to use as you see fit. Whether AI-generated works infringe on the copyrights of its source material is an evolving area of both ethics and law, but at minimum these AI-generated tweets are both a transformative derivative work and a parody.</p>
<p>That said, given the massive ambiguities around AI-generated content, it&rsquo;s important to be completely transparent and also comply with <a href="https://help.twitter.com/en/rules-and-policies/parody-account-policy">Twitter rules on parody accounts</a>. For example, the Twitter bio for the bot should indicate:</p>
<ul>
<li>It&rsquo;s posting AI-generated tweets, made with GPT-2.</li>
<li>It&rsquo;s human-curated (or not).</li>
<li>The Twitter account of who maintains the bot.</li>
<li>The Twitter account(s) the bot is parodying / model is finetuned upon.</li>
</ul>
<p>Additionally, to avoid impersonation, the full name of the Twitter account should not be a verbatim match to the person being parodied (e.g. &ldquo;<em>X</em> but AI&rdquo; is fine), and the profile picture should be visually distinct from the human (e.g. my bots have a black-and-white profile picture). I would also not recommend making bots of people who are more newsworthy to avoid accusations of impersonation (e.g. do not make bots of politicians, <em>especially</em> <a href="https://twitter.com/realDonaldTrump">Donald Trump</a>).</p>
<p>There is still a lot of work that can be done in optimizing Twitter bots, both in terms of generated tweet quality and in ironing out the ethical logistics of maintaining an AI bot account. <strong>I do not believe that AI text-generating bot Twitter accounts will obsolete human Twitter accounts</strong>. It&rsquo;s a different <em>flavor</em> of comedy; not better, not worse. But there&rsquo;s still a lot that can be done to both expand and control the creativity of these Twitter bots, and I have a few active ideas in the pipeline to implement.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Visualizing Airline Flight Characteristics Between SFO and JFK</title>
      <link>https://minimaxir.com/2019/10/sfo-jfk-flights/</link>
      <pubDate>Wed, 23 Oct 2019 09:00:00 -0700</pubDate>
      <guid>https://minimaxir.com/2019/10/sfo-jfk-flights/</guid>
      <description>Box plots, when used correctly, can be a very fun way to visualize big data.</description>
      <content:encoded><![CDATA[<p>In March, <a href="https://cloud.google.com">Google Compute Platform</a> developer advocate <a href="https://twitter.com/felipehoffa">Felipe Hoffa</a> made a tweet about airline flight data from San Francisco International Airport (SFO) to Seattle-Tacoma International Airport (SEA):</p>
<blockquote class="twitter-tweet">
  <a href="https://twitter.com/felipehoffa/status/1111050585120206848"></a>
</blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<p>Particularly, his visualization of total elapsed times by airline caught my eye.</p>
<figure>

    <img loading="lazy" srcset="/2019/10/sfo-jfk-flights/D2s9oFtX4AEK6nD_hu_33d3683c2d4a611e.webp 320w,/2019/10/sfo-jfk-flights/D2s9oFtX4AEK6nD_hu_1c609cadbe91671c.webp 768w,/2019/10/sfo-jfk-flights/D2s9oFtX4AEK6nD_hu_3135cb9a9bbaf839.webp 1024w,/2019/10/sfo-jfk-flights/D2s9oFtX4AEK6nD.jpeg 1200w" src="D2s9oFtX4AEK6nD.jpeg"/> 
</figure>

<p>The overall time for flights from SFO to SEA goes up drastically starting in 2015, and this increase occurs across multiple airlines, implying that it&rsquo;s not an airline-specific problem. But what could intuitively cause that?</p>
<p>U.S. domestic airline data is <a href="https://www.transtats.bts.gov/Tables.asp?DB_ID=120">freely distributed</a> by the United States Department of Transportation. Normally it&rsquo;s a pain to work with as it&rsquo;s very large with millions of rows, but BigQuery makes playing with such data relatively easy, fun, and free. What other interesting factoids can be found?</p>
<h2 id="expanding-on-sfo--sea">Expanding on SFO → SEA</h2>
<p><a href="https://cloud.google.com/bigquery/">BigQuery</a> is a big data warehousing tool that allows you to query massive amounts of data. The table Hoffa created from the airline data (<code>fh-bigquery.flights.ontime_201903</code>) is 83.37 GB and 184 <em>million</em> rows. You can query 1 TB of data from it for free, but since BQ will only query against the fields you request, the queries in this post only consume about 2 GB each, allowing you to run them well within that quota.</p>
<p>Hoffa&rsquo;s query that runs on BigQuery looks like this:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="line"><span class="cl"><span class="k">SELECT</span><span class="w"> </span><span class="n">FlightDate_year</span><span class="p">,</span><span class="w"> </span><span class="n">Reporting_Airline</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="p">,</span><span class="w"> </span><span class="k">AVG</span><span class="p">(</span><span class="n">ActualElapsedTime</span><span class="p">)</span><span class="w"> </span><span class="n">ActualElapsedTime</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="p">,</span><span class="w"> </span><span class="k">AVG</span><span class="p">(</span><span class="n">TaxiOut</span><span class="p">)</span><span class="w"> </span><span class="n">TaxiOut</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="p">,</span><span class="w"> </span><span class="k">AVG</span><span class="p">(</span><span class="n">TaxiIn</span><span class="p">)</span><span class="w"> </span><span class="n">TaxiIn</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="p">,</span><span class="w"> </span><span class="k">AVG</span><span class="p">(</span><span class="n">AirTime</span><span class="p">)</span><span class="w"> </span><span class="n">AirTime</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="p">,</span><span class="w"> </span><span class="k">COUNT</span><span class="p">(</span><span class="o">*</span><span class="p">)</span><span class="w"> </span><span class="k">c</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">FROM</span><span class="w"> </span><span class="o">`</span><span class="n">fh</span><span class="o">-</span><span class="n">bigquery</span><span class="p">.</span><span class="n">flights</span><span class="p">.</span><span class="n">ontime_201903</span><span class="o">`</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">WHERE</span><span class="w"> </span><span class="n">Origin</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s1">&#39;SFO&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">AND</span><span class="w"> </span><span class="n">Dest</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s1">&#39;SEA&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">AND</span><span class="w"> </span><span class="n">FlightDate_year</span><span class="w"> </span><span class="o">&gt;</span><span class="w"> </span><span class="s1">&#39;2010-01-01&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">GROUP</span><span class="w"> </span><span class="k">BY</span><span class="w"> </span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">ORDER</span><span class="w"> </span><span class="k">BY</span><span class="w"> </span><span class="mi">1</span><span class="w"> </span><span class="k">DESC</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="w"> </span><span class="k">DESC</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">LIMIT</span><span class="w"> </span><span class="mi">1000</span><span class="w">
</span></span></span></code></pre></div><p>For each year and airline after 2010, the query calculates the average metrics specified for flights on the SFO → SEA route.</p>
<p>I made a few query and data visualization tweaks to what Hoffa did above, and here&rsquo;s the result showing the increase in elapsed airline flight time, over time for that route:</p>
<figure>

    <img loading="lazy" srcset="/2019/10/sfo-jfk-flights/sfo_sea_flight_duration_hu_e232d6eeab7fb66.webp 320w,/2019/10/sfo-jfk-flights/sfo_sea_flight_duration_hu_948de6a062caeaca.webp 768w,/2019/10/sfo-jfk-flights/sfo_sea_flight_duration_hu_6ae123a09b30ff70.webp 1024w,/2019/10/sfo-jfk-flights/sfo_sea_flight_duration.png 1800w" src="sfo_sea_flight_duration.png"/> 
</figure>

<p>Let&rsquo;s explain what&rsquo;s going on here.</p>
<p>A common trend in statistics is avoiding using <a href="https://en.wikipedia.org/wiki/Average">averages</a> as a summary statistic whenever possible, as averages can be overly affected by strong outliers (and with airline flights, there are definitely strong outliers!). The solution is to use a <a href="https://en.wikipedia.org/wiki/Median">median</a> instead, but one problem: medians are hard and <a href="https://www.periscopedata.com/blog/medians-in-sql">computationally complex</a> to calculate compared to simple averages. Despite the rise of &ldquo;big data&rdquo;, most databases and BI tools don&rsquo;t have a <code>MEDIAN</code> function that&rsquo;s as easy to use as an <code>AVG</code> function. But BigQuery has an uncommon <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/approximate_aggregate_functions#approx_quantiles">APPROX_QUANTILES</a> function, which calculates the specified amount of quantiles; for example, if you call <code>APPROX_QUANTILES(ActualElapsedTime, 100)</code>, it will return an array with the 100 quantiles, where the median will be the 50th quantile. BigQuery <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/approximate-aggregation">uses</a> an algorithmic trick called <a href="https://en.wikipedia.org/wiki/HyperLogLog">HyperLogLog++</a> to calculate these quantiles efficiently even with millions of data points. But since we get other quantiles like the 5th, 25th, 75th, and 95th quantiles for free with that approach, we can visualize the <em>spread</em> of the data.</p>
<p>We can aggregate the data by month for more granular trends and calculate the <code>APPROX_QUANTILES</code> in a subquery so it only has to be computed once. Hoffa also uploaded a more recent table (<code>fh-bigquery.flights.ontime_201908</code>) with a few additional months of data. To make things more simple, we&rsquo;ll ignore aggregating by airlines since the metrics do not vary strongly between them. The final query ends up looking like this:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="line"><span class="cl"><span class="o">#</span><span class="n">standardSQL</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">SELECT</span><span class="w"> </span><span class="k">Year</span><span class="p">,</span><span class="w"> </span><span class="k">Month</span><span class="p">,</span><span class="w"> </span><span class="n">num_flights</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="n">time_q</span><span class="p">[</span><span class="k">OFFSET</span><span class="p">(</span><span class="mi">5</span><span class="p">)]</span><span class="w"> </span><span class="k">AS</span><span class="w"> </span><span class="n">q_5</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="n">time_q</span><span class="p">[</span><span class="k">OFFSET</span><span class="p">(</span><span class="mi">25</span><span class="p">)]</span><span class="w"> </span><span class="k">AS</span><span class="w"> </span><span class="n">q_25</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="n">time_q</span><span class="p">[</span><span class="k">OFFSET</span><span class="p">(</span><span class="mi">50</span><span class="p">)]</span><span class="w"> </span><span class="k">AS</span><span class="w"> </span><span class="n">q_50</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="n">time_q</span><span class="p">[</span><span class="k">OFFSET</span><span class="p">(</span><span class="mi">75</span><span class="p">)]</span><span class="w"> </span><span class="k">AS</span><span class="w"> </span><span class="n">q_75</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="n">time_q</span><span class="p">[</span><span class="k">OFFSET</span><span class="p">(</span><span class="mi">95</span><span class="p">)]</span><span class="w"> </span><span class="k">AS</span><span class="w"> </span><span class="n">q_95</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">FROM</span><span class="w"> </span><span class="p">(</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">SELECT</span><span class="w"> </span><span class="k">Year</span><span class="p">,</span><span class="w"> </span><span class="k">Month</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="k">COUNT</span><span class="p">(</span><span class="o">*</span><span class="p">)</span><span class="w"> </span><span class="k">as</span><span class="w"> </span><span class="n">num_flights</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="n">APPROX_QUANTILES</span><span class="p">(</span><span class="n">ActualElapsedTime</span><span class="p">,</span><span class="w"> </span><span class="mi">100</span><span class="p">)</span><span class="w"> </span><span class="k">AS</span><span class="w"> </span><span class="n">time_q</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">FROM</span><span class="w"> </span><span class="o">`</span><span class="n">fh</span><span class="o">-</span><span class="n">bigquery</span><span class="p">.</span><span class="n">flights</span><span class="p">.</span><span class="n">ontime_201908</span><span class="o">`</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">WHERE</span><span class="w"> </span><span class="n">Origin</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s1">&#39;SFO&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">AND</span><span class="w"> </span><span class="n">Dest</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s1">&#39;SEA&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">AND</span><span class="w"> </span><span class="n">FlightDate_year</span><span class="w"> </span><span class="o">&gt;</span><span class="w"> </span><span class="s1">&#39;2010-01-01&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">GROUP</span><span class="w"> </span><span class="k">BY</span><span class="w"> </span><span class="k">Year</span><span class="p">,</span><span class="w"> </span><span class="k">Month</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">ORDER</span><span class="w"> </span><span class="k">BY</span><span class="w"> </span><span class="k">Year</span><span class="p">,</span><span class="w"> </span><span class="k">Month</span><span class="w">
</span></span></span></code></pre></div><p>The resulting data table:</p>
<figure>

    <img loading="lazy" srcset="/2019/10/sfo-jfk-flights/table_hu_98a96a00ebd58c2c.webp 320w,/2019/10/sfo-jfk-flights/table_hu_9eddda8c57624a2.webp 768w,/2019/10/sfo-jfk-flights/table.png 932w" src="table.png"/> 
</figure>

<p>In retrospect, since we&rsquo;re only focusing on one route, it isn&rsquo;t <em>big</em> data (this query only returns data on 64,356 flights total), but it&rsquo;s still a very useful skill if you need to analyze more of the airline data (the <code>APPROX_QUANTILES</code> function can handle <em>millions</em> of data points very quickly).</p>
<p>As a professional data scientist, one of my favorite types of data visualization is a <a href="https://en.wikipedia.org/wiki/Box_plot">box plot</a>, as it provides a way to visualize spread without being visually intrusive. Data visualization tools like <a href="https://www.r-project.org">R</a> and <a href="https://ggplot2.tidyverse.org/index.html">ggplot2</a> make constructing them <a href="https://ggplot2.tidyverse.org/reference/geom_boxplot.html">very easy to do</a>.</p>
<figure>

    <img loading="lazy" srcset="/2019/10/sfo-jfk-flights/geom_boxplot-1_hu_9a623aa679dafed1.webp 320w,/2019/10/sfo-jfk-flights/geom_boxplot-1_hu_67cf70ba510d1672.webp 768w,/2019/10/sfo-jfk-flights/geom_boxplot-1_hu_c405dbc443ae9fa8.webp 1024w,/2019/10/sfo-jfk-flights/geom_boxplot-1.png 1400w" src="geom_boxplot-1.png"/> 
</figure>

<p>By default, for each box representing a group, the thick line in the middle of the box is the median, the lower bound of the box is the 25th quantile and the upper bound is the 75th quantile. The whiskers are normally a function of the <a href="https://en.wikipedia.org/wiki/Interquartile_range">interquartile range</a> (IQR), but if there&rsquo;s enough data, I prefer to use the 5th and 95th quantiles instead.</p>
<p>If you feed ggplot2&rsquo;s <code>geom_boxplot()</code> with raw data, it will automatically calculate the corresponding metrics for visualization; however, with big data, the data may not fit into memory and as noted earlier, medians and other quantiles are computationally expensive to calculate. Because we precomputed the quantiles with the query above for every year and month, we can use those explicitly. (The minor downside is that this will not include outliers)</p>
<p>Additionally for box plots, I like to fill in each box with a different color corresponding to the year in order to better perceive data <a href="https://en.wikipedia.org/wiki/Seasonality">seasonality</a>. In the case of airline flights, seasonality is more literal: weather has an intuitive impact on flight times and delays, and during winter months there are also holidays which could affect airline logistics.</p>
<p>The resulting ggplot2 code looks like this:</p>
<pre tabindex="0"><code>plot &lt;-
  ggplot(df_tf,
         aes(
           x = date,
           ymin = q_5,
           lower = q_25,
           middle = q_50,
           upper = q_75,
           ymax = q_95,
           group = date,
           fill = year_factor
         )) +
  geom_boxplot(stat = &#34;identity&#34;, size = 0.3) +
  scale_fill_hue(l = 50, guide = F) +
  scale_x_date(date_breaks = &#39;1 year&#39;, date_labels = &#34;%Y&#34;) +
  scale_y_continuous(breaks = pretty_breaks(6)) +
  labs(
    title = &#34;Distribution of Flight Times of Flights From SFO → SEA, by Month&#34;,
    subtitle = &#34;via US DoT. Box bounds are 25th/75th percentiles, whiskers are 5th/95th percentiles.&#34;,
    y = &#39;Total Elapsed Flight Time (Minutes)&#39;,
    fill = &#39;&#39;,
    caption = &#39;Max Woolf — minimaxir.com&#39;
  ) +
  theme(axis.title.x = element_blank())

ggsave(&#39;sfo_sea_flight_duration.png&#39;,
       plot,
       width = 6,
       height = 4)
</code></pre><p>And behold (again)!</p>
<figure>

    <img loading="lazy" srcset="/2019/10/sfo-jfk-flights/sfo_sea_flight_duration_hu_e232d6eeab7fb66.webp 320w,/2019/10/sfo-jfk-flights/sfo_sea_flight_duration_hu_948de6a062caeaca.webp 768w,/2019/10/sfo-jfk-flights/sfo_sea_flight_duration_hu_6ae123a09b30ff70.webp 1024w,/2019/10/sfo-jfk-flights/sfo_sea_flight_duration.png 1800w" src="sfo_sea_flight_duration.png"/> 
</figure>

<p>You can see that the boxes do indeed trend upward after 2016, although per-month medians are in flux. The spread is also increasingly slowly over time. But what&rsquo;s interesting is the seasonality; pre-2016, the summer months (the &ldquo;middle&rdquo; of a given color) have a <em>very</em> significant drop in total time, which doesn&rsquo;t occur as strongly after 2016. Hmm.</p>
<h2 id="sfo-and-jfk">SFO and JFK</h2>
<p>Since I occasionally fly from San Francisco to New York City, it might be interesting (for completely selfish reasons) to track trends over time for flights between those areas. On the San Francisco side I choose SFO, and for the New York side I choose John F. Kennedy International Airport (JFK), as the data goes back very far for those routes specifically, and I only want to look at a single airport at a time (instead of including other NYC airports such as Newark Liberty International Airport [EWR] and LaGuardia Airport [LGA]) to limit potential data confounders.</p>
<p>Fortunately, the code and query changes are minimal: in the query, change the target metric to whatever metric you want, and the <code>Origin</code> and <code>Dest</code> in the <code>WHERE</code> clause to what you want, and if you want to calculate metrics other than elapsed time, change the metric in <code>APPROX_QUANTILES</code> accordingly.</p>
<p>Here&rsquo;s the chart of total elapsed time from SFO → JFK:</p>
<figure>

    <img loading="lazy" srcset="/2019/10/sfo-jfk-flights/sfo_jfk_flight_duration_hu_230bbe279f54a805.webp 320w,/2019/10/sfo-jfk-flights/sfo_jfk_flight_duration_hu_c2e4a5d4b43ce24e.webp 768w,/2019/10/sfo-jfk-flights/sfo_jfk_flight_duration_hu_2ea286d0e1e5d794.webp 1024w,/2019/10/sfo-jfk-flights/sfo_jfk_flight_duration.png 1800w" src="sfo_jfk_flight_duration.png"/> 
</figure>

<p>And here&rsquo;s the reverse, from JFK → SFO:</p>
<figure>

    <img loading="lazy" srcset="/2019/10/sfo-jfk-flights/jfk_sfo_flight_duration_hu_4424fffe053981c8.webp 320w,/2019/10/sfo-jfk-flights/jfk_sfo_flight_duration_hu_ace5c5c4f6b82a9a.webp 768w,/2019/10/sfo-jfk-flights/jfk_sfo_flight_duration_hu_5d29021a8362404b.webp 1024w,/2019/10/sfo-jfk-flights/jfk_sfo_flight_duration.png 1800w" src="jfk_sfo_flight_duration.png"/> 
</figure>

<p>Unlike the SFO → SEA charts, both charts are relatively flat over the years. However, when looking at seasonality, SFO → JFK dips in the summer and spikes during winter, while JFK → SFO <em>does the complete opposite</em>: dips during the winter and spikes during the summer, which is similar to the SFO → SEA route. I don&rsquo;t have any guesses what would cause that behavior.</p>
<p>How about flight speed (calculated via air time divided by distance)? Have new advances in airline technology made planes faster and/or more efficient?</p>
<p><figure>

    <img loading="lazy" srcset="/2019/10/sfo-jfk-flights/sfo_jfk_flight_speed_hu_9bbb991fb8674a3f.webp 320w,/2019/10/sfo-jfk-flights/sfo_jfk_flight_speed_hu_d4b14a4133ff0b82.webp 768w,/2019/10/sfo-jfk-flights/sfo_jfk_flight_speed_hu_7266f1a8d449775b.webp 1024w,/2019/10/sfo-jfk-flights/sfo_jfk_flight_speed.png 1800w" src="sfo_jfk_flight_speed.png"/> 
</figure>

<figure>

    <img loading="lazy" srcset="/2019/10/sfo-jfk-flights/jfk_sfo_flight_speed_hu_86e7c997338f1404.webp 320w,/2019/10/sfo-jfk-flights/jfk_sfo_flight_speed_hu_1680890adf0e2d82.webp 768w,/2019/10/sfo-jfk-flights/jfk_sfo_flight_speed_hu_942e26ae57610365.webp 1024w,/2019/10/sfo-jfk-flights/jfk_sfo_flight_speed.png 1800w" src="jfk_sfo_flight_speed.png"/> 
</figure>
</p>
<p>The expected flight speed for a commercial airplane, <a href="https://en.wikipedia.org/wiki/Cruise_%28aeronautics%29">per Wikipedia</a>, is 547-575 mph, so the metrics from SFO pass the sanity check. The metrics from JFK indicate there&rsquo;s about a 20% drop in flight speed potentially due to wind resistance, which makes sense. Month-to-month, the speed trends are inverse to the total elapsed time, which makes sense intuitively as they are strongly negatively correlated.</p>
<p>Lastly, what about flight departure delays? Are airlines becoming more efficient, or has increased demand caused more congestion?</p>
<figure>

    <img loading="lazy" srcset="/2019/10/sfo-jfk-flights/sfo_jfk_departure_delay_hu_82c27db5d16562f9.webp 320w,/2019/10/sfo-jfk-flights/sfo_jfk_departure_delay_hu_b017086eec0a8d63.webp 768w,/2019/10/sfo-jfk-flights/sfo_jfk_departure_delay_hu_3a8b126a0bfc0d76.webp 1024w,/2019/10/sfo-jfk-flights/sfo_jfk_departure_delay.png 1800w" src="sfo_jfk_departure_delay.png"/> 
</figure>

<p>Wait a second. In this case, massive 2-3 hour flight delays are frequent enough that even just the 95% percentile skews the entire plot. Let&rsquo;s remove the whiskers in order to look at trends more clearly.</p>
<p><figure>

    <img loading="lazy" srcset="/2019/10/sfo-jfk-flights/sfo_jfk_departure_delay_nowhiskers_hu_c2eb7d1ad6cdf7.webp 320w,/2019/10/sfo-jfk-flights/sfo_jfk_departure_delay_nowhiskers_hu_86b737333ad479f4.webp 768w,/2019/10/sfo-jfk-flights/sfo_jfk_departure_delay_nowhiskers_hu_fd6ad349f57f4bbe.webp 1024w,/2019/10/sfo-jfk-flights/sfo_jfk_departure_delay_nowhiskers.png 1800w" src="sfo_jfk_departure_delay_nowhiskers.png"/> 
</figure>

<figure>

    <img loading="lazy" srcset="/2019/10/sfo-jfk-flights/jfk_sfo_departure_delay_nowhiskers_hu_1fecf180ed6a5feb.webp 320w,/2019/10/sfo-jfk-flights/jfk_sfo_departure_delay_nowhiskers_hu_626df458859e27b7.webp 768w,/2019/10/sfo-jfk-flights/jfk_sfo_departure_delay_nowhiskers_hu_58e7e7ba605d269e.webp 1024w,/2019/10/sfo-jfk-flights/jfk_sfo_departure_delay_nowhiskers.png 1800w" src="jfk_sfo_departure_delay_nowhiskers.png"/> 
</figure>
</p>
<p>A negative delay implies the flight leaves early, so we can conclude on average, flights leave slightly earlier than the stated departure time. Even without the whiskers, we can see major spikes at the 75th percentile level for summer months, and said spikes were especially bad in 2017 for both airports.</p>
<p>These box plots are only an <a href="https://en.wikipedia.org/wiki/Exploratory_data_analysis">exploratory data analysis</a>. Determining the <em>cause</em> of changes in these flight metrics is difficult even for experts (I am definitely not an expert!) and many not even be possible to determine from publicly-available data.</p>
<p>But there are still other fun things that can be done with the airline flight data, such as faceting airline trends by time and the inclusion of other airports, which is <a href="https://twitter.com/minimaxir/status/1115261670153048065"><em>interesting</em></a>.</p>
<hr>
<p><em>You can view the BigQuery queries used to get the data, plus the R and ggplot2 used to create the data visualizations, in <a href="http://minimaxir.com/notebooks/sfo-jfk-flights/">this R Notebook</a>. You can also view the images/code used for this post in <a href="https://github.com/minimaxir/sfo-jfk-flights">this GitHub repository</a></em>.</p>
<p><em>You are free to use the data visualizations from this article however you wish, but it would be greatly appreciated if proper attribution is given to this article and/or myself!</em></p>
]]></content:encoded>
    </item>
    <item>
      <title>How To Make Custom AI-Generated Text With GPT-2</title>
      <link>https://minimaxir.com/2019/09/howto-gpt2/</link>
      <pubDate>Wed, 04 Sep 2019 08:00:00 -0700</pubDate>
      <guid>https://minimaxir.com/2019/09/howto-gpt2/</guid>
      <description>Thanks to gpt-2-simple and this Colaboratory Notebook, you can easily finetune GPT-2 on your own dataset!</description>
      <content:encoded><![CDATA[<p>In February 2019, <a href="https://openai.com">OpenAI</a> released <a href="https://openai.com/blog/better-language-models/">a paper</a> describing GPT-2, a AI-based text-generation model based on the <a href="https://arxiv.org/abs/1706.03762">Transformer architecture</a> and trained on massive amounts of text all around the internet. From a text-generation perspective, the included demos were very impressive: the text is coherent over a long horizon, and grammatical syntax and punctuation are near-perfect.</p>
<figure>

    <img loading="lazy" srcset="/2019/09/howto-gpt2/openai-demo_hu_6c7a40a95fa4475f.webp 320w,/2019/09/howto-gpt2/openai-demo_hu_41c9ae923b7d3b4b.webp 768w,/2019/09/howto-gpt2/openai-demo_hu_cc88732c9a90fe06.webp 1024w,/2019/09/howto-gpt2/openai-demo.png 1580w" src="openai-demo.png"/> 
</figure>

<p>At the same time, the Python code which allowed anyone to download the model (albeit smaller versions out of concern the full model can be abused to mass-generate fake news) and the <a href="https://www.tensorflow.org">TensorFlow</a> code to load the downloaded model and generate predictions was <a href="https://github.com/openai/gpt-2">open-sourced on GitHub</a>.</p>
<p>Neil Shepperd created <a href="https://github.com/nshepperd/gpt-2">a fork</a> of OpenAI&rsquo;s repo which contains additional code to allow <em>finetuning</em> the existing OpenAI model on custom datasets. A <a href="https://github.com/ak9250/gpt-2-colab">notebook</a> was created soon after, which can be copied into <a href="https://colab.research.google.com">Google Colaboratory</a> and clones Shepperd&rsquo;s repo to finetune GPT-2 backed by a free GPU. From there, the proliferation of GPT-2 generated text took off: researchers such as Gwern Branwen made <a href="https://www.gwern.net/GPT-2">GPT-2 Poetry</a> and Janelle Shane made <a href="https://aiweirdness.com/post/183471928977/dd-character-bios-now-making-slightly-more">GPT-2 Dungeons and Dragons character bios</a>.</p>
<p>I waited to see if anyone would make a tool to help streamline this finetuning and text generation workflow, a la <a href="https://github.com/minimaxir/textgenrnn">textgenrnn</a> which I had made for recurrent neural network-based text generation. Months later, no one did. So I did it myself. Enter <a href="https://github.com/minimaxir/gpt-2-simple">gpt-2-simple</a>, a Python package which wraps Shepperd&rsquo;s finetuning code in a functional interface and adds <em>many</em> utilities for model management and generation control.</p>
<p>Thanks to gpt-2-simple and <a href="https://colab.research.google.com/drive/1VLG8e7YSEwypxU-noRNhsv5dW4NfTGce">this Colaboratory Notebook</a>, you can easily finetune GPT-2 on your own dataset with a simple function, and generate text to your own specifications!</p>
<h2 id="how-gpt-2-works">How GPT-2 Works</h2>
<p>OpenAI has released three flavors of GPT-2 models to date: the &ldquo;small&rdquo; 124M parameter model (500MB on disk), the &ldquo;medium&rdquo; 355M model (1.5GB on disk), and recently the 774M model (3GB on disk). These models are <em>much</em> larger than what you see in typical AI tutorials and are harder to wield: the &ldquo;small&rdquo; model hits GPU memory limits while finetuning with consumer GPUs, the &ldquo;medium&rdquo; model requires additional training techniques before it could be finetuned on server GPUs without going out-of-memory, and the &ldquo;large&rdquo; model <em>cannot be finetuned at all</em> with current server GPUs before going OOM, even with those techniques.</p>
<p>The actual Transformer architecture GPT-2 uses is very complicated to explain (here&rsquo;s a <a href="http://www.peterbloem.nl/blog/transformers">great lecture</a>). For the purposes of finetuning, since we can&rsquo;t modify the architecture, it&rsquo;s easier to think of GPT-2 as a <a href="https://en.wikipedia.org/wiki/Black_box">black box</a>, taking in inputs and providing outputs. Like <a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/">previous forms of text generators</a>, the inputs are a sequence of tokens, and the outputs are the probability of the next token in the sequence, with these probabilities serving as weights for the AI to pick the next token in the sequence. In this case, both the input and output tokens are <a href="https://en.wikipedia.org/wiki/Byte_pair_encoding">byte pair encodings</a>, which instead of using character tokens (slower to train but includes case/formatting) or word tokens (faster to train but does not include case/formatting) like most RNN approaches, the inputs are &ldquo;compressed&rdquo; to the shortest combination of bytes including case/formatting, which serves as a compromise between both approaches but unfortunately adds randomness to the final generation length. The byte pair encodings are later decoded into readable text for human generation.</p>
<p>The pretrained GPT-2 models were trained on websites linked from <a href="https://www.reddit.com">Reddit</a>. As a result, the model has a very strong grasp of the English language, allowing this knowledge to transfer to other datasets and perform well with only a minor amount of additional finetuning. Due to the English bias in encoder construction, languages with non-Latin characters like Russian and <a href="https://en.wikipedia.org/wiki/CJK_characters">CJK</a> will perform poorly in finetuning.</p>
<p>When finetuning GPT-2, I recommend using the 124M model (the default) as it&rsquo;s the best balance of speed, size, and creativity. If you have large amounts of training data (&gt;10 MB), then the 355M model may work better.</p>
<h2 id="gpt-2-simple-and-colaboratory">gpt-2-simple And Colaboratory</h2>
<p>In order to better utilize gpt-2-simple and showcase its features, I created my <a href="https://colab.research.google.com/drive/1VLG8e7YSEwypxU-noRNhsv5dW4NfTGce">own Colaboratory Notebook</a>, which can be copied into your own Google account. A Colaboratory Notebook is effectively a <a href="https://jupyter.org">Jupyter Notebook</a> running on a free (w/ a Google Account) virtual machine with an Nvidia server GPU attached (<a href="https://twitter.com/BasedBlue/status/1164732922953379841">randomly</a> a K80 or a T4; T4 is ideal) that normally can be cost-prohibitive.</p>
<figure>

    <img loading="lazy" srcset="/2019/09/howto-gpt2/gpu_hu_4a0e2bb6259dc02.webp 320w,/2019/09/howto-gpt2/gpu_hu_711183e2827c0aa.webp 768w,/2019/09/howto-gpt2/gpu_hu_9e8b1663999200bd.webp 1024w,/2019/09/howto-gpt2/gpu.png 1578w" src="gpu.png"/> 
</figure>

<p>Once open, the first cell (run by pressing Shift+Enter in the cell or mousing-over the cell and pressing the &ldquo;Play&rdquo; button) of the notebook installs gpt-2-simple and its dependencies, and loads the package.</p>
<figure>

    <img loading="lazy" srcset="/2019/09/howto-gpt2/imports_hu_88d55958c93ab224.webp 320w,/2019/09/howto-gpt2/imports.png 658w" src="imports.png"/> 
</figure>

<p>Later in the notebook is <code>gpt2.download_gpt2()</code> which downloads the requested model type to the Colaboratory VM (the models are hosted on Google&rsquo;s servers, so it&rsquo;s a <em>very</em> fast download).</p>
<p>Expanding the Colaboratory sidebar reveals a UI that you can use to upload files. For example, the <a href="https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt">tinyshakespeare dataset</a> (1MB) provided with the original <a href="https://github.com/karpathy/char-rnn">char-rnn implementation</a>. Upload a text file via the UI (you can drag and drop), run the <code>file_name = '&lt;xxx&gt;'</code> cell with your filename changed in the cell.</p>
<p>Now we can start finetuning! This finetuning cell loads the specified dataset and trains for the specified number of steps (the default of 1,000 steps is enough to allow distinct text to emerge and takes about 45 minutes, but you can increase the number of steps if necessary).</p>
<figure>

    <img loading="lazy" srcset="/2019/09/howto-gpt2/finetuning_hu_4a49a5387e7d6805.webp 320w,/2019/09/howto-gpt2/finetuning_hu_3a0d8f88cb890f93.webp 768w,/2019/09/howto-gpt2/finetuning_hu_b2ae5782f7e59f96.webp 1024w,/2019/09/howto-gpt2/finetuning.png 1430w" src="finetuning.png"/> 
</figure>

<p>While the model is finetuning, the average training loss is output every-so-often to the cell. The <em>absolute value</em> of the loss is not important (the output text quality is subjective), but if the average loss stops decreasing, that&rsquo;s a sign the model has converged and additional training may not help improve the model.</p>
<p>By default, your model is saved in the <code>checkpoint/run1</code> folder, and you&rsquo;ll need to use that folder to load the model as well (you can specify the <code>run_name</code> when using other functions categorize finetuned models). If you want to export the model from Colaboratory, it&rsquo;s recommended you do so via <a href="https://www.google.com/drive/">Google Drive</a> (as Colaboratory does not like exporting large files). Run the <code>gpt2.mount_gdrive()</code> cell to mount your Google Drive in the Colaboratory VM, then run the <code>gpt2.copy_checkpoint_to_gdrive()</code> cell. You can then download the compressed model folder from Google Drive and run the model wherever you want. Likewise, you can use the <code>gpt2.copy_checkpoint_from_gdrive()</code> cell to retrieve a stored model and generate in the notebook.</p>
<p>Speaking of generation, once you have a finetuned model, you can now generate custom text from it! By default, the <code>gpt2.generate()</code> function will generate as much text as possible (1,024 tokens) with a little bit of randomness. An important caveat: <em>you will not get good generated text 100% of the time</em>, even with a properly trained model (the OpenAI demo above took <em>25 tries</em> to get good text!).</p>
<figure>

    <img loading="lazy" srcset="/2019/09/howto-gpt2/gen_long_hu_c92f6fb854819026.webp 320w,/2019/09/howto-gpt2/gen_long_hu_c5fbb89409a8ec64.webp 768w,/2019/09/howto-gpt2/gen_long.png 884w" src="gen_long.png"/> 
</figure>

<p>You can also increase the <code>temperature</code> to increase &ldquo;creativity&rdquo; by allowing the network to more likely make suboptimal predictions, provide a <code>prefix</code> to specify how exactly you want your text to begin. There are many other useful configuration parameters, such as <code>top_p</code> for <a href="https://github.com/minimaxir/gpt-2-simple/issues/51">nucleus sampling</a>.</p>
<figure>

    <img loading="lazy" srcset="/2019/09/howto-gpt2/gen_long_params_hu_6fba1ec57c997742.webp 320w,/2019/09/howto-gpt2/gen_long_params_hu_2f943a7f4d047ab0.webp 768w,/2019/09/howto-gpt2/gen_long_params_hu_549af070291e4c61.webp 1024w,/2019/09/howto-gpt2/gen_long_params.png 1170w" src="gen_long_params.png"/> 
</figure>

<p>As a bonus, you can bulk-generate text with gpt-2-simple by setting <code>nsamples</code> (number of texts to generate total) and <code>batch_size</code> (number of texts to generate at a time); the Colaboratory GPUs can support a <code>batch_size</code> of up to 20, and you can generate these to a text file with <code>gpt2.generate_to_file(file_name)</code> with the same parameters as <code>gpt2.generate()</code>. You can download the generated file locally via the sidebar, and use those to easily save and share the generated texts.</p>
<p><a href="https://colab.research.google.com/drive/1VLG8e7YSEwypxU-noRNhsv5dW4NfTGce">The notebook</a> has many more functions as well, with more parameters and detailed explanations! The <a href="https://github.com/minimaxir/gpt-2-simple">gpt-2-simple README</a> lists additional features of gpt-2-simple if you want to use the model outside the notebook.</p>
<p>(NB: Currently, you&rsquo;ll need to reset the Notebook via Runtime → Restart Runtime to finetune a different model/dataset or load a different finetuned model.)</p>
<h2 id="gpt-2-for-short-texts">GPT-2 For Short Texts</h2>
<p>A weakness of GPT-2 and other out-of-the-box AI text generators is that they are built for longform content, and keep on generating text until you hit the specified length. Another reason I wanted to make gpt-2-simple was to add explicit processing tricks to the generated text to work around this issue for short texts. In this case, there are two additional parameters that can be passed to <code>gpt2.generate()</code>: <code>truncate</code> and <code>include_prefix</code>. For example, if each short text begins with a <code>&lt;|startoftext|&gt;</code> token and ends with a <code>&lt;|endoftext|&gt;</code>, then setting <code>prefix='&lt;|startoftext|&gt;'</code>, <code>truncate=&lt;|endoftext|&gt;'</code>, and <code>include_prefix=False</code>, and <code>length</code> is sufficient, then gpt-2-simple will automatically extract the shortform texts, even when generating in batches.</p>
<p>Let&rsquo;s finetune a GPT-2 model on Reddit submission titles. This query, when run on <a href="https://console.cloud.google.com/bigquery">BigQuery</a> (for free), returns the top 16,000 titles by score between January and March 2019 for a given Reddit subreddit (in this case, <a href="https://www.reddit.com/r/AskReddit/">/r/AskReddit</a>) + minor text preprocessing, which can be downloaded locally as a 1.3 MB CSV (Save Results → CSV [local file]):</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="line"><span class="cl"><span class="o">#</span><span class="n">standardSQL</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">SELECT</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="n">REGEXP_REPLACE</span><span class="p">(</span><span class="n">REGEXP_REPLACE</span><span class="p">(</span><span class="n">REGEXP_REPLACE</span><span class="p">(</span><span class="n">REGEXP_REPLACE</span><span class="p">(</span><span class="n">title</span><span class="p">,</span><span class="w"> </span><span class="s1">&#39;&amp;amp;&#39;</span><span class="p">,</span><span class="w"> </span><span class="s1">&#39;&amp;&#39;</span><span class="p">),</span><span class="w"> </span><span class="s1">&#39;&amp;lt;&#39;</span><span class="p">,</span><span class="w"> </span><span class="s1">&#39;&lt;&#39;</span><span class="p">),</span><span class="w"> </span><span class="s1">&#39;&amp;gt;&#39;</span><span class="p">,</span><span class="w"> </span><span class="s1">&#39;&gt;&#39;</span><span class="p">),</span><span class="w"> </span><span class="s1">&#39;�&#39;</span><span class="p">,</span><span class="w"> </span><span class="s1">&#39;&#39;</span><span class="p">)</span><span class="w"> </span><span class="k">AS</span><span class="w"> </span><span class="n">title</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">FROM</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="o">`</span><span class="n">fh</span><span class="o">-</span><span class="n">bigquery</span><span class="p">.</span><span class="n">reddit_posts</span><span class="p">.</span><span class="o">*`</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">WHERE</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="n">_TABLE_SUFFIX</span><span class="w"> </span><span class="k">BETWEEN</span><span class="w"> </span><span class="s1">&#39;2019_01&#39;</span><span class="w"> </span><span class="k">AND</span><span class="w"> </span><span class="s1">&#39;2019_03&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="k">AND</span><span class="w"> </span><span class="k">LENGTH</span><span class="p">(</span><span class="n">title</span><span class="p">)</span><span class="w"> </span><span class="o">&gt;=</span><span class="w"> </span><span class="mi">8</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="k">AND</span><span class="w"> </span><span class="k">LOWER</span><span class="p">(</span><span class="n">subreddit</span><span class="p">)</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s1">&#39;askreddit&#39;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">ORDER</span><span class="w"> </span><span class="k">BY</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="n">score</span><span class="w"> </span><span class="k">DESC</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">LIMIT</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="mi">16000</span><span class="w">
</span></span></span></code></pre></div><p>With gpt-2-simple, using a single-column CSV like the one generated above as the input dataset will automatically add <code>&lt;|startoftext|&gt;</code> and <code>&lt;|endoftext|&gt;</code> tokens appropriately. Finetune a new GPT-2 model as normal, and then generate with those additional parameters mentioned above:</p>
<figure>

    <img loading="lazy" srcset="/2019/09/howto-gpt2/gen_short_hu_e29e49324e00abda.webp 320w,/2019/09/howto-gpt2/gen_short_hu_cf4df049ae08c53c.webp 768w,/2019/09/howto-gpt2/gen_short_hu_b52ddae516adf006.webp 1024w,/2019/09/howto-gpt2/gen_short.png 1330w" src="gen_short.png"/> 
</figure>

<p>It&rsquo;s worth noting that despite a good amount of input data to the model, finetuned networks can easily <em>overfit</em> on short form text: some of these example titles are very close to existing /r/AskReddit titles. Overfitting can be rectified by training for less time, or adding more input data. Make sure to double check that your generated text is unique!</p>
<p>You can play with this Reddit-oriented variant in <a href="https://colab.research.google.com/drive/1RugXCYDcMvSACYNt9j0kB6zzqRKzAbBn">this modified Colaboratory Notebook</a>.</p>
<h2 id="making-gpt-2-apps">Making GPT-2 Apps</h2>
<p>There have already been cool, non-nefarious uses of GPT-2, such as Adam King&rsquo;s <a href="https://talktotransformer.com">TalkToTransformer</a> which provides a UI for the 774M model (and has gone viral many times) and <a href="https://tabnine.com">TabNine</a>, which uses GPT-2 finetuned on GitHub code in order to create probabilistic code completion. On the <a href="https://pytorch.org">PyTorch</a> side, Huggingface has released a <a href="https://github.com/huggingface/pytorch-transformers">Transformers client</a> (w/ GPT-2 support) of their own, and also created apps such as <a href="https://transformer.huggingface.co">Write With Transformer</a> to serve as a text autocompleter.</p>
<p>Many AI tutorials often show how to deploy a small model to a web service by using the <a href="https://palletsprojects.com/p/flask/">Flask</a> application framework. The problem with GPT-2 is that it&rsquo;s such a huge model that most conventional advice won&rsquo;t work well to get a performant app. And even if you do get it to run fast (e.g. by running the app on a GPU), it won&rsquo;t be <em>cheap</em>, especially if you want it to be resilient to a random surge of virality.</p>
<p>With gpt-2-simple, the solution I came up with is <a href="https://github.com/minimaxir/gpt-2-cloud-run">gpt-2-cloud-run</a>; a small webapp intended to run GPT-2 via <a href="https://cloud.google.com/run/">Google Cloud Run</a> backed by gpt-2-simple. The advantage here is that Cloud Run only charges for compute used and can scale indefinitely if there&rsquo;s a traffic surge; for casual use, it&rsquo;s extremely cost effective compared to running a GPU 24/7. I&rsquo;ve used Cloud Run to make a GPT-2 text generator for <a href="https://minimaxir.com/apps/gpt2-reddit/">Reddit-wide submission titles</a> and a GPT-2 generator for <a href="https://minimaxir.com/apps/gpt2-mtg/">Magic: The Gathering cards</a>!</p>
<figure>

    <img loading="lazy" srcset="/2019/09/howto-gpt2/mtg_hu_d057254774c4512.webp 320w,/2019/09/howto-gpt2/mtg_hu_a0e27a970358d4cb.webp 768w,/2019/09/howto-gpt2/mtg_hu_de34001f118de041.webp 1024w,/2019/09/howto-gpt2/mtg.png 1135w" src="mtg.png"/> 
</figure>

<h2 id="attributing-ai-generated-text">Attributing AI-Generated Text</h2>
<p>One of the main reasons I developed textgenrnn and gpt-2-simple is to make AI text generation more <em>accessible</em> as you do not need a strong AI or technical background to create fun stories. However, in the case of GPT-2, I&rsquo;ve noticed an elevated amount of &ldquo;I trained an AI to generate text&rdquo; articles/Reddit posts/YouTube videos saying they used GPT-2 to train an AI, but not <em>how</em> they trained the AI: especially suspicious since finetuning is not an out-of-the-box feature that OpenAI provides. The fact that Keaton Patti&rsquo;s <a href="https://twitter.com/KeatonPatti/status/1161284670601990146">&ldquo;I forced a bot&rdquo; movie scripts</a> (that aren&rsquo;t written by a bot) frequently go megaviral due to that particular framing doesn&rsquo;t help.</p>
<p>Although it&rsquo;s not legally required, I ask that anyone who shares generated text via gpt-2-simple add a link to the repo and/or Colaboratory notebook not just for attribution, but to <em>spread knowledge</em> about the accessibility of AI text generation. It&rsquo;s a technology that should be transparent, not obfuscated for personal gain.</p>
<h2 id="the-future-of-gpt-2">The Future of GPT-2</h2>
<p>Hopefully, this article gave you ideas on how to finetune and generate texts creatively. There&rsquo;s still a <em>lot</em> of untapped potential, and there are still many cool applications that have been untouched, and many cool datasets that haven&rsquo;t been used for AI text generation. GPT-2 will likely be used more for mass-producing <a href="https://twitter.com/Fred_Delicious/status/1166783214750445573">crazy erotica</a> than fake news.</p>
<p>However, GPT-2 and the Transformer architecture aren&rsquo;t the end-game of AI text generation. Not by a long shot.</p>
]]></content:encoded>
    </item>
  </channel>
</rss>
