PHPackages                             kwakuofosuagyeman/ai-assistant - 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. kwakuofosuagyeman/ai-assistant

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

kwakuofosuagyeman/ai-assistant
==============================

AI-powered assistant for Laravel applications

v1.0.0(1y ago)451[3 issues](https://github.com/kwakuOfosuAgyeman/ai-assistant/issues)PHPPHP &gt;=8.0

Since Dec 31Pushed 1y ago1 watchersCompare

[ Source](https://github.com/kwakuOfosuAgyeman/ai-assistant)[ Packagist](https://packagist.org/packages/kwakuofosuagyeman/ai-assistant)[ RSS](/packages/kwakuofosuagyeman-ai-assistant/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (3)Versions (3)Used By (0)

AI Service Package
==================

[](#ai-service-package)

This package provides a unified interface to interact with various AI services, including OpenAI, Gemini and Claude. It is designed for Laravel applications and offers an extensible and configurable solution for AI-powered functionality such as text generation, embeddings, and more.

---

Features
--------

[](#features)

- **Multi-Provider Support**: Interact with OpenAI, Gemini, and Claude.
- **Centralized Configuration**: Manage settings from a single `config/ai.php` file.
- **Extensible Interface**: Add support for new AI providers with ease.
- **Error Handling**: Includes `try...catch` blocks to handle API errors gracefully.
- **Laravel Compatible**: Designed to work seamlessly with Laravel’s dependency injection and service container.

---

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

[](#installation)

### Step 1: Require the Package

[](#step-1-require-the-package)

```
composer require kwakuofosuagyeman/ai-assistant
```

### Step 2: Publish Configuration File

[](#step-2-publish-configuration-file)

Publish the configuration file to customize settings:

```
php artisan vendor:publish --tag=ai-config
```

This will create a `config/ai.php` file in your Laravel application.

### Step 3: Set Environment Variables

[](#step-3-set-environment-variables)

Add your API keys and configuration to the `.env` file:

```
YOUR_PROVIDER_API_KEY=your-provider-api-key
```

---

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

[](#configuration)

The `config/ai.php` file contains all the settings for the supported AI providers. Example:

```
return [
    'default' => 'openai',
    'providers' => [
        'services' => [
            'openai' => [
                'api_key' => env('OPENAI_API_KEY'),
                'default_model' => 'text-davinci-003',
                'chat_model' => 'gpt-4',
                'default_max_tokens' => 150,
                'embedding_model' => 'text-embedding-ada-002',
                'default_temperature' => 0.7,
            ],
            'claude' => [
                'api_key' => env('CLAUDE_API_KEY'),
                'base_url' => 'https://api.anthropic.com/v1/messages/',
                'default_max_tokens' => 1024,
                'batch_url' => 'https://api.anthropic.com/v1/messages/batches/',
                'model' => 'claude-3-5-sonnet-20241022',
                'version' => env('CLAUDE_API_VERSION'),

            ],
            'gemini' => [
                'api_key' => env('GEMINI_API_KEY'),
                'base_url' => 'https://generativelanguage.googleapis.com/v1beta/models/',
                'default_model' => 'gemini-2.0-flash:generateContent',
            ]
        ],
    ]

];
```

---

Usage
-----

[](#usage)

### Method 1: Use the Service in Your Application

[](#method-1-use-the-service-in-your-application)

Use the required service where needed, such as in controllers or other services:

```
use Kwakuofosuagyeman\AIAssistant\Services\OpenAIService;

class ExampleController extends Controller
{
    protected $aiManager;

    public function generateText(Request $request)
    {
        $prompt = $request->input('prompt');

        try {
            $openAIService = new OpenAIService();
            $response = $openAIService->generateText("Write a poem about the sea.");

            return response()->json($response);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}
```

### Method 2: Use the Service in Your Application (If you wish to use multiple AI providers)

[](#method-2-use-the-service-in-your-application-if-you-wish-to-use-multiple-ai-providers)

Inject the `AIService` interface where needed, such as in controllers or other services:

```
use Kwakuofosuagyeman\AIAssistant\AIManager;

class ExampleController extends Controller
{
    protected $aiManager;

    public function __construct(AIManager $aiManager)
    {
        $this->aiManager = $aiManager;
    }

    public function generateText(Request $request)
    {
        $provider = $request->input('provider'); // Optional, defaults to config('ai.default')
        $prompt = $request->input('prompt');

        try {
            $response = $this->aiManager->resolveService($provider)->generateText($prompt);

            return response()->json($response);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}
```

---

Supported Methods
-----------------

[](#supported-methods)

### OpenAI

[](#openai)

### This system uses `openai-php/client` to aid in making requests to openai

[](#this-system-uses-openai-phpclient-to-aid-in-making-requests-to-openai)

### `generateText(string $prompt, array $options = []): array`

[](#generatetextstring-prompt-array-options---array)

Generates text based on the given prompt.

```
$response = $aiService->resolveService('openai')->generateText('Tell me a story about space exploration.', [
    'temperature' => 0.8,
    'max_tokens' => 200,
]);

echo $response['data'];
```

### `generateEmbeddings(string $text): array`

[](#generateembeddingsstring-text-array)

Generates embeddings for the given text. This uses the `text-embedding-ada-002` by default.

```
$response = $aiService->resolveService('openai')->generateEmbeddings('Artificial Intelligence');

print_r($response['data']);
```

### `chat(array $messages, array $options = []): array`

[](#chatarray-messages-array-options---array)

Facilitates a conversation-like interaction with the AI model.

```
$messages = [
    ['role' => 'user', 'content' => 'What is the capital of France?'],
    ['role' => 'assistant', 'content' => 'The capital of France is Paris.'],
];

$response = $aiService->resolveService('openai')->chat($messages);

echo $response['data']['content'];
```

### `analyzeSentiment(string $text, array $options = []): array`

[](#analyzesentimentstring-text-array-options---array)

Analyze the sentiment of a text. The labels given to the ai are \['negative', 'neutral', 'positive'\]

```
$text = 'Text to analyze';

$response = $aiService->resolveService('openai')->analyzeSentiment($text);
```

### `summarizeText(string $text, array $options = []): array`

[](#summarizetextstring-text-array-options---array)

Transcribes audio files.

```
$text = 'Text to summarize';

$response = $aiService->resolveService('openai')->summarizeText($text);
```

### `translateText(string $text, string $targetLanguage, array $options = []): array`

[](#translatetextstring-text-string-targetlanguage-array-options---array)

Translates text from its current language to the targetLanguage.

```
$text = 'Text to translate';
$targetLangugae = 'French';

$response = $aiService->resolveService('openai')->translateText($text, $targetLanguage);
```

### `generateCode(string $prompt, array $options = []): array`

[](#generatecodestring-prompt-array-options---array)

Generates code. This has a default temperature of 0.2

```
$text = 'Generate python code to reverse a string';

$response = $aiService->resolveService('openai')->generateCode($prompt);
```

### Gemini

[](#gemini)

### `generateText(string $prompt, array $options = []): array`

[](#generatetextstring-prompt-array-options---array-1)

Generates text based on the given prompt.

```
$response = $aiService->resolveService('gemini')->generateText('Tell me a story about space exploration.');

echo $response['data'];
```

### `transcribeAudio(string $audioPath, array $options = []): array`

[](#transcribeaudiostring-audiopath-array-options---array)

Transcribes the given audio into text.

```
$audio = "path/to/audio";

$response = $aiService->resolveService('gemini')->transcribeAudio($audio);
```

### Claude

[](#claude)

### Generate Text

[](#generate-text)

Use the generateText method to generate AI responses based on a text prompt.

```
use Kwakuofosuagyeman\AIAssistant\Services\ClaudeAIService;

$aiService = new ClaudeAIService();

$prompt = "Write a short story about a brave cat.";
$options = ['maxTokens' => 150];

$response = $aiService->generateText($prompt, $options);

if (isset($response['error'])) {
    echo "Error: " . $response['error'];
} else {
    echo "Generated Text: " . $response['content'];
}
```

### Analyze a Document with a Query

[](#analyze-a-document-with-a-query)

### Analyze a document (e.g., a PDF file) and provide answers to a query about its content.

[](#analyze-a-document-eg-a-pdf-file-and-provide-answers-to-a-query-about-its-content)

```
$fileUrl = 'https://example.com/path-to-document.pdf';
$options = ['query' => 'Summarize the main points of this document.'];

$response = $aiService->analyzeDocumentWithQuery($fileUrl, $options);

if (isset($response['error'])) {
    echo "Error: " . $response['error'];
} else {
    echo "Analysis Result: " . json_encode($response);
}
```

### Use Tool with Messages

[](#use-tool-with-messages)

### Send specific messages to the Claude AI service along with tools for interaction. This can be used for chatbots,

[](#send-specific-messages-to-the-claude-ai-service-along-with-tools-for-interaction-this-can-be-used-for-chatbots)

```
$messages = [
    ['role' => 'user', 'content' => 'What is the weather like in San Francisco']
];
$options = [
    'tool' => [
      {
        "name": "get_weather",
        "description": "Get the current weather in a given location",
        "input_schema": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA"
            }
          },
          "required": ["location"]
        }
      }
    ],
    'maxTokens' => 1024
];

$response = $aiService->useTool($messages, $options);

if (isset($response['error'])) {
    echo "Error: " . $response['error'];
} else {
    echo "Tool Response: " . json_encode($response);
}
```

### Generate Batch Messages

[](#generate-batch-messages)

### Send multiple prompts as a batch and receive responses.

[](#send-multiple-prompts-as-a-batch-and-receive-responses)

```
$batches = [
        {
            "custom_id": "my-first-request",
            "params": {
                "model": "claude-3-5-sonnet-20241022",
                "max_tokens": 1024,
                "messages": [
                    {"role": "user", "content": "Hello, world"}
                ]
            }
        },
        {
            "custom_id": "my-second-request",
            "params": {
                "model": "claude-3-5-sonnet-20241022",
                "max_tokens": 1024,
                "messages": [
                    {"role": "user", "content": "Hi again, friend"}
                ]
            }
        }
    ];

$response = $aiService->generateBatchMessages($batches);

if (isset($response['error'])) {
    echo "Error: " . $response['error'];
} else {
    echo "Batch Responses: " . json_encode($response);
}
```

### Manage Batch Requests

[](#manage-batch-requests)

List Batch Requests:

```
$response = $aiService->listBatchMessages();
echo json_encode($response);
```

### Retrieve a Batch Result:

[](#retrieve-a-batch-result)

```
$token = 'batch-id';
$response = $aiService->getBatchMessagesResult($token);
echo json_encode($response);
```

### Cancel a Batch Request:

[](#cancel-a-batch-request)

```
$token = 'batch-id';
$response = $aiService->cancelMessageBatch($token);
echo json_encode($response);
```

---

Adding a New AI Provider
------------------------

[](#adding-a-new-ai-provider)

To add support for a new AI provider:

1. **Create a New Service**: Implement the `AIService` interface:

    ```
    namespace Kwakuofosuagyeman\AIAssistant\Services;

    use Kwakuofosuagyeman\AIAssistant\Contracts\AIService;

    class NewAIProviderService implements AIService
    {
        public function generateText(string $prompt, array $options = []): array
        {
            // Implement text generation
        }

        // Implement other methods as needed
    }
    ```
2. **Register the New Service**: Bind the new service in your service provider.

---

Testing
-------

[](#testing)

You can test the service using PHPUnit. Example test for the OpenAI integration:

```
use Tests\TestCase;
use Kwakuofosuagyeman\AIAssistant\Contracts\AIService;

class OpenAIServiceTest extends TestCase
{
    public function testGenerateText()
    {
        $aiService = $this->app->make(AIService::class);
        $response = $aiService->resolveService('openai')->generateText('Test prompt');

        $this->assertArrayHasKey('data', $response);
    }
}
```

---

Contributing
------------

[](#contributing)

Contributions are welcome! Please follow the standard Laravel and PHP development guidelines.

1. Fork the repository.
2. Create a new branch for your feature or bug fix.
3. Submit a pull request with a clear description of your changes.

---

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

---

Support
-------

[](#support)

For issues, please open an issue on the GitHub repository or contact the maintainers.

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance28

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 97.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

498d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5f833b6e630582dc3e44abe5995d6be02be1d9f76756f5b61ff7e0184216d2fa?d=identicon)[kwakuAgyeman](/maintainers/kwakuAgyeman)

---

Top Contributors

[![kwakuOfosuAgyeman](https://avatars.githubusercontent.com/u/112822461?v=4)](https://github.com/kwakuOfosuAgyeman "kwakuOfosuAgyeman (47 commits)")[![AlainCis](https://avatars.githubusercontent.com/u/28144511?v=4)](https://github.com/AlainCis "AlainCis (1 commits)")

---

Tags

claudegemini-apigenerative-ailaravelopenai-apiphpphplaravelautomationailaravel-packageopenainlpmachine learningGeminiclaudeanthropicgptnatural language processingChatGpttext-generationai-integrationai-toolsassistantai-serviceopenai-api

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/kwakuofosuagyeman-ai-assistant/health.svg)

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

###  Alternatives

[sbsaga/toon

🧠 TOON for Laravel — a compact, human-readable, and token-efficient data format for AI prompts &amp; LLM contexts. Perfect for ChatGPT, Gemini, Claude, Mistral, and OpenAI integrations (JSON ⇄ TOON).

6115.6k](/packages/sbsaga-toon)[vizra/vizra-adk

Vizra Agent Development Kit - A comprehensive Laravel package for building intelligent AI agents.

29026.1k](/packages/vizra-vizra-adk)[cognesy/instructor-php

The complete AI toolkit for PHP: unified LLM API, structured outputs, agents, and coding agent control

310107.9k1](/packages/cognesy-instructor-php)[deepseek-php/deepseek-php-client

deepseek PHP client is a robust and community-driven PHP client library for seamless integration with the Deepseek API, offering efficient access to advanced AI and data processing capabilities.

47073.9k5](/packages/deepseek-php-deepseek-php-client)

PHPackages © 2026

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