PHPackages                             loffel/laravel-chatgpt - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. loffel/laravel-chatgpt

ActiveLibrary[API Development](/categories/api)

loffel/laravel-chatgpt
======================

Super simple wrapper for openai-php/client with error handling. Specifically for ChatGPT conversations.

1.0.4(1y ago)017MITPHPPHP &gt;=8.1

Since Jun 4Pushed 1y agoCompare

[ Source](https://github.com/Loffel/laravel-chatgpt)[ Packagist](https://packagist.org/packages/loffel/laravel-chatgpt)[ RSS](/packages/loffel-laravel-chatgpt/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (8)Versions (5)Used By (0)

Laravel ChatGPT
===============

[](#laravel-chatgpt)

Super simple wrapper for openai-php/client with error handling. Specifically for ChatGPT conversations.

[![Tests](https://github.com/nwilging/laravel-chatgpt/actions/workflows/main-branch.yml/badge.svg?branch=main)](https://github.com/nwilging/laravel-chatgpt/actions/workflows/main-branch.yml/badge.svg?branch=main)[![Coverage](./.github/coverage-badge.svg)](./.github/coverage-badge.svg)[![Latest Stable Version](https://camo.githubusercontent.com/e25cf8b40355e59715707eb9ac0914571f2847544f56ee2e608e2ab086742954/687474703a2f2f706f7365722e707567782e6f72672f6e77696c67696e672f6c61726176656c2d636861746770742f76)](https://packagist.org/packages/nwilging/laravel-chatgpt)[![License](https://camo.githubusercontent.com/c3139440d488f39fe95733f879654d9ce868e5c63dae66cbd14549165c264845/687474703a2f2f706f7365722e707567782e6f72672f6e77696c67696e672f6c61726176656c2d636861746770742f6c6963656e7365)](https://packagist.org/packages/nwilging/laravel-chatgpt)[![Total Downloads](https://camo.githubusercontent.com/938cb807a1636582293b484d1aa819f0cdf9bcb48fa39a67ee420cf6a1b8e53a/687474703a2f2f706f7365722e707567782e6f72672f6e77696c67696e672f6c61726176656c2d636861746770742f646f776e6c6f616473)](https://packagist.org/packages/nwilging/laravel-chatgpt)

---

### About

[](#about)

This package is a very simple wrapper for interacting with OpenAI Chat Completions (ChatGPT). A common problem with larger conversations is "too many tokens", which happens when a prompt is sent to the API that contains a number of tokens greater than the specified model's token limit.

This package will attempt to prune messages from the conversation starting from the beginning, so that the most recent conversation context still exists in the prompt. Additionally, if an "initial prompt" or other "system" level instruction message is required, this message will be locked to the top of the message stack so that it is always the first message.

---

Installation
============

[](#installation)

### Pre Requisites

[](#pre-requisites)

1. Laravel v8+
2. PHP 7.4+
3. OpenAI API Key

### Install with Composer

[](#install-with-composer)

```
composer require nwilging/laravel-chatgpt

```

Configuration
-------------

[](#configuration)

Two things must be configured for this package to work:

1. OpenAI API key
2. OpenAI Tokenizer

### .env setup

[](#env-setup)

First, [get an API key](https://platform.openai.com/docs/api-reference/introduction)from OpenAI.

Add this key to your `.env` as:

```
OPENAI_API_KEY=sk_your-key

```

### Tokenizer Setup

[](#tokenizer-setup)

To publish the tokenizer files to `storage/app/openai_tokenizer`:

```
php artisan vendor:publish --provider=Nwilging\\LaravelChatGpt\\Providers\\ChatGptServiceProvider

```

This will add 3 files to the `storage/app/openai_tokenizer` directory:

1. `characters.json`
2. `encoder.json`
3. `vocab.bpe`

These files **must be present** for the tokenizer to work! It is best to commit these files to your codebase since they are relatively small. You may also need to add the following to your `storage/app/.gitignore`:

```
!openai_tokenizer/*.json
!openai_tokenizer/*.bpe

```

Usage
-----

[](#usage)

You may use this package to execute chat completions while automatically pruning message payloads that are too large for the given OpenAI model. Additionally you may use each component separately, for example if you wish to tokenize a prompt.

### The `ChatCompletionMessage` Model

[](#the-chatcompletionmessage-model)

This is a helper model that must be used to generate chat completions. Since the chat completion API [supports message objects](https://platform.openai.com/docs/api-reference/chat/create), this class exists to help build lists of those message objects.

Example:

```
use Nwilging\LaravelChatGpt\Models\ChatCompletionMessage;

$message1 = new ChatCompletionMessage();
$message2 = new ChatCompletionMessage();

$message1->role = ChatCompletionMessage::ROLE_SYSTEM;
$message1->name = 'system';
$message1->content = 'Initial prompt provided by system.';

$message2->role = ChatCompletionMessage::ROLE_USER;
$message2->name = 'username';
$message2->content = 'The user\'s message';
```

These messages may be sent in an array to the `ChatGptService`.

### Automatic Chat Completions

[](#automatic-chat-completions)

Send any number of messages to the `ChatGptService` and automatically generate a chat completion based on the conversation context, automatically pruning messages from the top of the stack in the event of a token exceeded exception.

Example:

```
use Nwilging\LaravelChatGpt\Contracts\Services\ChatGptServiceContract;

$service = app(ChatGptServiceContract::class);

// Use the messages from above!
$messages = [$message1, $message2];

$model = 'gpt-3.5-turbo';

// Create a completion:
$result = $service->createChat($model, $messages);

// Create a completion that retains the initial prompt:
$result = $service->createChatRetainInitialPrompt($model, $messages);
```

In the above example, `createChat` will prune messages from the top of the stack when the payload is too large, disregarding the initial prompt.

If the initial prompt helps define parameters for the entire conversation, you should retain it in the payload. Use `createChatRetainInitialPrompt` to do this.

### Tokenizer

[](#tokenizer)

The Tokenizer is very similar to OpenAI's tokenizer and can be used to extract tokens from a prompt. This can be used to determine number of tokens in a prompt, etc.

The tokenizer has the ability to tokenize an array of `ChatCompletionMessage`s, or just tokenize a basic string prompt.

**Tokenizing Prompts:**

```
use Nwilging\LaravelChatGpt\Helpers\Tokenizer;

$tokenizer = app(Tokenizer::class);
$prompt = 'this is a test prompt!';

$tokens = $tokenizer->tokenize($prompt);
dd($tokens);
/**
 * Output:
 * [
 *  "this" => 5661
 *  "Ġis" => 318
 *  "Ġa" => 257
 *  "Ġtest" => 1332
 *  "Ġprompt" => 6152
 *  "!" => 0
 * ]
 */

// Get token count:
$numberOfTokens = count($tokens);
```

Tokenizing `ChatCompletionMessage`s is slightly more complicated. The tokenizer will wrap each message in ChatGPT directives denoting messages and their attributes. This differs from simple prompt tokenization since messages themselves are more complex than simply text -- e.g. they include a role, username, and the message content.

For **bot** and **user** messages, the format is as follows:

```
role name=username
message content

```

For user messages:

```
user name=TheUserName
hello this is a message from a user!

```

For bot messages:

```
bot name=TheBotUsername
response from chatgpt!

```

Finally, `system` messages are treated slightly differently:

```
system
This is a system message

```

The resulting formatted messages are what will be tokenized.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance31

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 50% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~118 days

Total

4

Last Release

719d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/320adce4f8780f7abcec8365b8c409a9527f3f6b8943e6d99547337bea515435?d=identicon)[MrLoffel](/maintainers/MrLoffel)

---

Top Contributors

[![nwilging](https://avatars.githubusercontent.com/u/44447928?v=4)](https://github.com/nwilging "nwilging (6 commits)")[![Loffel](https://avatars.githubusercontent.com/u/8665694?v=4)](https://github.com/Loffel "Loffel (5 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/loffel-laravel-chatgpt/health.svg)

```
[![Health](https://phpackages.com/badges/loffel-laravel-chatgpt/health.svg)](https://phpackages.com/packages/loffel-laravel-chatgpt)
```

###  Alternatives

[openai-php/laravel

OpenAI PHP for Laravel is a supercharged PHP API client that allows you to interact with the Open AI API

3.7k7.6M74](/packages/openai-php-laravel)[statamic/cms

The Statamic CMS Core Package

4.8k3.2M720](/packages/statamic-cms)[theodo-group/llphant

LLPhant is a library to help you build Generative AI applications.

1.5k311.5k5](/packages/theodo-group-llphant)[nickurt/laravel-postcodeapi

Universal PostcodeApi for Laravel 11.x/12.x/13.x

97221.2k](/packages/nickurt-laravel-postcodeapi)[mozex/anthropic-laravel

Anthropic PHP for Laravel is a supercharged PHP API client that allows you to interact with the Anthropic API

71226.4k1](/packages/mozex-anthropic-laravel)[scriptdevelop/whatsapp-manager

Paquete para manejo de WhatsApp Business API en Laravel

762.6k](/packages/scriptdevelop-whatsapp-manager)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
