Laravel AI Assistant is a comprehensive package designed to seamlessly integrate OpenAI’s powerful language models into your Laravel applications. It provides an easy-to-use, fluent API to configure, manage, and interact with AI-driven chatbots, audio transcription services, custom function calls, and additional advanced tools.
- Overview
- Features
- Installation
- Configuration
- Usage
- Data Transfer Objects (DTOs) and Factories
- Configuration File
- Error Handling
- Examples
- Contributing
- License
Laravel AI Assistant simplifies the integration of AI models into your Laravel application. Whether you’re building a conversational chatbot, automating content creation, or transcribing audio files, this package provides a clean, expressive API to handle complex tasks with minimal effort.
It leverages OpenAI’s API to:
- Generate chat completions
- Process audio transcriptions using Whisper
- Manage custom function calls for dynamic workflows
- Support advanced configurations like streaming, caching, and tool integrations
- Fluent API: Chain method calls for a clean and intuitive setup.
- Chat Messaging: Easily manage user, developer, and tool messages.
- Audio Transcription: Convert audio files to text with optional prompts.
- Tool Integration: Extend functionality with file search, code interpreter, and custom function call tools.
- Custom Configuration: Configure model parameters, temperature, top_p, and more.
- DTOs & Factories: Use data transfer objects to structure and validate your data.
- Error Handling: Robust exception handling for file operations and API interactions.
- Caching & Streaming: Optimize chat workflows with caching and streaming options.
You can install the package via composer:
composer require creativecrafts/laravel-ai-assistant
You can publish the config file with:
php artisan vendor:publish --tag="ai-assistant-config"
After publishing, you will find a configuration file at config/ai-assistant.php. This file includes settings for:
Set your OpenAI API key and organization:
'api_key' => env('OPENAI_API_KEY', null),
'organization' => env('OPENAI_ORGANIZATION', null),
Choose your default models for chat, editing, and audio transcription:
'model' => env('OPENAI_CHAT_MODEL', 'gpt-3.5-turbo'),
'chat_model' => env('OPENAI_CHAT_MODEL', 'gpt-3.5-turbo'),
'edit_model' => 'gpt-4o',
'audio_model' => 'whisper-1',
Configure parameters such as temperature, top_p, max tokens, streaming options, stop sequences, etc.:
'temperature' => 0.3,
'top_p' => 1,
'max_completion_tokens' => 400,
'stream' => false,
'n' => 1,
'stop' => null,
'suffix' => null,
'presence_penalty' => 0,
'frequency_penalty' => 0,
'best_of' => 1,
Define the roles for AI responses and user messages:
'ai_role' => 'assistant',
'user_role' => 'user',
Create a new assistant instance using the fluent API:
use CreativeCrafts\LaravelAiAssistant\Tasks\AiAssistant;
$assistant = AiAssistant::init();
Configure the model, temperature, and other parameters:
$assistant->setModelName('gpt-3.5-turbo')
->adjustTemperature(0.7)
->setDeveloperMessage('Please maintain a friendly tone.')
->setUserMessage('What is the weather like today?');
Send your chat message and retrieve a response:
$response = $assistant->sendChatMessage();
You can also manage caching of chat messages, adjust the maximum number of tokens, or define stop sequences using dedicated methods.
Transcribe audio files by setting the file path and specifying language and an optional prompt:
$assistant->setFilePath('/path/to/audio.mp3');
$transcription = $assistant->transcribeTo('en', 'Transcribe the following audio:');
Integrate additional tools like custom function calls, code interpreter, or file search:
// Adding a custom function tool
$assistant->includeFunctionCallTool(
'calculateSum',
'Calculates the sum of two numbers',
['num1' => 'number', 'num2' => 'number'],
isStrict: true,
requiredParameters: ['num1', 'num2']
);
The package includes several DTOs and factory classes to structure data consistently: • CreateAssistantData: Used when creating a new assistant. • ChatCompletionData: Represents data for chat completions. • ChatAssistantMessageData: Structures assistant messages. • TranscribeToData: Structures data for audio transcription requests. • CustomFunctionData: Represents custom function tool data.
Each DTO includes a toArray() method to facilitate easy conversion and integration with the API.
This is the contents of the published config file:
The config/ai-assistant.php file allows you to customize settings such as API credentials, model names, temperature, top_p, and more. Adjust these settings to fit your use case:
return [
'api_key' => env('OPENAI_API_KEY', null),
'organization' => env('OPENAI_ORGANIZATION', null),
'model' => env('OPENAI_CHAT_MODEL', 'gpt-3.5-turbo'),
'temperature' => 0.3,
'top_p' => 1,
'max_completion_tokens' => 400,
'stream' => false,
'n' => 1,
'stop' => null,
'chat_model' => env('OPENAI_CHAT_MODEL', 'gpt-3.5-turbo'),
'ai_role' => 'assistant',
'user_role' => 'user',
'edit_model' => 'gpt-4o',
'audio_model' => 'whisper-1',
];
The package provides robust error handling: • File Operations: Methods like openFile() throw a RuntimeException if the file cannot be opened. • API Interactions: The create() method catches exceptions from OpenAI and rethrows them as a CreateNewAssistantException with a descriptive message. • Validation: Methods that require specific parameters (e.g., audio voice and format for audio output) throw an InvalidArgumentException when expectations are not met.
use CreativeCrafts\LaravelAiAssistant\AiAssistant;
$assistant = AiAssistant::init()
->setModelName('gpt-3.5-turbo')
->adjustTemperature(0.7)
->setDeveloperMessage('Maintain a formal tone.')
->setUserMessage('Tell me a joke.')
->sendChatMessage();
use CreativeCrafts\LaravelAiAssistant\AiAssistant;
$transcription = AiAssistant::init()
->setFilePath('/path/to/audio.mp3');
->transcribeTo('en', 'Transcribe this audio:');
use CreativeCrafts\LaravelAiAssistant\AiAssistant;
$response = AiAssistant::init()
->includeFunctionCallTool(
'calculateSum',
'Calculates the sum of two numbers',
['num1' => 'number', 'num2' => 'number'],
isStrict: true,
requiredParameters: ['num1', 'num2']
)
->create();
use CreativeCrafts\LaravelAiAssistant\AiAssistant;
$assistant = AiAssistant::init()
->setModelName('gpt-4') // Optional, defaults to config default model
->adjustTemperature(0.5) // Optional defaults to 0.7
->setAssistantName('My Assistant') // Optional, defaults to '' and Open Ai will assign random name
->setAssistantDescription('An assistant for handling tasks') // Optional, defaults to ''
->setInstructions('Be as helpful as possible.') // Optional, defaults to ''
->create();
use CreativeCrafts\LaravelAiAssistant\AiAssistant;
$response = \CreativeCrafts\LaravelAiAssistant\AiAssistant::init()
->setAssistantId($assistantId) // Required
->createTask() // Can optionally pass a list of tasks as an array, defaults to []
->askQuestion('Translate this text to French: "Hello, how are you?"')
->process()
->response(); // returns the response from the assistant as a string
• Create and manage AI assistants.
• Set models, temperature, and custom instructions for the assistant.
• Utilize tools like code interpretation, file search, and custom function calls.
• Interact with assistants via threads for tasks like message completion, chat, and task processing.
• Supports both synchronous and streamed completions.
• Handle audio transcription and translation with OpenAI models.
init(): Assistant: Initializes the AI assistant.
• setModelName(string $modelName): Assistant: Sets the model name for the AI assistant.
• adjustTemperature(int|float $temperature): Assistant: Adjusts the assistant’s response temperature.
• setAssistantName(string $assistantName): Assistant: Sets the name for the assistant.
• setAssistantDescription(string $assistantDescription): Assistant: Sets the assistant’s description.
• setInstructions(string $instructions): Assistant: Sets instructions for the assistant.
• includeCodeInterpreterTool(array $fileIds = []): Assistant: Adds the code interpreter tool to the assistant.
• includeFileSearchTool(array $vectorStoreIds = []): Assistant: Adds the file search tool to the assistant.
• includeFunctionCallTool(...): Assistant: Adds a function call tool to the assistant.
• create(): NewAssistantResponseData: Creates the assistant using the specified configurations.
• assignAssistant(string $assistantId): Assistant: Assigns an existing assistant by ID.
• createTask(array $parameters = []): Assistant: Creates a new task thread for interactions.
• askQuestion(string $message): Assistant: Asks a question in the task thread.
• process(): Assistant: Processes the task thread.
• response(): string: Retrieves the assistant’s response.
. setAssistantId(string $assistantId): Assistant: Sets the assistant ID for the current interaction.
• Create and upload files for code interpretation, then assign it to a specific assistant.
• Create and upload vector store, then attach the vector store ids to an assistant.
• Get a list of all created assistant.
• Get a list of all created files.
• Get a list of all created vector stores.
• Update assistant.
• Delete assistant.
If you have any feature requests or suggestions, please feel free to open an issue or submit a pull request.
This fork is compatible with OpenAI API as of August 2024. It uses the gpt-3.5-turbo model by default, but you can specify gpt-4 or other available models in your configuration if you have access to them.
OPENAI_API_KEY=
OPENAI_ORGANIZATION=
OPENAI_CHAT_MODEL=
The package now has 100% code and mutation test coverage. You can run the tests using the following command:
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.