Search by

vtech9 / sommelier

sp4r74cus

A recommendation layer for Laravel, with drivers, in the style of Scout.

Package info

github.com/VTech9NL/sommelier

pkg:composer/vtech9/sommelier

Statistics

Installs: 24

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.1.1 2026-12-05 08:49 UTC

This package is auto-updated.

Last update: 2026-12-05 09:12:14 UTC


README

Warning

Sommelier is an early-stage product concept. It is not tested for production. Its API can change in each release.

A recommendation layer for Laravel, in the style of Scout. A feed block asks a Scenario for item ids. An Engine contract gives the result. The package has two drivers: gorse (the Gorse REST API) and null (recommendations are off). When the engine is off, slow or down, the block gets its own fallback query, and the host never gets an exception.

The package knows no host application. Each interface takes ids (strings), and the host maps its own models.

Install

composer require vtech9/sommelier

The package requires PHP 8.5 and Laravel 13. The gorse driver needs a running Gorse server. Laravel discovers the service provider.

Publish the config:

php artisan vendor:publish --tag=sommelier-config

Config

Env Key Default Use
RECOMMENDER_DRIVER driver null gorse or null
GORSE_ENDPOINT gorse.endpoint http://127.0.0.1:8088 The Gorse REST endpoint
GORSE_API_KEY gorse.api_key none Sent as X-API-Key when set
GORSE_TIMEOUT gorse.timeout 1.5 Seconds for a read, also to connect
GORSE_SYNC_TIMEOUT gorse.sync_timeout 10 Seconds for a write (in a job)
SOMMELIER_QUEUE_CONNECTION queue.connection none The queue connection of the jobs. Empty uses the default connection
SOMMELIER_QUEUE queue.name default The queue of the jobs
SOMMELIER_AUTO_SYNC auto_sync true Send the changes of the models to the engine
none breaker.failures 3 Failures inside the window that open the breaker
none breaker.window 60 Seconds of the failure window
none breaker.cooldown 30 Seconds the breaker stays open
none anonymous.ttl_minutes 1440 Minutes a guest session stays in the cache
none anonymous.max_feedback 50 Newest feedback rows kept for each guest

For development, use RECOMMENDER_DRIVER=null. Each block then uses its fallback query.

A scenario

Make a scenario with php artisan make:scenario ForYou. The command writes app/Recommendations/ForYou.php. Facet and Recommender in the example are enums of the host. Recommender implements NamedRecommender.

final class Related extends Scenario
{
    public function kind(): ScenarioKind
    {
        return ScenarioKind::ItemToItem;
    }

    public function facets(): array
    {
        return [Facet::Country, Facet::Language];
    }

    public function fallbacks(): array
    {
        return [[Facet::Country], []];
    }

    public function recommender(): NamedRecommender
    {
        return Recommender::Similar;
    }
}
  • kind() selects the Gorse recommender: Recommend, ItemToItem, Latest, NonPersonalized or Collaborative.
  • facets() gives the label keys of the context item. Their values become the categories of the query.
  • fallbacks() gives looser facet lists. The scenario tries each list in order while the result is empty.
  • recommender() gives the Gorse name of an item-to-item or a non-personalized recommender.
  • limit() gives the number of results. The default is 12.

Run it:

$scores = Related::make()
    ->for($userId)
    ->around($itemId)
    ->where(Facet::Language, ['hi', 'en'])
    ->take(6)
    ->fallback(fn (): Collection => $query->pluck('id'))
    ->get();

get() gives a collection of Score objects (id, score). The result never holds the context item.

The fallback and the breaker

A scenario gives its fallback when the driver is null, when the breaker is open, or when the engine fails (a timeout too). The fallback ids become scores with a null score, cut to the limit. With no fallback, the scenario gives an empty collection.

The circuit breaker keeps its state in the cache, so all workers share it:

  1. It opens after breaker.failures failures inside breaker.window seconds.
  2. It stays open for breaker.cooldown seconds. No call goes to the engine.
  3. Then it lets one call through. A success closes it. A failure opens it again.

The package reports the first failure in a closed window, and a failed probe that opens the breaker again. It does not report every failure.

Sync only on change

Use Recommendable on an item model and RecommendableUser on a user model:

final class Article extends Model
{
    use Recommendable;

    public function recommendableAttributes(): array
    {
        return ['topic', 'published'];
    }

    public function recommendableCategories(): array
    {
        return [$this->topic];
    }

    public function recommendableHidden(): bool
    {
        return ! $this->published;
    }
}
  1. A new row sends an upsert job.
  2. An update sends an upsert job only when an attribute of recommendableAttributes() changed.
  3. A delete sends a delete job.

The observer runs after the commit and reads auto_sync at each event. A job reads the row again when it runs, so a late job sends the current row. When that row is already gone, the upsert job is dropped. Each job is safe to run two times, tries 3 times, and waits at most 300 seconds between the tries.

Record feedback through the queue: $user->recordFeedback($itemId, 'like'). Gorse keeps one feedback for each type, user and item, so a second run of the job changes nothing.

Send all rows: php artisan sommelier:sync-items "App\Models\Article" --chunk=500 and php artisan sommelier:sync-users "App\Models\User".

Anonymous sessions

A guest has no account. The client sends a guest id:

$session = Sommelier::anonymous($guestId);

$session->record($itemId, 'view');
$session->recordFacet(Facet::Country, 'in');
$scores = $session->recommend(12, 0, [], fn (): Collection => $query->pluck('id'));
$session->claim($userId);

The cache keeps the newest anonymous.max_feedback entries of each guest for anonymous.ttl_minutes. recommend() uses the same breaker and fallback rule as a scenario. claim() removes the guest document from the store, queues its feedback for the user, and queues UpdateUserLabels with the facet values ordered by count, the most counted first. That job merges those labels into the user: a facet from the claim replaces the same facet, and the other labels stay. If a dispatch fails, claim() puts the document back. forget() empties the store.

The fake

$fake = Sommelier::fake();
$fake->recommendUsing(fn (Query $query, array $feedback): Collection => collect([new Score('i1', 0.9)]));

// The code under test.

$fake->assertRecommended(new Query(ScenarioKind::Recommend, 'u1'));
$fake->assertItemUpserted('i1');
$fake->assertFeedbackInserted('like', 'u1', 'i1');

The fake also has failWith(), assertItemNotUpserted(), assertItemDeleted(), assertUserUpserted(), assertUserDeleted(), assertNothingSent() and recommended().

Commands and MCP tools

  • php artisan sommelier:scenario "App\Recommendations\ForYou" --user=u1 --item=i1 --limit=5 prints the ids and the scores.
  • php artisan sommelier:health prints the driver, the breaker state and the engine health. It exits with 1 when the engine is not ready.

The package has five read MCP tools, each with #[IsReadOnly]: sommelier-health, sommelier-run-scenario, sommelier-find-item, sommelier-find-user and sommelier-list-user-feedback. The package has no MCP server. Add the tools to the server of the host, in its boot() method:

protected function boot(): void
{
    $this->tools = [...$this->tools, ...SommelierTools::all()];
}

Development

composer update
composer test

AGENTS.md has the rules for the work on this package.

License

Sommelier is open-source software licensed under the MIT license.