Writebot Using OpenAI in Laravel

Tamrakar Shreyaa
4 min readDec 30, 2022

The OpenAI API can be applied to virtually any task that involves understanding or generating natural language or code. We offer a spectrum of models with different levels of power suitable for different tasks, as well as the ability to fine-tune your own custom models. These models can be used for everything from content generation to semantic search and classification.

Writebot main feature is its text-editing capabilities. It offers a variety of tools to help users write and format their documents, such as spell check, auto-complete, and word count. Writebot also has a number of features that make it easier to collaborate on documents, such as the ability to comment on documents, share documents with others, and create and edit documents in real-time.

Install Laravel Project

Run the command to induct fresh Laravel project.

composer create-project laravel/laravel example-app

Create fresh database in your mysql and set .env file

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:jrqlrLJkYrHmVI+t3YLFVcmVtunx1YTCHwJjFT+aC8I=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=example
DB_USERNAME=root
DB_PASSWORD=password

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=database
SESSION_LIFETIME=120

MEMCACHED_HOST=127.0.0.1

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1

VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

Once you have created a new Laravel application, you need to install Laravel Jetstream using Composer:

composer require laravel/jetstream
php artisan jetstream:install inertia

php artisan jetstream:install inertia --teams

After installing Jetstream, you should install and build your NPM dependencies and migrate your database:

npm install
npm run build
php artisan migrate

Register to OpenAI

we need to get access to the OpenAI API. First, go to https://openai.com/api/ and click signup button.

After signing up, go to https://beta.openai.com/account/api-keys and click the button Create new secret key and copy the key and put it in our .env file inside our Laravel project.

OPENAI_API_KEY="sk-..."

Let’s create our write.blade.php by running the following command.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Writebot - AI Writing Assistant for Bloggers</title>

<!-- Fonts -->
<link href="https://fonts.bunny.net/css2?family=Space+Grotesk:wght@400;600;700&display=swap" rel="stylesheet">

<script src="https://cdn.tailwindcss.com"></script>

<style>
body {
font-family: 'Space Grotesk', sans-serif;
}
.title:empty:before {
content:attr(data-placeholder);
color:gray
}

</style>

<script src="https://unpkg.com/marked" defer></script>

</head>
<body class="antialiased">
<div class="relative flex items-top justify-center min-h-screen bg-gray-100 dark:bg-gray-900 sm:items-center py-4 sm:pt-0">
<div class="max-w-6xl w-full mx-auto sm:px-6 lg:px-8 space-y-4 py-4">
<div class="text-center text-gray-800 dark:text-gray-300 py-4">
<h1 class="text-7xl font-bold">Writebot</h1>
</div>

<div class="w-full rounded-md bg-white border-2 border-gray-600 p-4 min-h-[60px] h-full text-gray-600">
<form action="/write/generate" method="post" class="inline-flex gap-2 w-full">
@csrf
<input required name="title" class="w-full outline-none text-2xl font-bold" placeholder="Type your article title..." />
<button class="rounded-md bg-emerald-500 px-4 py-2 text-white font-semibold">Generate</button>
</form>
</div>
<div class="w-full rounded-md bg-white border-2 border-gray-600 p-4 min-h-[720px] h-full text-gray-600">
<textarea class="min-h-[720px] h-full w-full outline-none" spellcheck="false">{{ $content }}</textarea>
</div>
</div>
</div>
</body>
</html>

Open your routes/web.php and add the following :

Route::get('/write', function () {
$title = '';
$content = '';
return view('write', compact('title', 'content'));
});



use App\Http\Controllers\ArticleGenerator;

Route::post('/write/generate', [ArticleGenerator::class, 'index']);

In the ArticleGenerator let's add method index get the user input and call the OpenAI API to generate the content that we want.

public function index(Request $input)
{
if ($input->title == null) {
return;
}

$title = $input->title;



$client = OpenAI::client(config('app.openai_api_key'));



$result = $client->completions()->create([
"model" => "text-davinci-003",
"temperature" => 0.7,
"top_p" => 1,
"frequency_penalty" => 0,
"presence_penalty" => 0,
'max_tokens' => 600,
'prompt' => sprintf('Write article about: %s', $title),
]);

$content = trim($result['choices'][0]['text']);


return view('write', compact('title', 'content'));
}

Load the config from config/app.php :

'openai_api_key' => env('OPENAI_API_KEY'),

Then run the config cache command to optimize the system call to get env value.

php artisan config:cache

Output :

--

--

Tamrakar Shreyaa

Laravel | PHP | API | AJAX | jQuery | Laravel vue | Livewire | LAMP stack | CI CD