Download the PHP package creativecrafts/laravel-ai-assistant without Composer

On this page you can find all versions of the php package creativecrafts/laravel-ai-assistant. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-ai-assistant

Laravel AI Assistant

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Laravel AI Assistant is an enterprise-grade, comprehensive package designed to seamlessly integrate OpenAI's powerful language models into your Laravel applications. It provides an easy-to-use, fluent API with advanced features including streaming responses, background job processing, lazy loading optimization, comprehensive metrics collection, robust security controls, and sophisticated error handling. Perfect for building production-ready AI-powered applications with enterprise-level reliability and performance.


🔄 Migration Guide (Version 3.x is current in beta and not ready for production)

Upgrading to Latest Version

From v2.x to v3.x

From v1.x to v2.x

Migration Steps

  1. Update Dependencies:

  2. Update Configuration:

  3. Update Environment Variables:

    • Review your .env file against the new configuration options
    • Update any deprecated environment variables
  4. Test Your Implementation:

    • Run your test suite to ensure compatibility
    • Check for any deprecated method usage
  5. Update Database (if using Eloquent persistence):

Deprecated Features

For detailed migration instructions, see the migration documentation.


Table of Contents


Overview

Laravel AI Assistant simplifies the integration of AI models into your Laravel application with enterprise-grade features. Whether you're building a conversational chatbot, automating content creation, transcribing audio files, or processing large-scale AI operations, this package provides a clean, expressive API to handle complex tasks with minimal effort.

The package now includes advanced architectural improvements:


⚡ Quick Start (5 Minutes)

Get up and running with Laravel AI Assistant in just 5 minutes:

1. Install the Package

2. Set Your API Key

Add your OpenAI API key to your .env file:

3. Publish Configuration (Optional)

4. Start Using AI Assistant

5. Enable Advanced Features (Optional)

For production use, consider enabling these features in your .env:

That's it! You now have a powerful AI assistant integrated into your Laravel application. Continue reading for advanced features and configuration options.


Features

Core Features

Advanced Features


Choosing the right class

Pick the entrypoint that best matches your use case:

Quick examples

When to choose which

See also: Migration Guide in docs/Migrate_from_AssistantAPI_to_ResponseAPI.md.

Installation

You can install the package via composer:

You can publish the config file with:


Configuration

After publishing, you will find a configuration file at config/ai-assistant.php. The configuration includes:

API Credentials

Set your OpenAI API key and organization:

Note:

Model Settings

Configure your default models for different operations:

Advanced Configuration

Configure advanced features like streaming, caching, and security:


Core Usage

Initializing the Assistant

Create a new assistant instance using the fluent API:

Basic Chat Operations

Configure and send chat messages:

Audio Transcription

Transcribe audio files with language specification:

Creating AI Assistants

Create and configure AI assistants with custom tools:


Advanced Features

Streaming Service

The streaming service provides real-time response processing with advanced memory management and performance monitoring.

Basic Streaming Usage

Advanced Streaming Configuration

Streaming Metrics

Background Jobs

Queue long-running AI operations with progress tracking and retry mechanisms.

Queuing Operations

Batch Operations

Job Monitoring

Lazy Loading

Optimize resource usage with intelligent lazy initialization of AI models and HTTP clients.

Resource Registration

AI Model Lazy Loading

Performance Metrics

Metrics Collection

Comprehensive monitoring and analytics for API usage, performance, and costs.

API Monitoring

Performance Analysis

System Health Monitoring

Security Features

Advanced security controls including API key validation, rate limiting, and request integrity.

API Key Validation

Rate Limiting

Request Integrity

Data Sanitization

Performance Optimizations

Memory Management

Caching Strategies

Advanced Caching Configuration

Configure caching for optimal performance in your environment variables:

Cache Best Practices

Queue Configuration for Background Jobs

Configure background job processing for better scalability:

