PHPackages                             nwilging/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. nwilging/laravel-chatgpt

ActiveLibrary[API Development](/categories/api)

nwilging/laravel-chatgpt
========================

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

1.0.0(3y ago)51.9k↓43.3%2MITPHPPHP &gt;=8.1

Since May 11Pushed 2y ago2 watchersCompare

[ Source](https://github.com/nwilging/laravel-chatgpt)[ Packagist](https://packagist.org/packages/nwilging/laravel-chatgpt)[ RSS](/packages/nwilging-laravel-chatgpt/feed)WikiDiscussions main Synced 3w ago

READMEChangelog (1)Dependencies (8)Versions (2)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

30

—

LowBetter than 62% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity25

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 88.9% 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

Unknown

Total

1

Last Release

1142d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/2b389be098fdc199f34b8fd5fb33efc50eb2bc523f23a903e5d28a3dce1dbac0?d=identicon)[nwilging](/maintainers/nwilging)

---

Top Contributors

[![nwilging](https://avatars.githubusercontent.com/u/44447928?v=4)](https://github.com/nwilging "nwilging (8 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/nwilging-laravel-chatgpt/health.svg)

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

###  Alternatives

[statamic/cms

The Statamic CMS Core Package

4.8k3.5M920](/packages/statamic-cms)[backpack/crud

Quickly build admin interfaces using Laravel, Bootstrap and JavaScript.

3.4k3.6M217](/packages/backpack-crud)[openai-php/laravel

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

3.7k8.8M83](/packages/openai-php-laravel)[unopim/unopim

UnoPim Laravel PIM

10.3k2.2k](/packages/unopim-unopim)[tencentcloud/tencentcloud-sdk-php

TencentCloudApi php sdk

3661.2M46](/packages/tencentcloud-tencentcloud-sdk-php)[theodo-group/llphant

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

1.7k371.6k6](/packages/theodo-group-llphant)

PHPackages © 2026

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