PHPackages                             memran/marwa-ai - 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. [Testing &amp; Quality](/categories/testing)
4. /
5. memran/marwa-ai

ActiveLibrary[Testing &amp; Quality](/categories/testing)

memran/marwa-ai
===============

A comprehensive AI abstraction library for PHP with multi-provider support

v1.0.1(1mo ago)01971MITPHPPHP ^8.2CI passing

Since Apr 19Pushed 1mo agoCompare

[ Source](https://github.com/memran/marwa-ai)[ Packagist](https://packagist.org/packages/memran/marwa-ai)[ RSS](/packages/memran-marwa-ai/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (12)Versions (2)Used By (1)

Marwa AI
========

[](#marwa-ai)

[![Latest Stable Version](https://camo.githubusercontent.com/5eb6a8eb7f358dec7f0ef89c5c01ae3b1c069c6536d1276b7756c683f379b09b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d656d72616e2f6d617277612d61692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/memran/marwa-ai)[![PHP Version Support](https://camo.githubusercontent.com/7de2881317d89a8577f58099a66fda8df3c1d952a8f6f88e8053e921392ccf95/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6d656d72616e2f6d617277612d61692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/memran/marwa-ai)[![Tests Status](https://camo.githubusercontent.com/9705733743330a166c792b5ea1b76a6491383e78fb5cecde61256ecd2b49b725/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d656d72616e2f6d617277612d61692f74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/memran/marwa-ai/actions)[![PHPStan Status](https://camo.githubusercontent.com/79ccd43815a7df7150f9d33e770b3c3dce3cb8ab6dfe9bce0fbd9928de10dbaf/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230362d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](https://phpstan.org/)[![Total Downloads](https://camo.githubusercontent.com/8c95228315e0cf2baf7b40e0aa8e6a964e23b0b79bf1fd55100badb6b5773d19/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d656d72616e2f6d617277612d61692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/memran/marwa-ai)[![License](https://camo.githubusercontent.com/3d796ee9e9864ef657373325a83acb62e69b969873aa66d30730b120ebf2914b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d656d72616e2f6d617277612d61692e7376673f7374796c653d666c61742d737175617265)](LICENSE)

A comprehensive AI abstraction library for PHP with unified support for multiple AI providers.

Features
--------

[](#features)

- **Multi-provider support**: OpenAI, Anthropic Claude, Google Gemini, xAI Grok, Mistral, DeepSeek, Ollama
- **Unified API**: Same interface across all providers
- **Streaming**: Real-time token streaming
- **Function/Tool calling**: Structured function execution
- **Prompt templates**: Reusable template system with variables, conditionals, loops
- **Conversation memory**: Persistent context across requests
- **Batch processing**: Queue and process multiple AI requests
- **MCP server support**: Model Context Protocol integration
- **Text classification**: Sentiment, intent, entity extraction
- **Embeddings**: Vector generation and similarity search
- **Image generation**: DALL-E integration
- **Structured output**: JSON schema enforcement

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

[](#installation)

```
composer require memran/marwa-ai
```

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

[](#quick-start)

```
use Marwa\AI\MarwaAI;

// Simple completion
$response = MarwaAI::instance()->conversation('Hello, how are you?')->send();
echo $response->getContent();

// With provider-specific options
$response = MarwaAI::driver('anthropic')
    ->completion([
        ['role' => 'user', 'content' => 'Explain quantum computing']
    ], [
        'temperature' => 0.7,
        'max_tokens' => 500,
    ]);
```

### Using the Helper Functions

[](#using-the-helper-functions)

```
use function Marwa\AI\{ai, complete, conversation};

// Quick completion
$result = complete('Tell me a joke');
echo $result->getContent();

// Create conversation with helper
$conv = conversation('You are a helpful assistant');
$conv->user('What is PHP?')
     ->send()
     ->getContent();
```

Conversations
-------------

[](#conversations)

```
$conv = ai()->conversation([
    ['role' => 'system', 'content' => 'You are a PHP expert.'],
    ['role' => 'user', 'content' => 'What is dependency injection?']
]);

$response = $conv->send();
echo $response->getContent();

// Continue the conversation
$conv->user('Can you show me an example?')
     ->send();
```

### Context &amp; Metadata

[](#context--metadata)

```
$conv = ai()->conversation()
    ->withContext(['user_id' => 123, 'locale' => 'en'])
    ->setSystem('Remember the user prefers concise answers.');

// Later, restore from storage
$conv = \Marwa\AI\Support\Conversation::fromArray($savedData);
```

### Streaming

[](#streaming)

```
// Using the helper
use function Marwa\AI\stream;

stream('Write a poem about code', function ($chunk) {
    echo $chunk->getDelta();
    flush();
});

// Or using conversation directly
foreach (ai()->conversation('Write a poem about code')->stream() as $chunk) {
    echo $chunk->getDelta();
}
```

Prompt Templates
----------------

[](#prompt-templates)

```
$template = ai()->prompt('
    You are a {{role}} expert.
    {{#show_tips}}
    Provide practical examples.
    {{/show_tips}}
    Question: {{question}}
');

$response = $template
    ->variable('role', 'PHP developer')
    ->variable('show_tips', true)
    ->render([
        'question' => 'What is a closure?'
    ]);
```

Tools / Function Calling
------------------------

[](#tools--function-calling)

```
use function Marwa\AI\ai_tool;

ai()->tool(ai_tool(
    'get_weather',
    'Get current weather for a location',
    [
        'type' => 'object',
        'properties' => [
            'city' => ['type' => 'string', 'description' => 'City name'],
            'country' => ['type' => 'string', 'description' => 'Country code'],
        ],
        'required' => ['city'],
    ],
    function (array $args) {
        // Your business logic here
        return "Weather in {$args['city']}: 22°C, sunny";
    }
));

$conv = ai()->conversation('What is the weather in Paris?');
$response = $conv->send(['tools' => ai()->getTools()]);

if ($response->hasToolCalls()) {
    // Auto-execute tools and continue
    $final = $conv->continueWithTools(ai()->getTools());
    echo $final->getContent();
}
```

Classification
--------------

[](#classification)

```
use function Marwa\AI\ai_classify;

// Sentiment analysis
$sentiment = ai_classify()->sentiment('I love this product!');
if ($sentiment->isPositive()) {
    echo "Positive score: " . $sentiment->getSentimentScore();
}

// Intent detection
$intent = ai_classify()->detectIntent(
    'I need to reset my password',
    ['greeting', 'password_reset', 'billing', 'technical_support']
);
echo "Detected: " . $intent->getIntent();
echo "Confidence: " . $intent->getConfidence();

// Entity extraction
$entities = ai_classify()->extractEntities(
    'Contact John Doe at john@example.com',
    ['person', 'email', 'organization']
);

// Zero-shot classification
$result = ai_classify()->zeroShot(
    'The new iPhone has an amazing camera',
    ['technology', 'sports', 'politics']
);
```

Batch Processing
----------------

[](#batch-processing)

```
$batch = ai_batch();

// Add multiple tasks
$batch->add('completion', ['prompt' => 'Summarize article A'], ['provider' => 'openai']);
$batch->add('completion', ['prompt' => 'Summarize article B'], ['provider' => 'openai']);
$batch->add('embedding', ['texts' => ['doc1', 'doc2']], ['provider' => 'openai']);

// Process all
$result = $batch->process();

foreach ($result->getResults() as $id => $output) {
    echo "Task {$id}: Done\n";
}

foreach ($result->getFailures() as $failure) {
    echo "Task {$failure['id']} failed: {$failure['error']}\n";
}
```

Memory &amp; Context
--------------------

[](#memory--context)

```
use function Marwa\AI\ai_memory;

$memory = ai_memory();

// Store semantic memories for RAG
$memory->rememberSemantic(
    'Users prefer dark mode with large fonts',
    ['user_id' => 123, 'category' => 'preferences']
);

// Search by semantic similarity
$results = $memory->search('interface preferences');
foreach ($results as $match) {
    echo "Score: {$match['score']}\n";
    echo "Memory: {$match['memory']['text']}\n";
}

// Conversation history storage
$memory->storeMessages('conv_123', $messages);
$history = $memory->getMessages('conv_123');
```

Embeddings
----------

[](#embeddings)

```
use function Marwa\AI\embed;
use function Marwa\AI\cosine_similarity;

$embeddings = embed(['Text 1', 'Text 2', 'Text 3']);

// Get individual vectors
$vec1 = $embeddings->getEmbedding(0);

// Cosine similarity
$sim = cosine_similarity(
    $embeddings->getEmbedding(0),
    $embeddings->getEmbedding(1)
);

// Dimensions
$dim = $embeddings->getDimensions();
```

Image Generation
----------------

[](#image-generation)

```
use function Marwa\AI\image;

$images = image('A sunset over mountains', [
    'size' => '1024x1024',
    'quality' => 'hd',
    'n' => 3,
]);

foreach ($images->getUrls() as $url) {
    echo "Image URL: {$url}\n";
}

// Save to disk
$paths = $images->save('/path/to/save', 'sunset_');
```

Structured Output
-----------------

[](#structured-output)

```
use function Marwa\AI\ai_structured;

$result = ai_structured(
    [
        'type' => 'object',
        'properties' => [
            'name' => ['type' => 'string'],
            'age' => ['type' => 'integer'],
            'skills' => [
                'type' => 'array',
                'items' => ['type' => 'string']
            ],
        ],
    ],
    [
        ['role' => 'user', 'content' => 'Extract: John is 30 and knows PHP, JS']
    ]
);

echo $result->name;  // "John"
echo $result->age;   // 30
echo implode(', ', $result->skills); // "PHP, JS"
```

Health Checks
-------------

[](#health-checks)

```
use function Marwa\AI\ai_health;

$health = ai_health('openai');

if ($health->check()->isOperational()) {
    echo "Latency: " . $health->getLatency() . "ms\n";
    $models = $health->getModels();
    print_r($models);
}
```

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

[](#configuration)

### Standalone Usage (Singleton)

[](#standalone-usage-singleton)

```
use Marwa\AI\MarwaAI;

$ai = MarwaAI::initialize([
    'default' => 'anthropic',
    'anthropic' => [
        'api_key' => 'sk-ant-...',
        'model' => 'claude-3-sonnet',
    ],
    'openai' => [
        'api_key' => 'sk-...',
        'model' => 'gpt-4o',
    ],
]);

$response = $ai->conversation('Hello')->send();
```

### Alternative: Application Instance (Non-singleton)

[](#alternative-application-instance-non-singleton)

If you prefer not to use the global singleton, you can instantiate the `Application` class.

```
use Marwa\AI\Application;

$ai = new Application([
    'default' => 'openai',
    'openai' => ['api_key' => '...']
]);

$response = $ai->conversation('Hello')->send();
```

### Using a Config File

[](#using-a-config-file)

```
// config/ai.php
return [
    'default' => 'ollama',

    'providers' => [
        'openai' => [
            'api_key' => getenv('OPENAI_API_KEY'),
            'model' => 'gpt-4o',
            'timeout' => 60,
            'retries' => 3,
        ],
        'anthropic' => [
            'api_key' => getenv('ANTHROPIC_API_KEY'),
            'model' => 'claude-3-opus-20240229',
        ],
        'google' => [
            'api_key' => getenv('GOOGLE_API_KEY'),
            'model' => 'gemini-1.5-pro',
        ],
        'grok' => [
            'api_key' => getenv('XAI_API_KEY'),
            'model' => 'grok-2-latest',
        ],
        'mistral' => [
            'api_key' => getenv('MISTRAL_API_KEY'),
            'model' => 'mistral-large-latest',
        ],
        'deepseek' => [
            'api_key' => getenv('DEEPSEEK_API_KEY'),
            'model' => 'deepseek-chat',
        ],
        'ollama' => [
            'base_url' => 'http://localhost:11434/v1/',
            'model' => 'llama3.2',
        ],
    ],
];
```

Detailed Provider Configuration
-------------------------------

[](#detailed-provider-configuration)

Each provider supports the following parameters in the configuration array:

ParameterTypeDescription`api_key`stringYour provider API key`model`stringDefault model to use for requests`base_url`stringCustom API endpoint (e.g., for proxies or local Ollama)`timeout`intRequest timeout in seconds (default: 30)`retries`intNumber of automatic retries on failure (default: 3)### Environment Variables Reference

[](#environment-variables-reference)

ProviderAPI Key EnvDefault ModelBase URL Env**OpenAI**`OPENAI_API_KEY``gpt-4o``OPENAI_BASE_URL`**Anthropic**`ANTHROPIC_API_KEY``claude-3-opus`-**Google**`GOOGLE_API_KEY``gemini-pro`-**xAI (Grok)**`XAI_API_KEY``grok-2-latest`-**Mistral**`MISTRAL_API_KEY``mistral-large`-**DeepSeek**`DEEPSEEK_API_KEY``deepseek-chat`-**Ollama**-`llama3.2``OLLAMA_BASE_URL`Chain / Pipeline
----------------

[](#chain--pipeline)

```
use function Marwa\AI\ai;

$chain = ai()->chain([
    fn($input) => "Analyze: {$input}",
    fn($analysis) => strtoupper($analysis),
    fn($upper) => "Final: {$upper}",
]);

$result = $chain->execute();

// Streaming chain
foreach ($chain->stream() as $chunk) {
    echo $chunk->getDelta();
}

// View execution history
$history = $chain->getHistory();
foreach ($history->getSteps() as $step) {
    printf(
        "Step %s: %.3fs\n",
        $step['name'],
        $step['duration']
    );
}
```

MCP Server
----------

[](#mcp-server)

```
use Marwa\AI\Contracts\MCPServerInterface;
use Marwa\AI\Contracts\MCPResponse;

$server = new class implements MCPServerInterface {
    public function getName(): string { return 'my-server'; }
    public function getVersion(): string { return '1.0.0'; }
    public function getCapabilities() { /* ... */ }
    public function listTools(): array { return [/* ... */]; }
    public function handleToolCall(string $tool, array $args): MCPResponse {
        // Handle MCP tool calls
        return MCPResponse::success($result);
    }
};

ai()->registerMcpServer('my-server', $server);
```

Error Handling
--------------

[](#error-handling)

```
use Marwa\AI\Exceptions\AIException;
use Marwa\AI\Exceptions\ConfigurationException;
use Marwa\AI\Exceptions\RateLimitException;

try {
    $resp = ai()->driver('openai')->completion($messages);
} catch (RateLimitException $e) {
    echo "Rate limited. Retry after {$e->retryAfter} seconds";
    sleep($e->retryAfter);
} catch (ConfigurationException $e) {
    echo "Check your API key configuration";
} catch (AIException $e) {
    echo "AI error: " . $e->getMessage();
}
```

CLI Tool
--------

[](#cli-tool)

```
# Interactive chat session
php bin/marwa-ai chat --provider=openai

# Single question
php bin/marwa-ai ask "What is PHP?"

# List available providers
php bin/marwa-ai providers
```

Providers Reference
-------------------

[](#providers-reference)

ProviderStreamingToolsVisionEmbeddingsOpenAIYesYesYesYesAnthropic ClaudeYesYesYesYesGoogle GeminiYesYesYesYesxAI GrokYesYesYesNoMistralYesYesNoYesDeepSeekYesYesNoYesOllama (local)YesYesYesYes\*\*Embeddings depend on the loaded model

Environment Variables
---------------------

[](#environment-variables)

VariablePurpose`AI_PROVIDER`Default provider`OPENAI_API_KEY`OpenAI credentials`OPENAI_MODEL`OpenAI model override`ANTHROPIC_API_KEY`Anthropic credentials`ANTHROPIC_MODEL`Anthropic model override`GOOGLE_API_KEY`Google credentials`GOOGLE_MODEL`Google model override`XAI_API_KEY`xAI Grok credentials`MISTRAL_API_KEY`Mistral credentials`DEEPSEEK_API_KEY`DeepSeek credentials`OLLAMA_BASE_URL`Ollama endpointLicense
-------

[](#license)

MIT

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance90

Actively maintained with recent releases

Popularity15

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity46

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

Unknown

Total

1

Last Release

52d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/8cf906a31a250a940314fe42f8a18f449647bfe18095457350ff0081cf8dd3c2?d=identicon)[memran](/maintainers/memran)

---

Top Contributors

[![memran](https://avatars.githubusercontent.com/u/7415198?v=4)](https://github.com/memran "memran (8 commits)")

---

Tags

aiai-assistantai-chatcomposermarwamarwaphpphpphp82phpstanphpunit

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/memran-marwa-ai/health.svg)

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

###  Alternatives

[drupal/core-recommended

Locked core dependencies; require this project INSTEAD OF drupal/core.

6941.5M395](/packages/drupal-core-recommended)[shopware/platform

The Shopware e-commerce core

3.4k1.5M3](/packages/shopware-platform)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.4M506](/packages/shopware-core)[typo3/cms

TYPO3 CMS is a free open source Content Management Framework initially created by Kasper Skaarhoj and licensed under GNU/GPL.

1.2k1.9M122](/packages/typo3-cms)[eliashaeussler/cache-warmup

Composer package to warm up website caches, based on a given XML sitemap

75419.2k9](/packages/eliashaeussler-cache-warmup)[testo/testo

A lightweight PHP testing framework.

1843.4k30](/packages/testo-testo)

PHPackages © 2026

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