Environment Configuration
Queue Setup Examples
Redis Queue Configuration

Load Testing and Performance Verification

Performance Benchmarking

Run the included performance tests to verify package performance:

Load Testing Setup

Create load testing scenarios for your application:

Production Load Testing

Use tools like Apache Bench or Siege for production load testing:

Performance Monitoring

Set up comprehensive metrics collection:

Scaling Best Practices

  1. Queue Management: Use dedicated queue workers for AI processing
  2. Connection Pooling: Enable HTTP connection pooling for better throughput
  3. Caching Strategy: Implement multi-layer caching (Redis + Application)
  4. Resource Monitoring: Set up alerts for memory and performance thresholds
  5. Load Balancing: Distribute requests across multiple application instances
  6. Rate Limiting: Implement appropriate rate limiting for API endpoints

Error Handling & Exceptions

The package includes 8+ custom exception types for precise error handling:

Exception Types

Exception Handling Examples

Configuration Validation


Best Practices

Performance Best Practices

  1. Use Streaming for Real-time Applications

  2. Queue Long-running Operations

  3. Implement Lazy Loading for Resources

Security Best Practices

  1. Always Validate API Keys

  2. Implement Rate Limiting

  3. Sanitize Sensitive Data in Logs

Monitoring Best Practices

  1. Enable Comprehensive Metrics

  2. Set Up Health Monitoring

  3. Monitor Token Usage and Costs

Cookbook

Chat with JSON output

Tips:

Function calling with a Laravel job executor (queue)

This recipe demonstrates enabling queued function (tool) execution. The executor dispatches tool calls as jobs and returns an inline result for determinism while the job runs in your queue.

1) Configure the executor to queue

2) Define a callable tool and let the assistant invoke it

Notes:

Troubleshooting:

Attach files and enable file search (vector stores)

Variants:


📊 Performance Benchmarks

Laravel AI Assistant is optimized for enterprise-scale applications. Below are performance metrics and optimization recommendations:

Benchmark Results

Response Times (Average)

Throughput (With Connection Pooling)

Performance Optimization Tips

1. Enable Connection Pooling

Impact: 30-50% improvement in response times for multiple requests

2. Use Background Jobs for Long Operations

Impact: Prevents blocking the main thread, improves user experience

3. Optimize Streaming Configuration

Impact: 60-80% faster perceived response times for long responses

4. Configure Memory Monitoring

Impact: Prevents memory exhaustion, maintains system stability

5. Enable Metrics Collection

Impact: Provides insights for further optimization

Model-Specific Performance

Model Avg Response Time Tokens/Sec Best Use Case
gpt-5 1.2s 80-120 Complex reasoning, latest features
gpt-4o 0.8s 120-180 Balanced performance and capability
gpt-4o-mini 0.4s 200-300 Simple tasks, high throughput

Scaling Recommendations

Small Applications (< 1,000 requests/day)

Medium Applications (1,000 - 50,000 requests/day)

Large Applications (> 50,000 requests/day)

Monitoring & Profiling

The package provides built-in performance monitoring:


Examples

Example 1: Building a Chat Interface with Streaming

Example 2: Background Processing with Progress Tracking

Example 3: Advanced AI Assistant with Custom Tools

Example 4: Comprehensive Monitoring Dashboard


Environment Variables

Add the following to your .env file:

Notes:


🔧 Troubleshooting

Common issues and their solutions when working with Laravel AI Assistant:

Installation & Configuration Issues

Issue: "Class 'OpenAI\Client' not found"

Solution:

Issue: "OPENAI_API_KEY environment variable is required"

Solution:

  1. Add your API key to .env:

  2. Clear config cache:

Issue: Service provider not loading

Solution:

Runtime Issues

Issue: "Connection timeout" errors

Symptoms: Requests taking too long or timing out Solutions:

  1. Increase timeout values:

  2. Enable connection pooling:

Issue: High memory usage

Symptoms: Memory exhaustion during large operations Solutions:

  1. Enable memory monitoring:

  2. Use background jobs for large operations:

Issue: "Rate limit exceeded" errors

Symptoms: 429 HTTP status codes from OpenAI Solutions:

  1. Enable retry mechanism:

  2. Implement request queuing:

Database & Persistence Issues

Issue: "Table doesn't exist" when using Eloquent persistence

Solution:

Issue: Eloquent models not found

Solution:

Performance Issues

Issue: Slow response times

Diagnostic Steps:

  1. Check your model selection:

  2. Enable streaming for better perceived performance:

  3. Use connection pooling:

Issue: Queue jobs not processing

Solution:

  1. Ensure queue worker is running:

  2. Check queue configuration:

API & Authentication Issues

Issue: "Invalid API key" errors

Solutions:

  1. Verify your API key format (starts with sk-):

  2. Check API key permissions in OpenAI dashboard
  3. Ensure no extra spaces in .env file

Issue: Organization access errors

Solution:

Streaming Issues

Issue: Streaming responses not working

Solutions:

  1. Check if streaming is enabled:

  2. Verify buffer settings:

  3. Ensure proper headers in your frontend:

Development & Testing Issues

Issue: Tests failing with API key errors

Solution: Use the test configuration override:

Issue: Mock responses not working

Solution:

Debug Mode

Enable debug logging for troubleshooting:

Then check your Laravel logs:

Getting Help

If you're still experiencing issues:

  1. Check the logs: Laravel logs often contain detailed error information
  2. Review configuration: Compare your config with the defaults
  3. Test with minimal setup: Try with basic configuration first
  4. Check GitHub issues: Search existing issues for similar problems
  5. Create an issue: Provide detailed error messages and configuration

Useful Commands for Debugging


Testing

Bootstrap: tests/Pest.php applies the shared TestCase across the test suite. The shared tests/TestCase.php configures:

If you author tests that boot the app outside the shared TestCase, set this config key manually inside the test or provide OPENAI_API_KEY in env to avoid ConfigurationValidationException during package boot.

The package has 100% code and mutation test coverage. Run tests using:


Compatibility


Changelog

Please see CHANGELOG for more information on what has changed recently.


Contributing

Please see CONTRIBUTING for details on how to contribute to this package.


Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.


Credits


License

The MIT License (MIT). Please see License File for more information.


Responses + Conversations (New API)

This package now uses OpenAI's Responses + Conversations APIs under the hood. Below are copy‑paste examples that match the current fluent methods and payload shapes.

Quickstart: Start and use a conversation

To continue the same conversation:

Instructions (system/developer persona)

Tool choice and response format (json_schema)

File search and attachments

Disable auto file_search insertion if you want to pass file_ids but avoid the tool:

Images: from file and by URL

Streaming with onEvent and shouldStop

Cancel an in‑flight response

Continue a turn with tool results

Deprecation notes (legacy Assistants/Threads/Runs)

The following legacy methods are deprecated. Use the new replacements:

See docs/Migrate_from_AssistantAPI_to_ResponseAPI.md for the complete migration guide.

QA checklist for examples


Additional Documentation


Migration Guide (2.0)

This release introduces a unified, typed, Laravel-native API while preserving backwards compatibility. Here’s how to migrate gradually.

Key goals

Recommended new entrypoint

Files and Tools helpers

Backwards compatibility and deprecations

Why DTOs?

Minimal migration examples

Notes


All versions of laravel-ai-assistant with dependencies

PHP Build Version
Package Version
Requires php Version ^8.3|^8.2
guzzlehttp/guzzle Version ^7.9
illuminate/contracts Version ^12|^11|^10.0
spatie/laravel-package-tools Version ^1.19
symfony/http-client Version ^6.3|^7.2
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package creativecrafts/laravel-ai-assistant contains the following files

Loading the files please wait ....