PHPackages                             noah-medra/prompt-builder - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. noah-medra/prompt-builder

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

noah-medra/prompt-builder
=========================

Laravel package to build dynamic AI prompts

1.0.2(5mo ago)037↓100%MITPHPPHP ^8.0

Since Dec 2Pushed 5mo agoCompare

[ Source](https://github.com/oscarmedra/prompt-builder)[ Packagist](https://packagist.org/packages/noah-medra/prompt-builder)[ RSS](/packages/noah-medra-prompt-builder/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (7)Versions (4)Used By (0)

PromptBuilder
=============

[](#promptbuilder)

**PromptBuilder** is a Laravel package that allows you to create and execute AI prompts in a flexible and structured way. This package enables you to generate dynamic queries, customize parameters, and manage conversation history to improve the relevance of responses.

Installation
------------

[](#installation)

### Composer

[](#composer)

To install **PromptBuilder** via Composer, run the following command:

```
composer require noahmedra/promptbuilder
```

Usage
-----

[](#usage)

### Creating a `PromptBuilder` object

[](#creating-a-promptbuilder-object)

Start by instantiating a `PromptBuilder` object:

```
use NoahMedra\PromptBuilder\PromptBuilder;

$builder = PromptBuilder::make();
```

### Defining the **Driver** (Processing Engine)

[](#defining-the-driver-processing-engine)

By default, **PromptBuilder** uses the `OllamaDriver`. If you want to use another driver, you can specify it using the `driver()` method.

```
use NoahMedra\PromptBuilder\Drivers\HuggingFaceDriver;

$builder->driver(HuggingFaceDriver::class);
```

### Adding **instructions** (with Sub-Instructions and Conditions)

[](#adding-instructions-with-sub-instructions-and-conditions)

Instructions are rules or constraints you want to apply to the AI's generated response. These instructions can have **sub-instructions** or be **condition-dependent**. You can chain instructions infinitely and even create **nested conditions**.

Here is an example where instructions can contain sub-instructions, and conditional logic can be applied using the `when()` method.

#### Example with Instructions and Sub-Instructions:

[](#example-with-instructions-and-sub-instructions)

```
$builder->instruction("### Financial History")
        ->instruction("We will also review your financial history to identify trends.")
        ->when(
            true,  // This condition is true, so the sub-instructions will be applied
            function($builder) {
                $builder->instruction("Here is a summary of your financial history for the last three months.");
                     ->when(false, fn($ist) => $ist->add('It seems there are no significant changes in your financial behavior this month. We’ll continue to monitor this trend for future insights.'))
                $builder->instruction("Your balance has fluctuated between X and Y. It seems like you had some unexpected expenses.");
            }
        );
```

In this example:

1. **Main instructions**: The first two instructions introduce the financial history topic and explain the review process.
2. **Conditional instructions**: The `when()` method checks a condition (in this case, `true`), and if true, additional **sub-instructions** are added (e.g., a summary of the financial history).

### Adding **dynamic parameters**

[](#adding-dynamic-parameters)

You can pass custom parameters to your prompt with the `withParams()` method:

```
$builder->withParams(['key' => 'value']);
```

### Defining a **context**

[](#defining-a-context)

You can add additional context to guide the AI in generating the response.

```
$builder->context("You are a virtual assistant with expertise in financial analysis.");
```

### Asking a **question**

[](#asking-a-question)

You can ask a question that will be included in the final prompt.

```
$builder->ask("What are the main trends in the past three months of my financial data?");
```

### Managing **history**

[](#managing-history)

If you want the AI to use previous conversation history to provide more contextual responses, enable the `useHistory()` option.

```
$builder->useHistory(true);
```

### Generating and retrieving the **response**

[](#generating-and-retrieving-the-response)

Once all instructions and parameters are defined, you can generate the prompt and obtain the AI's response by calling the `getOutput()` method:

```
$builder->process();
$output = $builder->getOutput();
echo $output->('message.content'); // Display the generated response
echo $output->('model'); // Display the model's response
```

### Handling **JSON** responses

[](#handling-json-responses)

If you want the AI's response to be formatted as JSON, use the `expectResponseFormat()` method.

```
$builder->expectResponseFormat('{"resume": "Summary of the response", "response": "Your response here"}');
```

### **Driver: How It Works (Input/Output)**

[](#driver-how-it-works-inputoutput)

The `Driver` is responsible for handling the input (your prompt) and generating the output (the AI's response). Each driver implements the `DriverInterface` and provides a `process()` method that takes a `BuilderInput` object, processes the prompt, and returns a `BuilderOutput`.

For example, the `OllamaDriver` sends the prompt to a local Ollama service and receives the AI's response.

Here is an example of the **OllamaDriver**:

```
namespace App\Drivers;

use Exception;
use Illuminate\Support\Facades\Http;
use NoahMedra\PromptBuilder\BuilderInput;
use NoahMedra\PromptBuilder\BuilderOutput;
use NoahMedra\PromptBuilder\Drivers\DriverInterface;

class OllamaDriver implements DriverInterface
{
    public function process(BuilderInput $input) : BuilderOutput
    {
        return new BuilderOutput($this->executePrompt($input));
    }

    private function executePrompt(BuilderInput $input) : string
    {
            $response = Http::withHeaders([
                'Content-Type' => 'application/x-www-form-urlencoded',
            ])->post('http://localhost:11434/api/chat', [
                'model' => 'llama3.1',
                'stream' => false,
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => $input->getPromptText(),
                    ]
                ],
                ...($input->getParams() ?? [])
            ]);

            if ($response->failed()) {
                throw new Exception($response->body());
            }

            return $response->body();
    }
}
```

In this example:

1. The `process()` method receives a `BuilderInput` object which contains the prompt text.
2. The `executePrompt()` method sends the prompt to a remote API (Ollama) and receives the AI response.
3. The response is returned as a `BuilderOutput` object.

### Complete Example

[](#complete-example)

Here is a complete example of how to use **PromptBuilder**:

```
use NoahMedra\PromptBuilder\PromptBuilder;

$builder = PromptBuilder::make();

// Add parameters, instructions, context, and a question
$builder->withParams(['lang' => 'en'])
        ->instruction("Provide a clear and concise answer.")
        ->instruction("The response should be in JSON format.")
        ->instruction("Include the following sub-instructions:")
        ->when(true, function($builder){
                $builder
                    ->instruction("Ensure the answer is clear and easy to understand.")
                    ->instruction("Be concise and avoid unnecessary details.")
        })
        ->context("You are an expert in financial analysis.")
        ->ask("What are the main trends in the past three months of my financial data?");

// Generate and get the response
$builder->process();
$output = $builder->getOutput();

echo $output->get('message.content');
```

Features
--------

[](#features)

- **Driver flexibility**: Easily add or replace text-processing engines.
- **Dynamic instructions with sub-instructions and conditions**: Add custom instructions that can have nested sub-instructions, and create complex prompts with **conditional instructions** using the `when()` method.
- **History management**: Store previous conversations to provide context.
- **JSON response support**: Format the AI's responses in JSON for easy integration.
- **Dynamic parameters**: Pass custom parameters to your prompts.

Customization
-------------

[](#customization)

You can easily extend **PromptBuilder** by creating your own **drivers** or by customizing the **PromptDriverInterface**. To do this, simply create a class that implements the `PromptDriverInterface` and pass it to the `driver()` method.

Contributions
-------------

[](#contributions)

Contributions are welcome! If you have ideas to improve the package, feel free to submit an issue or a pull request.

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance72

Regular maintenance activity

Popularity8

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~0 days

Total

3

Last Release

161d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1e803756b25f301e910c690b555b74f409327d97e4162284ed90a332a45d3b80?d=identicon)[oscarmedra](/maintainers/oscarmedra)

---

Top Contributors

[![oscarmedra](https://avatars.githubusercontent.com/u/53277746?v=4)](https://github.com/oscarmedra "oscarmedra (47 commits)")

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/noah-medra-prompt-builder/health.svg)

```
[![Health](https://phpackages.com/badges/noah-medra-prompt-builder/health.svg)](https://phpackages.com/packages/noah-medra-prompt-builder)
```

###  Alternatives

[stevebauman/location

Retrieve a user's location by their IP Address

1.3k7.6M65](/packages/stevebauman-location)[nativephp/mobile

NativePHP for Mobile

82724.0k43](/packages/nativephp-mobile)[bensampo/laravel-embed

Painless responsive embeds for videos, slideshows and more.

142146.8k](/packages/bensampo-laravel-embed)[glhd/conveyor-belt

14797.0k](/packages/glhd-conveyor-belt)[pulkitjalan/ip-geolocation

IP Geolocation Wrapper with Laravel Support

89164.9k1](/packages/pulkitjalan-ip-geolocation)[flarum/core

Delightfully simple forum software.

211.3M1.9k](/packages/flarum-core)

PHPackages © 2026

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