PHP code example of omarseyam / laravel-chatbot

1. Go to this page and download the library: Download omarseyam/laravel-chatbot library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

omarseyam / laravel-chatbot example snippets


return [
    'assistant' => \App\Ai\Agents\ExampleAgent::class,
];

use App\Ai\Data\ChatRequest;
use App\Ai\Services\ChatService;

$response = app(ChatService::class)->ask(new ChatRequest(
    prompt: 'What can you help me with?',
    conversationId: null, // pass an existing conversation id to continue it
    agent: 'assistant',
));

// $response = ['conversation_id' => '...', 'content' => '...' | [...]]



namespace App\Ai\Agents;

use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\Conversational;
use Laravel\Ai\Contracts\HasStructuredOutput;
use Laravel\Ai\Contracts\HasTools;
use Laravel\Ai\Messages\Message;
use Laravel\Ai\Promptable;
use Stringable;

class ExampleAgent implements Agent, Conversational, HasTools, HasStructuredOutput
{
    use Promptable;

    public function __construct(public ?array $messages = null) {}

    /**
     * Get the instructions that the agent should follow.
     */
    public function instructions(): Stringable|string
    {
        return "Your role is ...";
    }

    /**
     * Get the list of messages comprising the conversation so far.
     *
     * @return Message[]
     */
    public function messages(): iterable
    {
        return $this->messages ?? [];
    }
}

AgentConversationMessage::query()
    ->where('conversation_id', $conversationId)
    ->oldest()
    ->select('role', 'content', 'structured')
    ->get();

// On your model:
public function conversation(): BelongsTo
{
    return $this->belongsTo(AgentConversation::class, 'conversation_id');
}

// On AgentConversation, replacing the example post() relation:
public function yourModel(): HasOne // or HasMany
{
    return $this->hasOne(YourModel::class, 'conversation_id');
}

use Illuminate\Support\Facades\Schedule;

Schedule::command('model:prune')->daily();

   // routes/web.php
   Route::post('/ai/chat', function (\Illuminate\Http\Request $request) {
       return app(\App\Ai\Services\ChatService::class)->ask(new \App\Ai\Data\ChatRequest(
           prompt: $request->string('prompt')->toString(),
           conversationId: $request->input('conversation_id'),
           agent: 'assistant',
       ));
   })->middleware('auth');
   
bash
php artisan vendor:publish --provider="Laravel\Ai\AiServiceProvider"
php artisan migrate