├── public ├── favicon.ico ├── robots.txt ├── index.php └── .htaccess ├── resources ├── css │ └── app.css ├── js │ ├── app.js │ └── bootstrap.js └── views │ └── welcome.blade.php ├── database ├── .gitignore ├── seeders │ └── DatabaseSeeder.php ├── migrations │ ├── 2024_09_01_072614_create_session_table.php │ ├── 0001_01_01_000001_create_cache_table.php │ ├── 0001_01_01_000000_create_users_table.php │ └── 0001_01_01_000002_create_jobs_table.php └── factories │ └── UserFactory.php ├── bootstrap ├── cache │ └── .gitignore ├── providers.php └── app.php ├── storage ├── logs │ └── .gitignore ├── app │ ├── public │ │ └── .gitignore │ └── .gitignore └── framework │ ├── testing │ └── .gitignore │ ├── views │ └── .gitignore │ ├── cache │ ├── data │ │ └── .gitignore │ └── .gitignore │ ├── sessions │ └── .gitignore │ └── .gitignore ├── app ├── Http │ └── Controllers │ │ └── Controller.php ├── Agents │ ├── CodeReviewer │ │ ├── ReadFileInput.php │ │ ├── ListProjectInput.php │ │ ├── CodeReviewAgentFactory.php │ │ ├── ReviewInput.php │ │ ├── ListProjectTool.php │ │ ├── ReviewTool.php │ │ ├── ReadFileTool.php │ │ └── CodeReviewAgent.php │ ├── Delivery │ │ ├── OrderNumberInput.php │ │ ├── ProfileInput.php │ │ ├── DeliveryAgentFactory.php │ │ ├── DeliveryDateInput.php │ │ ├── StatusCheckOutput.php │ │ ├── GetOrderNumberTool.php │ │ ├── GetProfileTool.php │ │ ├── GetDeliveryDateTool.php │ │ └── DeliveryAgent.php │ ├── TaskSplitter │ │ ├── ProjectDescriptionInput.php │ │ ├── TaskSplitterAgentFactory.php │ │ ├── TaskCreateInput.php │ │ ├── TaskCreateTool.php │ │ ├── GetProjectDescription.php │ │ └── TaskSplitterAgent.php │ ├── DynamicMemoryTool │ │ ├── DynamicMemoryInput.php │ │ ├── Memories.php │ │ ├── DynamicMemoryTool.php │ │ └── DynamicMemoryService.php │ ├── AgentsCaller │ │ ├── AskAgentInput.php │ │ └── AskAgentTool.php │ └── SmartHome │ │ └── DeviceStateManager.php ├── Models │ ├── Casts │ │ ├── Uuid.php │ │ └── History.php │ ├── User.php │ ├── ValueObject │ │ └── History.php │ └── Session.php ├── Chat │ ├── PromptGenerator │ │ ├── Dump.php │ │ └── SessionContextInjector.php │ ├── ChatHistoryRepository.php │ └── SimpleChatService.php ├── Console │ └── Commands │ │ ├── ToolListCommand.php │ │ ├── ChatWindowCommand.php │ │ ├── AgentListCommand.php │ │ └── ChatSessionCommand.php ├── Providers │ ├── AppServiceProvider.php │ ├── AgentsChatServiceProvider.php │ ├── AgentsServiceProvider.php │ └── SmartHomeServiceProvider.php └── Event │ └── ChatEventsListener.php ├── routes ├── web.php └── console.php ├── tests ├── TestCase.php ├── Unit │ └── ExampleTest.php └── Feature │ └── ExampleTest.php ├── .gitattributes ├── package.json ├── vite.config.js ├── Makefile ├── .editorconfig ├── .gitignore ├── artisan ├── config ├── openai.php ├── services.php ├── agents.php ├── filesystems.php ├── cache.php ├── mail.php ├── queue.php ├── auth.php ├── app.php ├── logging.php ├── database.php └── session.php ├── phpunit.xml ├── .env.example ├── docker-compose.yml ├── composer.json └── README.md /public/favicon.ico: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /resources/css/app.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /database/.gitignore: -------------------------------------------------------------------------------- 1 | *.sqlite* 2 | -------------------------------------------------------------------------------- /bootstrap/cache/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /resources/js/app.js: -------------------------------------------------------------------------------- 1 | import './bootstrap'; 2 | -------------------------------------------------------------------------------- /storage/logs/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | User-agent: * 2 | Disallow: 3 | -------------------------------------------------------------------------------- /storage/app/public/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /storage/app/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !public/ 3 | !.gitignore 4 | -------------------------------------------------------------------------------- /storage/framework/testing/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /storage/framework/views/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /storage/framework/cache/data/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /storage/framework/sessions/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /storage/framework/cache/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !data/ 3 | !.gitignore 4 | -------------------------------------------------------------------------------- /app/Http/Controllers/Controller.php: -------------------------------------------------------------------------------- 1 | comment(Inspiring::quote()); 8 | })->purpose('Display an inspiring quote')->hourly(); 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "type": "module", 4 | "scripts": { 5 | "dev": "vite", 6 | "build": "vite build" 7 | }, 8 | "devDependencies": { 9 | "axios": "^1.6.4", 10 | "laravel-vite-plugin": "^1.0", 11 | "vite": "^5.0" 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /vite.config.js: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite'; 2 | import laravel from 'laravel-vite-plugin'; 3 | 4 | export default defineConfig({ 5 | plugins: [ 6 | laravel({ 7 | input: ['resources/css/app.css', 'resources/js/app.js'], 8 | refresh: true, 9 | }), 10 | ], 11 | }); 12 | -------------------------------------------------------------------------------- /tests/Unit/ExampleTest.php: -------------------------------------------------------------------------------- 1 | assertTrue(true); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | up: 2 | ./vendor/bin/sail up -d 3 | ./vendor/bin/sail exec laravel.test php artisan migrate 4 | 5 | down: 6 | ./vendor/bin/sail down 7 | 8 | restart: 9 | ./vendor/bin/sail down 10 | ./vendor/bin/sail up -d 11 | 12 | chat: 13 | ./vendor/bin/sail artisan chat 14 | 15 | bash: 16 | ./vendor/bin/sail exec laravel.test /bin/bash 17 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | indent_size = 4 7 | indent_style = space 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | trim_trailing_whitespace = false 13 | 14 | [*.{yml,yaml}] 15 | indent_size = 2 16 | 17 | [docker-compose.yml] 18 | indent_size = 4 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.phpunit.cache 2 | /node_modules 3 | /public/build 4 | /public/hot 5 | /public/storage 6 | /storage/*.key 7 | /vendor 8 | composer.lock 9 | .env 10 | .env.backup 11 | .env.production 12 | .phpactor.json 13 | .phpunit.result.cache 14 | Homestead.json 15 | Homestead.yaml 16 | auth.json 17 | npm-debug.log 18 | yarn-error.log 19 | /.fleet 20 | /.idea 21 | /.vscode 22 | -------------------------------------------------------------------------------- /app/Agents/CodeReviewer/ReadFileInput.php: -------------------------------------------------------------------------------- 1 | handleCommand(new ArgvInput); 14 | 15 | exit($status); 16 | -------------------------------------------------------------------------------- /app/Agents/CodeReviewer/ListProjectInput.php: -------------------------------------------------------------------------------- 1 | get('/'); 16 | 17 | $response->assertStatus(200); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /bootstrap/providers.php: -------------------------------------------------------------------------------- 1 | handleRequest(Request::capture()); 18 | -------------------------------------------------------------------------------- /app/Agents/DynamicMemoryTool/DynamicMemoryInput.php: -------------------------------------------------------------------------------- 1 | create(); 17 | 18 | User::factory()->create([ 19 | 'name' => 'Test User', 20 | 'email' => 'test@example.com', 21 | ]); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /bootstrap/app.php: -------------------------------------------------------------------------------- 1 | withRouting( 9 | web: __DIR__.'/../routes/web.php', 10 | commands: __DIR__.'/../routes/console.php', 11 | health: '/up', 12 | ) 13 | ->withMiddleware(function (Middleware $middleware) { 14 | // 15 | }) 16 | ->withExceptions(function (Exceptions $exceptions) { 17 | // 18 | })->create(); 19 | -------------------------------------------------------------------------------- /app/Models/Casts/Uuid.php: -------------------------------------------------------------------------------- 1 | toString(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /app/Agents/Delivery/StatusCheckOutput.php: -------------------------------------------------------------------------------- 1 | prompt->format()); 19 | 20 | return $next($input); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /app/Console/Commands/ToolListCommand.php: -------------------------------------------------------------------------------- 1 | all() as $tool) { 17 | $rows[] = [$tool->getName(), $tool->getDescription()]; 18 | } 19 | 20 | $this->table(['Tool', 'Description'], $rows); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /public/.htaccess: -------------------------------------------------------------------------------- 1 | 2 | 3 | Options -MultiViews -Indexes 4 | 5 | 6 | RewriteEngine On 7 | 8 | # Handle Authorization Header 9 | RewriteCond %{HTTP:Authorization} . 10 | RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] 11 | 12 | # Redirect Trailing Slashes If Not A Folder... 13 | RewriteCond %{REQUEST_FILENAME} !-d 14 | RewriteCond %{REQUEST_URI} (.+)/$ 15 | RewriteRule ^ %1 [L,R=301] 16 | 17 | # Send Requests To Front Controller... 18 | RewriteCond %{REQUEST_FILENAME} !-d 19 | RewriteCond %{REQUEST_FILENAME} !-f 20 | RewriteRule ^ index.php [L] 21 | 22 | -------------------------------------------------------------------------------- /app/Agents/DynamicMemoryTool/Memories.php: -------------------------------------------------------------------------------- 1 | */ 16 | public array $memories = [], 17 | ) {} 18 | 19 | public function addMemory(SolutionMetadata $metadata): void 20 | { 21 | $this->memories[] = $metadata; 22 | } 23 | 24 | public function getIterator(): Traversable 25 | { 26 | yield from $this->memories; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /app/Agents/CodeReviewer/ListProjectTool.php: -------------------------------------------------------------------------------- 1 | 11 | */ 12 | final class ListProjectTool extends PhpTool 13 | { 14 | public const NAME = 'list_project'; 15 | 16 | public function __construct() 17 | { 18 | parent::__construct( 19 | name: self::NAME, 20 | inputSchema: ListProjectInput::class, 21 | description: 'List all files in a project with the given project name.', 22 | ); 23 | } 24 | 25 | public function execute(object $input): string 26 | { 27 | // Implementation to list project files 28 | return json_encode(['files' => ['file1.php', 'file2.php']]); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /app/Agents/CodeReviewer/ReviewTool.php: -------------------------------------------------------------------------------- 1 | 11 | */ 12 | final class ReviewTool extends PhpTool 13 | { 14 | public const NAME = 'submit_review'; 15 | 16 | public function __construct() 17 | { 18 | parent::__construct( 19 | name: self::NAME, 20 | inputSchema: ReviewInput::class, 21 | description: 'Submit a code review for a pull request. Call this whenever you need to submit a code review for a pull request.', 22 | ); 23 | } 24 | 25 | public function execute(object $input): string 26 | { 27 | // Implementation to submit code review 28 | return json_encode(['status' => 'OK']); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /app/Models/Casts/History.php: -------------------------------------------------------------------------------- 1 | 11 | */ 12 | final class GetOrderNumberTool extends PhpTool 13 | { 14 | public const NAME = 'get_order_number'; 15 | 16 | public function __construct() 17 | { 18 | parent::__construct( 19 | name: self::NAME, 20 | inputSchema: OrderNumberInput::class, 21 | description: 'Get the order number for a customer.', 22 | ); 23 | } 24 | 25 | public function execute(object $input): string 26 | { 27 | return \json_encode([ 28 | 'customer_id' => $input->customerId, 29 | 'customer' => 'John Doe', 30 | 'order_number' => 'abc-' . $input->customerId, 31 | ]); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /app/Agents/Delivery/GetProfileTool.php: -------------------------------------------------------------------------------- 1 | 11 | */ 12 | final class GetProfileTool extends PhpTool 13 | { 14 | public const NAME = 'get_profile'; 15 | 16 | public function __construct() 17 | { 18 | parent::__construct( 19 | name: self::NAME, 20 | inputSchema: ProfileInput::class, 21 | description: 'Get the customer\'s profile information.', 22 | ); 23 | } 24 | 25 | public function execute(object $input): string 26 | { 27 | return \json_encode([ 28 | 'account_uuid' => $input->accountId, 29 | 'first_name' => 'John', 30 | 'last_name' => 'Doe', 31 | 'age' => \rand(10, 100), 32 | ]); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /app/Console/Commands/ChatWindowCommand.php: -------------------------------------------------------------------------------- 1 | input, 22 | output: $this->output, 23 | chatHistory: $chatHistory, 24 | chat: $chatService, 25 | ); 26 | 27 | $chatWindow->run(Uuid::fromString($this->argument('session_uuid'))); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /app/Agents/TaskSplitter/TaskCreateInput.php: -------------------------------------------------------------------------------- 1 | 12 | */ 13 | final class GetDeliveryDateTool extends PhpTool 14 | { 15 | public const NAME = 'get_delivery_date'; 16 | 17 | public function __construct() 18 | { 19 | parent::__construct( 20 | name: self::NAME, 21 | inputSchema: DeliveryDateInput::class, 22 | description: 'Get the delivery date for a customer\'s order. Call this whenever you need to know the delivery date, for example when a customer asks \'Where is my package\'', 23 | ); 24 | } 25 | 26 | public function execute(object $input): string 27 | { 28 | return \json_encode([ 29 | 'delivery_date' => Carbon::now()->addDays(\rand(1, 100))->toDateString(), 30 | ]); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /database/migrations/2024_09_01_072614_create_session_table.php: -------------------------------------------------------------------------------- 1 | uuid('id')->primary(); 16 | $table->uuid('account_uuid'); 17 | $table->string('agent_name'); 18 | $table->string('title')->nullable(); 19 | $table->json('history')->nullable(); 20 | $table->timestamp('finished_at')->nullable(); 21 | $table->softDeletes(); 22 | $table->timestamps(); 23 | }); 24 | } 25 | 26 | /** 27 | * Reverse the migrations. 28 | */ 29 | public function down(): void 30 | { 31 | Schema::dropIfExists('session'); 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /app/Providers/AppServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->singleton(EventDispatcherInterface::class, function () { 18 | return new class implements EventDispatcherInterface { 19 | public function dispatch(object $event): object 20 | { 21 | Event::dispatch($event); 22 | return $event; 23 | } 24 | }; 25 | }); 26 | } 27 | 28 | /** 29 | * Bootstrap any application services. 30 | */ 31 | public function boot(): void 32 | { 33 | Event::subscribe(ChatEventsListener::class); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /database/migrations/0001_01_01_000001_create_cache_table.php: -------------------------------------------------------------------------------- 1 | string('key')->primary(); 16 | $table->mediumText('value'); 17 | $table->integer('expiration'); 18 | }); 19 | 20 | Schema::create('cache_locks', function (Blueprint $table) { 21 | $table->string('key')->primary(); 22 | $table->string('owner'); 23 | $table->integer('expiration'); 24 | }); 25 | } 26 | 27 | /** 28 | * Reverse the migrations. 29 | */ 30 | public function down(): void 31 | { 32 | Schema::dropIfExists('cache'); 33 | Schema::dropIfExists('cache_locks'); 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /app/Console/Commands/AgentListCommand.php: -------------------------------------------------------------------------------- 1 | info('Available agents:'); 17 | 18 | $rows = []; 19 | foreach ($agents->all() as $agent) { 20 | $tools = \array_map(static fn(ToolLink $tool): string => '- ' . $tool->getName(), $agent->getTools()); 21 | $rows[] = [ 22 | $agent->getKey() . PHP_EOL . '- ' . $agent->getModel()->name, 23 | \implode(PHP_EOL, $tools), 24 | \wordwrap($agent->getDescription(), 50, "\n", true), 25 | ]; 26 | } 27 | 28 | $this->table(['Agent', 'Tools', 'Description'], $rows); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /config/openai.php: -------------------------------------------------------------------------------- 1 | env('OPENAI_API_KEY'), 16 | 'organization' => env('OPENAI_ORGANIZATION'), 17 | 18 | /* 19 | |-------------------------------------------------------------------------- 20 | | Request Timeout 21 | |-------------------------------------------------------------------------- 22 | | 23 | | The timeout may be used to specify the maximum number of seconds to wait 24 | | for a response. By default, the client will time out after 30 seconds. 25 | */ 26 | 27 | 'request_timeout' => env('OPENAI_REQUEST_TIMEOUT', 30), 28 | ]; 29 | -------------------------------------------------------------------------------- /app/Chat/ChatHistoryRepository.php: -------------------------------------------------------------------------------- 1 | cache->get((string) $sessionUuid); 20 | 21 | foreach ($messages as $message) { 22 | yield $message; 23 | } 24 | } 25 | 26 | public function addMessage(UuidInterface $sessionUuid, object $message): void 27 | { 28 | $messages = (array) $this->cache->get((string) $sessionUuid); 29 | $messages[] = $message; 30 | 31 | $this->cache->set((string) $sessionUuid, $messages); 32 | } 33 | 34 | public function clear(UuidInterface $sessionUuid): void 35 | { 36 | $this->cache->delete((string) $sessionUuid); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /app/Models/User.php: -------------------------------------------------------------------------------- 1 | 18 | */ 19 | protected $fillable = [ 20 | 'name', 21 | 'email', 22 | 'password', 23 | ]; 24 | 25 | /** 26 | * The attributes that should be hidden for serialization. 27 | * 28 | * @var array 29 | */ 30 | protected $hidden = [ 31 | 'password', 32 | 'remember_token', 33 | ]; 34 | 35 | /** 36 | * Get the attributes that should be cast. 37 | * 38 | * @return array 39 | */ 40 | protected function casts(): array 41 | { 42 | return [ 43 | 'email_verified_at' => 'datetime', 44 | 'password' => 'hashed', 45 | ]; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /config/services.php: -------------------------------------------------------------------------------- 1 | [ 18 | 'token' => env('POSTMARK_TOKEN'), 19 | ], 20 | 21 | 'ses' => [ 22 | 'key' => env('AWS_ACCESS_KEY_ID'), 23 | 'secret' => env('AWS_SECRET_ACCESS_KEY'), 24 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), 25 | ], 26 | 27 | 'resend' => [ 28 | 'key' => env('RESEND_KEY'), 29 | ], 30 | 31 | 'slack' => [ 32 | 'notifications' => [ 33 | 'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'), 34 | 'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'), 35 | ], 36 | ], 37 | 38 | ]; 39 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | tests/Unit 10 | 11 | 12 | tests/Feature 13 | 14 | 15 | 16 | 17 | app 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /app/Models/ValueObject/History.php: -------------------------------------------------------------------------------- 1 | data === []; 24 | } 25 | 26 | public function toPrompt(): Prompt 27 | { 28 | return Prompt::fromArray($this->data); 29 | } 30 | 31 | public function jsonSerialize(): array 32 | { 33 | return $this->data instanceof \JsonSerializable 34 | ? $this->data->jsonSerialize() 35 | : $this->data; 36 | } 37 | 38 | public function __toString(): string 39 | { 40 | return \json_encode($this); 41 | } 42 | 43 | public function getIterator(): Traversable 44 | { 45 | return new \ArrayIterator($this->data); 46 | } 47 | } 48 | 49 | -------------------------------------------------------------------------------- /app/Agents/DynamicMemoryTool/DynamicMemoryTool.php: -------------------------------------------------------------------------------- 1 | preference, 32 | ); 33 | 34 | $sessionUuid = Uuid::fromString($input->sessionId); 35 | $this->memoryService->addMemory($sessionUuid, $metadata); 36 | 37 | return 'Memory updated'; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /database/factories/UserFactory.php: -------------------------------------------------------------------------------- 1 | 11 | */ 12 | class UserFactory extends Factory 13 | { 14 | /** 15 | * The current password being used by the factory. 16 | */ 17 | protected static ?string $password; 18 | 19 | /** 20 | * Define the model's default state. 21 | * 22 | * @return array 23 | */ 24 | public function definition(): array 25 | { 26 | return [ 27 | 'name' => fake()->name(), 28 | 'email' => fake()->unique()->safeEmail(), 29 | 'email_verified_at' => now(), 30 | 'password' => static::$password ??= Hash::make('password'), 31 | 'remember_token' => Str::random(10), 32 | ]; 33 | } 34 | 35 | /** 36 | * Indicate that the model's email address should be unverified. 37 | */ 38 | public function unverified(): static 39 | { 40 | return $this->state(fn (array $attributes) => [ 41 | 'email_verified_at' => null, 42 | ]); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | APP_NAME=Laravel 2 | APP_ENV=local 3 | APP_KEY= 4 | APP_DEBUG=true 5 | APP_TIMEZONE=UTC 6 | APP_URL=http://localhost 7 | 8 | APP_LOCALE=en 9 | APP_FALLBACK_LOCALE=en 10 | APP_FAKER_LOCALE=en_US 11 | 12 | APP_MAINTENANCE_DRIVER=file 13 | # APP_MAINTENANCE_STORE=database 14 | 15 | BCRYPT_ROUNDS=12 16 | 17 | LOG_CHANNEL=stack 18 | LOG_STACK=single 19 | LOG_DEPRECATIONS_CHANNEL=null 20 | LOG_LEVEL=debug 21 | 22 | DB_CONNECTION=pgsql 23 | DB_HOST=pgsql 24 | DB_PORT=5432 25 | DB_DATABASE=laravel 26 | DB_USERNAME=sail 27 | DB_PASSWORD=password 28 | 29 | SESSION_DRIVER=database 30 | SESSION_LIFETIME=120 31 | SESSION_ENCRYPT=false 32 | SESSION_PATH=/ 33 | SESSION_DOMAIN=null 34 | 35 | BROADCAST_CONNECTION=log 36 | FILESYSTEM_DISK=local 37 | QUEUE_CONNECTION=database 38 | 39 | CACHE_STORE=database 40 | CACHE_PREFIX= 41 | 42 | MEMCACHED_HOST=127.0.0.1 43 | 44 | REDIS_CLIENT=phpredis 45 | REDIS_HOST=127.0.0.1 46 | REDIS_PASSWORD=null 47 | REDIS_PORT=6379 48 | 49 | MAIL_MAILER=log 50 | MAIL_HOST=127.0.0.1 51 | MAIL_PORT=2525 52 | MAIL_USERNAME=null 53 | MAIL_PASSWORD=null 54 | MAIL_ENCRYPTION=null 55 | MAIL_FROM_ADDRESS="hello@example.com" 56 | MAIL_FROM_NAME="${APP_NAME}" 57 | 58 | AWS_ACCESS_KEY_ID= 59 | AWS_SECRET_ACCESS_KEY= 60 | AWS_DEFAULT_REGION=us-east-1 61 | AWS_BUCKET= 62 | AWS_USE_PATH_STYLE_ENDPOINT=false 63 | 64 | VITE_APP_NAME="${APP_NAME}" 65 | 66 | OPENAI_API_KEY= 67 | OPENAI_ORGANIZATION= 68 | -------------------------------------------------------------------------------- /app/Agents/DynamicMemoryTool/DynamicMemoryService.php: -------------------------------------------------------------------------------- 1 | getCurrentMemory($sessionUuid); 21 | 22 | $memories->addMemory($metadata); 23 | 24 | $this->cache->set($this->getKey($sessionUuid), $memories); 25 | } 26 | 27 | public function updateMemory(UuidInterface $sessionUuid, SolutionMetadata $metadata): void 28 | { 29 | $memories = $this->getCurrentMemory($sessionUuid); 30 | $memories->updateMemory($metadata); 31 | 32 | $this->cache->set($this->getKey($sessionUuid), $memories); 33 | } 34 | 35 | public function getCurrentMemory(UuidInterface $sessionUuid): Memories 36 | { 37 | return $this->cache->get($this->getKey($sessionUuid)) ?? new Memories( 38 | Uuid::uuid4(), 39 | ); 40 | } 41 | 42 | private function getKey(UuidInterface $sessionUuid): string 43 | { 44 | return 'user_memory'; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /app/Agents/SmartHome/DeviceStateManager.php: -------------------------------------------------------------------------------- 1 | cache->get('device_' . $id); 24 | } 25 | 26 | public function update(SmartDevice $device): void 27 | { 28 | $this->cache->set( 29 | 'device_' . $device->id, 30 | $device, 31 | CarbonInterval::seconds(self::DEVICE_STATE_TTL), 32 | ); 33 | 34 | $this->cache->set(self::LAST_ACTION_KEY, \time(), CarbonInterval::seconds(self::LAST_ACTION_TTL)); 35 | } 36 | 37 | public function getLastActionTime(): ?int 38 | { 39 | return $this->cache->get(self::LAST_ACTION_KEY) ?? null; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /app/Console/Commands/ChatSessionCommand.php: -------------------------------------------------------------------------------- 1 | output); 27 | $cursor->clearScreen(); 28 | Artisan::call('agent:list'); 29 | 30 | $chat = new ChatSession( 31 | input: $this->input, 32 | output: $this->output, 33 | agents: $agents, 34 | chat: $chat, 35 | chatHistory: $chatHistory, 36 | tools: $tools, 37 | ); 38 | 39 | $chat->run( 40 | accountUuid: Uuid::fromString('00000000-0000-0000-0000-000000000000'), 41 | binPath: 'artisan', 42 | ); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /app/Chat/PromptGenerator/SessionContextInjector.php: -------------------------------------------------------------------------------- 1 | prompt instanceof Prompt); 22 | 23 | if ( 24 | (!$input->context instanceof Context) 25 | || $input->context->getAuthContext() === null 26 | ) { 27 | return $next($input); 28 | } 29 | 30 | return $next( 31 | input: $input->withPrompt( 32 | $input->prompt 33 | ->withAddedMessage( 34 | MessagePrompt::system( 35 | prompt: 'Session context: {active_context}', 36 | ), 37 | )->withValues( 38 | values: [ 39 | 'active_context' => \json_encode($input->context->getAuthContext()), 40 | ], 41 | ), 42 | ), 43 | ); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /database/migrations/0001_01_01_000000_create_users_table.php: -------------------------------------------------------------------------------- 1 | id(); 16 | $table->string('name'); 17 | $table->string('email')->unique(); 18 | $table->timestamp('email_verified_at')->nullable(); 19 | $table->string('password'); 20 | $table->rememberToken(); 21 | $table->timestamps(); 22 | }); 23 | 24 | Schema::create('password_reset_tokens', function (Blueprint $table) { 25 | $table->string('email')->primary(); 26 | $table->string('token'); 27 | $table->timestamp('created_at')->nullable(); 28 | }); 29 | 30 | Schema::create('sessions', function (Blueprint $table) { 31 | $table->string('id')->primary(); 32 | $table->foreignId('user_id')->nullable()->index(); 33 | $table->string('ip_address', 45)->nullable(); 34 | $table->text('user_agent')->nullable(); 35 | $table->longText('payload'); 36 | $table->integer('last_activity')->index(); 37 | }); 38 | } 39 | 40 | /** 41 | * Reverse the migrations. 42 | */ 43 | public function down(): void 44 | { 45 | Schema::dropIfExists('users'); 46 | Schema::dropIfExists('password_reset_tokens'); 47 | Schema::dropIfExists('sessions'); 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /app/Agents/TaskSplitter/TaskCreateTool.php: -------------------------------------------------------------------------------- 1 | 14 | */ 15 | final class TaskCreateTool extends PhpTool 16 | { 17 | public const NAME = 'create_task'; 18 | 19 | public function __construct( 20 | private readonly Application $app, 21 | ) { 22 | parent::__construct( 23 | name: self::NAME, 24 | inputSchema: TaskCreateInput::class, 25 | description: 'Create a task or subtask in the task management system.', 26 | ); 27 | } 28 | 29 | public function execute(object $input): string 30 | { 31 | $uuid = (string) Uuid::uuid4(); 32 | $dir = $this->app->storagePath('tasks/'); 33 | 34 | if ($input->parentTaskUuid !== '') { 35 | $path = \sprintf('%s/%s/%s.json', $input->projectUuid, $input->parentTaskUuid, $uuid); 36 | } else { 37 | $path = \sprintf('%s/%s.json', $input->projectUuid, $uuid); 38 | } 39 | 40 | $fullPath = $dir . $path; 41 | 42 | Storage::createDirectory(\dirname($fullPath)); 43 | Storage::write( 44 | $fullPath, 45 | \sprintf( 46 | <<<'CONTENT' 47 | uuid: %s 48 | parent_uuid: %s 49 | project_uuid: %s 50 | 51 | --- 52 | 53 | ## %s 54 | 55 | %s 56 | CONTENT, 57 | $uuid, 58 | $input->parentTaskUuid ?? '-', 59 | $input->projectUuid, 60 | $input->name, 61 | \trim($input->description), 62 | ), 63 | ); 64 | 65 | return json_encode(['task_uuid' => $uuid]); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /app/Models/Session.php: -------------------------------------------------------------------------------- 1 | Uuid::class, 35 | 'account_uuid' => Uuid::class, 36 | 'finished_at' => 'datetime', 37 | 'history' => History::class, 38 | ]; 39 | } 40 | 41 | public function getUuid(): UuidInterface 42 | { 43 | return $this->getKey(); 44 | } 45 | 46 | public function getAgentName(): string 47 | { 48 | return $this->agent_name; 49 | } 50 | 51 | public function updateHistory(array $messages): void 52 | { 53 | $this->history = new ValueObject\History($messages); 54 | } 55 | 56 | public function isFinished(): bool 57 | { 58 | return $this->trashed(); 59 | } 60 | 61 | public function setDescription(string $description): void 62 | { 63 | $this->title = $description; 64 | } 65 | 66 | public function getDescription(): ?string 67 | { 68 | return $this->title; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /app/Providers/AgentsChatServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->singleton(ChatServiceInterface::class, SimpleChatService::class); 25 | 26 | // Register ChatHistoryRepositoryInterface here 27 | $this->app->singleton( 28 | ChatHistoryRepositoryInterface::class, 29 | static function (Application $app) { 30 | return new ChatHistoryRepository($app->make('cache.store')); 31 | }, 32 | ); 33 | 34 | $this->app->singleton(PromptGeneratorPipeline::class, static function ( 35 | Application $app, 36 | ): PromptGeneratorPipeline { 37 | $pipeline = new PromptGeneratorPipeline(); 38 | 39 | return $pipeline->withInterceptor( 40 | new InstructionGenerator(), 41 | new AgentMemoryInjector(), 42 | $app->make(LinkedAgentsInjector::class), 43 | new SessionContextInjector(), 44 | new UserPromptInjector(), 45 | ); 46 | }); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | laravel.test: 3 | build: 4 | context: ./vendor/laravel/sail/runtimes/8.3 5 | dockerfile: Dockerfile 6 | args: 7 | WWWGROUP: '${WWWGROUP}' 8 | image: sail-8.3/app 9 | extra_hosts: 10 | - 'host.docker.internal:host-gateway' 11 | ports: 12 | - '${APP_PORT:-80}:80' 13 | - '${VITE_PORT:-5173}:${VITE_PORT:-5173}' 14 | environment: 15 | WWWUSER: '${WWWUSER}' 16 | LARAVEL_SAIL: 1 17 | XDEBUG_MODE: '${SAIL_XDEBUG_MODE:-off}' 18 | XDEBUG_CONFIG: '${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}' 19 | IGNITION_LOCAL_SITES_PATH: '${PWD}' 20 | volumes: 21 | - '.:/var/www/html' 22 | networks: 23 | - sail 24 | depends_on: 25 | - pgsql 26 | pgsql: 27 | image: 'postgres:15' 28 | ports: 29 | - '${FORWARD_DB_PORT:-5432}:5432' 30 | environment: 31 | PGPASSWORD: '${DB_PASSWORD:-secret}' 32 | POSTGRES_DB: '${DB_DATABASE}' 33 | POSTGRES_USER: '${DB_USERNAME}' 34 | POSTGRES_PASSWORD: '${DB_PASSWORD:-secret}' 35 | volumes: 36 | - 'sail-pgsql:/var/lib/postgresql/data' 37 | - './vendor/laravel/sail/database/pgsql/create-testing-database.sql:/docker-entrypoint-initdb.d/10-create-testing-database.sql' 38 | networks: 39 | - sail 40 | healthcheck: 41 | test: 42 | - CMD 43 | - pg_isready 44 | - '-q' 45 | - '-d' 46 | - '${DB_DATABASE}' 47 | - '-U' 48 | - '${DB_USERNAME}' 49 | retries: 3 50 | timeout: 5s 51 | networks: 52 | sail: 53 | driver: bridge 54 | volumes: 55 | sail-pgsql: 56 | driver: local 57 | -------------------------------------------------------------------------------- /config/agents.php: -------------------------------------------------------------------------------- 1 | [ 13 | // CodeReviewAgentFactory::class, 14 | DeliveryAgentFactory::class, 15 | SmartHomeControlAgentFactory::class, 16 | TaskSplitterAgentFactory::class, 17 | SiteStatusChecker\SiteStatusCheckerAgentFactory::class, 18 | ], 19 | 'tools' => [ 20 | \App\Agents\AgentsCaller\AskAgentTool::class, 21 | 22 | // Code Reviewer 23 | // \App\Agents\CodeReviewer\ListProjectTool::class, 24 | // \App\Agents\CodeReviewer\ReadFileTool::class, 25 | // \App\Agents\CodeReviewer\ReviewTool::class, 26 | 27 | // Delivery 28 | \App\Agents\Delivery\GetOrderNumberTool::class, 29 | \App\Agents\Delivery\GetDeliveryDateTool::class, 30 | \App\Agents\Delivery\GetOrderNumberTool::class, 31 | \App\Agents\Delivery\GetProfileTool::class, 32 | 33 | // Dynamic memory 34 | \App\Agents\DynamicMemoryTool\DynamicMemoryTool::class, 35 | 36 | 37 | // Smart Home Control 38 | \LLM\Agents\Agent\SmartHomeControl\ControlDeviceTool::class, 39 | \LLM\Agents\Agent\SmartHomeControl\GetDeviceDetailsTool::class, 40 | \LLM\Agents\Agent\SmartHomeControl\GetRoomListTool::class, 41 | \LLM\Agents\Agent\SmartHomeControl\ListRoomDevicesTool::class, 42 | 43 | // Task splitter 44 | \App\Agents\TaskSplitter\TaskCreateTool::class, 45 | \App\Agents\TaskSplitter\GetProjectDescription::class, 46 | 47 | // Site Status Checker 48 | SiteStatusChecker\CheckSiteAvailabilityTool::class, 49 | SiteStatusChecker\GetDNSInfoTool::class, 50 | SiteStatusChecker\PerformPingTestTool::class, 51 | ], 52 | ]; 53 | -------------------------------------------------------------------------------- /database/migrations/0001_01_01_000002_create_jobs_table.php: -------------------------------------------------------------------------------- 1 | id(); 16 | $table->string('queue')->index(); 17 | $table->longText('payload'); 18 | $table->unsignedTinyInteger('attempts'); 19 | $table->unsignedInteger('reserved_at')->nullable(); 20 | $table->unsignedInteger('available_at'); 21 | $table->unsignedInteger('created_at'); 22 | }); 23 | 24 | Schema::create('job_batches', function (Blueprint $table) { 25 | $table->string('id')->primary(); 26 | $table->string('name'); 27 | $table->integer('total_jobs'); 28 | $table->integer('pending_jobs'); 29 | $table->integer('failed_jobs'); 30 | $table->longText('failed_job_ids'); 31 | $table->mediumText('options')->nullable(); 32 | $table->integer('cancelled_at')->nullable(); 33 | $table->integer('created_at'); 34 | $table->integer('finished_at')->nullable(); 35 | }); 36 | 37 | Schema::create('failed_jobs', function (Blueprint $table) { 38 | $table->id(); 39 | $table->string('uuid')->unique(); 40 | $table->text('connection'); 41 | $table->text('queue'); 42 | $table->longText('payload'); 43 | $table->longText('exception'); 44 | $table->timestamp('failed_at')->useCurrent(); 45 | }); 46 | } 47 | 48 | /** 49 | * Reverse the migrations. 50 | */ 51 | public function down(): void 52 | { 53 | Schema::dropIfExists('jobs'); 54 | Schema::dropIfExists('job_batches'); 55 | Schema::dropIfExists('failed_jobs'); 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /app/Event/ChatEventsListener.php: -------------------------------------------------------------------------------- 1 | history->addMessage($message->sessionUuid, $message); 24 | } 25 | 26 | public function listenMessage(Message $message): void 27 | { 28 | $this->history->addMessage($message->sessionUuid, $message); 29 | } 30 | 31 | public function listenMessageChunk(MessageChunk $message): void 32 | { 33 | $this->history->addMessage($message->sessionUuid, $message); 34 | } 35 | 36 | public function listenQuestion(Question $message): void 37 | { 38 | $this->history->addMessage($message->sessionUuid, $message); 39 | } 40 | 41 | public function listenToolCallResult(ToolCallResult $message): void 42 | { 43 | $this->history->addMessage($message->sessionUuid, $message); 44 | } 45 | 46 | public function subscribe(Dispatcher $events): void 47 | { 48 | $events->listen( 49 | ToolCall::class, 50 | [ChatEventsListener::class, 'listenToolCall'] 51 | ); 52 | 53 | $events->listen( 54 | Message::class, 55 | [ChatEventsListener::class, 'listenMessage'] 56 | ); 57 | 58 | $events->listen( 59 | MessageChunk::class, 60 | [ChatEventsListener::class, 'listenMessageChunk'] 61 | ); 62 | 63 | $events->listen( 64 | Question::class, 65 | [ChatEventsListener::class, 'listenQuestion'] 66 | ); 67 | 68 | $events->listen( 69 | ToolCallResult::class, 70 | [ChatEventsListener::class, 'listenToolCallResult'] 71 | ); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /app/Agents/AgentsCaller/AskAgentTool.php: -------------------------------------------------------------------------------- 1 | 16 | */ 17 | final class AskAgentTool extends PhpTool 18 | { 19 | public const NAME = 'ask_agent'; 20 | 21 | public function __construct( 22 | private readonly ExecutorInterface $executor, 23 | private readonly ToolExecutor $toolExecutor, 24 | ) { 25 | parent::__construct( 26 | name: self::NAME, 27 | inputSchema: AskAgentInput::class, 28 | description: 'Ask an agent with given name to execute a task.', 29 | ); 30 | } 31 | 32 | public function execute(object $input): string|\Stringable 33 | { 34 | $prompt = \sprintf( 35 | <<<'PROMPT' 36 | %s 37 | Important rules: 38 | - Think before responding to the user. 39 | - Don not markup the content. Only JSON is allowed. 40 | - Don't write anything except the answer using JSON schema. 41 | - Answer in JSON using this schema: 42 | %s 43 | PROMPT 44 | , 45 | $input->question, 46 | $input->outputSchema, 47 | ); 48 | 49 | // TODO: make async 50 | while (true) { 51 | $execution = $this->executor->execute(agent: $input->name, prompt: $prompt, promptContext: new Context()); 52 | $result = $execution->result; 53 | $prompt = $execution->prompt; 54 | 55 | if ($result instanceof ToolCalledResponse) { 56 | foreach ($result->tools as $tool) { 57 | $functionResult = $this->toolExecutor->execute($tool->name, $tool->arguments); 58 | 59 | $prompt = $prompt->withAddedMessage( 60 | new ToolCallResultMessage( 61 | id: $tool->id, 62 | content: [$functionResult], 63 | ), 64 | ); 65 | } 66 | 67 | continue; 68 | } 69 | 70 | break; 71 | } 72 | 73 | return \json_encode($result->content); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /app/Agents/CodeReviewer/ReadFileTool.php: -------------------------------------------------------------------------------- 1 | 11 | */ 12 | final class ReadFileTool extends PhpTool 13 | { 14 | public const NAME = 'read_file'; 15 | 16 | public function __construct() 17 | { 18 | parent::__construct( 19 | name: self::NAME, 20 | inputSchema: ReadFileInput::class, 21 | description: 'Read the contents of a file at the given path.', 22 | ); 23 | } 24 | 25 | public function execute(object $input): string 26 | { 27 | if ($input->path === 'file1.php') { 28 | return json_encode([ 29 | 'content' => <<<'PHP' 30 | class ReviewTool extends \App\Domain\Tool\Tool 31 | { 32 | public function __construct() 33 | { 34 | parent::__construct( 35 | name: 'review' 36 | inputSchema: ReviewInput::class, 37 | description: 'Submit a code review for a file at the given path.', 38 | ); 39 | } 40 | 41 | public function getLanguage(): \App\Domain\Tool\ToolLanguage 42 | { 43 | return \App\Domain\Tool\ToolLanguage::PHP; 44 | } 45 | 46 | public function execute(object $input): string 47 | { 48 | // Implementation to submit code review 49 | return json_encode(['status' => 'success', 'message' => 'Code review submitted']); 50 | } 51 | } 52 | PHP, 53 | ]); 54 | } 55 | 56 | if ($input->path === 'file2.php') { 57 | return json_encode([ 58 | 'content' => <<<'PHP' 59 | class ReadFileTool extends \App\Domain\Tool\Tool 60 | { 61 | public function __construct() 62 | { 63 | parent::__construct( 64 | name: 'read_file', 65 | inputSchema: ReadFileInput::class, 66 | description: 'Read the contents of a file at the given path.', 67 | ); 68 | } 69 | 70 | public function getLanguage(): \App\Domain\Tool\ToolLanguage 71 | { 72 | return \App\Domain\Tool\ToolLanguage:PHP; 73 | } 74 | 75 | public function execute(object $input): string 76 | { 77 | // Implementation to read file contents 78 | return json_encode(['content' => 'File contents here']); 79 | } 80 | } 81 | PHP, 82 | ]); 83 | } 84 | 85 | return 'File not found'; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /app/Agents/CodeReviewer/CodeReviewAgent.php: -------------------------------------------------------------------------------- 1 | addMetadata( 34 | new SolutionMetadata( 35 | type: MetadataType::Memory, 36 | key: 'user_submitted_code_review', 37 | content: 'Always submit code reviews using proper tool.', 38 | ), 39 | new SolutionMetadata( 40 | type: MetadataType::Memory, 41 | key: 'code_review_tip', 42 | content: 'Always submit constructive feedback and suggestions for improvement in your code reviews.', 43 | ), 44 | new SolutionMetadata( 45 | type: MetadataType::Memory, 46 | key: 'customer_name', 47 | content: 'If you know the customer name say hello to them.', 48 | ), 49 | new SolutionMetadata( 50 | type: MetadataType::Configuration, 51 | key: Option::MaxTokens->value, 52 | content: 3000, 53 | ), 54 | ); 55 | 56 | $model = new Model(model: OpenAIModel::Gpt4oMini->value); 57 | $aggregate->addAssociation($model); 58 | 59 | $aggregate->addAssociation(new ToolLink(name: ListProjectTool::NAME)); 60 | $aggregate->addAssociation(new ToolLink(name: ReadFileTool::NAME)); 61 | $aggregate->addAssociation(new ToolLink(name: ReviewTool::NAME)); 62 | 63 | return $aggregate; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "laravel/laravel", 3 | "type": "project", 4 | "description": "The skeleton application for the Laravel framework.", 5 | "keywords": ["laravel", "framework"], 6 | "license": "MIT", 7 | "require": { 8 | "php": "^8.2", 9 | "laravel/framework": "^11.9", 10 | "llm-agents/agent-site-status-checker": "^1.1", 11 | "llm-agents/agent-symfony-console": "^1.1", 12 | "llm-agents/agent-smart-home-control":"^1.1", 13 | "llm-agents/agents": "^1.5", 14 | "llm-agents/cli-chat": "^1.3", 15 | "llm-agents/prompt-generator": "^1.2", 16 | "llm-agents/json-schema-mapper": "^1.1", 17 | "llm-agents/openai-client": "^1.3", 18 | "openai-php/laravel": "^0.10.1" 19 | }, 20 | "require-dev": { 21 | "fakerphp/faker": "^1.23", 22 | "laravel/sail": "^1.31", 23 | "mockery/mockery": "^1.6", 24 | "nunomaduro/collision": "^8.0", 25 | "phpunit/phpunit": "^11.0.1" 26 | }, 27 | "autoload": { 28 | "psr-4": { 29 | "App\\": "app/", 30 | "Database\\Factories\\": "database/factories/", 31 | "Database\\Seeders\\": "database/seeders/" 32 | } 33 | }, 34 | "autoload-dev": { 35 | "psr-4": { 36 | "Tests\\": "tests/" 37 | } 38 | }, 39 | "scripts": { 40 | "post-autoload-dump": [ 41 | "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump", 42 | "@php artisan package:discover --ansi" 43 | ], 44 | "post-update-cmd": [ 45 | "@php artisan vendor:publish --tag=laravel-assets --ansi --force" 46 | ], 47 | "post-root-package-install": [ 48 | "@php -r \"file_exists('.env') || copy('.env.example', '.env');\"" 49 | ], 50 | "post-create-project-cmd": [ 51 | "@php artisan key:generate --ansi", 52 | "@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"", 53 | "@php artisan migrate --graceful --ansi" 54 | ] 55 | }, 56 | "extra": { 57 | "laravel": { 58 | "dont-discover": [] 59 | } 60 | }, 61 | "config": { 62 | "optimize-autoloader": true, 63 | "preferred-install": "dist", 64 | "sort-packages": true, 65 | "allow-plugins": { 66 | "pestphp/pest-plugin": true, 67 | "php-http/discovery": true 68 | } 69 | }, 70 | "minimum-stability": "stable", 71 | "prefer-stable": true 72 | } 73 | -------------------------------------------------------------------------------- /app/Agents/TaskSplitter/GetProjectDescription.php: -------------------------------------------------------------------------------- 1 | 11 | */ 12 | final class GetProjectDescription extends PhpTool 13 | { 14 | public const NAME = 'get_project_description'; 15 | 16 | public function __construct() 17 | { 18 | parent::__construct( 19 | name: self::NAME, 20 | inputSchema: ProjectDescriptionInput::class, 21 | description: 'Get the description of a project from the project management system.', 22 | ); 23 | } 24 | 25 | public function execute(object $input): string 26 | { 27 | return json_encode([ 28 | 'uuid' => $input->uuid, 29 | 'title' => 'Оплата услуг клиентом', 30 | 'description' => <<<'TEXT' 31 | **As a customer, I want to be able to:** 32 | 33 | - **Choose a subscription plan during registration:** 34 | - When creating an account on the service's website, I should be offered a choice of different subscription plans. 35 | - Each plan should include a clear description of the services provided and their costs. 36 | 37 | - **Subscribe to a plan using a credit card:** 38 | - After selecting a plan, I need to provide my credit card details for payment. 39 | - There should be an option to save my card details for automatic monthly payments. 40 | 41 | - **Receive monthly payment notifications:** 42 | - I expect to receive notifications via email or through my personal account about upcoming subscription charges. 43 | - The notification should arrive a few days before the charge, giving me enough time to ensure sufficient funds are available. 44 | 45 | - **Access all necessary documents in my personal account:** 46 | - All financial documents, such as receipts and invoices, should be available for download at any time in my personal account. 47 | 48 | - **Cancel the service if needed:** 49 | - I should be able to easily cancel my subscription through my personal account without needing to make additional calls or contact customer support. 50 | 51 | - **Add a new card if the current one expires:** 52 | - If my credit card expires, I want to easily add a new card to the system through my personal account. 53 | 54 | - **Continue using the service after cancellation until the end of the paid period:** 55 | - If I cancel my subscription, I expect to continue using the service until the end of the already paid period. 56 | TEXT 57 | , 58 | ]); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /config/filesystems.php: -------------------------------------------------------------------------------- 1 | env('FILESYSTEM_DISK', 'local'), 17 | 18 | /* 19 | |-------------------------------------------------------------------------- 20 | | Filesystem Disks 21 | |-------------------------------------------------------------------------- 22 | | 23 | | Below you may configure as many filesystem disks as necessary, and you 24 | | may even configure multiple disks for the same driver. Examples for 25 | | most supported storage drivers are configured here for reference. 26 | | 27 | | Supported drivers: "local", "ftp", "sftp", "s3" 28 | | 29 | */ 30 | 31 | 'disks' => [ 32 | 33 | 'local' => [ 34 | 'driver' => 'local', 35 | 'root' => storage_path('app'), 36 | 'throw' => false, 37 | ], 38 | 39 | 'public' => [ 40 | 'driver' => 'local', 41 | 'root' => storage_path('app/public'), 42 | 'url' => env('APP_URL').'/storage', 43 | 'visibility' => 'public', 44 | 'throw' => false, 45 | ], 46 | 47 | 's3' => [ 48 | 'driver' => 's3', 49 | 'key' => env('AWS_ACCESS_KEY_ID'), 50 | 'secret' => env('AWS_SECRET_ACCESS_KEY'), 51 | 'region' => env('AWS_DEFAULT_REGION'), 52 | 'bucket' => env('AWS_BUCKET'), 53 | 'url' => env('AWS_URL'), 54 | 'endpoint' => env('AWS_ENDPOINT'), 55 | 'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false), 56 | 'throw' => false, 57 | ], 58 | 59 | ], 60 | 61 | /* 62 | |-------------------------------------------------------------------------- 63 | | Symbolic Links 64 | |-------------------------------------------------------------------------- 65 | | 66 | | Here you may configure the symbolic links that will be created when the 67 | | `storage:link` Artisan command is executed. The array keys should be 68 | | the locations of the links and the values should be their targets. 69 | | 70 | */ 71 | 72 | 'links' => [ 73 | public_path('storage') => storage_path('app/public'), 74 | ], 75 | 76 | ]; 77 | -------------------------------------------------------------------------------- /app/Agents/TaskSplitter/TaskSplitterAgent.php: -------------------------------------------------------------------------------- 1 | addMetadata( 37 | new SolutionMetadata( 38 | type: MetadataType::Memory, 39 | key: 'task_organization_tip', 40 | content: 'Always aim to create a logical hierarchy of tasks and subtasks. Main tasks should be broad objectives, while subtasks should be specific, actionable items.', 41 | ), 42 | new SolutionMetadata( 43 | type: MetadataType::Memory, 44 | key: 'efficiency_tip', 45 | content: 'Try to keep the number of main tasks between 3 and 7 for better manageability. Break down complex tasks into subtasks when necessary.', 46 | ), 47 | 48 | // Prompts examples 49 | new SolutionMetadata( 50 | type: MetadataType::Prompt, 51 | key: 'split_task', 52 | content: 'Split the project description f47ac10b-58cc-4372-a567-0e02b2c3d479 into a list of tasks and subtasks.', 53 | ), 54 | new SolutionMetadata( 55 | type: MetadataType::Configuration, 56 | key: Option::MaxTokens->value, 57 | content: 3000, 58 | ), 59 | ); 60 | 61 | $model = new Model(model: OpenAIModel::Gpt4oMini->value); 62 | $aggregate->addAssociation($model); 63 | 64 | $aggregate->addAssociation(new ToolLink(name: TaskCreateTool::NAME)); 65 | $aggregate->addAssociation(new ToolLink(name: GetProjectDescription::NAME)); 66 | 67 | return $aggregate; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /app/Providers/AgentsServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->singleton(ToolRegistry::class, ToolRegistry::class); 34 | $this->app->singleton(ToolRegistryInterface::class, ToolRegistry::class); 35 | $this->app->singleton(ToolRepositoryInterface::class, ToolRegistry::class); 36 | 37 | $this->app->singleton(AgentRegistry::class, AgentRegistry::class); 38 | $this->app->singleton(AgentRegistryInterface::class, AgentRegistry::class); 39 | $this->app->singleton(AgentRepositoryInterface::class, AgentRegistry::class); 40 | 41 | $this->app->singleton(OptionsFactoryInterface::class, OptionsFactory::class); 42 | $this->app->singleton(ContextFactoryInterface::class, ContextFactory::class); 43 | 44 | $this->app->singleton(SchemaMapperInterface::class, SchemaMapper::class); 45 | 46 | $this->app->singleton(ExecutorInterface::class, static function ( 47 | Application $app, 48 | ) { 49 | return $app->make(ExecutorPipeline::class)->withInterceptor( 50 | $app->make(GeneratePromptInterceptor::class), 51 | $app->make(InjectModelInterceptor::class), 52 | $app->make(InjectToolsInterceptor::class), 53 | $app->make(InjectOptionsInterceptor::class), 54 | $app->make(InjectResponseIntoPromptInterceptor::class), 55 | ); 56 | }); 57 | } 58 | 59 | public function boot( 60 | AgentRegistryInterface $agents, 61 | ToolRegistryInterface $tools, 62 | ): void { 63 | foreach (config('agents.agents') as $agent) { 64 | $agents->register($this->app->make($agent)->create()); 65 | } 66 | 67 | foreach (config('agents.tools') as $tool) { 68 | $tools->register($this->app->make($tool)); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /config/cache.php: -------------------------------------------------------------------------------- 1 | env('CACHE_STORE', 'database'), 19 | 20 | /* 21 | |-------------------------------------------------------------------------- 22 | | Cache Stores 23 | |-------------------------------------------------------------------------- 24 | | 25 | | Here you may define all of the cache "stores" for your application as 26 | | well as their drivers. You may even define multiple stores for the 27 | | same cache driver to group types of items stored in your caches. 28 | | 29 | | Supported drivers: "array", "database", "file", "memcached", 30 | | "redis", "dynamodb", "octane", "null" 31 | | 32 | */ 33 | 34 | 'stores' => [ 35 | 36 | 'array' => [ 37 | 'driver' => 'array', 38 | 'serialize' => false, 39 | ], 40 | 41 | 'database' => [ 42 | 'driver' => 'database', 43 | 'connection' => env('DB_CACHE_CONNECTION'), 44 | 'table' => env('DB_CACHE_TABLE', 'cache'), 45 | 'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'), 46 | 'lock_table' => env('DB_CACHE_LOCK_TABLE'), 47 | ], 48 | 49 | 'file' => [ 50 | 'driver' => 'file', 51 | 'path' => storage_path('framework/cache/data'), 52 | 'lock_path' => storage_path('framework/cache/data'), 53 | ], 54 | 55 | 'memcached' => [ 56 | 'driver' => 'memcached', 57 | 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'), 58 | 'sasl' => [ 59 | env('MEMCACHED_USERNAME'), 60 | env('MEMCACHED_PASSWORD'), 61 | ], 62 | 'options' => [ 63 | // Memcached::OPT_CONNECT_TIMEOUT => 2000, 64 | ], 65 | 'servers' => [ 66 | [ 67 | 'host' => env('MEMCACHED_HOST', '127.0.0.1'), 68 | 'port' => env('MEMCACHED_PORT', 11211), 69 | 'weight' => 100, 70 | ], 71 | ], 72 | ], 73 | 74 | 'redis' => [ 75 | 'driver' => 'redis', 76 | 'connection' => env('REDIS_CACHE_CONNECTION', 'cache'), 77 | 'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'), 78 | ], 79 | 80 | 'dynamodb' => [ 81 | 'driver' => 'dynamodb', 82 | 'key' => env('AWS_ACCESS_KEY_ID'), 83 | 'secret' => env('AWS_SECRET_ACCESS_KEY'), 84 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), 85 | 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'), 86 | 'endpoint' => env('DYNAMODB_ENDPOINT'), 87 | ], 88 | 89 | 'octane' => [ 90 | 'driver' => 'octane', 91 | ], 92 | 93 | ], 94 | 95 | /* 96 | |-------------------------------------------------------------------------- 97 | | Cache Key Prefix 98 | |-------------------------------------------------------------------------- 99 | | 100 | | When utilizing the APC, database, memcached, Redis, and DynamoDB cache 101 | | stores, there might be other applications using the same cache. For 102 | | that reason, you may prefix every cache key to avoid collisions. 103 | | 104 | */ 105 | 106 | 'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache_'), 107 | 108 | ]; 109 | -------------------------------------------------------------------------------- /config/mail.php: -------------------------------------------------------------------------------- 1 | env('MAIL_MAILER', 'log'), 18 | 19 | /* 20 | |-------------------------------------------------------------------------- 21 | | Mailer Configurations 22 | |-------------------------------------------------------------------------- 23 | | 24 | | Here you may configure all of the mailers used by your application plus 25 | | their respective settings. Several examples have been configured for 26 | | you and you are free to add your own as your application requires. 27 | | 28 | | Laravel supports a variety of mail "transport" drivers that can be used 29 | | when delivering an email. You may specify which one you're using for 30 | | your mailers below. You may also add additional mailers if needed. 31 | | 32 | | Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2", 33 | | "postmark", "resend", "log", "array", 34 | | "failover", "roundrobin" 35 | | 36 | */ 37 | 38 | 'mailers' => [ 39 | 40 | 'smtp' => [ 41 | 'transport' => 'smtp', 42 | 'url' => env('MAIL_URL'), 43 | 'host' => env('MAIL_HOST', '127.0.0.1'), 44 | 'port' => env('MAIL_PORT', 2525), 45 | 'encryption' => env('MAIL_ENCRYPTION', 'tls'), 46 | 'username' => env('MAIL_USERNAME'), 47 | 'password' => env('MAIL_PASSWORD'), 48 | 'timeout' => null, 49 | 'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url(env('APP_URL', 'http://localhost'), PHP_URL_HOST)), 50 | ], 51 | 52 | 'ses' => [ 53 | 'transport' => 'ses', 54 | ], 55 | 56 | 'postmark' => [ 57 | 'transport' => 'postmark', 58 | // 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'), 59 | // 'client' => [ 60 | // 'timeout' => 5, 61 | // ], 62 | ], 63 | 64 | 'resend' => [ 65 | 'transport' => 'resend', 66 | ], 67 | 68 | 'sendmail' => [ 69 | 'transport' => 'sendmail', 70 | 'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'), 71 | ], 72 | 73 | 'log' => [ 74 | 'transport' => 'log', 75 | 'channel' => env('MAIL_LOG_CHANNEL'), 76 | ], 77 | 78 | 'array' => [ 79 | 'transport' => 'array', 80 | ], 81 | 82 | 'failover' => [ 83 | 'transport' => 'failover', 84 | 'mailers' => [ 85 | 'smtp', 86 | 'log', 87 | ], 88 | ], 89 | 90 | 'roundrobin' => [ 91 | 'transport' => 'roundrobin', 92 | 'mailers' => [ 93 | 'ses', 94 | 'postmark', 95 | ], 96 | ], 97 | 98 | ], 99 | 100 | /* 101 | |-------------------------------------------------------------------------- 102 | | Global "From" Address 103 | |-------------------------------------------------------------------------- 104 | | 105 | | You may wish for all emails sent by your application to be sent from 106 | | the same address. Here you may specify a name and address that is 107 | | used globally for all emails that are sent by your application. 108 | | 109 | */ 110 | 111 | 'from' => [ 112 | 'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'), 113 | 'name' => env('MAIL_FROM_NAME', 'Example'), 114 | ], 115 | 116 | ]; 117 | -------------------------------------------------------------------------------- /app/Agents/Delivery/DeliveryAgent.php: -------------------------------------------------------------------------------- 1 | addMetadata( 39 | // Memory 40 | new SolutionMetadata( 41 | type: MetadataType::Memory, 42 | key: 'order_tip', 43 | content: 'First, retrieve the customer profile to provide personalized service.', 44 | ), 45 | new SolutionMetadata( 46 | type: MetadataType::Memory, 47 | key: 'order_tip_server', 48 | content: 'Always check the server [google.com] status before providing any information.', 49 | ), 50 | new SolutionMetadata( 51 | type: MetadataType::Memory, 52 | key: 'order_tip_repeat', 53 | content: 'Don\'t repeat the same information to the customer. If you have already provided the order number, don\'t repeat it. Provide only new information.', 54 | ), 55 | new SolutionMetadata( 56 | type: MetadataType::Memory, 57 | key: 'order_tip_age', 58 | content: 'Tone of conversation is important, pay attention on age and fit the conversation to the age of the customer.', 59 | ), 60 | 61 | // Prompt 62 | new SolutionMetadata( 63 | type: MetadataType::Prompt, 64 | key: 'server_status', 65 | content: 'Check the server [google.com] status to ensure that the system is operational.', 66 | ), 67 | new SolutionMetadata( 68 | type: MetadataType::Prompt, 69 | key: 'what_is_order_number', 70 | content: 'What is my order number?', 71 | ), 72 | new SolutionMetadata( 73 | type: MetadataType::Prompt, 74 | key: 'when_is_delivery', 75 | content: 'When will my order be delivered?', 76 | ), 77 | new SolutionMetadata( 78 | type: MetadataType::Prompt, 79 | key: 'my_profile', 80 | content: 'Can you tell me more about my profile?', 81 | ), 82 | ); 83 | 84 | // Add a model to the agent 85 | $model = new Model(model: OpenAIModel::Gpt4oMini->value); 86 | $aggregate->addAssociation($model); 87 | 88 | $aggregate->addAssociation(new ToolLink(name: GetDeliveryDateTool::NAME)); 89 | $aggregate->addAssociation(new ToolLink(name: GetOrderNumberTool::NAME)); 90 | $aggregate->addAssociation(new ToolLink(name: GetProfileTool::NAME)); 91 | 92 | $aggregate->addAssociation(new ToolLink(name: AskAgentTool::NAME)); 93 | $aggregate->addAssociation( 94 | new AgentLink( 95 | name: SiteStatusCheckerAgent::NAME, 96 | outputSchema: StatusCheckOutput::class, 97 | ), 98 | ); 99 | 100 | return $aggregate; 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /config/queue.php: -------------------------------------------------------------------------------- 1 | env('QUEUE_CONNECTION', 'database'), 17 | 18 | /* 19 | |-------------------------------------------------------------------------- 20 | | Queue Connections 21 | |-------------------------------------------------------------------------- 22 | | 23 | | Here you may configure the connection options for every queue backend 24 | | used by your application. An example configuration is provided for 25 | | each backend supported by Laravel. You're also free to add more. 26 | | 27 | | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null" 28 | | 29 | */ 30 | 31 | 'connections' => [ 32 | 33 | 'sync' => [ 34 | 'driver' => 'sync', 35 | ], 36 | 37 | 'database' => [ 38 | 'driver' => 'database', 39 | 'connection' => env('DB_QUEUE_CONNECTION'), 40 | 'table' => env('DB_QUEUE_TABLE', 'jobs'), 41 | 'queue' => env('DB_QUEUE', 'default'), 42 | 'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90), 43 | 'after_commit' => false, 44 | ], 45 | 46 | 'beanstalkd' => [ 47 | 'driver' => 'beanstalkd', 48 | 'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'), 49 | 'queue' => env('BEANSTALKD_QUEUE', 'default'), 50 | 'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90), 51 | 'block_for' => 0, 52 | 'after_commit' => false, 53 | ], 54 | 55 | 'sqs' => [ 56 | 'driver' => 'sqs', 57 | 'key' => env('AWS_ACCESS_KEY_ID'), 58 | 'secret' => env('AWS_SECRET_ACCESS_KEY'), 59 | 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'), 60 | 'queue' => env('SQS_QUEUE', 'default'), 61 | 'suffix' => env('SQS_SUFFIX'), 62 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), 63 | 'after_commit' => false, 64 | ], 65 | 66 | 'redis' => [ 67 | 'driver' => 'redis', 68 | 'connection' => env('REDIS_QUEUE_CONNECTION', 'default'), 69 | 'queue' => env('REDIS_QUEUE', 'default'), 70 | 'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90), 71 | 'block_for' => null, 72 | 'after_commit' => false, 73 | ], 74 | 75 | ], 76 | 77 | /* 78 | |-------------------------------------------------------------------------- 79 | | Job Batching 80 | |-------------------------------------------------------------------------- 81 | | 82 | | The following options configure the database and table that store job 83 | | batching information. These options can be updated to any database 84 | | connection and table which has been defined by your application. 85 | | 86 | */ 87 | 88 | 'batching' => [ 89 | 'database' => env('DB_CONNECTION', 'sqlite'), 90 | 'table' => 'job_batches', 91 | ], 92 | 93 | /* 94 | |-------------------------------------------------------------------------- 95 | | Failed Queue Jobs 96 | |-------------------------------------------------------------------------- 97 | | 98 | | These options configure the behavior of failed queue job logging so you 99 | | can control how and where failed jobs are stored. Laravel ships with 100 | | support for storing failed jobs in a simple file or in a database. 101 | | 102 | | Supported drivers: "database-uuids", "dynamodb", "file", "null" 103 | | 104 | */ 105 | 106 | 'failed' => [ 107 | 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'), 108 | 'database' => env('DB_CONNECTION', 'sqlite'), 109 | 'table' => 'failed_jobs', 110 | ], 111 | 112 | ]; 113 | -------------------------------------------------------------------------------- /config/auth.php: -------------------------------------------------------------------------------- 1 | [ 17 | 'guard' => env('AUTH_GUARD', 'web'), 18 | 'passwords' => env('AUTH_PASSWORD_BROKER', 'users'), 19 | ], 20 | 21 | /* 22 | |-------------------------------------------------------------------------- 23 | | Authentication Guards 24 | |-------------------------------------------------------------------------- 25 | | 26 | | Next, you may define every authentication guard for your application. 27 | | Of course, a great default configuration has been defined for you 28 | | which utilizes session storage plus the Eloquent user provider. 29 | | 30 | | All authentication guards have a user provider, which defines how the 31 | | users are actually retrieved out of your database or other storage 32 | | system used by the application. Typically, Eloquent is utilized. 33 | | 34 | | Supported: "session" 35 | | 36 | */ 37 | 38 | 'guards' => [ 39 | 'web' => [ 40 | 'driver' => 'session', 41 | 'provider' => 'users', 42 | ], 43 | ], 44 | 45 | /* 46 | |-------------------------------------------------------------------------- 47 | | User Providers 48 | |-------------------------------------------------------------------------- 49 | | 50 | | All authentication guards have a user provider, which defines how the 51 | | users are actually retrieved out of your database or other storage 52 | | system used by the application. Typically, Eloquent is utilized. 53 | | 54 | | If you have multiple user tables or models you may configure multiple 55 | | providers to represent the model / table. These providers may then 56 | | be assigned to any extra authentication guards you have defined. 57 | | 58 | | Supported: "database", "eloquent" 59 | | 60 | */ 61 | 62 | 'providers' => [ 63 | 'users' => [ 64 | 'driver' => 'eloquent', 65 | 'model' => env('AUTH_MODEL', App\Models\User::class), 66 | ], 67 | 68 | // 'users' => [ 69 | // 'driver' => 'database', 70 | // 'table' => 'users', 71 | // ], 72 | ], 73 | 74 | /* 75 | |-------------------------------------------------------------------------- 76 | | Resetting Passwords 77 | |-------------------------------------------------------------------------- 78 | | 79 | | These configuration options specify the behavior of Laravel's password 80 | | reset functionality, including the table utilized for token storage 81 | | and the user provider that is invoked to actually retrieve users. 82 | | 83 | | The expiry time is the number of minutes that each reset token will be 84 | | considered valid. This security feature keeps tokens short-lived so 85 | | they have less time to be guessed. You may change this as needed. 86 | | 87 | | The throttle setting is the number of seconds a user must wait before 88 | | generating more password reset tokens. This prevents the user from 89 | | quickly generating a very large amount of password reset tokens. 90 | | 91 | */ 92 | 93 | 'passwords' => [ 94 | 'users' => [ 95 | 'provider' => 'users', 96 | 'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'), 97 | 'expire' => 60, 98 | 'throttle' => 60, 99 | ], 100 | ], 101 | 102 | /* 103 | |-------------------------------------------------------------------------- 104 | | Password Confirmation Timeout 105 | |-------------------------------------------------------------------------- 106 | | 107 | | Here you may define the amount of seconds before a password confirmation 108 | | window expires and users are asked to re-enter their password via the 109 | | confirmation screen. By default, the timeout lasts for three hours. 110 | | 111 | */ 112 | 113 | 'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800), 114 | 115 | ]; 116 | -------------------------------------------------------------------------------- /config/app.php: -------------------------------------------------------------------------------- 1 | env('APP_NAME', 'Laravel'), 17 | 18 | /* 19 | |-------------------------------------------------------------------------- 20 | | Application Environment 21 | |-------------------------------------------------------------------------- 22 | | 23 | | This value determines the "environment" your application is currently 24 | | running in. This may determine how you prefer to configure various 25 | | services the application utilizes. Set this in your ".env" file. 26 | | 27 | */ 28 | 29 | 'env' => env('APP_ENV', 'production'), 30 | 31 | /* 32 | |-------------------------------------------------------------------------- 33 | | Application Debug Mode 34 | |-------------------------------------------------------------------------- 35 | | 36 | | When your application is in debug mode, detailed error messages with 37 | | stack traces will be shown on every error that occurs within your 38 | | application. If disabled, a simple generic error page is shown. 39 | | 40 | */ 41 | 42 | 'debug' => (bool) env('APP_DEBUG', false), 43 | 44 | /* 45 | |-------------------------------------------------------------------------- 46 | | Application URL 47 | |-------------------------------------------------------------------------- 48 | | 49 | | This URL is used by the console to properly generate URLs when using 50 | | the Artisan command line tool. You should set this to the root of 51 | | the application so that it's available within Artisan commands. 52 | | 53 | */ 54 | 55 | 'url' => env('APP_URL', 'http://localhost'), 56 | 57 | /* 58 | |-------------------------------------------------------------------------- 59 | | Application Timezone 60 | |-------------------------------------------------------------------------- 61 | | 62 | | Here you may specify the default timezone for your application, which 63 | | will be used by the PHP date and date-time functions. The timezone 64 | | is set to "UTC" by default as it is suitable for most use cases. 65 | | 66 | */ 67 | 68 | 'timezone' => env('APP_TIMEZONE', 'UTC'), 69 | 70 | /* 71 | |-------------------------------------------------------------------------- 72 | | Application Locale Configuration 73 | |-------------------------------------------------------------------------- 74 | | 75 | | The application locale determines the default locale that will be used 76 | | by Laravel's translation / localization methods. This option can be 77 | | set to any locale for which you plan to have translation strings. 78 | | 79 | */ 80 | 81 | 'locale' => env('APP_LOCALE', 'en'), 82 | 83 | 'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'), 84 | 85 | 'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'), 86 | 87 | /* 88 | |-------------------------------------------------------------------------- 89 | | Encryption Key 90 | |-------------------------------------------------------------------------- 91 | | 92 | | This key is utilized by Laravel's encryption services and should be set 93 | | to a random, 32 character string to ensure that all encrypted values 94 | | are secure. You should do this prior to deploying the application. 95 | | 96 | */ 97 | 98 | 'cipher' => 'AES-256-CBC', 99 | 100 | 'key' => env('APP_KEY'), 101 | 102 | 'previous_keys' => [ 103 | ...array_filter( 104 | explode(',', env('APP_PREVIOUS_KEYS', '')) 105 | ), 106 | ], 107 | 108 | /* 109 | |-------------------------------------------------------------------------- 110 | | Maintenance Mode Driver 111 | |-------------------------------------------------------------------------- 112 | | 113 | | These configuration options determine the driver used to determine and 114 | | manage Laravel's "maintenance mode" status. The "cache" driver will 115 | | allow maintenance mode to be controlled across multiple machines. 116 | | 117 | | Supported drivers: "file", "cache" 118 | | 119 | */ 120 | 121 | 'maintenance' => [ 122 | 'driver' => env('APP_MAINTENANCE_DRIVER', 'file'), 123 | 'store' => env('APP_MAINTENANCE_STORE', 'database'), 124 | ], 125 | 126 | ]; 127 | -------------------------------------------------------------------------------- /config/logging.php: -------------------------------------------------------------------------------- 1 | env('LOG_CHANNEL', 'stack'), 22 | 23 | /* 24 | |-------------------------------------------------------------------------- 25 | | Deprecations Log Channel 26 | |-------------------------------------------------------------------------- 27 | | 28 | | This option controls the log channel that should be used to log warnings 29 | | regarding deprecated PHP and library features. This allows you to get 30 | | your application ready for upcoming major versions of dependencies. 31 | | 32 | */ 33 | 34 | 'deprecations' => [ 35 | 'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'), 36 | 'trace' => env('LOG_DEPRECATIONS_TRACE', false), 37 | ], 38 | 39 | /* 40 | |-------------------------------------------------------------------------- 41 | | Log Channels 42 | |-------------------------------------------------------------------------- 43 | | 44 | | Here you may configure the log channels for your application. Laravel 45 | | utilizes the Monolog PHP logging library, which includes a variety 46 | | of powerful log handlers and formatters that you're free to use. 47 | | 48 | | Available drivers: "single", "daily", "slack", "syslog", 49 | | "errorlog", "monolog", "custom", "stack" 50 | | 51 | */ 52 | 53 | 'channels' => [ 54 | 55 | 'stack' => [ 56 | 'driver' => 'stack', 57 | 'channels' => explode(',', env('LOG_STACK', 'single')), 58 | 'ignore_exceptions' => false, 59 | ], 60 | 61 | 'single' => [ 62 | 'driver' => 'single', 63 | 'path' => storage_path('logs/laravel.log'), 64 | 'level' => env('LOG_LEVEL', 'debug'), 65 | 'replace_placeholders' => true, 66 | ], 67 | 68 | 'daily' => [ 69 | 'driver' => 'daily', 70 | 'path' => storage_path('logs/laravel.log'), 71 | 'level' => env('LOG_LEVEL', 'debug'), 72 | 'days' => env('LOG_DAILY_DAYS', 14), 73 | 'replace_placeholders' => true, 74 | ], 75 | 76 | 'slack' => [ 77 | 'driver' => 'slack', 78 | 'url' => env('LOG_SLACK_WEBHOOK_URL'), 79 | 'username' => env('LOG_SLACK_USERNAME', 'Laravel Log'), 80 | 'emoji' => env('LOG_SLACK_EMOJI', ':boom:'), 81 | 'level' => env('LOG_LEVEL', 'critical'), 82 | 'replace_placeholders' => true, 83 | ], 84 | 85 | 'papertrail' => [ 86 | 'driver' => 'monolog', 87 | 'level' => env('LOG_LEVEL', 'debug'), 88 | 'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class), 89 | 'handler_with' => [ 90 | 'host' => env('PAPERTRAIL_URL'), 91 | 'port' => env('PAPERTRAIL_PORT'), 92 | 'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'), 93 | ], 94 | 'processors' => [PsrLogMessageProcessor::class], 95 | ], 96 | 97 | 'stderr' => [ 98 | 'driver' => 'monolog', 99 | 'level' => env('LOG_LEVEL', 'debug'), 100 | 'handler' => StreamHandler::class, 101 | 'formatter' => env('LOG_STDERR_FORMATTER'), 102 | 'with' => [ 103 | 'stream' => 'php://stderr', 104 | ], 105 | 'processors' => [PsrLogMessageProcessor::class], 106 | ], 107 | 108 | 'syslog' => [ 109 | 'driver' => 'syslog', 110 | 'level' => env('LOG_LEVEL', 'debug'), 111 | 'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER), 112 | 'replace_placeholders' => true, 113 | ], 114 | 115 | 'errorlog' => [ 116 | 'driver' => 'errorlog', 117 | 'level' => env('LOG_LEVEL', 'debug'), 118 | 'replace_placeholders' => true, 119 | ], 120 | 121 | 'null' => [ 122 | 'driver' => 'monolog', 123 | 'handler' => NullHandler::class, 124 | ], 125 | 126 | 'emergency' => [ 127 | 'path' => storage_path('logs/laravel.log'), 128 | ], 129 | 130 | ], 131 | 132 | ]; 133 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LLM Agents Sample App - Laravel edition 2 | 3 | This sample application demonstrates the practical implementation and usage patterns of the LLM Agents library. 4 | 5 | > For more information about the LLM Agents package and its capabilities, please refer to 6 | > the [LLM Agents documentation](https://github.com/llm-agents-php/agents). 7 | 8 | It provides a CLI interface to interact with various AI agents, showcasing the power and flexibility of the LLM Agents 9 | package. 10 | 11 | ![image](https://github.com/user-attachments/assets/53104067-d3df-4983-8a59-435708f2b70c) 12 | 13 | ## Features 14 | 15 | - Multiple pre-configured AI agents with different capabilities 16 | - CLI interface for easy interaction with agents 17 | - Integration with OpenAI's GPT models 18 | - Database support for session persistence 19 | 20 | ## Prerequisites 21 | 22 | - PHP 8.3 or higher 23 | - Composer 24 | - Git 25 | - OpenAI API key 26 | 27 | ## Quick Start with Docker 28 | 29 | The easiest way to run the app is using our pre-built Docker image. 30 | 31 | **Follow these steps to get started:** 32 | 33 | 1. Make sure you have Docker installed on your system. 34 | 35 | 2. Create a `.env` file in the project root directory: 36 | 37 | ```bash 38 | cp .env.example .env 39 | ``` 40 | 41 | and add your OpenAI API key to the `.env` file: 42 | 43 | ```bash 44 | OPENAI_API_KEY=your_api_key_here 45 | ``` 46 | 47 | > Replace `` with your OpenAI API key. 48 | 49 | 3. Run the Docker container with the following command: 50 | 51 | ```bash 52 | make up 53 | ``` 54 | 55 | 4Once the container is running, you can interact with the app using the following command: 56 | 57 | ## Usage 58 | 59 | ### Chatting with Agents 60 | 61 | To start a chat session with an AI agent: 62 | 63 | 1. Run the following command: 64 | 65 | **Using docker container** 66 | 67 | ```bash 68 | make chat 69 | ``` 70 | 71 | 2. You will see a list of available agents and their descriptions. Choose the desired agent by entering its number. 72 | 73 | ![image](https://github.com/user-attachments/assets/3cd223a8-3ab0-4879-9e85-83539c93003f) 74 | 75 | 3. After selecting an agent, you will see a message like this: 76 | 77 | ![image](https://github.com/user-attachments/assets/0d18ca6c-9ee9-4942-b383-fc42abf18bc7) 78 | 79 | ```bash 80 | ************************************************************ 81 | * Run the following command to see the AI response * 82 | ************************************************************ 83 | 84 | php artisan chat:session -v 85 | ``` 86 | 87 | **Using docker container** 88 | 89 | ```bash 90 | make bash 91 | ``` 92 | 93 | Then run the following command: 94 | 95 | ```bash 96 | php artisan chat:session -v 97 | ``` 98 | 99 | > Replace `` with the actual session UUID. 100 | 101 | 5. Copy the provided command and run it in a new terminal tab. This command will show the AI response to your message. 102 | 103 | ![image](https://github.com/user-attachments/assets/1dfdfdd1-f69d-44af-afb2-807f9fa2da84) 104 | 105 | ## Available CLI Commands 106 | 107 | The sample app provides several CLI commands for interacting with agents and managing the application: 108 | 109 | - `php artisan agent:list`: List all available agents 110 | - `php artisan tool:list`: List all available tools 111 | - `php artisan chat`: Start a new chat session 112 | - `php artisan chat:session `: Continue an existing chat session 113 | 114 | Use the `-h` or `--help` option with any command to see more details about its usage. 115 | 116 | ## Available Agents 117 | 118 | The sample app comes with several pre-configured agents, each designed for specific tasks: 119 | 120 | ### Site Status Checker 121 | 122 | - **Key**: `site_status_checker` 123 | - **Description**: This agent specializes in checking the online status of websites. It can verify if a given URL is 124 | accessible, retrieve basic information about the site, and provide insights on potential issues if a site is 125 | offline. 126 | - **Capabilities**: 127 | - Check site availability 128 | - Retrieve DNS information 129 | - Perform ping tests 130 | - Provide troubleshooting steps for offline sites 131 | 132 | ### Order Assistant 133 | 134 | - **Key**: `order_assistant` 135 | - **Description**: This agent helps customers with order-related questions. It can retrieve order information, check 136 | delivery status, and provide customer support for e-commerce related queries. 137 | - **Capabilities**: 138 | - Retrieve order numbers 139 | - Check delivery dates 140 | - Access customer profiles 141 | - Provide personalized assistance based on customer age and preferences 142 | 143 | ### Smart Home Control Assistant 144 | 145 | - **Key**: `smart_home_control` 146 | - **Description**: This agent manages and controls various smart home devices across multiple rooms, including 147 | lights, thermostats, and TVs. 148 | - **Capabilities**: 149 | - List devices in specific rooms 150 | - Control individual devices (turn on/off, adjust settings) 151 | - Retrieve device status and details 152 | - Suggest energy-efficient settings 153 | 154 | ### Code Review Agent 155 | 156 | - **Key**: `code_review` 157 | - **Description**: This agent specializes in reviewing code. It can analyze code files, provide feedback, and 158 | suggest improvements. 159 | - **Capabilities**: 160 | - List files in a project 161 | - Read file contents 162 | - Perform code reviews 163 | - Submit review comments 164 | 165 | ### Task Splitter 166 | 167 | - **Key**: `task_splitter` 168 | - **Description**: This agent analyzes project descriptions and breaks them down into structured task lists with 169 | subtasks. 170 | - **Capabilities**: 171 | - Retrieve project descriptions 172 | - Create hierarchical task structures 173 | - Assign task priorities 174 | - Generate detailed subtasks 175 | 176 | ## Contributing 177 | 178 | Contributions are welcome! Please feel free to submit a Pull Request. 179 | 180 | ## License 181 | 182 | This sample app is open-source software licensed under the MIT license. 183 | -------------------------------------------------------------------------------- /app/Providers/SmartHomeServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->singleton(DeviceStateStorageInterface::class, DeviceStateManager::class); 23 | $this->app->singleton(DeviceStateRepositoryInterface::class, DeviceStateManager::class); 24 | 25 | $this->app->singleton(SmartHomeSystem::class, static function (Application $app) { 26 | $smartHome = new SmartHomeSystem( 27 | stateStorage: $app->make(DeviceStateStorageInterface::class), 28 | stateRepository: $app->make(DeviceStateRepositoryInterface::class), 29 | ); 30 | 31 | // Living Room Devices 32 | $livingRoomAirConditioner = new SmartAppliance( 33 | 'LR_AC_01', 34 | 'Living Room Air Conditioner', 35 | 'living_room', 36 | 'air_conditioner', 37 | [ 38 | 'temperature' => 0, 39 | 'mode' => 'cool', 40 | ], 41 | ); 42 | $livingRoomMainLight = new Light('LR_MAIN_01', 'Living Room Main Light', 'living_room', 'dimmable'); 43 | $livingRoomTableLamp = new Light('LR_LAMP_01', 'Living Room Table Lamp', 'living_room', 'color'); 44 | $livingRoomThermostat = new Thermostat('LR_THERM_01', 'Living Room Thermostat', 'living_room', 24); 45 | $livingRoomTV = new TV('LR_TV_01', 'Living Room TV', 'living_room', 20, 'HDMI 1'); 46 | $livingRoomFireplace = new SmartAppliance( 47 | 'LR_FIRE_01', 48 | 'Living Room Fireplace', 49 | 'living_room', 50 | 'fireplace', 51 | [ 52 | 'temperature' => 0, 53 | ], 54 | ); 55 | $livingRoomSpeaker = new SmartAppliance( 56 | 'LR_SPEAK_01', 57 | 'Living Room Smart Speaker', 58 | 'living_room', 59 | 'speaker', 60 | [ 61 | 'volume' => 0, 62 | 'radio_station' => 'Classical FM', 63 | ], 64 | ); 65 | 66 | // Kitchen Devices 67 | $kitchenMainLight = new Light('KT_MAIN_01', 'Kitchen Main Light', 'kitchen', 'dimmable'); 68 | $kitchenPendantLights = new Light('KT_PEND_01', 'Kitchen Pendant Lights', 'kitchen', 'dimmable'); 69 | $kitchenRefrigerator = new SmartAppliance( 70 | 'KT_FRIDGE_01', 71 | 'Smart Refrigerator', 72 | 'kitchen', 73 | 'refrigerator', 74 | [ 75 | 'temperature' => 37, 76 | 'mode' => 'normal', 77 | ], 78 | ); 79 | $kitchenOven = new SmartAppliance('KT_OVEN_01', 'Smart Oven', 'kitchen', 'oven'); 80 | $kitchenCoffeeMaker = new SmartAppliance( 81 | 'KT_COFFEE_01', 'Smart Coffee Maker', 'kitchen', 'coffee_maker', 82 | ); 83 | 84 | // Bedroom Devices 85 | $bedroomMainLight = new Light('BR_MAIN_01', 'Bedroom Main Light', 'bedroom', 'dimmable'); 86 | $bedroomNightstandLeft = new Light('BR_NIGHT_L_01', 'Left Nightstand Lamp', 'bedroom', 'color'); 87 | $bedroomNightstandRight = new Light('BR_NIGHT_R_01', 'Right Nightstand Lamp', 'bedroom', 'color'); 88 | $bedroomThermostat = new Thermostat('BR_THERM_01', 'Bedroom Thermostat', 'bedroom', 68); 89 | $bedroomTV = new TV('BR_TV_01', 'Bedroom TV', 'bedroom', 15, 'HDMI 1'); 90 | $bedroomCeilingFan = new SmartAppliance('BR_FAN_01', 'Bedroom Ceiling Fan', 'bedroom', 'fan'); 91 | 92 | // Bathroom Devices 93 | $bathroomMainLight = new Light('BA_MAIN_01', 'Bathroom Main Light', 'bathroom', 'dimmable'); 94 | $bathroomMirrorLight = new Light('BA_MIRROR_01', 'Bathroom Mirror Light', 'bathroom', 'color'); 95 | $bathroomExhaustFan = new SmartAppliance('BA_FAN_01', 'Bathroom Exhaust Fan', 'bathroom', 'fan'); 96 | $bathroomSmartScale = new SmartAppliance('BA_SCALE_01', 'Smart Scale', 'bathroom', 'scale'); 97 | 98 | // Add all devices to the smart home system 99 | $smartHome->addDevice($livingRoomAirConditioner); 100 | $smartHome->addDevice($livingRoomMainLight); 101 | $smartHome->addDevice($livingRoomTableLamp); 102 | $smartHome->addDevice($livingRoomThermostat); 103 | $smartHome->addDevice($livingRoomTV); 104 | $smartHome->addDevice($livingRoomFireplace); 105 | $smartHome->addDevice($livingRoomSpeaker); 106 | 107 | $smartHome->addDevice($kitchenMainLight); 108 | $smartHome->addDevice($kitchenPendantLights); 109 | $smartHome->addDevice($kitchenRefrigerator); 110 | $smartHome->addDevice($kitchenOven); 111 | $smartHome->addDevice($kitchenCoffeeMaker); 112 | 113 | $smartHome->addDevice($bedroomMainLight); 114 | $smartHome->addDevice($bedroomNightstandLeft); 115 | $smartHome->addDevice($bedroomNightstandRight); 116 | $smartHome->addDevice($bedroomThermostat); 117 | $smartHome->addDevice($bedroomTV); 118 | $smartHome->addDevice($bedroomCeilingFan); 119 | 120 | $smartHome->addDevice($bathroomMainLight); 121 | $smartHome->addDevice($bathroomMirrorLight); 122 | $smartHome->addDevice($bathroomExhaustFan); 123 | $smartHome->addDevice($bathroomSmartScale); 124 | 125 | return $smartHome; 126 | }); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /config/database.php: -------------------------------------------------------------------------------- 1 | env('DB_CONNECTION', 'sqlite'), 20 | 21 | /* 22 | |-------------------------------------------------------------------------- 23 | | Database Connections 24 | |-------------------------------------------------------------------------- 25 | | 26 | | Below are all of the database connections defined for your application. 27 | | An example configuration is provided for each database system which 28 | | is supported by Laravel. You're free to add / remove connections. 29 | | 30 | */ 31 | 32 | 'connections' => [ 33 | 34 | 'sqlite' => [ 35 | 'driver' => 'sqlite', 36 | 'url' => env('DB_URL'), 37 | 'database' => env('DB_DATABASE', database_path('database.sqlite')), 38 | 'prefix' => '', 39 | 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true), 40 | 'busy_timeout' => null, 41 | 'journal_mode' => null, 42 | 'synchronous' => null, 43 | ], 44 | 45 | 'mysql' => [ 46 | 'driver' => 'mysql', 47 | 'url' => env('DB_URL'), 48 | 'host' => env('DB_HOST', '127.0.0.1'), 49 | 'port' => env('DB_PORT', '3306'), 50 | 'database' => env('DB_DATABASE', 'laravel'), 51 | 'username' => env('DB_USERNAME', 'root'), 52 | 'password' => env('DB_PASSWORD', ''), 53 | 'unix_socket' => env('DB_SOCKET', ''), 54 | 'charset' => env('DB_CHARSET', 'utf8mb4'), 55 | 'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'), 56 | 'prefix' => '', 57 | 'prefix_indexes' => true, 58 | 'strict' => true, 59 | 'engine' => null, 60 | 'options' => extension_loaded('pdo_mysql') ? array_filter([ 61 | PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), 62 | ]) : [], 63 | ], 64 | 65 | 'mariadb' => [ 66 | 'driver' => 'mariadb', 67 | 'url' => env('DB_URL'), 68 | 'host' => env('DB_HOST', '127.0.0.1'), 69 | 'port' => env('DB_PORT', '3306'), 70 | 'database' => env('DB_DATABASE', 'laravel'), 71 | 'username' => env('DB_USERNAME', 'root'), 72 | 'password' => env('DB_PASSWORD', ''), 73 | 'unix_socket' => env('DB_SOCKET', ''), 74 | 'charset' => env('DB_CHARSET', 'utf8mb4'), 75 | 'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'), 76 | 'prefix' => '', 77 | 'prefix_indexes' => true, 78 | 'strict' => true, 79 | 'engine' => null, 80 | 'options' => extension_loaded('pdo_mysql') ? array_filter([ 81 | PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), 82 | ]) : [], 83 | ], 84 | 85 | 'pgsql' => [ 86 | 'driver' => 'pgsql', 87 | 'url' => env('DB_URL'), 88 | 'host' => env('DB_HOST', '127.0.0.1'), 89 | 'port' => env('DB_PORT', '5432'), 90 | 'database' => env('DB_DATABASE', 'laravel'), 91 | 'username' => env('DB_USERNAME', 'root'), 92 | 'password' => env('DB_PASSWORD', ''), 93 | 'charset' => env('DB_CHARSET', 'utf8'), 94 | 'prefix' => '', 95 | 'prefix_indexes' => true, 96 | 'search_path' => 'public', 97 | 'sslmode' => 'prefer', 98 | ], 99 | 100 | 'sqlsrv' => [ 101 | 'driver' => 'sqlsrv', 102 | 'url' => env('DB_URL'), 103 | 'host' => env('DB_HOST', 'localhost'), 104 | 'port' => env('DB_PORT', '1433'), 105 | 'database' => env('DB_DATABASE', 'laravel'), 106 | 'username' => env('DB_USERNAME', 'root'), 107 | 'password' => env('DB_PASSWORD', ''), 108 | 'charset' => env('DB_CHARSET', 'utf8'), 109 | 'prefix' => '', 110 | 'prefix_indexes' => true, 111 | // 'encrypt' => env('DB_ENCRYPT', 'yes'), 112 | // 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'), 113 | ], 114 | 115 | ], 116 | 117 | /* 118 | |-------------------------------------------------------------------------- 119 | | Migration Repository Table 120 | |-------------------------------------------------------------------------- 121 | | 122 | | This table keeps track of all the migrations that have already run for 123 | | your application. Using this information, we can determine which of 124 | | the migrations on disk haven't actually been run on the database. 125 | | 126 | */ 127 | 128 | 'migrations' => [ 129 | 'table' => 'migrations', 130 | 'update_date_on_publish' => true, 131 | ], 132 | 133 | /* 134 | |-------------------------------------------------------------------------- 135 | | Redis Databases 136 | |-------------------------------------------------------------------------- 137 | | 138 | | Redis is an open source, fast, and advanced key-value store that also 139 | | provides a richer body of commands than a typical key-value system 140 | | such as Memcached. You may define your connection settings here. 141 | | 142 | */ 143 | 144 | 'redis' => [ 145 | 146 | 'client' => env('REDIS_CLIENT', 'phpredis'), 147 | 148 | 'options' => [ 149 | 'cluster' => env('REDIS_CLUSTER', 'redis'), 150 | 'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'), 151 | ], 152 | 153 | 'default' => [ 154 | 'url' => env('REDIS_URL'), 155 | 'host' => env('REDIS_HOST', '127.0.0.1'), 156 | 'username' => env('REDIS_USERNAME'), 157 | 'password' => env('REDIS_PASSWORD'), 158 | 'port' => env('REDIS_PORT', '6379'), 159 | 'database' => env('REDIS_DB', '0'), 160 | ], 161 | 162 | 'cache' => [ 163 | 'url' => env('REDIS_URL'), 164 | 'host' => env('REDIS_HOST', '127.0.0.1'), 165 | 'username' => env('REDIS_USERNAME'), 166 | 'password' => env('REDIS_PASSWORD'), 167 | 'port' => env('REDIS_PORT', '6379'), 168 | 'database' => env('REDIS_CACHE_DB', '1'), 169 | ], 170 | 171 | ], 172 | 173 | ]; 174 | -------------------------------------------------------------------------------- /app/Chat/SimpleChatService.php: -------------------------------------------------------------------------------- 1 | agents->has($agentName)) { 46 | throw new AgentNotFoundException($agentName); 47 | } 48 | 49 | $agent = $this->agents->get($agentName); 50 | 51 | $session = Session::create([ 52 | 'id' => Uuid::uuid7(), 53 | 'account_uuid' => $accountUuid, 54 | 'agent_name' => $agentName, 55 | 'title' => $agent->getDescription(), 56 | ]); 57 | 58 | return $session->getUuid(); 59 | } 60 | 61 | public function ask(UuidInterface $sessionUuid, string|\Stringable $message): UuidInterface 62 | { 63 | $session = $this->getSession($sessionUuid); 64 | 65 | $prompt = null; 66 | if (!$session->history->isEmpty()) { 67 | $prompt = $session->history->toPrompt(); 68 | } 69 | 70 | $messageUuid = Uuid::uuid4(); 71 | $this->eventDispatcher?->dispatch( 72 | new \LLM\Agents\Chat\Event\Question( 73 | sessionUuid: $session->getUuid(), 74 | messageUuid: $messageUuid, 75 | createdAt: new \DateTimeImmutable(), 76 | message: $message, 77 | ), 78 | ); 79 | 80 | $execution = $this->buildAgent( 81 | session: $session, 82 | prompt: $prompt, 83 | )->ask($message); 84 | 85 | $this->handleResult($execution, $session); 86 | 87 | return $messageUuid; 88 | } 89 | 90 | public function closeSession(UuidInterface $sessionUuid): void 91 | { 92 | $session = $this->getSession($sessionUuid); 93 | $session->finished_at = now(); 94 | 95 | $this->updateSession($session); 96 | } 97 | 98 | public function updateSession(SessionInterface $session): void 99 | { 100 | $session->save(); 101 | } 102 | 103 | private function handleResult(Execution $execution, SessionInterface $session): void 104 | { 105 | $finished = false; 106 | while (true) { 107 | $result = $execution->result; 108 | $prompt = $execution->prompt; 109 | 110 | if ($result instanceof ToolCalledResponse) { 111 | // First, call all tools. 112 | $toolsResponse = []; 113 | foreach ($result->tools as $tool) { 114 | $toolsResponse[] = $this->callTool($session, $tool); 115 | } 116 | 117 | // Then add the tools responses to the prompt. 118 | foreach ($toolsResponse as $toolResponse) { 119 | $prompt = $prompt->withAddedMessage($toolResponse); 120 | } 121 | 122 | $execution = $this->buildAgent( 123 | session: $session, 124 | prompt: $prompt, 125 | )->continue(); 126 | } elseif ($result instanceof ChatResponse) { 127 | $finished = true; 128 | 129 | $this->eventDispatcher?->dispatch( 130 | new \LLM\Agents\Chat\Event\Message( 131 | sessionUuid: $session->getUuid(), 132 | createdAt: new \DateTimeImmutable(), 133 | message: $result->content, 134 | ), 135 | ); 136 | } 137 | 138 | $session->updateHistory($prompt->toArray()); 139 | $this->updateSession($session); 140 | 141 | if ($finished) { 142 | break; 143 | } 144 | } 145 | } 146 | 147 | private function buildAgent(SessionInterface $session, ?Prompt $prompt): AgentExecutorBuilder 148 | { 149 | $context = new Context(); 150 | $context->setAuthContext([ 151 | 'account_uuid' => (string) $session->account_uuid, 152 | 'session_uuid' => (string) $session->getUuid(), 153 | ]); 154 | 155 | $agent = $this->builder 156 | ->withAgentKey($session->getAgentName()) 157 | ->withStreamChunkCallback( 158 | new StreamChunkCallback( 159 | sessionUuid: $session->getUuid(), 160 | eventDispatcher: $this->eventDispatcher, 161 | ), 162 | ) 163 | ->withPromptContext($context); 164 | 165 | if ($prompt === null) { 166 | return $agent; 167 | } 168 | 169 | $memories = $this->memoryService->getCurrentMemory($session->getUuid()); 170 | 171 | return $agent->withPrompt($prompt->withValues([ 172 | 'dynamic_memory' => \implode( 173 | "\n", 174 | \array_map( 175 | fn(SolutionMetadata $memory) => $memory->content, 176 | $memories->memories, 177 | ), 178 | ), 179 | ])); 180 | } 181 | 182 | private function callTool(SessionInterface $session, ToolCall $tool): ToolCallResultMessage 183 | { 184 | $this->eventDispatcher?->dispatch( 185 | new \LLM\Agents\Chat\Event\ToolCall( 186 | sessionUuid: $session->getUuid(), 187 | id: $tool->id, 188 | tool: $tool->name, 189 | arguments: $tool->arguments, 190 | createdAt: new \DateTimeImmutable(), 191 | ), 192 | ); 193 | 194 | try { 195 | $functionResult = $this->toolExecutor->execute($tool->name, $tool->arguments); 196 | 197 | $this->eventDispatcher?->dispatch( 198 | new \LLM\Agents\Chat\Event\ToolCallResult( 199 | sessionUuid: $session->getUuid(), 200 | id: $tool->id, 201 | tool: $tool->name, 202 | result: $functionResult, 203 | createdAt: new \DateTimeImmutable(), 204 | ), 205 | ); 206 | } catch (\Throwable $e) { 207 | $this->eventDispatcher?->dispatch( 208 | new \LLM\Agents\Chat\Event\ToolCallResult( 209 | sessionUuid: $session->getUuid(), 210 | id: $tool->id, 211 | tool: $tool->name, 212 | result: \json_encode([ 213 | 'error' => $e->getMessage(), 214 | ]), 215 | createdAt: new \DateTimeImmutable(), 216 | ), 217 | ); 218 | 219 | return new ToolCallResultMessage( 220 | id: $tool->id, 221 | content: [ 222 | $e->getMessage(), 223 | ], 224 | ); 225 | } 226 | 227 | return new ToolCallResultMessage( 228 | id: $tool->id, 229 | content: [$functionResult], 230 | ); 231 | } 232 | 233 | public function getLatestSession(): ?SessionInterface 234 | { 235 | return Session::latest()->first(); 236 | } 237 | 238 | public function getLatestSessions(int $limit = 3): array 239 | { 240 | return Session::latest()->limit($limit)->get(); 241 | } 242 | } 243 | -------------------------------------------------------------------------------- /config/session.php: -------------------------------------------------------------------------------- 1 | env('SESSION_DRIVER', 'database'), 22 | 23 | /* 24 | |-------------------------------------------------------------------------- 25 | | Session Lifetime 26 | |-------------------------------------------------------------------------- 27 | | 28 | | Here you may specify the number of minutes that you wish the session 29 | | to be allowed to remain idle before it expires. If you want them 30 | | to expire immediately when the browser is closed then you may 31 | | indicate that via the expire_on_close configuration option. 32 | | 33 | */ 34 | 35 | 'lifetime' => env('SESSION_LIFETIME', 120), 36 | 37 | 'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false), 38 | 39 | /* 40 | |-------------------------------------------------------------------------- 41 | | Session Encryption 42 | |-------------------------------------------------------------------------- 43 | | 44 | | This option allows you to easily specify that all of your session data 45 | | should be encrypted before it's stored. All encryption is performed 46 | | automatically by Laravel and you may use the session like normal. 47 | | 48 | */ 49 | 50 | 'encrypt' => env('SESSION_ENCRYPT', false), 51 | 52 | /* 53 | |-------------------------------------------------------------------------- 54 | | Session File Location 55 | |-------------------------------------------------------------------------- 56 | | 57 | | When utilizing the "file" session driver, the session files are placed 58 | | on disk. The default storage location is defined here; however, you 59 | | are free to provide another location where they should be stored. 60 | | 61 | */ 62 | 63 | 'files' => storage_path('framework/sessions'), 64 | 65 | /* 66 | |-------------------------------------------------------------------------- 67 | | Session Database Connection 68 | |-------------------------------------------------------------------------- 69 | | 70 | | When using the "database" or "redis" session drivers, you may specify a 71 | | connection that should be used to manage these sessions. This should 72 | | correspond to a connection in your database configuration options. 73 | | 74 | */ 75 | 76 | 'connection' => env('SESSION_CONNECTION'), 77 | 78 | /* 79 | |-------------------------------------------------------------------------- 80 | | Session Database Table 81 | |-------------------------------------------------------------------------- 82 | | 83 | | When using the "database" session driver, you may specify the table to 84 | | be used to store sessions. Of course, a sensible default is defined 85 | | for you; however, you're welcome to change this to another table. 86 | | 87 | */ 88 | 89 | 'table' => env('SESSION_TABLE', 'sessions'), 90 | 91 | /* 92 | |-------------------------------------------------------------------------- 93 | | Session Cache Store 94 | |-------------------------------------------------------------------------- 95 | | 96 | | When using one of the framework's cache driven session backends, you may 97 | | define the cache store which should be used to store the session data 98 | | between requests. This must match one of your defined cache stores. 99 | | 100 | | Affects: "apc", "dynamodb", "memcached", "redis" 101 | | 102 | */ 103 | 104 | 'store' => env('SESSION_STORE'), 105 | 106 | /* 107 | |-------------------------------------------------------------------------- 108 | | Session Sweeping Lottery 109 | |-------------------------------------------------------------------------- 110 | | 111 | | Some session drivers must manually sweep their storage location to get 112 | | rid of old sessions from storage. Here are the chances that it will 113 | | happen on a given request. By default, the odds are 2 out of 100. 114 | | 115 | */ 116 | 117 | 'lottery' => [2, 100], 118 | 119 | /* 120 | |-------------------------------------------------------------------------- 121 | | Session Cookie Name 122 | |-------------------------------------------------------------------------- 123 | | 124 | | Here you may change the name of the session cookie that is created by 125 | | the framework. Typically, you should not need to change this value 126 | | since doing so does not grant a meaningful security improvement. 127 | | 128 | */ 129 | 130 | 'cookie' => env( 131 | 'SESSION_COOKIE', 132 | Str::slug(env('APP_NAME', 'laravel'), '_').'_session' 133 | ), 134 | 135 | /* 136 | |-------------------------------------------------------------------------- 137 | | Session Cookie Path 138 | |-------------------------------------------------------------------------- 139 | | 140 | | The session cookie path determines the path for which the cookie will 141 | | be regarded as available. Typically, this will be the root path of 142 | | your application, but you're free to change this when necessary. 143 | | 144 | */ 145 | 146 | 'path' => env('SESSION_PATH', '/'), 147 | 148 | /* 149 | |-------------------------------------------------------------------------- 150 | | Session Cookie Domain 151 | |-------------------------------------------------------------------------- 152 | | 153 | | This value determines the domain and subdomains the session cookie is 154 | | available to. By default, the cookie will be available to the root 155 | | domain and all subdomains. Typically, this shouldn't be changed. 156 | | 157 | */ 158 | 159 | 'domain' => env('SESSION_DOMAIN'), 160 | 161 | /* 162 | |-------------------------------------------------------------------------- 163 | | HTTPS Only Cookies 164 | |-------------------------------------------------------------------------- 165 | | 166 | | By setting this option to true, session cookies will only be sent back 167 | | to the server if the browser has a HTTPS connection. This will keep 168 | | the cookie from being sent to you when it can't be done securely. 169 | | 170 | */ 171 | 172 | 'secure' => env('SESSION_SECURE_COOKIE'), 173 | 174 | /* 175 | |-------------------------------------------------------------------------- 176 | | HTTP Access Only 177 | |-------------------------------------------------------------------------- 178 | | 179 | | Setting this value to true will prevent JavaScript from accessing the 180 | | value of the cookie and the cookie will only be accessible through 181 | | the HTTP protocol. It's unlikely you should disable this option. 182 | | 183 | */ 184 | 185 | 'http_only' => env('SESSION_HTTP_ONLY', true), 186 | 187 | /* 188 | |-------------------------------------------------------------------------- 189 | | Same-Site Cookies 190 | |-------------------------------------------------------------------------- 191 | | 192 | | This option determines how your cookies behave when cross-site requests 193 | | take place, and can be used to mitigate CSRF attacks. By default, we 194 | | will set this value to "lax" to permit secure cross-site requests. 195 | | 196 | | See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value 197 | | 198 | | Supported: "lax", "strict", "none", null 199 | | 200 | */ 201 | 202 | 'same_site' => env('SESSION_SAME_SITE', 'lax'), 203 | 204 | /* 205 | |-------------------------------------------------------------------------- 206 | | Partitioned Cookies 207 | |-------------------------------------------------------------------------- 208 | | 209 | | Setting this value to true will tie the cookie to the top-level site for 210 | | a cross-site context. Partitioned cookies are accepted by the browser 211 | | when flagged "secure" and the Same-Site attribute is set to "none". 212 | | 213 | */ 214 | 215 | 'partitioned' => env('SESSION_PARTITIONED_COOKIE', false), 216 | 217 | ]; 218 | -------------------------------------------------------------------------------- /resources/views/welcome.blade.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Laravel 8 | 9 | 10 | 11 | 12 | 13 | 14 | 17 | 18 | 19 |
20 | 21 |
22 |
23 |
24 |
25 | 26 |
27 | @if (Route::has('login')) 28 | 54 | @endif 55 |
56 | 57 |
58 | 163 |
164 | 165 | 168 |
169 |
170 |
171 | 172 | 173 | --------------------------------------------------------------------------------