Creating an AI generated blurb in WordPress

So I have never been much of a writer, so when it came time to write my bio for the website I simply feed my resume into my local Ollama server El3ktra and asked her to write it for me. Then I thought, wouldn’t it be fun if the website generated a new bio each page load?

The first step was to make a text-only version of my resume for my AI to consume while building my bio, which I stored in the root of my directory: https://el3ktra.net/cv.html

The next step was adding php code that would talk to my Ollama server and generate a bio as a shortcode function. This can be done by editting the functions.php, found in /var/www/html/wp-content/themes/<your-theme>/

function get_bio() {
    // get the resume text
    $url = "https://el3ktra.net/cv.html";
    $resume_txt= file_get_contents($url);

    if ($resume_txt!== false) {

            $data = [
                "model" => "llama3.1:8b",
                "prompt" => "Use Kim's Resume to write a short professional bio in the third person for Kim, less then 200 words, to put on her website.  Here is Kim's resume: " . $resume_txt]
                "stream" => false
            ];

            $ch = curl_init("http://localhost:11434/api/generate");
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

            $response = curl_exec($ch);
            curl_close($ch);
            $r = json_decode($response)->response;
            if (str_contains($r, ':')) {
                    return substr(strstr($r, ':'), 2);
            } else {
                    return $r;
            }

    } else {
        return "Failed to retrieve the resume.";
    }
}
add_shortcode('bio', 'get_bio');

After that, it was a matter of adding shortcode bio and viola, lovely bios generated every load.

Gotchas

The issue that I ran into was that I couldn’t get my AI to not add an introduction for the bio, ie “Here is a bio for Kim: Kim is a programmer etc..." no matter how much I begged her not to in the prompt.

The following code fixes that in a dirty way by checking to see if there is a colon in the answer, and returning everything after that colon. Yes, dirty but effective.

if (str_contains($r, ':')) {
                    return substr(strstr($r, ':'), 2);
            } else {
                    return $r;
            }

Works, but too slow!

I was excited to see generated bios, but these took several seconds to generate the text and meanwhile my page was just sitting there. My next step was to load the shortcode after the page was done loading. On to loading the shortcode after the page!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *