PHPackages                             mindwave/mindwave - 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. mindwave/mindwave

ActiveLibrary

mindwave/mindwave
=================

Production AI utilities for Laravel: auto-fit prompts, streaming, tracing, and context discovery.

v1.0.0(4mo ago)69677MITPHPPHP ^8.2|^8.3|^8.4CI failing

Since May 27Pushed 3mo ago4 watchersCompare

[ Source](https://github.com/HelgeSverre/mindwave)[ Packagist](https://packagist.org/packages/mindwave/mindwave)[ Docs](https://github.com/helgesverre/mindwave)[ RSS](/packages/mindwave-mindwave/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (32)Versions (6)Used By (0)

[![Mindwave](art/header.png)](art/header.png)

[![Latest Version on Packagist](https://camo.githubusercontent.com/169b95ae52666faa778e31d24df639bb62431482df2a21e897827b4969ce620d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d696e64776176652f6d696e64776176652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mindwave/mindwave)[![GitHub Tests Action Status](https://camo.githubusercontent.com/66334a67f89bfee476c5fe08586a61d86e5b85c09a6e3b50c6e00136df972b25/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d696e64776176652f6d696e64776176652f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/mindwave/mindwave/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/0f7ae101a42efd87b7afb5ed40166d1b1093aaa7affa9fd53ffd7341d225d265/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d696e64776176652f6d696e64776176652f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/mindwave/mindwave/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/c97b25a306a2325d48f3037b847e96835ce2c361c78046240ffd9f989336e33a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d696e64776176652f6d696e64776176652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mindwave/mindwave)

Mindwave: Production AI Utilities for Laravel
=============================================

[](#mindwave-production-ai-utilities-for-laravel)

**The working developer's AI toolkit** - Long prompts, streaming, tracing, and context discovery made simple.

> **v1.0.0 Released** - All 4 pillars complete with 1300+ tests.
>
> **Experimental** - This package is under active development. APIs may change. Use in production at your own risk.

What is Mindwave?
-----------------

[](#what-is-mindwave)

Mindwave is a Laravel package that provides **production-grade AI utilities** for building LLM-powered features. Unlike complex agent frameworks, Mindwave focuses on practical tools that Laravel developers actually need:

- ✅ **Auto-fit long prompts** to any model's context window
- ✅ **Stream LLM responses** with 3 lines of code (SSE/EventSource)
- ✅ **OpenTelemetry tracing** with database storage for costs, tokens, and performance
- ✅ **Ad-hoc context discovery** from your database/CSV using TNTSearch

Why Mindwave?
-------------

[](#why-mindwave)

**Not another agent framework.** Just batteries-included utilities for shipping AI features fast.

```
// Write long prompts, Mindwave auto-fits to model limits
Mindwave::prompt()
    ->section('system', $instructions)
    ->section('context', $largeDocument, priority: 50, shrinker: 'summarize')
    ->section('user', $question)
    ->fit()  // Auto-trims to context window
    ->run();

// Stream responses in 3 lines (backend)
return Mindwave::stream($prompt)->respond();

// View traces and costs
$traces = MindwaveTrace::expensive(0.10)->with('spans')->get();

// Pull context from your DB on-the-fly
Mindwave::prompt()
    ->context(TntSearchSource::fromEloquent(User::query(), fn($u) => "Name: {$u->name}"))
    ->ask('Who has Laravel expertise?');
```

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

[](#installation)

Install via Composer:

```
composer require mindwave/mindwave
```

Publish the config files:

```
php artisan vendor:publish --tag="mindwave-config"
```

Run migrations for tracing (optional but recommended):

```
php artisan migrate
```

Quick Start
-----------

[](#quick-start)

### 1. Basic LLM Chat

[](#1-basic-llm-chat)

```
use Mindwave\Mindwave\Facades\Mindwave;

$response = Mindwave::llm()->chat([
    ['role' => 'system', 'content' => 'You are a helpful assistant.'],
    ['role' => 'user', 'content' => 'Explain Laravel in one sentence.'],
]);

echo $response->content;
```

### 2. Streaming Responses

[](#2-streaming-responses)

**Backend:**

```
use Mindwave\Mindwave\Facades\Mindwave;

Route::get('/chat', function (Request $request) {
    return Mindwave::stream($request->input('message'))
        ->model('gpt-4')
        ->respond();
});
```

**Frontend:**

```
const stream = new EventSource('/chat?message=' + encodeURIComponent(question));
stream.onmessage = e => output.textContent += e.data;
stream.addEventListener('done', () => stream.close());
```

### 3. Auto-Fit Long Prompts

[](#3-auto-fit-long-prompts)

```
use Mindwave\Mindwave\Facades\Mindwave;

// Automatically handles token limits
Mindwave::prompt()
    ->reserveOutputTokens(500)
    ->section('system', 'You are an expert analyst', priority: 100)
    ->section('documentation', $longDocContent, priority: 50, shrinker: 'summarize')
    ->section('history', $conversationHistory, priority: 75)
    ->section('user', $userQuestion, priority: 100)
    ->fit()  // Trims to model's context window
    ->run();
```

### 4. View Costs &amp; Traces

[](#4-view-costs--traces)

```
use Mindwave\Mindwave\Observability\Models\Trace;
use Mindwave\Mindwave\Observability\Models\Span;

// Find expensive traces
$expensive = Trace::where('estimated_cost', '>', 0.10)
    ->with('spans')
    ->orderByDesc('created_at')
    ->get();

// Find slow LLM calls
$slow = Span::where('operation_name', 'chat')
    ->where('duration', '>', 5_000_000_000) // 5 seconds in nanoseconds
    ->with('trace')
    ->get();

// Daily cost summary
$dailyCosts = Trace::selectRaw('
        DATE(created_at) as date,
        COUNT(*) as total_traces,
        SUM(estimated_cost) as total_cost,
        SUM(total_input_tokens) as input_tokens,
        SUM(total_output_tokens) as output_tokens
    ')
    ->groupBy('date')
    ->orderByDesc('date')
    ->get();
```

### 5. Ad-Hoc Context Discovery

[](#5-ad-hoc-context-discovery)

```
use Mindwave\Mindwave\Context\Sources\TntSearchSource;

// Search your database on-the-fly
Mindwave::prompt()
    ->context(
        TntSearchSource::fromEloquent(
            Product::where('active', true),
            fn($p) => "Product: {$p->name}, Price: {$p->price}"
        )
    )
    ->ask('What products under $50 do you have?');

// Or from CSV files
Mindwave::prompt()
    ->context(TntSearchSource::fromCsv('data/knowledge-base.csv'))
    ->ask('How do I reset my password?');
```

Core Features
-------------

[](#core-features)

### 🧩 Prompt Composer

[](#-prompt-composer)

Automatically manage context windows with priority-based section trimming:

- **Token budgeting** - Reserve tokens for output, auto-fit sections
- **Smart shrinkers** - Summarize, truncate, or compress content
- **Priority system** - Keep important sections, trim less critical ones
- **Multi-model support** - Works with GPT-4, Claude, Mistral, etc.

### 🌊 Streaming (SSE)

[](#-streaming-sse)

Production-ready Server-Sent Events streaming:

- **3-line setup** - Backend and frontend
- **Proper headers** - Works with Nginx/Apache out of the box
- **Connection monitoring** - Handles client disconnects
- **Error handling** - Graceful failure and retry

### 📊 OpenTelemetry Tracing

[](#-opentelemetry-tracing)

Industry-standard observability with GenAI semantic conventions:

- **Automatic tracing** - All LLM calls tracked (zero configuration)
- **Database storage** - Query traces via Eloquent models
- **OTLP export** - Send to Jaeger, Grafana, Datadog, Honeycomb, etc.
- **Cost tracking** - Automatic cost estimation per call
- **Token usage** - Input/output/total tokens tracked
- **PII protection** - Configurable message capture and redaction
- **Artisan commands** - Export, prune, and analyze traces

**Quick Start:**

```
// 1. Enable tracing in .env
// MINDWAVE_TRACING_ENABLED=true

// 2. LLM calls are automatically traced
$response = Mindwave::llm()->generateText('Hello!');

// 3. Query traces
use Mindwave\Mindwave\Observability\Models\Trace;

$expensive = Span::where('cost_usd', '>', 0.10)
    ->orderBy('cost_usd', 'desc')
    ->get();
```

📖 **[Complete Tracing Guide](examples/tracing-examples.md)** - Querying, cost analysis, custom spans, OTLP setup

📐 **[Architecture Documentation](TRACING_ARCHITECTURE.md)** - Technical deep dive

### 🔍 TNTSearch Context Discovery

[](#-tntsearch-context-discovery)

Pull context from your application data without complex RAG setup:

- **No infrastructure** - Pure PHP, no external services
- **Multiple sources** - Eloquent, arrays, CSV files, VectorStores
- **Fast indexing** - Ephemeral indexes with automatic cleanup
- **BM25 ranking** - Industry-standard relevance scoring
- **Auto-query extraction** - Automatically extracts search terms from user messages
- **OpenTelemetry tracing** - Track search performance and results

**Quick Example:**

```
use Mindwave\Mindwave\Context\Sources\TntSearch\TntSearchSource;
use Mindwave\Mindwave\Context\ContextPipeline;

// Search Eloquent models
$userSource = TntSearchSource::fromEloquent(
    User::where('active', true),
    fn($u) => "Name: {$u->name}, Skills: {$u->skills}"
);

// Search CSV files
$docsSource = TntSearchSource::fromCsv('data/knowledge-base.csv');

// Combine multiple sources
$pipeline = (new ContextPipeline)
    ->addSource($userSource)
    ->addSource($docsSource)
    ->deduplicate()  // Remove duplicates
    ->rerank();      // Sort by relevance

// Use in prompt (query auto-extracted from user message)
Mindwave::prompt()
    ->context($pipeline, limit: 5)
    ->section('user', 'Who has Laravel expertise?')
    ->run();
```

📖 **[Complete Context Discovery Guide](examples/context-discovery-examples.md)** - All source types, pipelines, advanced features

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

[](#configuration)

### LLM Configuration

[](#llm-configuration)

```
// config/mindwave-llm.php
return [
    'default' => env('MINDWAVE_LLM_DRIVER', 'openai'),

    'llms' => [
        'openai' => [
            'api_key' => env('OPENAI_API_KEY'),
            'model' => env('OPENAI_MODEL', 'gpt-4-turbo'),
            'max_tokens' => 4096,
            'temperature' => 0.7,
        ],
        'mistral' => [
            'api_key' => env('MISTRAL_API_KEY'),
            'model' => env('MISTRAL_MODEL', 'mistral-large-latest'),
        ],
    ],
];
```

### Tracing Configuration

[](#tracing-configuration)

```
// config/mindwave-tracing.php
return [
    'enabled' => env('MINDWAVE_TRACING_ENABLED', true),

    'database' => [
        'enabled' => true,  // Store in database
    ],

    'otlp' => [
        'enabled' => env('MINDWAVE_TRACE_OTLP_ENABLED', false),
        'endpoint' => env('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://localhost:4318'),
    ],

    'capture_messages' => false,  // PII protection
    'retention_days' => 30,
];
```

Artisan Commands
----------------

[](#artisan-commands)

```
# Export traces to CSV/JSON
php artisan mindwave:export-traces --since=yesterday --format=csv

# Prune old traces
php artisan mindwave:prune-traces --older-than=30days

# View trace statistics
php artisan mindwave:trace-stats

# View TNTSearch index statistics
php artisan mindwave:index-stats

# Clear old TNTSearch indexes (default: 24 hours)
php artisan mindwave:clear-indexes --ttl=24 --force
```

Use Cases
---------

[](#use-cases)

### 💬 AI-Powered Customer Support

[](#-ai-powered-customer-support)

```
Mindwave::prompt()
    ->section('system', 'You are a helpful support agent')
    ->context(TntSearchSource::fromEloquent(
        FAQ::published(),
        fn($f) => "Q: {$f->question}\nA: {$f->answer}"
    ))
    ->section('history', $conversation)
    ->section('user', $userMessage)
    ->fit()
    ->run();
```

### 📄 Document Q&amp;A

[](#-document-qa)

```
Mindwave::prompt()
    ->context(TntSearchSource::fromCsv('uploads/company-handbook.csv'))
    ->ask('What is the vacation policy?');
```

### 🔍 Data Analysis

[](#-data-analysis)

```
Mindwave::prompt()
    ->context(TntSearchSource::fromEloquent(
        Order::where('created_at', '>', now()->subMonth()),
        fn($o) => "Order #{$o->id}: {$o->total}, Status: {$o->status}"
    ))
    ->ask('Summarize sales trends from last month');
```

Supported LLM Providers
-----------------------

[](#supported-llm-providers)

- ✅ **OpenAI** (GPT-4, GPT-3.5, etc.)
- ✅ **Mistral AI** (Mistral Large, Small, etc.)
- ✅ **Anthropic** (Claude 3.5 Sonnet, Opus, Haiku, etc.)
- 🔄 **Google Gemini** (Coming soon)

Supported Vector Stores
-----------------------

[](#supported-vector-stores)

- ✅ **Qdrant** - High-performance vector database with UUID-based IDs
- ✅ **Weaviate** - Open-source vector search engine
- ✅ **Pinecone** - Managed vector database service
- ✅ **In-Memory** - For testing and development
- ✅ **File-based** - JSON file storage for simple use cases

**Vector Store Configuration:**

All vector stores now support configurable embedding dimensions. Set the dimension in your `.env` file to match your embedding model:

```
# Common values: 1536 (OpenAI ada-002, 3-small), 3072 (OpenAI 3-large)
MINDWAVE_QDRANT_DIMENSIONS=1536
MINDWAVE_WEAVIATE_DIMENSIONS=1536
MINDWAVE_PINECONE_DIMENSIONS=1536
```

Breaking Changes in v2.0
------------------------

[](#breaking-changes-in-v20)

**⚠️ Important:** Version 2.0 introduces breaking changes:

1. **Removed `OPENAI_EMBEDDING_LENGTH` constant** - Embedding dimensions are now configured per vector store in `config/mindwave-vectorstore.php` and environment variables.
2. **Qdrant ID generation changed** - Now uses UUID strings instead of auto-incrementing integers. Existing Qdrant collections will need to be recreated.
3. **Weaviate dependency moved** - `timkley/weaviate-php` is now in `require` instead of `require-dev` to prevent production crashes.

**Migration Guide:**

```
# 1. Update your .env file with dimension settings
MINDWAVE_QDRANT_DIMENSIONS=1536
MINDWAVE_WEAVIATE_DIMENSIONS=1536

# 2. Update your config (if you published it)
php artisan vendor:publish --tag="mindwave-config" --force

# 3. Rebuild Qdrant collections (if using Qdrant)
# The new UUID-based IDs are incompatible with old integer IDs
```

Documentation
-------------

[](#documentation)

Full documentation available at [mindwave.no](https://mindwave.no) (coming soon).

For now, see:

- [PIVOT\_PLAN.md](PIVOT_PLAN.md) - Implementation roadmap
- [TRACING\_ARCHITECTURE.md](TRACING_ARCHITECTURE.md) - OpenTelemetry details

Roadmap
-------

[](#roadmap)

### v1.0 (December 2025) - RELEASED

[](#v10-december-2025---released)

- LLM abstraction (OpenAI, Anthropic, Mistral)
- Prompt Composer with auto-fitting
- Streaming SSE support
- OpenTelemetry tracing + database storage
- TNTSearch context discovery
- Laravel Telescope integration
- 500+ tests passing

### v1.1 (Q1 2026)

[](#v11-q1-2026)

- More LLM providers (Cohere, Groq)
- Advanced shrinkers (semantic compression)
- Cost budgets and alerts
- Grafana dashboard templates

### v2.0 (Q2 2026)

[](#v20-q2-2026)

- Multi-modal support (images, audio)
- Prompt testing framework
- A/B testing utilities
- Batch processing

Credits
-------

[](#credits)

- [Helge Sverre](https://twitter.com/helgesverre) - Creator
- [OpenAI PHP Client](https://github.com/openai-php/client) - OpenAI integration
- [TeamTNT/TNTSearch](https://github.com/teamtnt/tntsearch) - Full-text search
- [OpenTelemetry PHP](https://github.com/open-telemetry/opentelemetry-php) - Observability
- [Tiktoken PHP](https://github.com/yethee/tiktoken-php) - Token counting

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

48

—

FairBetter than 94% of packages

Maintenance78

Regular maintenance activity

Popularity23

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity65

Established project with proven stability

 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 ~472 days

Total

3

Last Release

142d ago

Major Versions

v0.0.2-alpha → v1.0.02025-12-27

PHP version history (2 changes)v0.0.1-alphaPHP ^8.1

v1.0.0PHP ^8.2|^8.3|^8.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/68f3958f40262d577ddc0596e4ba78b42c0409ebc7de948bab47edee392d5f68?d=identicon)[HelgeSverre](/maintainers/HelgeSverre)

---

Top Contributors

[![HelgeSverre](https://avatars.githubusercontent.com/u/1089652?v=4)](https://github.com/HelgeSverre "HelgeSverre (260 commits)")

---

Tags

laravel-packagemindwavelaravelaistreamingtracingopentelemetryopenaillmtntsearchmindwave

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/mindwave-mindwave/health.svg)

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

###  Alternatives

[maestroerror/laragent

Power of AI Agents in your Laravel project

630106.4k](/packages/maestroerror-laragent)[laravel/boost

Laravel Boost accelerates AI-assisted development by providing the essential context and structure that AI needs to generate high-quality, Laravel-specific code.

3.4k10.6M274](/packages/laravel-boost)[theodo-group/llphant

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

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

Monitor the health of a Laravel application

85810.0M83](/packages/spatie-laravel-health)[helgesverre/extractor

AI-Powered Data Extraction for your Laravel application.

22128.0k](/packages/helgesverre-extractor)[keepsuit/laravel-opentelemetry

OpenTelemetry integration for laravel

142347.8k](/packages/keepsuit-laravel-opentelemetry)

PHPackages © 2026

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