PHPackages                             tourze/open-ai-bundle - 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. [API Development](/categories/api)
4. /
5. tourze/open-ai-bundle

ActiveSymfony-bundle[API Development](/categories/api)

tourze/open-ai-bundle
=====================

DeepSeek API integration for Symfony

0.0.1(11mo ago)00MITPHPPHP ^8.1CI passing

Since Jun 3Pushed 4mo agoCompare

[ Source](https://github.com/tourze/open-ai-bundle)[ Packagist](https://packagist.org/packages/tourze/open-ai-bundle)[ RSS](/packages/tourze-open-ai-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (36)Versions (2)Used By (0)

OpenAIBundle
============

[](#openaibundle)

[English](README.md) | [中文](README.zh-CN.md)

[![Latest Version](https://camo.githubusercontent.com/fd8bb5236166fdb6719e6a1c1045f1c4614e2bf8427eabad0197b5c6b0ddafe4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f75727a652f6f70656e2d61692d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/open-ai-bundle)[![Total Downloads](https://camo.githubusercontent.com/d500a7196c43c886ca37b6d6343020322a4a91aaf65d8f3dffcc3a32fad5e607/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f746f75727a652f6f70656e2d61692d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/open-ai-bundle)[![License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![PHP Version](https://camo.githubusercontent.com/c3d372b55ac2d4fcf386a178e11d9788310097b35f3893cf3daae574b6b4cd3e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e312d626c75652e7376673f7374796c653d666c61742d737175617265)](https://www.php.net/)[![Build Status](https://camo.githubusercontent.com/f6680d21769229fe8004b83a844502fcb9fb05282418a2d1ce3517c6786ac9ed/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f746f75727a652f7068702d6d6f6e6f7265706f2f43493f7374796c653d666c61742d737175617265)](https://github.com/tourze/php-monorepo/actions)[![Code Coverage](https://camo.githubusercontent.com/6ce0146325478eb7cebae4cc6139b2af2c161735dd0e3c6ff6802f2c5a708179/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f746f75727a652f7068702d6d6f6e6f7265706f3f7374796c653d666c61742d737175617265)](https://codecov.io/gh/tourze/php-monorepo)

A comprehensive Symfony bundle for integrating with DeepSeek API and other AI models, providing conversation management, function calling, and easy-to-use chat interfaces.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Advanced Configuration](#advanced-configuration)
- [Usage](#usage)
- [Advanced Usage](#advanced-usage)
- [Security](#security)
- [Contributing](#contributing)
- [License](#license)

Features
--------

[](#features)

- 🤖 **Multiple AI Model Support**: DeepSeek (coder, chat, math, chinese), and customizable models
- 💬 **Conversation Management**: Full conversation history with role-based characters
- 🔧 **Function Calling**: Built-in AI functions for code analysis, file operations, and database queries
- 🌊 **Streaming Responses**: Real-time streaming output with chain-of-thought support
- 🎨 **Admin Interface**: EasyAdmin integration for managing API keys, characters, and conversations
- 💻 **CLI Tools**: Interactive chat command with multiple modes
- 🔒 **Secure**: API key management with character-specific permissions

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Symfony 6.4 or higher
- Doctrine ORM 3.0 or higher

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

[](#installation)

```
composer require tourze/open-ai-bundle
```

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

[](#quick-start)

### 1. Configure Database

[](#1-configure-database)

Run migrations to create the required tables:

```
php bin/console doctrine:migrations:migrate
```

### 2. Set Up API Keys

[](#2-set-up-api-keys)

Create an API key in the database:

```
INSERT INTO open_ai_api_key (id, title, base_url, api_key, model, status)
VALUES (1, 'DeepSeek API', 'https://api.deepseek.com', 'your-api-key', 'deepseek-chat', 1);
```

### 3. Create a Character

[](#3-create-a-character)

```
INSERT INTO open_ai_character (id, name, system_prompt, status, preferred_api_key_id)
VALUES (1, 'Assistant', 'You are a helpful assistant.', 1, 1);
```

### 4. Start Chatting

[](#4-start-chatting)

```
# Interactive mode
php bin/console open-ai:chat -c 1

# Single prompt mode
php bin/console open-ai:chat -c 1 -p "Write a poem about coding"
```

Usage
-----

[](#usage)

### Command Line Interface

[](#command-line-interface)

The `open-ai:chat` command provides flexible interaction modes:

```
# Basic interactive chat
php bin/console open-ai:chat --character 1

# Non-streaming mode
php bin/console open-ai:chat -c 1 --no-stream

# Quiet mode (only AI responses)
php bin/console open-ai:chat -c 1 --prompt "Hello" --quiet

# Debug mode
php bin/console open-ai:chat -c 1 --debug
```

**Interactive Commands:**

- Type `q`, `quit`, or `exit` to exit
- Type `c` or `clear` to clear conversation history

### Programmatic Usage

[](#programmatic-usage)

```
use OpenAIBundle\Service\OpenAiService;
use OpenAIBundle\Service\ConversationService;
use OpenAIBundle\VO\StreamRequestOptions;

// Inject services
$openAiService = $container->get(OpenAiService::class);
$conversationService = $container->get(ConversationService::class);

// Initialize conversation
$conversation = $conversationService->initConversation($character, $apiKey);

// Add user message
$conversationService->createUserMessage($conversation, $apiKey, "Hello!");

// Get AI response (streaming)
$options = new StreamRequestOptions(
    model: 'deepseek-chat',
    temperature: 0.7,
    maxTokens: 2000
);

foreach ($openAiService->streamReasoner($apiKey, $messages, $options) as $chunk) {
    // Process streaming chunks
    foreach ($chunk->getChoices() as $choice) {
        echo $choice->getContent();
    }
}
```

### Function Calling

[](#function-calling)

The bundle includes several built-in AI functions:

- **Code Analysis**: Analyze code structure, find references
- **File Operations**: List files, read text files
- **Database Operations**: Query tables, fetch results
- **System Information**: Get timezone, random numbers

Enable function calling on an API key:

```
UPDATE open_ai_api_key SET function_calling = 1 WHERE id = 1;
```

### Admin Interface

[](#admin-interface)

Access the admin panel to manage:

- API Keys: `/admin?crudAction=index&crudControllerFqcn=OpenAIBundle\Controller\Admin\ApiKeyCrudController`
- Characters: `/admin?crudAction=index&crudControllerFqcn=OpenAIBundle\Controller\Admin\CharacterCrudController`
- Conversations: `/admin?crudAction=index&crudControllerFqcn=OpenAIBundle\Controller\Admin\ConversationCrudController`

Advanced Configuration
----------------------

[](#advanced-configuration)

### Character Customization

[](#character-customization)

```
$character = new Character();
$character->setName('Code Expert');
$character->setSystemPrompt('You are an expert programmer...');
$character->setTemperature(0.5);
$character->setMaxTokens(4000);
$character->setTopP(0.9);
$character->setFrequencyPenalty(0.0);
$character->setPresencePenalty(0.0);
```

### Custom AI Functions

[](#custom-ai-functions)

Create custom functions by implementing the function interface:

```
namespace App\AiFunction;

use OpenAIBundle\Service\AiFunctionInterface;
use OpenAIBundle\VO\FunctionDefinition;

class MyCustomFunction implements AiFunctionInterface
{
    public function getDefinition(): FunctionDefinition
    {
        // Define function parameters and description
    }

    public function execute(array $args): string
    {
        // Implement function logic
    }
}
```

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

[](#error-handling)

The bundle provides specific exception types:

```
try {
    $result = $openAiService->chat($apiKey, $messages, $options);
} catch (ConfigurationException $e) {
    // Handle configuration errors
} catch (ModelException $e) {
    // Handle model-related errors
} catch (OpenAiException $e) {
    // Handle general errors
}
```

Advanced Usage
--------------

[](#advanced-usage)

### Custom AI Functions

[](#custom-ai-functions-1)

Create custom AI functions by implementing the `AiFunctionInterface`:

```
use OpenAIBundle\AiFunction\AiFunctionInterface;

class CustomFunction implements AiFunctionInterface
{
    public function getDefinition(): FunctionDefinition
    {
        return new FunctionDefinition(
            'custom_function',
            'Description of your function',
            [
                new FunctionParam('param_name', FunctionParamType::STRING, 'Parameter description', true)
            ]
        );
    }

    public function execute(array $arguments): string
    {
        // Your custom logic here
        return json_encode(['result' => 'success']);
    }
}
```

### Conversation Callbacks

[](#conversation-callbacks)

Implement conversation callbacks for custom processing:

```
$conversationService->onMessageCreated(function (Message $message) {
    // Custom processing for each message
});
```

### Stream Processing

[](#stream-processing)

Handle streaming responses with custom processors:

```
foreach ($openAiService->streamReasoner($apiKey, $messages, $options) as $chunk) {
    // Custom stream processing
    $this->processChunk($chunk);
}
```

Security
--------

[](#security)

### API Key Management

[](#api-key-management)

- Store API keys securely using Symfony's parameter encryption
- Rotate API keys regularly
- Use environment-specific keys for different environments

### Character Permissions

[](#character-permissions)

- Configure character-specific API key access
- Implement role-based access control for characters
- Audit character usage and permissions regularly

### Function Calling Security

[](#function-calling-security)

- Validate all function parameters
- Implement function-level permissions
- Log and monitor function calls for security auditing

### Data Protection

[](#data-protection)

- Encrypt sensitive conversation data
- Implement data retention policies
- Ensure GDPR compliance for user data

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

[](#contributing)

Contributions are welcome! Please:

1. Fork the repository
2. Create a feature branch
3. Write tests for new functionality
4. Ensure all tests pass
5. Submit a pull request

License
-------

[](#license)

The MIT License (MIT). See [LICENSE](LICENSE) for details.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance68

Regular maintenance activity

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity35

Early-stage or recently created project

 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

340d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (6 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-open-ai-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-open-ai-bundle/health.svg)](https://phpackages.com/packages/tourze-open-ai-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M647](/packages/sylius-sylius)[contao/core-bundle

Contao Open Source CMS

1231.6M2.3k](/packages/contao-core-bundle)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M151](/packages/sulu-sulu)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)[netgen/layouts-core

Netgen Layouts enables you to build and manage complex web pages in a simpler way and with less coding. This is the core of Netgen Layouts, its heart and soul.

3689.4k10](/packages/netgen-layouts-core)

PHPackages © 2026

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