diff --git a/README.md b/README.md index 833e7f6..e815562 100644 --- a/README.md +++ b/README.md @@ -46,11 +46,20 @@ npm install && npm run build It needs [Auth](https://github.com/saucebase-dev/auth) for sign-in. Conversation titles are written by a queued job, so run a queue worker. +## Upgrade from 0.x + +Version 1 needs laravel/ai 1.4 or newer, which stores chats in a new format. The module's migration creates the new tables on a fresh install only, so an app that already has chats must convert them: + +- **Keep the chats:** back up the database, copy the backfill migration from [laravel/ai's upgrade guide](https://github.com/laravel/ai/blob/1.x/UPGRADE.md#conversation-messages-now-store-steps) into `database/migrations`, and run `php artisan migrate`. +- **Start over:** rebuild the database with `php artisan migrate:fresh`. This deletes all of the app's data, not only the chats. + +Until then, chats don't save or reopen. + ## Configuration In the admin panel, under **Settings → AI chat** (people with the `manage ai chat` permission, and admins), in four sections: -- **Models**: each provider with its API key (stored encrypted; a key set in `.env`, laravel/ai's `config/ai.php`, works too) and the models users can pick, and the default model. Only providers with a key are offered. In test mode the page says the demos replace them. +- **Models**: each provider with its API key (stored encrypted; a key set in `.env`, laravel/ai's `config/ai.php`, works too) and the models users can pick, and the default model. Only providers with a key are offered. Amazon Bedrock also needs `composer require aws/aws-sdk-php`. In test mode the page says the demos replace them. - **Assistant**: instructions added to the assistant's own. - **Images**: the provider, model and quality `generate_image` uses. `.env` can set them too (`AI_CHAT_IMAGE_PROVIDER`, `AI_CHAT_IMAGE_MODEL`, `AI_CHAT_IMAGE_QUALITY`); without either, laravel/ai's default for images. - **WebMCP (beta)**: off by default. On, the chat offers its tools to the visitor's own browser agent, in browsers that support WebMCP (a draft standard). diff --git a/composer.json b/composer.json index 4a229aa..663eca1 100644 --- a/composer.json +++ b/composer.json @@ -65,6 +65,6 @@ "minimum-stability": "stable", "require": { "saucebase/core": "^3.3", - "laravel/ai": "^0.11" + "laravel/ai": "^1.4" } } diff --git a/database/migrations/1000_00_00_000001_create_agent_conversations_table.php b/database/migrations/1000_00_00_000001_create_agent_conversations_table.php index d5c0ce7..083db9b 100644 --- a/database/migrations/1000_00_00_000001_create_agent_conversations_table.php +++ b/database/migrations/1000_00_00_000001_create_agent_conversations_table.php @@ -38,15 +38,14 @@ public function up(): void $table->string('role', 25); $table->text('content'); $table->text('attachments'); - $table->text('tool_calls'); - $table->text('tool_results'); + $table->longText('steps'); $table->text('usage'); $table->text('meta'); - $table->text('approval_state')->nullable(); + $table->string('status', 25); $table->timestamps(); $table->index(['conversation_id', 'participant_type', 'participant_id', 'updated_at'], 'conversation_index'); - $table->index(['participant_type', 'participant_id'], 'participant_index'); + $table->index(['participant_type', 'participant_id', 'agent'], 'participant_index'); }); } diff --git a/resources/boost/skills/saucebase-ai-chat-development/SKILL.md b/resources/boost/skills/saucebase-ai-chat-development/SKILL.md index 3dde8c5..26e1dc1 100644 --- a/resources/boost/skills/saucebase-ai-chat-development/SKILL.md +++ b/resources/boost/skills/saucebase-ai-chat-development/SKILL.md @@ -38,6 +38,7 @@ Provider-hosted tools (`WebSearch`) stream no parts: the steps list never shows - Over the monthly message limit the route answers 429 JSON before creating anything. The page shows the message and puts the text back in the box (422 too). - laravel/ai stores the turn only after the stream completes. So the stream sets `ignore_user_abort(true)` (Stop would otherwise end PHP before storing; the reply finishes and is kept) and `set_time_limit(300)` (the default 30 s cuts long replies). - `regenerate: true` (Ask again, Try again) deletes the previous turn after the new one is stored, only when its question matches: a failed reply stores nothing, so the turn before it stays. +- A reply that fails after its first step is stored by laravel/ai with the `failed` status; `forgetFailedTurn()` deletes it and its question, so it costs no monthly message. Read tool calls from a message's `steps` (or its read-only `tool_results`), never from columns of their own. - A chat opens on its newest 50 messages (`AiChatController::MESSAGES_PER_PAGE`, `hasOlder`). Older pages come from `GET chat/{id}/history?before=` when the marker above the messages scrolls into view, and go before the ones shown. The marker sits outside `MessageScrollerContent`: the scroller treats each of its children as a message, and keeps the view in place on a prepend by its first one. - Steps are built on `trace`, like shadcn-vue's Reasoning: a thought is a plain "Thinking…" line until its first words, then a closed line that opens onto it, rendered as markdown (models write bold and headings). Closed while streaming too: a thought that opened, grew and closed again moved the reply under the reader and pulled the view back. Until a reply shows anything, `ChatMessage` renders that same line (`showsNothing()`), and before the reply exists the page renders an empty `ChatMessage` in its place: the line never moves when the thought takes over. The `thinking` demo has a long thought. - Scrolling, as in ChatGPT minus the blank screen: a chat opens at the end, and a new question takes the view there once (`ChatScrollButton`, by the question count); nothing else moves it. No `auto-scroll` (chasing the reply moved the text from under the reader) and no `scroll-anchor` (holding the question at the top took a spacer up to a screen tall, which, shrinking, yanked the view). Instead a fixed `pb-48` under the messages, and while the end is out of view the button over it shows dots while a reply streams, an arrow after. diff --git a/resources/views/filament/transcript.blade.php b/resources/views/filament/transcript.blade.php new file mode 100644 index 0000000..73983ef --- /dev/null +++ b/resources/views/filament/transcript.blade.php @@ -0,0 +1,45 @@ +@php + use Modules\AiChat\Ai\Tools\GenerateImage; +@endphp + +@if ($messages->isEmpty()) + +@else +
+ @foreach ($messages as $message) + @php + $isUser = $message->role === 'user'; + $images = collect($message->tool_results) + ->filter(fn (array $result): bool => $result['name'] === GenerateImage::NAME && empty($result['failed'])) + ->map(fn (array $result): mixed => is_string($result['result']) ? json_decode($result['result'], true) : $result['result']) + ->filter(fn (mixed $image): bool => is_array($image) && filled($image['url'] ?? null)); + @endphp + +
$isUser, 'items-start' => ! $isUser])> +
+ {{ $isUser ? $name : __('Assistant') }} + +
+ + @foreach ($images as $image) + {{ $image['prompt'] ?? '' }} + @endforeach + + @if (filled($message->content)) + @if ($isUser) +
{{ $message->content }}
+ @else +
+ {!! str($message->content)->markdown()->sanitizeHtml() !!} +
+ @endif + @endif +
+ @endforeach +
+@endif diff --git a/src/Ai/Demo/DemoGateway.php b/src/Ai/Demo/DemoGateway.php index db770eb..8996f9e 100644 --- a/src/Ai/Demo/DemoGateway.php +++ b/src/Ai/Demo/DemoGateway.php @@ -17,10 +17,11 @@ use Laravel\Ai\Responses\Data\Citation as CitationData; use Laravel\Ai\Responses\Data\FinishReason; use Laravel\Ai\Responses\Data\GeneratedImage; +use Laravel\Ai\Responses\Data\ImageUsage; use Laravel\Ai\Responses\Data\Meta; +use Laravel\Ai\Responses\Data\TextUsage; use Laravel\Ai\Responses\Data\ToolCall; use Laravel\Ai\Responses\Data\UrlCitation; -use Laravel\Ai\Responses\Data\Usage; use Laravel\Ai\Responses\ImageResponse; use Laravel\Ai\Streaming\Events\Citation; use Laravel\Ai\Streaming\Events\Error; @@ -142,10 +143,11 @@ public function generateImage( ?string $size = null, ?string $quality = null, ?int $timeout = null, + array $providerOptions = [], ): ImageResponse { return new ImageResponse( new Collection([new GeneratedImage(base64_encode($this->drawing($prompt)), 'image/png')]), - new Usage, + new ImageUsage, new Meta($provider->name(), $model), ); } @@ -214,7 +216,7 @@ protected function response(TextProvider $provider, string $model, string $text, $text, $calls, $calls === [] ? FinishReason::Stop : FinishReason::ToolCalls, - new Usage, + new TextUsage, new Meta($provider->name(), $model, new Collection($citations)), ); } diff --git a/src/Ai/Providers.php b/src/Ai/Providers.php index d61734f..17b569a 100644 --- a/src/Ai/Providers.php +++ b/src/Ai/Providers.php @@ -10,7 +10,7 @@ * * Asked of laravel/ai rather than listed here: a provider it can't build a * text (or image) client for can't answer the chat (or draw), whatever its - * config says. Cohere, Jina and Voyage AI are embeddings and reranking; + * config says. Jina and Voyage AI are embeddings and reranking; * ElevenLabs is audio. */ class Providers diff --git a/src/Filament/Resources/Conversations/ConversationResource.php b/src/Filament/Resources/Conversations/ConversationResource.php index f32e9da..1425b13 100644 --- a/src/Filament/Resources/Conversations/ConversationResource.php +++ b/src/Filament/Resources/Conversations/ConversationResource.php @@ -4,10 +4,11 @@ use BackedEnum; use Filament\Actions\ViewAction; -use Filament\Infolists\Components\RepeatableEntry; -use Filament\Infolists\Components\TextEntry; use Filament\Resources\Resource; +use Filament\Schemas\Components\Section; +use Filament\Schemas\Components\View; use Filament\Schemas\Schema; +use Filament\Support\Enums\Width; use Filament\Support\Icons\Heroicon; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Table; @@ -63,18 +64,25 @@ public static function table(Table $table): Table public static function infolist(Schema $schema): Schema { return $schema->columns(1)->components([ - TextEntry::make('participant.name')->label(__('User')), - // Ordered by id: laravel/ai keys messages with time-ordered UUIDv7. - RepeatableEntry::make('transcript') - ->label(__('Transcript')) - ->state(fn (Conversation $record) => $record->messages()->whereIn('role', ['user', 'assistant'])->orderBy('id')->get(['role', 'content'])->toArray()) + Section::make(fn (Conversation $record): string => self::participantName($record)) + ->description(fn (Conversation $record): ?string => $record->participant?->getAttribute('email')) + ->icon(Heroicon::OutlinedUser) + ->maxWidth(Width::FourExtraLarge) ->schema([ - TextEntry::make('role')->hiddenLabel()->badge(), - TextEntry::make('content')->hiddenLabel()->markdown(), + View::make('ai-chat::filament.transcript')->viewData(fn (Conversation $record): array => [ + 'name' => self::participantName($record), + // Ordered by id: laravel/ai keys messages with time-ordered UUIDv7. + 'messages' => $record->messages()->whereIn('role', ['user', 'assistant'])->orderBy('id')->get(['id', 'role', 'content', 'steps', 'created_at']), + ]), ]), ]); } + protected static function participantName(Conversation $record): string + { + return $record->participant?->getAttribute('name') ?? __('User'); + } + public static function getPages(): array { return [ diff --git a/src/Http/Controllers/AiChatController.php b/src/Http/Controllers/AiChatController.php index fde2719..f422e9a 100644 --- a/src/Http/Controllers/AiChatController.php +++ b/src/Http/Controllers/AiChatController.php @@ -12,6 +12,7 @@ use Illuminate\Validation\Rule; use Inertia\Inertia; use Inertia\Response; +use Laravel\Ai\Enums\MessageStatus; use Laravel\Ai\Messages\Message; use Laravel\Ai\Models\Conversation; use Laravel\Ai\Models\ConversationMessage; @@ -91,13 +92,11 @@ protected function transcript(Conversation $conversation, ?string $before = null ->when($before, fn ($query) => $query->where('id', '<', $before)) ->orderByDesc('id') ->limit(self::MESSAGES_PER_PAGE + 1) - ->get(['id', 'role', 'content', 'tool_results']); + ->get(['id', 'role', 'content', 'steps']); $messages = $rows->take(self::MESSAGES_PER_PAGE)->reverse() ->map(function (ConversationMessage $message): array { - // Cast to an array by the model; decoded here too in case a store keeps raw JSON. - $results = $message->getAttribute('tool_results'); - $images = collect(is_array($results) ? $results : (json_decode((string) $results, true) ?: [])) + $images = collect($message->tool_results) ->filter(fn (array $result): bool => ($result['name'] ?? null) === GenerateImage::NAME && empty($result['failed'])) ->map(fn (array $result): array => [ 'type' => 'tool-'.GenerateImage::NAME, @@ -218,6 +217,7 @@ public function stream(Request $request): SymfonyResponse $conversation->messages()->whereKey($replaced)->delete(); $this->retitle($conversation); }) + ->catch(fn () => $this->forgetFailedTurn($conversation)) ->usingVercelDataProtocol() ->toResponse($request); @@ -246,6 +246,24 @@ protected function lastTurn(Conversation $conversation, string $message): array return $conversation->messages()->where('id', '>=', $last->getKey())->pluck('id')->all(); } + /** + * Drop the turn laravel/ai stores when a reply fails after its first step: a + * failed reply stores nothing, so it doesn't count against the user's monthly + * messages and trying again doesn't repeat the question. + */ + protected function forgetFailedTurn(Conversation $conversation): void + { + $failed = $conversation->messages()->where('role', 'assistant')->where('status', MessageStatus::Failed)->max('id'); + + if ($failed === null) { + return; + } + + $question = $conversation->messages()->where('role', 'user')->where('id', '<', $failed)->max('id'); + + $conversation->messages()->whereKey(array_filter([$question, $failed]))->delete(); + } + /** * The user's chats matching the search box, by title. */ diff --git a/tests/Feature/AdminTest.php b/tests/Feature/AdminTest.php index 663336d..7cb4b9c 100644 --- a/tests/Feature/AdminTest.php +++ b/tests/Feature/AdminTest.php @@ -6,6 +6,7 @@ use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Str; use Laravel\Ai\Ai; +use Laravel\Ai\Enums\MessageStatus; use Laravel\Ai\Models\Conversation; use Livewire\Livewire; use Modules\AiChat\Ai\ChatAgent; @@ -162,7 +163,7 @@ public function test_managers_can_read_a_conversation(): void 'agent' => ChatAgent::class, 'role' => 'user', 'content' => 'Draft our launch email', - 'attachments' => '[]', 'tool_calls' => '[]', 'tool_results' => '[]', 'usage' => '[]', 'meta' => '[]', + 'attachments' => [], 'steps' => [], 'usage' => [], 'meta' => [], 'status' => MessageStatus::Completed, ]); $this->actingAs($this->manager()); @@ -170,4 +171,56 @@ public function test_managers_can_read_a_conversation(): void $this->get(ConversationResource::getUrl())->assertOk()->assertSee('Launch email')->assertSee('Ada'); $this->get(ConversationResource::getUrl('view', ['record' => $conversation]))->assertOk()->assertSee('Draft our launch email'); } + + public function test_a_conversation_reads_as_a_chat_with_its_images(): void + { + $owner = User::factory()->create(['name' => 'Ada', 'email' => 'ada@example.com']); + $conversation = Conversation::create([ + 'id' => (string) Str::uuid(), + 'participant_type' => $owner->getMorphClass(), + 'participant_id' => $owner->getKey(), + 'title' => 'Kites', + ]); + $say = fn (string $role, string $content, array $calls = []) => $conversation->messages()->create([ + 'id' => (string) Str::uuid7(), + 'participant_type' => $owner->getMorphClass(), + 'participant_id' => $owner->getKey(), + 'agent' => ChatAgent::class, + 'role' => $role, + 'content' => $content, + 'attachments' => [], 'usage' => [], 'meta' => [], 'status' => MessageStatus::Completed, + 'steps' => [['content' => $content, 'tool_calls' => $calls, 'reasoning' => '', 'replay_blocks' => [], 'provider_tool_calls' => []]], + ]); + $say('user', 'Draw a red kite'); + $say('assistant', 'Here is **your kite**.', [[ + 'id' => 'call-1', 'name' => 'generate_image', 'arguments' => ['prompt' => 'A red kite'], + 'result' => json_encode(['url' => '/storage/kite.png', 'prompt' => 'A red kite']), + ]]); + + $this->actingAs($this->manager()); + + $this->get(ConversationResource::getUrl('view', ['record' => $conversation])) + ->assertOk() + ->assertSeeInOrder(['Ada', 'ada@example.com', 'data-role="user"', 'data-role="assistant"'], false) + // What the user typed, as they typed it; the reply as the chat shows it. + ->assertSee('Draw a red kite') + ->assertSee('your kite', false) + ->assertSee('src="/storage/kite.png"', false) + ->assertDontSee('', false); + } + + public function test_a_conversation_without_messages_says_so(): void + { + $owner = User::factory()->create(); + $conversation = Conversation::create([ + 'id' => (string) Str::uuid(), + 'participant_type' => $owner->getMorphClass(), + 'participant_id' => $owner->getKey(), + 'title' => 'What plan am I on?', + ]); + + $this->actingAs($this->manager()); + + $this->get(ConversationResource::getUrl('view', ['record' => $conversation]))->assertOk()->assertSee('No saved messages'); + } } diff --git a/tests/Feature/HistoryTest.php b/tests/Feature/HistoryTest.php index c026315..b876695 100644 --- a/tests/Feature/HistoryTest.php +++ b/tests/Feature/HistoryTest.php @@ -5,9 +5,14 @@ use App\Models\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Str; +use Laravel\Ai\Ai; +use Laravel\Ai\Enums\MessageStatus; use Laravel\Ai\Models\Conversation; +use Laravel\Ai\Responses\Data\ToolCall; use Modules\AiChat\Ai\ChatAgent; use Modules\AiChat\Http\Controllers\AiChatController; +use Modules\AiChat\Usage; +use RuntimeException; use Tests\TestCase; class HistoryTest extends TestCase @@ -42,11 +47,11 @@ protected function longChat(User $user, int $count): string 'agent' => ChatAgent::class, 'role' => $n % 2 ? 'user' : 'assistant', 'content' => "Message {$n}", - 'attachments' => '[]', - 'tool_calls' => '[]', - 'tool_results' => '[]', - 'usage' => '[]', - 'meta' => '[]', + 'attachments' => [], + 'steps' => [], + 'usage' => [], + 'meta' => [], + 'status' => MessageStatus::Completed, ]); } @@ -130,6 +135,31 @@ public function test_a_failed_reply_stores_nothing_as_a_real_one(): void ->assertInertia(fn ($page) => $page->has('initialMessages', 0)); } + public function test_a_reply_that_fails_after_a_tool_ran_stores_nothing_and_keeps_the_turns_before_it(): void + { + config(['ai-chat.test_mode' => false]); + $user = User::factory()->create(); + $send = function (array $data) use ($user): string { + $response = $this->actingAs($user)->post(route('ai-chat.stream'), $data); + $response->streamedContent(); + + return (string) $response->headers->get('X-Conversation-Id'); + }; + + Ai::fakeAgent(ChatAgent::class, ['Hi.']); + $id = $send(['message' => 'Hello']); + + // The first step calls a tool, the second one dies. + Ai::fakeAgent(ChatAgent::class, [ + new ToolCall('call-1', 'about_my_account', []), + fn () => throw new RuntimeException('Rate limited.'), + ]); + $send(['message' => 'What is my plan?', 'conversation_id' => $id]); + + $this->assertSame(['Hello', 'Hi.'], Conversation::findOrFail($id)->messages()->orderBy('id')->pluck('content')->all()); + $this->assertSame(1, Usage::messagesThisMonth($user)); + } + public function test_a_reopened_chat_shows_its_generated_images(): void { $user = User::factory()->create(); @@ -140,18 +170,18 @@ public function test_a_reopened_chat_shows_its_generated_images(): void 'title' => 'Kites', ]); - $row = fn (string $role, string $content, array $toolResults = []) => $conversation->messages()->create([ + $row = fn (string $role, string $content, array $toolCalls = []) => $conversation->messages()->create([ 'id' => (string) Str::uuid7(), 'participant_type' => $user->getMorphClass(), 'participant_id' => $user->getKey(), 'agent' => ChatAgent::class, 'role' => $role, 'content' => $content, - 'attachments' => '[]', - 'tool_calls' => '[]', - 'tool_results' => json_encode($toolResults), - 'usage' => '[]', - 'meta' => '[]', + 'attachments' => [], + 'steps' => [['content' => $content, 'tool_calls' => $toolCalls, 'reasoning' => '', 'replay_blocks' => [], 'provider_tool_calls' => []]], + 'usage' => [], + 'meta' => [], + 'status' => MessageStatus::Completed, ]); $row('user', 'Draw a red kite'); @@ -160,7 +190,6 @@ public function test_a_reopened_chat_shows_its_generated_images(): void 'name' => 'generate_image', 'arguments' => ['prompt' => 'A red kite'], 'result' => json_encode(['url' => '/storage/ai-chat/images/1/2026-11/kite.png', 'prompt' => 'A red kite']), - 'result_id' => null, ]]); $this->actingAs($user)->get(route('ai-chat.show', $conversation->id))->assertInertia(fn ($page) => $page diff --git a/tests/Feature/ProviderCatalogTest.php b/tests/Feature/ProviderCatalogTest.php index 31a73ea..f15e430 100644 --- a/tests/Feature/ProviderCatalogTest.php +++ b/tests/Feature/ProviderCatalogTest.php @@ -24,7 +24,7 @@ public function test_only_providers_that_can_chat_are_offered_for_models(): void $this->assertArrayHasKey('gemini', $text); // Embeddings, reranking and audio only: laravel/ai has no text provider for them. - foreach (['cohere', 'jina', 'voyageai', 'eleven'] as $provider) { + foreach (['jina', 'voyageai', 'eleven'] as $provider) { $this->assertArrayNotHasKey($provider, $text, $provider); } } @@ -61,7 +61,7 @@ public function test_the_settings_form_refuses_providers_that_cannot_do_the_job( Livewire::test(SettingsPage::class) ->fillForm([ 'default_model' => null, - 'providers' => [['provider' => 'cohere', 'key' => '', 'forget_key' => false, 'models' => []]], + 'providers' => [['provider' => 'jina', 'key' => '', 'forget_key' => false, 'models' => []]], 'image_provider' => 'anthropic', ]) ->call('save') diff --git a/tests/Support/AiChatTestHelper.php b/tests/Support/AiChatTestHelper.php index 48dc7a5..4b50927 100644 --- a/tests/Support/AiChatTestHelper.php +++ b/tests/Support/AiChatTestHelper.php @@ -4,6 +4,7 @@ use App\Models\User; use Illuminate\Support\Str; +use Laravel\Ai\Enums\MessageStatus; use Laravel\Ai\Models\Conversation; use Modules\AiChat\Ai\ChatAgent; use Modules\AiChat\Settings\AiChatSettings; @@ -45,10 +46,10 @@ public static function conversation(string $email, string $title = 'Chat', int $ // Cast to JSON by the model: arrays, not JSON strings, or the stored history won't load. 'content' => "Message {$n} ".str_repeat('words ', $n % 7 * 10), 'attachments' => [], - 'tool_calls' => [], - 'tool_results' => [], + 'steps' => [], 'usage' => [], 'meta' => [], + 'status' => MessageStatus::Completed, ]); }