Skip to content
Welcome to the new era of Laravel. Today, Dec 1, at 10am PT / 1pm ET.Add it to your calendar

Converse

AI

Laravel Converse

Introduction

Laravel Converse gives you a unified API for building chat bots that communicate across Slack, Telegram, GitHub, and your own application's web pages. You write your bot once, and Converse handles each platform's webhooks, threads, and message formats.

For example, you might build a support bot that answers questions in your team's Slack channels, replies to new GitHub issues, and chats with customers on your application's help page. Converse also integrates with the Laravel AI SDK, so an AI agent can answer your bot's messages while Converse manages conversation memory, typing indicators, tools, and tool approvals.

If you're starting a new agent project from scratch, check out Agent Kit, which ships with Converse and the AI SDK already configured.

Installation

Converse requires PHP 8.4 or higher. Install it in your application with Composer:

1composer require laravel/converse
1composer require laravel/converse

Next, run the converse:install Artisan command:

1php artisan converse:install
1php artisan converse:install

This command publishes config/converse.php, routes/bot.php, and the Converse and AI SDK migrations. It also generates an Assistant agent in app/Ai/Agents, registers it as the assistant bot, and offers to run your database migrations.

During installation, the command asks whether you plan to build a web chat. Answering yes registers the assistant bot on the web connection and, in an Inertia application using Vue or React, scaffolds the chat page described in the web chat guide. Answering no leaves assistant without platform connections until you add them in routes/bot.php. You may skip this prompt by passing --without-web.

The Assistant agent uses the AI SDK's default provider, so add your provider's credentials, such as OPENAI_API_KEY, to .env. To configure another provider, check out the AI SDK configuration guide.

Once Converse is installed, test the assistant bot right in your terminal with php artisan converse:chat assistant. To learn more about terminal chat options, check out chatting from the terminal.

Converse processes messages from chat platforms and web chats on your queue, so your bots reply only while a queue worker is running.

Configuration

Converse keeps its settings in config/converse.php. Its connections array pairs each driver with the credentials for a single platform account, and starts with one connection for every supported platform:

1'connections' => [
2 'slack' => [
3 'driver' => 'slack',
4 'bot_token' => env('SLACK_BOT_TOKEN'),
5 'webhook_secret' => env('SLACK_WEBHOOK_SECRET'),
6 ],
7 
8 'telegram' => [
9 'driver' => 'telegram',
10 'bot_token' => env('TELEGRAM_BOT_TOKEN'),
11 'bot_username' => env('TELEGRAM_BOT_USERNAME'),
12 'webhook_secret' => env('TELEGRAM_WEBHOOK_SECRET'),
13 ],
14 
15 'github' => [
16 'driver' => 'github',
17 'app_id' => env('GITHUB_APP_ID'),
18 'private_key' => env('GITHUB_PRIVATE_KEY'),
19 'webhook_secret' => env('GITHUB_WEBHOOK_SECRET'),
20 ],
21 
22 'web' => [
23 'driver' => 'web',
24 // ...
25 ],
26],
1'connections' => [
2 'slack' => [
3 'driver' => 'slack',
4 'bot_token' => env('SLACK_BOT_TOKEN'),
5 'webhook_secret' => env('SLACK_WEBHOOK_SECRET'),
6 ],
7 
8 'telegram' => [
9 'driver' => 'telegram',
10 'bot_token' => env('TELEGRAM_BOT_TOKEN'),
11 'bot_username' => env('TELEGRAM_BOT_USERNAME'),
12 'webhook_secret' => env('TELEGRAM_WEBHOOK_SECRET'),
13 ],
14 
15 'github' => [
16 'driver' => 'github',
17 'app_id' => env('GITHUB_APP_ID'),
18 'private_key' => env('GITHUB_PRIVATE_KEY'),
19 'webhook_secret' => env('GITHUB_WEBHOOK_SECRET'),
20 ],
21 
22 'web' => [
23 'driver' => 'web',
24 // ...
25 ],
26],

Because each connection represents one account, you may define multiple connections using the same driver, such as two Slack connections for separate Slack workspaces. To learn about the web connection's options, check out running web turns.

Webhooks

Each bot receives webhooks for its connections at this URL:

1{APP_URL}/converse/{bot}/{connection}
1{APP_URL}/converse/{bot}/{connection}

For example, a bot named support receives Slack webhooks at /converse/support/slack. Converse verifies and acknowledges every incoming webhook immediately, then processes the event on your queue.

A bot accepts webhooks only for connections registered on that bot in routes/bot.php. Converse returns a 404 status code for webhooks sent to any unregistered connection, including a platform's verification request. Register the bot on its connection before configuring the platform.

Queues

Converse uses your application's default queue connection and queue name unless you override them with CONVERSE_QUEUE_CONNECTION and CONVERSE_QUEUE_NAME:

1CONVERSE_QUEUE_CONNECTION=redis
2CONVERSE_QUEUE_NAME=converse
1CONVERSE_QUEUE_CONNECTION=redis
2CONVERSE_QUEUE_NAME=converse

Queued jobs that answer your bots' messages time out after 60 seconds by default. If your agents call several slow tools, raise the limit with CONVERSE_TURN_TIMEOUT, keeping your queue connection's retry_after value higher than the timeout:

1CONVERSE_TURN_TIMEOUT=180
1CONVERSE_TURN_TIMEOUT=180

This timeout also applies to web chat turns, as covered in running web turns.

Rate Limits

When Slack, Telegram, or GitHub rate-limits an API request, Converse waits for the duration the platform asks for before retrying. For short waits, up to 5 seconds by default, Converse pauses the job and retries the request in place. You may adjust that threshold by adding rate_limit_wait to the turns array in config/converse.php:

1'turns' => [
2 // ...
3 'rate_limit_wait' => 10,
4],
1'turns' => [
2 // ...
3 'rate_limit_wait' => 10,
4],

For longer waits, Converse releases the job back onto your queue so it runs again once the wait expires, and it releases rate-limited actions, reactions, and commands back onto the queue too. Each job gets up to 3 attempts by default, which you may change with max_attempts in the turns array. Once attempts run out, Converse drops the turn without sending a failure message. Because the sync, deferred, and background queue drivers can't delay jobs, a rate-limited job on those drivers fails immediately, and Converse re-processes its messages when the next message arrives.

A retried handler runs from the beginning, so it resends any messages it sent before hitting the rate limit. For an agent bot, Converse caches the finished reply and sends it on the next attempt without prompting the agent again, unless a new message arrived in the meantime.

Outside a turn, such as in your own queued jobs, a rate-limited request throws RateLimitedException. Call its retryAfter method to get the number of seconds to wait:

1use Laravel\Converse\Exceptions\RateLimitedException;
2 
3try {
4 $thread->send('Your deployment finished.');
5} catch (RateLimitedException $exception) {
6 $this->release($exception->retryAfter());
7}
1use Laravel\Converse\Exceptions\RateLimitedException;
2 
3try {
4 $thread->send('Your deployment finished.');
5} catch (RateLimitedException $exception) {
6 $this->release($exception->retryAfter());
7}

Database, Cache, and Storage

Converse stores threads and messages on your application's default database connection, and uses your default cache store to lock each thread while a bot answers it. The cache store must support atomic locks, and if you run queue workers across multiple servers, every worker must share the same cache store. Set CONVERSE_DB_CONNECTION and CONVERSE_CACHE_STORE to choose a different database connection or cache store:

1CONVERSE_DB_CONNECTION=pgsql
2CONVERSE_CACHE_STORE=redis
1CONVERSE_DB_CONNECTION=pgsql
2CONVERSE_CACHE_STORE=redis

Converse saves files users send to your application's default filesystem disk. Because a queue worker stores each file while handling the message and your web server may later serve it to the browser, both processes must be able to reach the same disk. When your queue workers run on separate servers from your web server, as on Laravel Cloud, store attachments in object storage such as an S3 bucket.

Platforms

Converse ships with drivers for Slack, Telegram, and GitHub. Each platform requires its own credentials and sends webhooks to a public HTTPS URL, such as your Laravel Cloud domain or a tunnel from Laravel Herd, Expose, or Ngrok.

Run the converse:setup Artisan command to connect a platform and write its credentials to your local .env file. If the webhook URL points at a deployed environment, copy those variables into your production environment as well. You may re-run converse:setup whenever your URL changes, and pass --bot when several bots share a connection.

Slack

The fastest way to connect a Slack bot is converse:setup. Make sure you've registered your bot on the slack connection first, then run:

1php artisan converse:setup slack
1php artisan converse:setup slack

The command creates the Slack App with an app configuration token that you can generate under Your App Configuration Tokens at api.slack.com/apps. Converse doesn't save that token. After you install the app and paste its bot token, the command writes SLACK_BOT_TOKEN and SLACK_WEBHOOK_SECRET to .env and points the app at your webhook URL, which Slack verifies right away.

Configuring Slack Manually

If you'd rather create the Slack App yourself, make sure your application is reachable at a public HTTPS URL and your bot is registered on the slack connection first, because Slack sends a verification request as soon as you create the app. While developing locally, expose your application with a tunnel such as Cloudflare Tunnel, Expose, or Ngrok.

Open api.slack.com/apps, click Create New App, choose From a manifest, and select your workspace. Paste the manifest below, replacing support with your bot's name and each URL with your bot's webhook URL:

1{
2 "display_information": {
3 "name": "support"
4 },
5 "features": {
6 "app_home": {
7 "home_tab_enabled": false,
8 "messages_tab_enabled": true,
9 "messages_tab_read_only_enabled": false
10 },
11 "bot_user": {
12 "display_name": "support",
13 "always_online": true
14 },
15 "agent_view": {
16 "agent_description": "Answers questions from the support team."
17 },
18 "slash_commands": [
19 {
20 "command": "/support",
21 "url": "https://example.com/converse/support/slack",
22 "description": "Talk to the support bot",
23 "should_escape": false
24 }
25 ]
26 },
27 "oauth_config": {
28 "scopes": {
29 "bot": [
30 "app_mentions:read",
31 "assistant:write",
32 "channels:history",
33 "channels:read",
34 "chat:write",
35 "chat:write.public",
36 "commands",
37 "files:read",
38 "files:write",
39 "groups:history",
40 "groups:read",
41 "im:history",
42 "im:read",
43 "im:write",
44 "mpim:history",
45 "mpim:read",
46 "reactions:read",
47 "reactions:write",
48 "users:read"
49 ]
50 },
51 "pkce_enabled": false
52 },
53 "settings": {
54 "event_subscriptions": {
55 "request_url": "https://example.com/converse/support/slack",
56 "bot_events": [
57 "app_mention",
58 "message.channels",
59 "message.groups",
60 "message.im",
61 "message.mpim",
62 "reaction_added",
63 "reaction_removed"
64 ]
65 },
66 "interactivity": {
67 "is_enabled": true,
68 "request_url": "https://example.com/converse/support/slack"
69 },
70 "org_deploy_enabled": false,
71 "socket_mode_enabled": false,
72 "token_rotation_enabled": false,
73 "is_mcp_enabled": false
74 }
75}
1{
2 "display_information": {
3 "name": "support"
4 },
5 "features": {
6 "app_home": {
7 "home_tab_enabled": false,
8 "messages_tab_enabled": true,
9 "messages_tab_read_only_enabled": false
10 },
11 "bot_user": {
12 "display_name": "support",
13 "always_online": true
14 },
15 "agent_view": {
16 "agent_description": "Answers questions from the support team."
17 },
18 "slash_commands": [
19 {
20 "command": "/support",
21 "url": "https://example.com/converse/support/slack",
22 "description": "Talk to the support bot",
23 "should_escape": false
24 }
25 ]
26 },
27 "oauth_config": {
28 "scopes": {
29 "bot": [
30 "app_mentions:read",
31 "assistant:write",
32 "channels:history",
33 "channels:read",
34 "chat:write",
35 "chat:write.public",
36 "commands",
37 "files:read",
38 "files:write",
39 "groups:history",
40 "groups:read",
41 "im:history",
42 "im:read",
43 "im:write",
44 "mpim:history",
45 "mpim:read",
46 "reactions:read",
47 "reactions:write",
48 "users:read"
49 ]
50 },
51 "pkce_enabled": false
52 },
53 "settings": {
54 "event_subscriptions": {
55 "request_url": "https://example.com/converse/support/slack",
56 "bot_events": [
57 "app_mention",
58 "message.channels",
59 "message.groups",
60 "message.im",
61 "message.mpim",
62 "reaction_added",
63 "reaction_removed"
64 ]
65 },
66 "interactivity": {
67 "is_enabled": true,
68 "request_url": "https://example.com/converse/support/slack"
69 },
70 "org_deploy_enabled": false,
71 "socket_mode_enabled": false,
72 "token_rotation_enabled": false,
73 "is_mcp_enabled": false
74 }
75}

Once you create the Slack App, Slack warns that the request URL isn't verified yet. That's expected, because Converse rejects Slack's verification request until you configure the signing secret.

Install the Slack App in your workspace, then copy the "Bot User OAuth Token" from Install App and the "Signing Secret" from Basic Information into your environment variables:

1SLACK_BOT_TOKEN=xoxb-your-bot-token
2SLACK_WEBHOOK_SECRET=your-signing-secret
1SLACK_BOT_TOKEN=xoxb-your-bot-token
2SLACK_WEBHOOK_SECRET=your-signing-secret

Redeploy your application, then click Click here to verify in the warning on the App Manifest page. Slack resends the verification challenge and Converse confirms the endpoint.

Next, invite the bot to every channel it should read by sending /invite @support in each channel. The bot receives direct messages without an invitation. Reinstall the Slack App in your workspace whenever you change its scopes.

Your bot answers the manifest's /support slash command only when its handler implements HandlesCommands, because agent bots don't answer slash commands on their own. If you don't need slash commands, remove the slash_commands block from the manifest.

Telegram

The fastest way to connect a Telegram bot is converse:setup. Make sure you've registered your bot on the telegram connection first, then run:

1php artisan converse:setup telegram
1php artisan converse:setup telegram

The command walks you through creating the bot with @BotFather, writes TELEGRAM_BOT_TOKEN, TELEGRAM_BOT_USERNAME, and TELEGRAM_WEBHOOK_SECRET to .env, and registers your bot's webhook URL with Telegram.

Configuring Telegram Manually

If you'd rather configure the bot yourself, send /newbot to @BotFather. Add the bot's token, its username without the @, and a random webhook secret to .env. Telegram allows letters, numbers, underscores, and hyphens in the secret:

1TELEGRAM_BOT_TOKEN=123456789:your-bot-token
2TELEGRAM_BOT_USERNAME=support_bot
3TELEGRAM_WEBHOOK_SECRET=your-random-secret
1TELEGRAM_BOT_TOKEN=123456789:your-bot-token
2TELEGRAM_BOT_USERNAME=support_bot
3TELEGRAM_WEBHOOK_SECRET=your-random-secret

Next, register the bot's webhook URL and secret with Telegram, substituting your bot token, webhook URL, and secret:

1curl -X POST "https://api.telegram.org/bot<your-bot-token>/setWebhook" \
2 -d "url=https://example.com/converse/support/telegram" \
3 -d "secret_token=<your-webhook-secret>" \
4 -d "allowed_updates=[\"message\",\"edited_message\",\"channel_post\",\"edited_channel_post\",\"callback_query\",\"message_reaction\"]"
1curl -X POST "https://api.telegram.org/bot<your-bot-token>/setWebhook" \
2 -d "url=https://example.com/converse/support/telegram" \
3 -d "secret_token=<your-webhook-secret>" \
4 -d "allowed_updates=[\"message\",\"edited_message\",\"channel_post\",\"edited_channel_post\",\"callback_query\",\"message_reaction\"]"

By default, Telegram's privacy mode limits a bot to group messages aimed directly at it, such as commands and replies to the bot. To receive every message in a group, send /setprivacy to BotFather, choose "Disable", then remove the bot from each group and add it back. Telegram also delivers reaction events only to bots that are group administrators.

On Telegram, each chat is a channel. In a group with topics enabled, each topic is its own thread. Otherwise, the entire chat is a single thread.

GitHub

On GitHub, a repository is a channel, each issue or pull request is a thread, and each comment is a message. Your bot posts comments as a GitHub App.

The fastest way to connect a GitHub bot is converse:setup. Make sure you've registered your bot on the github connection first, then run:

1php artisan converse:setup github
1php artisan converse:setup github

The command opens a GitHub page prefilled with the permissions, events, and webhook URL your bot needs. Once you confirm on GitHub, the command writes GITHUB_APP_ID, GITHUB_PRIVATE_KEY, GITHUB_WEBHOOK_SECRET, GITHUB_CLIENT_ID, and GITHUB_CLIENT_SECRET to .env and prints a link to install the app.

Configuring GitHub Manually

If you'd rather create the GitHub App yourself, open Settings > Developer settings > GitHub Apps for your user or organization, click New GitHub App, and configure these settings:

  • Webhook URL: Your bot's webhook URL, such as https://example.com/converse/support/github.
  • Webhook secret: A random string that Converse uses to verify each webhook.
  • Repository permissions: "Read and write" for Issues and Pull requests, and "Read-only" for Metadata.
  • Subscribe to events: Issues, Issue comment, Pull request, and Pull request review comment.
  • Where can this GitHub App be installed?: "Any account" if the app should serve accounts other than your own.

Once you create the app, copy its "App ID" and click Generate a private key. Install the app on the repositories your bot serves, then add the App ID, private key, and webhook secret to .env. Wrap the key in double quotes so it can span multiple lines, or pass a file:// URL pointing to the key file:

1GITHUB_APP_ID=123456
2GITHUB_WEBHOOK_SECRET=your-random-secret
3GITHUB_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
4MIIEpAIBAAKCAQEA...
5-----END RSA PRIVATE KEY-----"
6 
7# Or...
8GITHUB_PRIVATE_KEY=file:///path/to/your-app.private-key.pem
1GITHUB_APP_ID=123456
2GITHUB_WEBHOOK_SECRET=your-random-secret
3GITHUB_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
4MIIEpAIBAAKCAQEA...
5-----END RSA PRIVATE KEY-----"
6 
7# Or...
8GITHUB_PRIVATE_KEY=file:///path/to/your-app.private-key.pem

For repositories hosted on GitHub Enterprise Server, add a base_url option with your instance's API URL to the github connection in config/converse.php:

1'github' => [
2 'driver' => 'github',
3 // ...
4 'base_url' => 'https://github.example.com/api/v3',
5],
1'github' => [
2 'driver' => 'github',
3 // ...
4 'base_url' => 'https://github.example.com/api/v3',
5],

GitHub Platform Differences

The body of an issue or pull request is the first message in its thread. Comments on a pull request's Files changed tab form separate threads, so your bot's reply appears under the review comment it answers. Converse treats both @{slug} and @{slug}[bot] as mentions, where {slug} is your GitHub App's slug.

GitHub renders comments as GitHub Flavored Markdown. Converse posts plain strings as literal text, so Markdown characters are escaped and @ handles don't notify anyone. To format a comment or mention a user, send a Markdown instance. Converse also renders cards as Markdown, turning link buttons into links and other controls into bold labels.

Because GitHub doesn't support interactive buttons, tool approval requests ask the user to reply with a word such as approve or reject. The reply may mention the bot, as in @support approve.

On GitHub, an event's user id method returns the author's GitHub login, such as taylorotwell.

Your bot may add and remove the eight reactions GitHub supports, which map to these Emoji enum cases: ThumbsUp, ThumbsDown, Laugh, Thinking, Heart, Party, Rocket, and Eyes. GitHub doesn't deliver reaction events to your bot, and while your bot may edit an issue or pull request body, it can't delete it. To check which other features GitHub supports, check out the capabilities table.

GitHub Installation Tokens

Sometimes another GitHub client, such as GitHub's MCP server, should act as your bot. Instead of signing a GitHub App token yourself, you may ask the GitHub driver for an installation access token using the installationToken method. Since Converse::connection may return any driver, check for the GithubDriver before calling it:

1use Laravel\Converse\Drivers\Github\GithubDriver;
2use Laravel\Converse\Facades\Converse;
3 
4$github = Converse::connection('github');
5 
6if ($github instanceof GithubDriver) {
7 $token = $github->installationToken('laravel/converse');
8}
1use Laravel\Converse\Drivers\Github\GithubDriver;
2use Laravel\Converse\Facades\Converse;
3 
4$github = Converse::connection('github');
5 
6if ($github instanceof GithubDriver) {
7 $token = $github->installationToken('laravel/converse');
8}

By default, the token can only reach the repository you name, which makes it safe to hand to an agent's tools. If the client needs every repository your GitHub App's installation serves, set the scoped argument to false. Converse then returns the same token it uses for its own GitHub requests:

1$token = $github->installationToken('laravel/converse', scoped: false);
1$token = $github->installationToken('laravel/converse', scoped: false);

GitHub installation tokens expire after an hour. Converse caches each token and replaces it before it expires, so you should call installationToken each time you need a token instead of storing the value yourself.

Defining Bots

You register bots in routes/bot.php with the Converse facade. Running converse:install already registers the assistant bot there:

1use App\Ai\Agents\Assistant;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::agent('assistant', Assistant::class)
5 ->connections([
6 'web',
7 // 'slack',
8 // 'telegram',
9 ]);
1use App\Ai\Agents\Assistant;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::agent('assistant', Assistant::class)
5 ->connections([
6 'web',
7 // 'slack',
8 // 'telegram',
9 ]);

Every bot has a name, one or more connections, and either an AI agent or a handler that answers incoming messages:

  • An agent bot answers messages with an AI agent and is registered with Converse::agent. Choose an agent bot for open-ended conversations, such as answering support questions.
  • A handler bot answers messages with a PHP handler class you write and is registered with Converse::bot. Choose a handler bot for predictable commands and workflows, such as running a deployment when someone types /deploy.

An agent bot can also pair with a handler for specific events such as slash commands. To learn how they work together, check out combining agents and handlers.

Generate an agent with php artisan make:bot SupportAgent --agent, or a handler with php artisan make:bot DeployBot. To learn how to customize each class, check out agent bots and creating handlers. Register them in routes/bot.php using connection for one or more connection names, or connections for an array:

1use App\Ai\Agents\SupportAgent;
2use App\Bots\DeployBot;
3use Laravel\Converse\Facades\Converse;
4 
5Converse::agent('support', SupportAgent::class)
6 ->connection('slack', 'telegram');
7 
8Converse::bot('deploy', DeployBot::class)
9 ->connection('slack');
1use App\Ai\Agents\SupportAgent;
2use App\Bots\DeployBot;
3use Laravel\Converse\Facades\Converse;
4 
5Converse::agent('support', SupportAgent::class)
6 ->connection('slack', 'telegram');
7 
8Converse::bot('deploy', DeployBot::class)
9 ->connection('slack');

Each time a bot answers new messages in a thread is called a "turn". Converse runs at most one turn per thread at a time.

To inspect every registered bot and its connections, run the converse:list Artisan command:

1php artisan converse:list
1php artisan converse:list

Chatting From the Terminal

While building a bot, you can chat with it locally in your terminal using converse:chat:

1php artisan converse:chat support
1php artisan converse:chat support

To chat as one of your application's users, pass the user's ID to --user. Converse loads the user through the guard configured on the bot's web connection, or your application's default guard, and runs it through your user resolver if you've defined one. Each bot event's user method returns that user, and an agent bot receives them as its $participant, as on the web connection:

1php artisan converse:chat support --user=1
1php artisan converse:chat support --user=1

Terminal chat runs synchronously in your shell, so it doesn't need a chat platform, a deployment, or a queue worker. For agent bots, it also prints each tool call the agent makes.

Every line you type arrives as a direct message. If a handler implements HandlesMentions without implementing HandlesDirectMessages or HandlesMessages, Converse delivers terminal messages to handleMention, so the handler generated by make:bot answers them out of the box.

Lines starting with / arrive as slash commands, except for built-in terminal chat commands, which you can list by typing /help. Type exit or press Escape to leave the chat. The command prints the thread's ID so you can resume the conversation later with --thread. When resuming a user conversation, pass the same --user ID you started with.

You may omit the bot name when your application defines only one bot. You may also pass a message as the second argument to send a single prompt, print the reply, and exit:

1php artisan converse:chat support "Where is my order?"
1php artisan converse:chat support "Where is my order?"

Debouncing Messages

People often send several short messages in a row instead of one paragraph. Call debounce to wait a few seconds after a message arrives before starting a turn, so Converse groups follow-up messages into the same turn:

1use App\Ai\Agents\SupportAgent;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::agent('support', SupportAgent::class)
5 ->connection('slack')
6 ->debounce(3);
1use App\Ai\Agents\SupportAgent;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::agent('support', SupportAgent::class)
5 ->connection('slack')
6 ->debounce(3);

To apply a default debounce delay to every bot, set CONVERSE_TURN_DEBOUNCE in .env.

Middleware

Middleware let you inspect, transform, or drop incoming bot events before your bot handles them. Generate a middleware class in app/Bots/Middleware with make:bot-middleware:

1php artisan make:bot-middleware EnsureUserIsEmployee
1php artisan make:bot-middleware EnsureUserIsEmployee

Call $next($event) to pass the event to your bot, or return null to drop it:

1<?php
2 
3namespace App\Bots\Middleware;
4 
5use Closure;
6use Laravel\Converse\Contracts\BotEvent;
7 
8class EnsureUserIsEmployee
9{
10 /**
11 * Handle an incoming bot event.
12 */
13 public function handle(BotEvent $event, Closure $next): mixed
14 {
15 if (! in_array($event->user()->id(), config('services.slack.employees', []))) {
16 return null;
17 }
18 
19 return $next($event);
20 }
21}
1<?php
2 
3namespace App\Bots\Middleware;
4 
5use Closure;
6use Laravel\Converse\Contracts\BotEvent;
7 
8class EnsureUserIsEmployee
9{
10 /**
11 * Handle an incoming bot event.
12 */
13 public function handle(BotEvent $event, Closure $next): mixed
14 {
15 if (! in_array($event->user()->id(), config('services.slack.employees', []))) {
16 return null;
17 }
18 
19 return $next($event);
20 }
21}

Attach middleware to a bot in routes/bot.php with middleware, which accepts class names, closures, and middleware instances:

1use App\Ai\Agents\SupportAgent;
2use App\Bots\Middleware\EnsureUserIsEmployee;
3use Laravel\Converse\Facades\Converse;
4 
5Converse::agent('support', SupportAgent::class)
6 ->connection('slack')
7 ->middleware(EnsureUserIsEmployee::class);
1use App\Ai\Agents\SupportAgent;
2use App\Bots\Middleware\EnsureUserIsEmployee;
3use Laravel\Converse\Facades\Converse;
4 
5Converse::agent('support', SupportAgent::class)
6 ->connection('slack')
7 ->middleware(EnsureUserIsEmployee::class);

For example, to restrict a bot to direct messages, pass a closure that drops every other event:

1use App\Ai\Agents\SupportAgent;
2use Closure;
3use Laravel\Converse\Contracts\BotEvent;
4use Laravel\Converse\Facades\Converse;
5 
6Converse::agent('support', SupportAgent::class)
7 ->connection('slack')
8 ->middleware(function (BotEvent $event, Closure $next) {
9 return $event->isDirectMessage() ? $next($event) : null;
10 });
1use App\Ai\Agents\SupportAgent;
2use Closure;
3use Laravel\Converse\Contracts\BotEvent;
4use Laravel\Converse\Facades\Converse;
5 
6Converse::agent('support', SupportAgent::class)
7 ->connection('slack')
8 ->middleware(function (BotEvent $event, Closure $next) {
9 return $event->isDirectMessage() ? $next($event) : null;
10 });

When Converse batches messages that arrive mid-turn into the next turn, your middleware runs once for each message in the batch. A message your middleware drops is left out of the turn, and the newest message that passes drives it.

Middleware also runs for scheduled and prompted turns, where the user is anonymous, so EnsureUserIsEmployee above would drop them. Check $event->isScheduled() if you want to let those turns through.

AI Agents

Any agent built with the Laravel AI SDK can answer a bot's messages. Converse installs the AI SDK as a dependency, and converse:install publishes the migrations agents need to store conversation history.

Agent Bots

An agent that answers a bot's messages should use the AI SDK's RemembersConversations trait so it keeps earlier messages from each thread in its conversation history. Running make:bot with --agent generates an agent with that trait already applied, or you may generate one with the AI SDK's make:agent command and add the trait yourself:

1php artisan make:bot SupportAgent --agent
1php artisan make:bot SupportAgent --agent

Once registered with Converse::agent, the agent answers mentions, direct messages, and messages in subscribed threads, and Converse shows a typing indicator while it works. Unlike a handler bot, an agent bot doesn't wait for an in-progress turn to finish: if a new message arrives mid-turn, Converse stops the current turn and starts a new one with every waiting message. Stopping a turn won't undo work that a tool has already executed.

On Slack, Telegram, and converse:chat, agent bots don't answer slash commands. To handle slash commands, pair the agent with a handler that implements HandlesCommands. On the web connection, a message starting with / is treated as a slash command only when the bot's handler implements HandlesCommands. Otherwise, it reaches the agent as a regular message.

By default, an agent bot subscribes to every thread where someone mentions it, so follow-up replies don't need another mention. Call unsubscribeFromMentions in routes/bot.php to require a mention on every message:

1use App\Ai\Agents\SupportAgent;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::agent('support', SupportAgent::class)
5 ->connection('slack')
6 ->unsubscribeFromMentions();
1use App\Ai\Agents\SupportAgent;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::agent('support', SupportAgent::class)
5 ->connection('slack')
6 ->unsubscribeFromMentions();

If you need to choose which agent handles a turn at runtime, pass a closure to Converse::agent. Converse passes the current Thread to the closure:

1use App\Ai\Agents\ConciergeAgent;
2use App\Ai\Agents\SupportAgent;
3use Laravel\Converse\Facades\Converse;
4use Laravel\Converse\Thread;
5 
6Converse::agent('support', fn (Thread $thread) => $thread->isDirectMessage()
7 ? new ConciergeAgent
8 : new SupportAgent
9)->connection('slack');
1use App\Ai\Agents\ConciergeAgent;
2use App\Ai\Agents\SupportAgent;
3use Laravel\Converse\Facades\Converse;
4use Laravel\Converse\Thread;
5 
6Converse::agent('support', fn (Thread $thread) => $thread->isDirectMessage()
7 ? new ConciergeAgent
8 : new SupportAgent
9)->connection('slack');

Your closure may also declare a $message parameter to receive the newest BotEvent, such as to pass the sender to your agent. On scheduled and prompted turns, that user is anonymous:

1use App\Ai\Agents\SupportAgent;
2use Laravel\Converse\Contracts\BotEvent;
3use Laravel\Converse\Facades\Converse;
4 
5Converse::agent('support', fn (BotEvent $message) => new SupportAgent($message->user()))
6 ->connection('slack');
1use App\Ai\Agents\SupportAgent;
2use Laravel\Converse\Contracts\BotEvent;
3use Laravel\Converse\Facades\Converse;
4 
5Converse::agent('support', fn (BotEvent $message) => new SupportAgent($message->user()))
6 ->connection('slack');

On the web connection, or when chatting from the terminal with --user, your closure may also declare a $participant parameter to receive the chat's owner. Typically, this is your application's authenticated user, so you can pass them to your agent and its tools to scope queries to their own records:

1use App\Ai\Agents\Assistant;
2use App\Models\User;
3use Laravel\Converse\Facades\Converse;
4 
5Converse::agent('assistant', fn (?User $participant) => new Assistant($participant))
6 ->connection('web');
1use App\Ai\Agents\Assistant;
2use App\Models\User;
3use Laravel\Converse\Facades\Converse;
4 
5Converse::agent('assistant', fn (?User $participant) => new Assistant($participant))
6 ->connection('web');

Web turns run on your queue, where no user is authenticated, so auth()->user() returns null inside your agent and its tools. Pass $participant to your agent instead. $participant is null for guests and on other connections unless you chat from the terminal with --user.

Agent Tools

Converse gives every agent bot built-in tools for interacting with the current thread. With these tools, an agent can read thread history, look up users and channels, download attachments, add and remove reactions, and manage thread subscriptions. The tools are grouped by capability:

Group Tools Enabled by Default
threadContext ListMessages, ListUsers, GetUser, GetChannel, DownloadAttachment Yes
reactions AddReaction, RemoveReaction Yes
subscriptions Subscribe, Unsubscribe Yes
messaging SendMessage, EditMessage, DeleteMessage, UpdateStatus No
cards SendCard, EditCard No

Converse registers only the tools supported in the current thread. For example, reaction tools are registered only when the platform supports reactions, and ListUsers, GetChannel, Subscribe, and Unsubscribe aren't registered in direct messages. Because a web chat has a single user and no channel, agents on the web connection receive none of the default tools.

To disable specific default tools for an agent bot, call withoutTools in routes/bot.php:

1use App\Ai\Agents\SupportAgent;
2use Laravel\Converse\Ai\Tools\Subscribe;
3use Laravel\Converse\Facades\Converse;
4 
5Converse::agent('support', SupportAgent::class)
6 ->connection('slack')
7 ->withoutTools([Subscribe::class]);
1use App\Ai\Agents\SupportAgent;
2use Laravel\Converse\Ai\Tools\Subscribe;
3use Laravel\Converse\Facades\Converse;
4 
5Converse::agent('support', SupportAgent::class)
6 ->connection('slack')
7 ->withoutTools([Subscribe::class]);

The messaging and cards groups are disabled by default. To enable them, return them from your agent's tools method using Converse::tools():

1use Laravel\Converse\Facades\Converse;
2 
3/**
4 * Get the tools available to the agent.
5 *
6 * @return Tool[]
7 */
8public function tools(): iterable
9{
10 return [
11 ...Converse::tools()->messaging(),
12 ...Converse::tools()->cards(),
13 ];
14}
1use Laravel\Converse\Facades\Converse;
2 
3/**
4 * Get the tools available to the agent.
5 *
6 * @return Tool[]
7 */
8public function tools(): iterable
9{
10 return [
11 ...Converse::tools()->messaging(),
12 ...Converse::tools()->cards(),
13 ];
14}

The cards tools let an agent send interactive cards with buttons. Clicking one of those buttons starts a new turn for the agent. To handle button clicks with your own PHP code instead, pair the agent with a handler that implements HandlesActions. Converse still handles tool approval buttons automatically.

On Slack, you may also return SendEphemeralMessage from your agent's tools method to send a reply visible only to the user who started the turn. Unlike the grouped tools, SendEphemeralMessage requires approval by default. Call withoutApproval if the agent should send ephemeral messages without asking:

1use Laravel\Converse\Ai\Tools\Slack\SendEphemeralMessage;
2 
3/**
4 * Get the tools available to the agent.
5 *
6 * @return Tool[]
7 */
8public function tools(): iterable
9{
10 return [
11 (new SendEphemeralMessage)->withoutApproval(),
12 ];
13}
1use Laravel\Converse\Ai\Tools\Slack\SendEphemeralMessage;
2 
3/**
4 * Get the tools available to the agent.
5 *
6 * @return Tool[]
7 */
8public function tools(): iterable
9{
10 return [
11 (new SendEphemeralMessage)->withoutApproval(),
12 ];
13}

Your own AI SDK tools run alongside Converse's tools. To register a custom tool conditionally based on the thread, add a shouldRegister method to the tool. Converse passes the current Thread, injects any other type-hinted dependencies from the service container, and registers the tool only when the method returns true:

1use Laravel\Converse\Enums\Capability;
2use Laravel\Converse\Thread;
3 
4/**
5 * Determine if the tool should be registered for the given thread.
6 */
7public function shouldRegister(Thread $thread): bool
8{
9 return $thread->supports(Capability::EditMessage);
10}
1use Laravel\Converse\Enums\Capability;
2use Laravel\Converse\Thread;
3 
4/**
5 * Determine if the tool should be registered for the given thread.
6 */
7public function shouldRegister(Thread $thread): bool
8{
9 return $thread->supports(Capability::EditMessage);
10}

Converse calls shouldRegister only when a bot is answering a thread. If you prompt the agent directly, as in (new SupportAgent)->prompt('...'), your custom tool is always registered, while the groups returned by Converse::tools() are empty because they require an active thread.

Using the Current Thread in Tools

Your custom tools can also act on the current thread, such as sending a card. Resolve Laravel\Converse\ThreadContext from the service container and call its thread method, which returns null when you prompt the agent directly outside a bot:

1use App\Models\Order;
2use Laravel\Ai\Tools\Request;
3use Laravel\Converse\Cards\Card;
4use Laravel\Converse\Cards\Text;
5use Laravel\Converse\ThreadContext;
6use Stringable;
7 
8/**
9 * Execute the tool.
10 */
11public function handle(Request $request): Stringable|string
12{
13 $thread = app(ThreadContext::class)->thread();
14 
15 if ($thread === null) {
16 return 'This tool may only be used in a chat.';
17 }
18 
19 $order = Order::findOrFail($request['order_id']);
20 
21 $thread->send(
22 Card::make("Order #{$order->id}")
23 ->withChildren(Text::make("**Total:** {$order->total}"))
24 ->withFallback("Order #{$order->id}"),
25 );
26 
27 return 'The order card was sent.';
28}
1use App\Models\Order;
2use Laravel\Ai\Tools\Request;
3use Laravel\Converse\Cards\Card;
4use Laravel\Converse\Cards\Text;
5use Laravel\Converse\ThreadContext;
6use Stringable;
7 
8/**
9 * Execute the tool.
10 */
11public function handle(Request $request): Stringable|string
12{
13 $thread = app(ThreadContext::class)->thread();
14 
15 if ($thread === null) {
16 return 'This tool may only be used in a chat.';
17 }
18 
19 $order = Order::findOrFail($request['order_id']);
20 
21 $thread->send(
22 Card::make("Order #{$order->id}")
23 ->withChildren(Text::make("**Total:** {$order->total}"))
24 ->withFallback("Order #{$order->id}"),
25 );
26 
27 return 'The order card was sent.';
28}

Tool Approvals

Whenever an agent bot calls a tool that requires approval, Converse pauses the turn and sends a card with Approve and Reject buttons. Once the user responds, Converse resumes the turn. Your own tools that require approval work automatically with no extra configuration.

Tool approvals require an agent that uses the RemembersConversations trait.

Converse's built-in tool groups don't require approval by default. To require approval for specific tools, pass their class names to requireApproval on the tool group:

1use Laravel\Converse\Ai\Tools\SendMessage;
2use Laravel\Converse\Facades\Converse;
3 
4/**
5 * Get the tools available to the agent.
6 *
7 * @return Tool[]
8 */
9public function tools(): iterable
10{
11 return [
12 ...Converse::tools()->messaging()->requireApproval(SendMessage::class),
13 ];
14}
1use Laravel\Converse\Ai\Tools\SendMessage;
2use Laravel\Converse\Facades\Converse;
3 
4/**
5 * Get the tools available to the agent.
6 *
7 * @return Tool[]
8 */
9public function tools(): iterable
10{
11 return [
12 ...Converse::tools()->messaging()->requireApproval(SendMessage::class),
13 ];
14}

Calling requireApproval with no arguments requires approval for every tool in that group that supports it. The threadContext tools and UpdateStatus never require approval.

Only the user whose message started the turn can answer the approval request. On scheduled and prompted turns, where no user started the turn, anyone in the thread can answer.

Users can answer by clicking a button or replying with a single word such as yes, approve, no, or reject. On platforms without buttons, such as GitHub, replying with text is the only option.

The approval card shows all of the tool's arguments in full. If the arguments are too large for the platform to display, Converse refuses to run the tool and notifies the user in the thread that the request was too large to review.

On chat platforms, pending approvals expire after one hour by default. To change that duration, add approval_ttl in seconds to the turns array in config/converse.php:

1'turns' => [
2 // ...
3 'approval_ttl' => 7200,
4],
1'turns' => [
2 // ...
3 'approval_ttl' => 7200,
4],

Converse dispatches ApprovalRequested and ApprovalResolved events on chat platforms as approvals are requested and decided. Register listeners in the boot method of AppServiceProvider to audit or log each decision:

1use Illuminate\Support\Facades\Event;
2use Illuminate\Support\Facades\Log;
3use Laravel\Converse\Events\ApprovalResolved;
4 
5/**
6 * Bootstrap any application services.
7 */
8public function boot(): void
9{
10 Event::listen(function (ApprovalResolved $event) {
11 Log::info('Tool approval resolved.', ['approved' => $event->isApproved()]);
12 });
13}
1use Illuminate\Support\Facades\Event;
2use Illuminate\Support\Facades\Log;
3use Laravel\Converse\Events\ApprovalResolved;
4 
5/**
6 * Bootstrap any application services.
7 */
8public function boot(): void
9{
10 Event::listen(function (ApprovalResolved $event) {
11 Log::info('Tool approval resolved.', ['approved' => $event->isApproved()]);
12 });
13}

On the web connection, the browser renders and submits approval requests instead, and Converse dispatches WebApprovalRequested and WebApprovalResolved. To handle approvals in your frontend, check out approving tools in the browser.

Scheduled Turns

An agent bot can run on a schedule through Laravel's task scheduler. In routes/bot.php, call schedule with a prompt and an optional schedule name, call in to choose a destination, and chain any scheduler frequency method:

1use App\Ai\Agents\SupportAgent;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::agent('support', SupportAgent::class)
5 ->connection('slack')
6 ->schedule('Summarize yesterday and flag anything unusual.', 'daily-summary')
7 ->in('slack', '#general')
8 ->weekdays()
9 ->dailyAt('09:00');
1use App\Ai\Agents\SupportAgent;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::agent('support', SupportAgent::class)
5 ->connection('slack')
6 ->schedule('Summarize yesterday and flag anything unusual.', 'daily-summary')
7 ->in('slack', '#general')
8 ->weekdays()
9 ->dailyAt('09:00');

The optional second argument names the schedule so you can trigger it with converse:schedule:run. Because the name defaults to the bot's name, give each schedule a unique name when a bot defines more than one.

The in method accepts a channel ID or name such as #general, and on Slack it also accepts a username such as @taylor to send a direct message. You may chain in multiple times to target several destinations, after calling connection.

If the agent decides there's nothing to report, such as when asked to post failed deployments and none failed, Converse sends no message. When the agent does post, users can reply in that thread without mentioning the bot.

Schedules use your application's timezone by default. Set CONVERSE_SCHEDULES_TIMEZONE in .env to change the default for every schedule, or chain timezone onto a single schedule:

1->weekdays()
2->dailyAt('09:00')
3->timezone('Europe/Lisbon');
1->weekdays()
2->dailyAt('09:00')
3->timezone('Europe/Lisbon');

To disable all scheduled turns, such as on your local machine, set CONVERSE_SCHEDULES_ENABLED=false in .env.

List every registered schedule with converse:schedule:list, or dispatch one immediately to your queue with converse:schedule:run:

1php artisan converse:schedule:list
2 
3php artisan converse:schedule:run support daily-summary
1php artisan converse:schedule:list
2 
3php artisan converse:schedule:run support daily-summary

Scheduled turns require both a running scheduler and a queue worker.

Prompting Agents

When an event in your application should trigger an agent turn, such as a failed deployment inside an event listener or queued job, call prompt on a thread retrieved from the agent bot. Like scheduled turns, the prompted turn runs on your queue:

1use Laravel\Converse\Facades\Converse;
2 
3Converse::bot('support')
4 ->thread('slack', '#deployments')
5 ->prompt("Deployment {$deployment->id} failed. Find out why and tell the team.");
1use Laravel\Converse\Facades\Converse;
2 
3Converse::bot('support')
4 ->thread('slack', '#deployments')
5 ->prompt("Deployment {$deployment->id} failed. Find out why and tell the team.");

Pass a key argument to make the prompt idempotent. Converse ignores any subsequent prompt with the same key in the same thread, preventing a retried job from triggering duplicate turns:

1->prompt('Summarize the incident.', key: "incident-{$incident->id}");
1->prompt('Summarize the incident.', key: "incident-{$incident->id}");

Unlike an incoming user message, a prompted turn waits for any active turn in the thread to finish instead of interrupting it. As with scheduled turns, Converse posts nothing if the agent decides there's nothing to report.

Handlers

Handler bots answer messages with your own PHP code instead of an AI agent. For example, a handler bot might trigger a deployment when someone runs /deploy, or post an interactive card when an order needs review.

Creating Handlers

Generate a new handler in app/Bots using the make:bot Artisan command:

1php artisan make:bot DeployBot
1php artisan make:bot DeployBot

Converse resolves handlers through the service container, so you can type-hint any dependencies in the constructor. Implement the contract for each type of event your handler should receive:

1<?php
2 
3namespace App\Bots;
4 
5use Laravel\Converse\BotEvents\Message;
6use Laravel\Converse\Contracts\HandlesMentions;
7 
8class DeployBot implements HandlesMentions
9{
10 /**
11 * Handle a message that mentions the bot.
12 */
13 public function handleMention(Message $message): void
14 {
15 $message->thread()->send('Hello, '.($message->user()->name() ?? 'there').'!');
16 }
17}
1<?php
2 
3namespace App\Bots;
4 
5use Laravel\Converse\BotEvents\Message;
6use Laravel\Converse\Contracts\HandlesMentions;
7 
8class DeployBot implements HandlesMentions
9{
10 /**
11 * Handle a message that mentions the bot.
12 */
13 public function handleMention(Message $message): void
14 {
15 $message->thread()->send('Hello, '.($message->user()->name() ?? 'there').'!');
16 }
17}

Converse provides these handler contracts in Laravel\Converse\Contracts, listed in the order Converse checks them:

Contract Method Receives
HandlesDirectMessages handleDirectMessage Messages sent directly to the bot.
HandlesSubscribedMessages handleSubscribedMessage Messages in subscribed threads.
HandlesMentions handleMention Messages that mention the bot.
HandlesMessages handleMessage Any other message.
HandlesMessageUpdates handleMessageUpdate Edited messages.
HandlesMessageDeletions handleMessageDeletion Deleted messages.
HandlesCommands handleCommand Slash commands.
HandlesActions handleAction Button clicks and menu selections.
HandlesReactions handleReaction Emoji reactions.
HandlesFallback handleFallback Any event that no other method handles.

Converse calls only the first matching method in this table, even if a message matches multiple contracts, and always ignores events triggered by your bot itself.

The handler generated by make:bot implements only HandlesMentions. In terminal chat and web chat, where every message is a direct message, Converse routes those messages to handleMention so the generated handler works out of the box.

Bot Events

Each handler method receives an event from Laravel\Converse\BotEvents, such as the Message event passed to handleMention. Every event provides a thread method returning the event's Thread:

Event Methods
Message id, text, user, sentAt, isMention, isDirectMessage, isEdited, isScheduled, attachments, batch, others, addReaction, removeReaction
Command name, text, user
Action actionId, value, messageId, user
Reaction emoji, is, isAdded, messageId, user
MessageUpdated message
MessageDeleted messageId, deletedAt

An event's user method returns a Laravel\Converse\User instance with id, name, username, isBot, and isAnonymous methods. name and username return null when the platform doesn't supply them, and isAnonymous returns true for guests and scheduled turns.

On a Command event, name returns the command name without its leading slash:

1use App\Jobs\DeployApplication;
2use Laravel\Converse\BotEvents\Command;
3 
4/**
5 * Handle a slash command.
6 */
7public function handleCommand(Command $command): void
8{
9 match ($command->name()) {
10 'deploy' => DeployApplication::dispatch($command->thread()),
11 default => $command->thread()->send("Unknown command [/{$command->name()}]."),
12 };
13}
1use App\Jobs\DeployApplication;
2use Laravel\Converse\BotEvents\Command;
3 
4/**
5 * Handle a slash command.
6 */
7public function handleCommand(Command $command): void
8{
9 match ($command->name()) {
10 'deploy' => DeployApplication::dispatch($command->thread()),
11 default => $command->thread()->send("Unknown command [/{$command->name()}]."),
12 };
13}

Because each platform names emoji differently, compare reactions against cases of the Emoji enum using is:

1use Laravel\Converse\BotEvents\Reaction;
2use Laravel\Converse\Enums\Emoji;
3 
4/**
5 * Handle an emoji reaction.
6 */
7public function handleReaction(Reaction $reaction): void
8{
9 if ($reaction->is(Emoji::ThumbsUp) && $reaction->isAdded()) {
10 // ...
11 }
12}
1use Laravel\Converse\BotEvents\Reaction;
2use Laravel\Converse\Enums\Emoji;
3 
4/**
5 * Handle an emoji reaction.
6 */
7public function handleReaction(Reaction $reaction): void
8{
9 if ($reaction->is(Emoji::ThumbsUp) && $reaction->isAdded()) {
10 // ...
11 }
12}

Linking Platform Accounts

Every platform assigns its own user ID, such as U0123456789 on Slack, so the same person has a different ID on each platform. Converse can link each platform account to one of your application's users. First, publish and run the migration that stores the links:

1php artisan vendor:publish --tag=converse-account-migrations
2 
3php artisan migrate
1php artisan vendor:publish --tag=converse-account-migrations
2 
3php artisan migrate

The migration stores the application user in a morphs column. If your users have UUID or ULID keys, change it to uuidMorphs or ulidMorphs in the published migration before migrating.

Once a platform account is linked, the account method of a bot event returns the application user who owns it, or null if nobody has linked the account yet:

1public function handleMessage(Message $message): void
2{
3 $user = $message->account();
4 
5 // ...
6}
1public function handleMessage(Message $message): void
2{
3 $user = $message->account();
4 
5 // ...
6}

Because an agent bot closure can accept both the web chat's $participant and the incoming $message, one bot definition can resolve the application user across every connection:

1use App\Ai\Agents\SupportAgent;
2use App\Models\User;
3use Laravel\Converse\BotEvents\Message;
4use Laravel\Converse\Facades\Converse;
5 
6Converse::agent('support', fn (?User $participant, Message $message) => new SupportAgent(
7 $participant ?? $message->account(),
8))->connection('web', 'slack', 'telegram');
1use App\Ai\Agents\SupportAgent;
2use App\Models\User;
3use Laravel\Converse\BotEvents\Message;
4use Laravel\Converse\Facades\Converse;
5 
6Converse::agent('support', fn (?User $participant, Message $message) => new SupportAgent(
7 $participant ?? $message->account(),
8))->connection('web', 'slack', 'telegram');

Requiring Linked Accounts

To answer only people who have linked their account, add the RequireLinkedAccount middleware to your bot:

1use Laravel\Converse\Accounts\RequireLinkedAccount;
2 
3Converse::agent('support', SupportAgent::class)
4 ->connection('slack', 'telegram', 'github')
5 ->middleware(RequireLinkedAccount::class);
1use Laravel\Converse\Accounts\RequireLinkedAccount;
2 
3Converse::agent('support', SupportAgent::class)
4 ->connection('slack', 'telegram', 'github')
5 ->middleware(RequireLinkedAccount::class);

The middleware drops events from people without a linked account and sends them a link instead. Anyone who opens the link becomes the owner of the platform account, so the middleware only sends it where the sender alone can see it: in the direct message the user wrote from, as an ephemeral message on Slack, or by direct message on Telegram. When the bot cannot message a Telegram user first, it asks them to send it a direct message. Until the user links, the bot keeps offering the same link. Events from other bots and from Telegram channels cannot be linked, so the middleware drops them without sending a link. The middleware does not apply to web chat or the terminal, where the connection's guard and guest settings decide who may chat, and the account method returns null there.

The link opens a confirmation page in your application, behind the web and auth middleware. Like Laravel Fortify, Converse does not ship this page, so you should tell Converse how to render it using the linkAccountView method, typically in the boot method of your application's AppServiceProvider. The closure receives a PendingLink that describes the platform account:

1use Laravel\Converse\Accounts\PendingLink;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::linkAccountView(fn (PendingLink $link) => view('accounts.link', [
5 'platform' => $link->platform(),
6 'handle' => $link->user()->username() ?? $link->user()->id(),
7 'action' => $link->url(),
8]));
1use Laravel\Converse\Accounts\PendingLink;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::linkAccountView(fn (PendingLink $link) => view('accounts.link', [
5 'platform' => $link->platform(),
6 'handle' => $link->user()->username() ?? $link->user()->id(),
7 'action' => $link->url(),
8]));

The page should ask the signed-in user to confirm, and submit a POST request to the link's url. Someone may send a user their own link and ask them to open it, and confirming would let that person's chat account act as the user. So the page should name the platform and the account's handle, and tell the user to continue only if they asked the bot for the link. Display names may be faked, so show the handle rather than the name:

1<form method="POST" action="{{ $action }}">
2 @csrf
3 
4 <p>Connect the {{ $platform }} account <strong>{{ $handle }}</strong> to your account?</p>
5 
6 <p>Only continue if you asked the bot for this link yourself.</p>
7 
8 <button type="submit">Connect</button>
9</form>
1<form method="POST" action="{{ $action }}">
2 @csrf
3 
4 <p>Connect the {{ $platform }} account <strong>{{ $handle }}</strong> to your account?</p>
5 
6 <p>Only continue if you asked the bot for this link yourself.</p>
7 
8 <button type="submit">Connect</button>
9</form>

Once the user confirms, Converse links the account, dispatches the Laravel\Converse\Events\AccountLinked event, and redirects the browser to /, flashing the connection name to the session as converse.linked. The bot then tells the user the account is connected and answers the message the user sent before linking, so they do not need to send it again. You may change the redirect path, the middleware that guards these routes, and how many seconds a link stays valid in the accounts section of the config/converse.php configuration file.

On GitHub, every comment is public, so the bot instead posts a link that signs the user in with GitHub. Signing in proves who owns the GitHub account, so a stranger who opens the link can only link their own account. To support this, add the GitHub App's client ID and client secret to your .env file, and add https://example.com/converse/accounts/github/callback as the app's callback URL. The converse:setup command does both for you when it creates the app. For an app that already exists, generate a client secret and add the callback URL in the app's settings on GitHub, and if you have published the config/converse.php configuration file, add the client_id and client_secret options to its github connection:

1GITHUB_CLIENT_ID=Iv1.0123456789abcdef
2GITHUB_CLIENT_SECRET=your-client-secret
1GITHUB_CLIENT_ID=Iv1.0123456789abcdef
2GITHUB_CLIENT_SECRET=your-client-secret

GitHub logins may change, and a new user may later take a login that someone else gave up. For this reason, Converse links each GitHub account by its numeric ID, which it reads from each comment's webhook, so a link never follows a login to a new owner.

Linking Accounts From Your Application

Users may also start linking from your application, such as from a settings page. The linkCode method creates a short-lived code for the given user and connection:

1use Laravel\Converse\Facades\Converse;
2 
3$code = Converse::linkCode($request->user(), 'telegram');
4 
5$code->code(); // link-...
6$code->url(); // https://t.me/your_bot?start=link-...
1use Laravel\Converse\Facades\Converse;
2 
3$code = Converse::linkCode($request->user(), 'telegram');
4 
5$code->code(); // link-...
6$code->url(); // https://t.me/your_bot?start=link-...

When a user sends the code to your bot in a direct message, Converse links their platform account to your user and replies that the account is connected. Anyone who sends the code first gets linked, so you should show it only to the signed-in user. Each code works once, and a code posted in a channel or group the bot can read stops working right away. A code never moves a platform account that is already linked to a different user, so that user must unlink it first. On Telegram, the url method returns a link that opens a chat with your bot and sends the code for the user. On GitHub, it returns the URL that signs the user in with GitHub. On Slack, url returns null, so you should show the code and ask the user to send it to your bot in a direct message.

To link, look up, or unlink an account yourself, use the linkAccount, linkedAccount, and unlinkAccount methods. Every link is stored as a Laravel\Converse\Models\LinkedAccount model, so you may add a relationship to your User model to list or remove a user's links:

1use Illuminate\Database\Eloquent\Relations\MorphMany;
2use Laravel\Converse\Facades\Converse;
3use Laravel\Converse\Models\LinkedAccount;
4 
5Converse::linkAccount('slack', 'U0123456789', $user);
6 
7Converse::linkedAccount('slack', 'U0123456789'); // App\Models\User
8 
9Converse::unlinkAccount('slack', 'U0123456789');
10 
11/**
12 * Get the user's linked chat accounts.
13 */
14public function linkedAccounts(): MorphMany
15{
16 return $this->morphMany(LinkedAccount::class, 'account');
17}
1use Illuminate\Database\Eloquent\Relations\MorphMany;
2use Laravel\Converse\Facades\Converse;
3use Laravel\Converse\Models\LinkedAccount;
4 
5Converse::linkAccount('slack', 'U0123456789', $user);
6 
7Converse::linkedAccount('slack', 'U0123456789'); // App\Models\User
8 
9Converse::unlinkAccount('slack', 'U0123456789');
10 
11/**
12 * Get the user's linked chat accounts.
13 */
14public function linkedAccounts(): MorphMany
15{
16 return $this->morphMany(LinkedAccount::class, 'account');
17}

Subscriptions

Call subscribe on a thread when your handler should receive every follow-up message in that thread without needing another mention. Converse routes subsequent messages in subscribed threads to handleSubscribedMessage:

1use Laravel\Converse\BotEvents\Message;
2 
3/**
4 * Handle a message that mentions the bot.
5 */
6public function handleMention(Message $message): void
7{
8 $message->thread()->subscribe();
9}
1use Laravel\Converse\BotEvents\Message;
2 
3/**
4 * Handle a message that mentions the bot.
5 */
6public function handleMention(Message $message): void
7{
8 $message->thread()->subscribe();
9}

Call unsubscribe to stop listening to the thread, or isSubscribed to check whether the bot is currently subscribed.

Batched Messages

Messages that arrive while a handler bot is mid-turn or debouncing wait until the next turn, and Converse passes the newest message to your handler. Call batch to iterate through every message in the turn from oldest to newest:

1foreach ($message->batch() as $turnMessage) {
2 // ...
3}
1foreach ($message->batch() as $turnMessage) {
2 // ...
3}

Call others to get those same messages excluding the newest message.

Combining Agents and Handlers

Sometimes you want an AI agent to handle open-ended conversation while your own PHP code handles specific events such as slash commands or button clicks. Pass a handler class to handler on your agent bot in routes/bot.php:

1use App\Ai\Agents\SupportAgent;
2use App\Bots\SupportBot;
3use Laravel\Converse\Facades\Converse;
4 
5Converse::agent('support', SupportAgent::class)
6 ->handler(SupportBot::class)
7 ->connection('slack');
1use App\Ai\Agents\SupportAgent;
2use App\Bots\SupportBot;
3use Laravel\Converse\Facades\Converse;
4 
5Converse::agent('support', SupportAgent::class)
6 ->handler(SupportBot::class)
7 ->connection('slack');

Your handler receives every event type covered by the contracts it implements. The agent continues to receive all remaining mentions, direct messages, messages in subscribed threads and bot-started threads, button clicks, and scheduled or prompted turns. If your handler implements HandlesFallback, handleFallback receives only events that neither the handler nor the agent claims.

Keep in mind that HandlesMessages catches every message not claimed by another handler contract, including mentions and direct messages. If your handler implements HandlesMessages, the agent will answer only button clicks and scheduled or prompted turns.

Threads

A Laravel\Converse\Thread represents one conversation thread on a platform, such as a Slack thread or a GitHub issue. Inside an AI tool, access the active thread through the thread context.

To post outside a turn, such as from a queued job, fetch a thread with thread on any bot. Pass the connection name, a channel ID or name, and an optional thread ID. Without a thread ID, Converse posts directly to the channel, which GitHub doesn't support:

1use Laravel\Converse\Facades\Converse;
2 
3$channel = Converse::bot('support')->thread('slack', '#support');
4 
5$thread = Converse::bot('support')->thread('slack', '#support', '1712345678.000100');
6 
7$issue = Converse::bot('support')->thread('github', 'laravel/converse', '42');
1use Laravel\Converse\Facades\Converse;
2 
3$channel = Converse::bot('support')->thread('slack', '#support');
4 
5$thread = Converse::bot('support')->thread('slack', '#support', '1712345678.000100');
6 
7$issue = Converse::bot('support')->thread('github', 'laravel/converse', '42');

Converse::bot returns any registered bot, whether it's an agent bot or a handler bot. As with in on a scheduled turn, thread resolves channel names such as #support to their platform ID.

To reply to a thread later, such as when a long-running job completes, store the thread's connection, channel()->id(), and id values and pass them back to thread:

1$order->update([
2 'chat_connection' => $thread->connection(),
3 'chat_channel' => $thread->channel()->id(),
4 'chat_thread' => $thread->id(),
5]);
6 
7Converse::bot('support')
8 ->thread($order->chat_connection, $order->chat_channel, $order->chat_thread)
9 ->send('Your order has shipped.');
1$order->update([
2 'chat_connection' => $thread->connection(),
3 'chat_channel' => $thread->channel()->id(),
4 'chat_thread' => $thread->id(),
5]);
6 
7Converse::bot('support')
8 ->thread($order->chat_connection, $order->chat_channel, $order->chat_thread)
9 ->send('Your order has shipped.');

Sending Messages

Call send with a string, a Markdown instance, or a card. It returns a SentMessage instance:

1use Laravel\Converse\Markdown;
2 
3$thread->send('Deployment complete.');
4 
5$thread->send(Markdown::make('**Deployed**. See the [release notes](https://example.com).'));
1use Laravel\Converse\Markdown;
2 
3$thread->send('Deployment complete.');
4 
5$thread->send(Markdown::make('**Deployed**. See the [release notes](https://example.com).'));

To mention a user, interpolate $thread->mention($user) inside a Markdown message:

1$thread->send(Markdown::make('Reviewed by '.$thread->mention($message->user())));
1$thread->send(Markdown::make('Reviewed by '.$thread->mention($message->user())));

Call sendEphemeral to send a message visible only to the user who triggered the event. On platforms without ephemeral messages, Converse sends the user a direct message instead, and inside a direct message it sends a regular reply. Outside a turn, pass the recipient as the second argument:

1$message->thread()->sendEphemeral('Only you can see this message.');
2 
3$thread->sendEphemeral('Only you can see this message.', $userId);
1$message->thread()->sendEphemeral('Only you can see this message.');
2 
3$thread->sendEphemeral('Only you can see this message.', $userId);

Because GitHub supports neither ephemeral messages nor direct messages, sendEphemeral throws UnsupportedCapabilityException on GitHub.

Editing, Deleting, and Reacting

You can edit, delete, and react to the SentMessage returned by send:

1use Laravel\Converse\Enums\Emoji;
2 
3$sent = $thread->send('Working on it...');
4 
5$sent->edit('All done!');
6$sent->addReaction(Emoji::ThumbsUp);
7$sent->removeReaction(Emoji::ThumbsUp);
8$sent->delete();
1use Laravel\Converse\Enums\Emoji;
2 
3$sent = $thread->send('Working on it...');
4 
5$sent->edit('All done!');
6$sent->addReaction(Emoji::ThumbsUp);
7$sent->removeReaction(Emoji::ThumbsUp);
8$sent->delete();

You can also react directly to an incoming Message in a handler, such as to acknowledge that your bot received it:

1$message->addReaction(Emoji::Eyes);
1$message->addReaction(Emoji::Eyes);

When you only have a message's ID, such as $action->messageId() from an Action or Reaction event, call edit, delete, addReaction, or removeReaction on the thread:

1$thread->edit($messageId, 'All done!');
2 
3$thread->addReaction($messageId, Emoji::ThumbsUp);
1$thread->edit($messageId, 'All done!');
2 
3$thread->addReaction($messageId, Emoji::ThumbsUp);

Alongside Emoji enum cases, reaction methods accept an emoji character or shortcode such as '👀' or 'eyes'. Each platform limits which reactions bots can use. ThumbsUp, ThumbsDown, Heart, Party, and Eyes work across Slack, Telegram, and GitHub.

Telegram allows one reaction per message from your bot, so adding a new reaction replaces the previous one.

Typing Indicators

Call updateStatus to show the platform's typing indicator and clearStatus to hide it. Slack and converse:chat also display the status text you pass, defaulting to "is thinking..." when omitted. Slack shows status text only inside threads, Telegram ignores the text, and on platforms without typing indicators such as GitHub, both methods do nothing:

1$thread->updateStatus('Searching the docs...');
2 
3$thread->clearStatus();
1$thread->updateStatus('Searching the docs...');
2 
3$thread->clearStatus();

Thread Metadata

Each thread can persist key-value metadata in your database so your bot can keep state across turns:

1$thread->putMeta('step', 'awaiting-order-number');
2 
3$step = $thread->meta('step', 'start');
4 
5$thread->forgetMeta('step');
1$thread->putMeta('step', 'awaiting-order-number');
2 
3$step = $thread->meta('step', 'start');
4 
5$thread->forgetMeta('step');

Pass a default value as the second argument to meta when the key might not exist yet.

Message History

Call messages to retrieve up to 500 messages from the thread, newest first. Pass the oldest message ID you've read as cursor to page further back. On platforms without a history API, such as Telegram, Converse returns the messages stored in your database for that thread instead:

1foreach ($thread->messages(limit: 20) as $message) {
2 // ...
3}
4 
5$older = $thread->messages(limit: 20, cursor: $message->id());
1foreach ($thread->messages(limit: 20) as $message) {
2 // ...
3}
4 
5$older = $thread->messages(limit: 20, cursor: $message->id());

Call users to list the human participants in the thread, excluding bots, and attachments to list every attachment Converse stored for the thread. Call getUser to look up a user's details, which returns null on platforms that don't support user lookups:

1$user = $thread->getUser($userId);
1$user = $thread->getUser($userId);

Channels and Direct Messages

To post in the parent channel instead of replying inside the thread, call forChannel, which returns a Thread targeting the channel itself. Because every GitHub comment lives on an issue or pull request, channel threads aren't available on GitHub:

1$thread->forChannel()->send('Deployment v2.0 is live.');
1$thread->forChannel()->send('Deployment v2.0 is live.');

Call channel to get a Channel instance with id, name, memberCount, and isDirectMessage methods. Any field the platform doesn't supply is null.

To start a direct message with a user, call directMessage on the bot:

1use Laravel\Converse\Facades\Converse;
2 
3Converse::bot('support')
4 ->directMessage('slack', $userId)
5 ->send('Your export is ready.');
1use Laravel\Converse\Facades\Converse;
2 
3Converse::bot('support')
4 ->directMessage('slack', $userId)
5 ->send('Your export is ready.');

On Telegram, your bot can send a direct message only to a user who has already started a chat with it.

Capabilities

Each platform supports a different set of features. Converse throws UnsupportedCapabilityException if you edit, delete, react, send an attachment, send an ephemeral message, or open a direct message on a platform that doesn't support it. Check support ahead of time with supports and the Capability enum:

1use Laravel\Converse\Enums\Capability;
2 
3if ($thread->supports(Capability::EditMessage)) {
4 $sent->edit('Updated.');
5}
1use Laravel\Converse\Enums\Capability;
2 
3if ($thread->supports(Capability::EditMessage)) {
4 $sent->edit('Updated.');
5}

This table shows which platforms support the most common Capability enum cases:

Capability Slack Telegram GitHub
EditMessage Yes Yes Yes
DeleteMessage Yes Yes Yes
AddReaction Yes Yes Yes
RemoveReaction Yes Yes Yes
UpdateStatus Yes Yes No
SendAttachment Yes Yes No
DownloadAttachment Yes Yes No
SendEphemeralMessage Yes No No
OpenDirectMessage Yes Yes No
ListMessages Yes No Yes
GetUser Yes No Yes
GetChannel Yes Yes Yes

Cards

Cards are structured messages that each driver renders natively. Slack receives Block Kit blocks, Telegram receives formatted text with an inline keyboard, and GitHub receives GitHub Flavored Markdown. On the web connection, cards render only their fallback text without buttons or menus:

1use Laravel\Converse\Cards\Actions;
2use Laravel\Converse\Cards\Button;
3use Laravel\Converse\Cards\Card;
4use Laravel\Converse\Cards\Field;
5use Laravel\Converse\Cards\Fields;
6use Laravel\Converse\Cards\Text;
7 
8$thread->send(
9 Card::make('Refund request')
10 ->withChildren(
11 Text::make('**Order #1042** on the _Pro_ plan'),
12 Fields::make(Field::make('Amount', '$49.00')),
13 Actions::make(
14 Button::make('approve-refund')
15 ->withLabel('Approve')
16 ->withValue('1042')
17 ->primary(),
18 Button::make('deny-refund')
19 ->withLabel('Deny')
20 ->withValue('1042')
21 ->danger(),
22 ),
23 )
24 ->withFallback('Refund request for order #1042'),
25);
1use Laravel\Converse\Cards\Actions;
2use Laravel\Converse\Cards\Button;
3use Laravel\Converse\Cards\Card;
4use Laravel\Converse\Cards\Field;
5use Laravel\Converse\Cards\Fields;
6use Laravel\Converse\Cards\Text;
7 
8$thread->send(
9 Card::make('Refund request')
10 ->withChildren(
11 Text::make('**Order #1042** on the _Pro_ plan'),
12 Fields::make(Field::make('Amount', '$49.00')),
13 Actions::make(
14 Button::make('approve-refund')
15 ->withLabel('Approve')
16 ->withValue('1042')
17 ->primary(),
18 Button::make('deny-refund')
19 ->withLabel('Deny')
20 ->withValue('1042')
21 ->danger(),
22 ),
23 )
24 ->withFallback('Refund request for order #1042'),
25);

Slack shows the fallback text in notifications, while other platforms use it when a card has no visible content. If you omit fallback text, Converse falls back to the card's title. The Laravel\Converse\Cards namespace provides these elements:

Element Description
Text A block of Markdown text.
Image An image with optional alt text.
Fields and Field Pairs of labels and values.
Table Headers, rows, and an optional caption.
Section A group of elements.
Divider A separator.
Link A link.
Actions A row of controls.
Button A button that sends an action to your bot.
LinkButton A button that opens a URL.
Select and RadioSelect A menu of options.

Cards and their elements are immutable. Methods such as withLabel and primary return a new instance, so chain them or assign the returned instance to a variable.

Converse throws InvalidCardException when a card exceeds platform limits, such as more than 25 controls in an Actions row or more than 100 options in a Select.

Handling Button Clicks

When a user clicks a Button, Converse passes an Action event to your handler's handleAction method, provided your handler implements HandlesActions. Call actionId to read the button's ID and value to read its value. Typically, you'll edit the card after handling the click so the buttons can't be clicked again:

1use App\Models\Order;
2use Laravel\Converse\BotEvents\Action;
3 
4/**
5 * Handle a button click or menu selection.
6 */
7public function handleAction(Action $action): void
8{
9 if ($action->actionId() !== 'approve-refund') {
10 return;
11 }
12 
13 Order::findOrFail($action->value())->refund();
14 
15 if ($action->messageId() !== null) {
16 $action->thread()->edit($action->messageId(), "Refund for order #{$action->value()} approved.");
17 }
18}
1use App\Models\Order;
2use Laravel\Converse\BotEvents\Action;
3 
4/**
5 * Handle a button click or menu selection.
6 */
7public function handleAction(Action $action): void
8{
9 if ($action->actionId() !== 'approve-refund') {
10 return;
11 }
12 
13 Order::findOrFail($action->value())->refund();
14 
15 if ($action->messageId() !== null) {
16 $action->thread()->edit($action->messageId(), "Refund for order #{$action->value()} approved.");
17 }
18}

To forward clicks to another application instead of handling them in your bot, call withCallbackUrl with a public HTTPS URL. Converse posts each click from a queued job, and chaining once delivers only the first click:

1use Laravel\Converse\Cards\Button;
2 
3Button::make('approve-refund')
4 ->withLabel('Approve')
5 ->withCallbackUrl('https://example.com/webhooks/refunds')
6 ->once();
1use Laravel\Converse\Cards\Button;
2 
3Button::make('approve-refund')
4 ->withLabel('Approve')
5 ->withCallbackUrl('https://example.com/webhooks/refunds')
6 ->once();

Each callback request sends a JSON body containing type, actionId, value, user, threadId, messageId, and deliveryId. The deliveryId value, which also appears in the Converse-Delivery header, stays identical across retries so you can deduplicate deliveries.

Converse caches callback buttons for 30 days. After the first click on a once button, or once a button expires, clicks fall back to your bot as normal Action events, so handleAction should ignore action IDs it doesn't expect.

Converse signs every callback request using CONVERSE_CALLBACKS_SIGNING_SECRET, which must be set to a dedicated random secret. Sending a callback button without this secret throws InvalidActionCallbackException. If the receiving application also uses Converse, attach the converse.signed middleware to the endpoint. converse.signed responds with 403 when the signature is invalid, the timestamp is more than five minutes off, or a nonce is replayed. Define the route in routes/api.php, or exempt it from CSRF protection, because Converse doesn't send a CSRF token:

1use Illuminate\Support\Facades\Route;
2 
3Route::post('/webhooks/refunds', function () {
4 // ...
5})->middleware('converse.signed');
1use Illuminate\Support\Facades\Route;
2 
3Route::post('/webhooks/refunds', function () {
4 // ...
5})->middleware('converse.signed');

Pass a number of seconds as a middleware parameter to tighten or extend the timestamp window:

1->middleware('converse.signed:60');
1->middleware('converse.signed:60');

If the receiving application doesn't use Converse, store the shared secret in a configuration value such as services.converse.signing_secret and verify Converse-Signature yourself. The header holds v1= followed by the HMAC SHA-256 hash of Converse-Timestamp, Converse-Nonce, and the raw request body joined by periods. Reject requests whose Converse-Timestamp is too old:

1use Illuminate\Http\Request;
2use Illuminate\Support\Facades\Route;
3 
4Route::post('/webhooks/refunds', function (Request $request) {
5 $payload = $request->header('Converse-Timestamp').'.'.$request->header('Converse-Nonce').'.'.$request->getContent();
6 
7 $signature = 'v1='.hash_hmac('sha256', $payload, config('services.converse.signing_secret'));
8 
9 abort_unless(hash_equals($signature, (string) $request->header('Converse-Signature')), 403);
10 abort_unless(abs(time() - (int) $request->header('Converse-Timestamp')) <= 300, 403);
11 
12 // ...
13});
1use Illuminate\Http\Request;
2use Illuminate\Support\Facades\Route;
3 
4Route::post('/webhooks/refunds', function (Request $request) {
5 $payload = $request->header('Converse-Timestamp').'.'.$request->header('Converse-Nonce').'.'.$request->getContent();
6 
7 $signature = 'v1='.hash_hmac('sha256', $payload, config('services.converse.signing_secret'));
8 
9 abort_unless(hash_equals($signature, (string) $request->header('Converse-Signature')), 403);
10 abort_unless(abs(time() - (int) $request->header('Converse-Timestamp')) <= 300, 403);
11 
12 // ...
13});

Select and RadioSelect elements also send an Action event when a user chooses an option. actionId returns the menu's ID, and value returns the selected option's value:

1use Laravel\Converse\Cards\Actions;
2use Laravel\Converse\Cards\Select;
3 
4Actions::make(
5 Select::make('priority')
6 ->withPlaceholder('Choose a priority')
7 ->option('High', 'high')
8 ->option('Low', 'low'),
9);
1use Laravel\Converse\Cards\Actions;
2use Laravel\Converse\Cards\Select;
3 
4Actions::make(
5 Select::make('priority')
6 ->withPlaceholder('Choose a priority')
7 ->option('High', 'high')
8 ->option('Low', 'low'),
9);

Slack renders Select as a dropdown menu and RadioSelect as radio buttons. Telegram renders each option as a button, and GitHub renders the options as text.

Use LinkButton when a button should open a URL directly in the user's browser instead of sending an Action event to your bot:

1use Laravel\Converse\Cards\LinkButton;
2 
3LinkButton::make('View the order', 'https://example.com/orders/1042');
1use Laravel\Converse\Cards\LinkButton;
2 
3LinkButton::make('View the order', 'https://example.com/orders/1042');

Raw Platform Payloads

When you need platform-specific formatting beyond what Card provides, pass the driver name and raw payload to withRaw. Other platforms still render the standard card:

1use Laravel\Converse\Cards\Card;
2use Laravel\Converse\Cards\Text;
3 
4Card::make('Release notes')
5 ->withChildren(Text::make('Version 2.0 has shipped.'))
6 ->withRaw('slack', ['blocks' => [
7 ['type' => 'section', 'text' => ['type' => 'mrkdwn', 'text' => '*Version 2.0* has shipped.']],
8 ]]);
1use Laravel\Converse\Cards\Card;
2use Laravel\Converse\Cards\Text;
3 
4Card::make('Release notes')
5 ->withChildren(Text::make('Version 2.0 has shipped.'))
6 ->withRaw('slack', ['blocks' => [
7 ['type' => 'section', 'text' => ['type' => 'mrkdwn', 'text' => '*Version 2.0* has shipped.']],
8 ]]);

For GitHub, put the comment's Markdown in the raw payload's body key:

1->withRaw('github', ['body' => "> [!TIP]\n> **Version 2.0** has shipped."]);
1->withRaw('github', ['body' => "> [!TIP]\n> **Version 2.0** has shipped."]);

Attachments

Before passing a message to your bot, Converse downloads and stores each attached file on your configured attachment disk. Read stored files with $message->attachments():

1foreach ($message->attachments() as $attachment) {
2 $name = $attachment->name();
3 $mimeType = $attachment->mimeType();
4 $contents = $attachment->contents();
5 
6 $attachment->store('exports/'.$name);
7}
1foreach ($message->attachments() as $attachment) {
2 $name = $attachment->name();
3 $mimeType = $attachment->mimeType();
4 $contents = $attachment->contents();
5 
6 $attachment->store('exports/'.$name);
7}

By default, Converse accepts up to 5 files per message, up to 10 MB each, restricted to images, PDFs, plain text, and CSV files. Converse verifies each file's MIME type from its contents rather than its filename. Adjust these limits under attachments in config/converse.php, where mime_types accepts wildcards such as image/*. The same limits apply to uploads on the web connection, which rejects messages over those limits with a 422 response.

Files that fail these checks aren't stored. Inspect skipped files with unavailableAttachments and read why each was rejected with unavailable:

1foreach ($message->unavailableAttachments() as $attachment) {
2 $message->thread()->send(
3 "I skipped {$attachment->name()}: {$attachment->unavailable()}."
4 );
5}
1foreach ($message->unavailableAttachments() as $attachment) {
2 $message->thread()->send(
3 "I skipped {$attachment->name()}: {$attachment->unavailable()}."
4 );
5}

GitHub doesn't send attachments to bots, so attachments always returns an empty collection on GitHub.

Because users upload these files, Converse refuses to store them on a public disk. When your queue workers run on separate servers from your web server, use object storage such as S3 so both processes can access the files.

To send a file from your bot, pass an Attachment instance and an optional caption to sendAttachment:

1use Laravel\Converse\Attachment;
2 
3$thread->sendAttachment(Attachment::fromStorage('reports/summary.pdf'), "This month's summary.");
4 
5$thread->sendAttachment(Attachment::fromPath(storage_path('app/exports/orders.csv')));
6 
7$thread->sendAttachment(Attachment::fromContents($csv, 'export.csv', 'text/csv'));
1use Laravel\Converse\Attachment;
2 
3$thread->sendAttachment(Attachment::fromStorage('reports/summary.pdf'), "This month's summary.");
4 
5$thread->sendAttachment(Attachment::fromPath(storage_path('app/exports/orders.csv')));
6 
7$thread->sendAttachment(Attachment::fromContents($csv, 'export.csv', 'text/csv'));

Web Chat

Converse can also power a chat directly inside your application's web pages. A web chat pairs a bot registered on the web connection with the Chat component from @laravel/converse-react or @laravel/converse-vue.

Answering yes to the web chat prompt during converse:install scaffolds everything for you: it registers assistant on the web connection, publishes the web chat migration, publishes a chat page and its components, adds the /chat routes, and offers to install and build the frontend package.

The installer publishes the chat page to resources/js/pages and its components to resources/js/components/converse, where you can customize them freely. Re-running converse:install never overwrites published files unless you pass --force.

Rendering the Chat

To wire up web chat manually, start by publishing and running the web chat migration, which creates the tables that store each web turn and its events:

1php artisan vendor:publish --tag=converse-web-migrations
2 
3php artisan migrate
1php artisan vendor:publish --tag=converse-web-migrations
2 
3php artisan migrate

Next, register your bot on the web connection in routes/bot.php:

1use App\Ai\Agents\Assistant;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::agent('assistant', Assistant::class)
5 ->connection('web');
1use App\Ai\Agents\Assistant;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::agent('assistant', Assistant::class)
5 ->connection('web');

Any agent on the web connection must use the AI SDK's RemembersConversations trait, because Converse reads the browser's message transcript from the agent's stored conversation.

Handler bots work on the web connection too. Every web message arrives as a direct message, and a handler that implements neither HandlesDirectMessages nor HandlesMessages receives them in handleMention.

The web connection registers routes for sending messages, streaming events, downloading attachments, and cancelling turns. Those routes apply every middleware listed under middleware in config/converse.php, defaulting to ['web']. Your bot middleware runs on web turns as well.

Next, pass the chat props to your Inertia page with Converse::chat. Those props include the authenticated user's latest thread with the bot and the URLs for the bot's endpoints. Protect the page route with auth middleware so a signed-in user owns the chat. Unless you allow guests, calling Converse::chat without an authenticated user throws AuthenticationException and the bot's routes respond with 401:

1use Illuminate\Support\Facades\Route;
2use Inertia\Inertia;
3use Laravel\Converse\Facades\Converse;
4 
5Route::get('/chat', function () {
6 return Inertia::render('Chat', [
7 'chat' => Converse::chat('assistant'),
8 ]);
9})->middleware('auth')->name('chat');
1use Illuminate\Support\Facades\Route;
2use Inertia\Inertia;
3use Laravel\Converse\Facades\Converse;
4 
5Route::get('/chat', function () {
6 return Inertia::render('Chat', [
7 'chat' => Converse::chat('assistant'),
8 ]);
9})->middleware('auth')->name('chat');

Install the frontend package for your framework:

1npm install @laravel/converse-react
1npm install @laravel/converse-react
1npm install @laravel/converse-vue
1npm install @laravel/converse-vue

Finally, render the Chat component with the chat prop from your page. Its render prop or slot exposes the thread's messages, a composer for the user's draft, and isAwaitingContent. Calling composer.submit sends and clears the draft, while composer.clear empties it without sending. isAwaitingContent returns true while a reply has started with no content yet, so you can show a "Thinking..." indicator:

1import { Chat } from "@laravel/converse-react";
2import type { ChatPayload } from "@laravel/converse-react";
3 
4export default function ChatPage({ chat }: { chat: ChatPayload }) {
5 return (
6 <Chat chat={chat}>
7 {({ messages, composer, isAwaitingContent }) => (
8 <>
9 {messages.map((message) => (
10 <div key={message.key}>
11 <strong>{message.role}</strong>
12 <p>{isAwaitingContent(message) ? "Thinking..." : message.content}</p>
13 </div>
14 ))}
15 
16 <form
17 onSubmit={(event) => {
18 event.preventDefault();
19 composer.submit();
20 }}
21 >
22 <input
23 value={composer.draft}
24 onChange={(event) => composer.setDraft(event.target.value)}
25 />
26 
27 <button type="submit">Send</button>
28 </form>
29 </>
30 )}
31 </Chat>
32 );
33}
1import { Chat } from "@laravel/converse-react";
2import type { ChatPayload } from "@laravel/converse-react";
3 
4export default function ChatPage({ chat }: { chat: ChatPayload }) {
5 return (
6 <Chat chat={chat}>
7 {({ messages, composer, isAwaitingContent }) => (
8 <>
9 {messages.map((message) => (
10 <div key={message.key}>
11 <strong>{message.role}</strong>
12 <p>{isAwaitingContent(message) ? "Thinking..." : message.content}</p>
13 </div>
14 ))}
15 
16 <form
17 onSubmit={(event) => {
18 event.preventDefault();
19 composer.submit();
20 }}
21 >
22 <input
23 value={composer.draft}
24 onChange={(event) => composer.setDraft(event.target.value)}
25 />
26 
27 <button type="submit">Send</button>
28 </form>
29 </>
30 )}
31 </Chat>
32 );
33}
1<script setup lang="ts">
2import { Chat } from "@laravel/converse-vue";
3import type { ChatPayload } from "@laravel/converse-vue";
4 
5defineProps<{ chat: ChatPayload }>();
6</script>
7 
8<template>
9 <Chat :chat v-slot="{ messages, composer, isAwaitingContent }">
10 <div v-for="message in messages" :key="message.key">
11 <strong>{{ message.role }}</strong>
12 <p>{{ isAwaitingContent(message) ? "Thinking..." : message.content }}</p>
13 </div>
14 
15 <form @submit.prevent="composer.submit()">
16 <input v-model="composer.draft" />
17 
18 <button type="submit">Send</button>
19 </form>
20 </Chat>
21</template>
1<script setup lang="ts">
2import { Chat } from "@laravel/converse-vue";
3import type { ChatPayload } from "@laravel/converse-vue";
4 
5defineProps<{ chat: ChatPayload }>();
6</script>
7 
8<template>
9 <Chat :chat v-slot="{ messages, composer, isAwaitingContent }">
10 <div v-for="message in messages" :key="message.key">
11 <strong>{{ message.role }}</strong>
12 <p>{{ isAwaitingContent(message) ? "Thinking..." : message.content }}</p>
13 </div>
14 
15 <form @submit.prevent="composer.submit()">
16 <input v-model="composer.draft" />
17 
18 <button type="submit">Send</button>
19 </form>
20 </Chat>
21</template>

Each message's content property holds its full text. When a turn includes tool calls or reasoning, render message.parts instead to display each piece in the order it arrived. Unlike isAwaitingContent, isAwaitingNextPart also returns true after a tool call finishes while the model prepares its next part, so you can keep a "Thinking..." indicator visible below the parts until the reply resumes.

Tools run by the AI provider itself, such as WebSearch or WebFetch, appear as a single provider-tool part per call. toolName holds the tool's name, state transitions from running to complete or error, and data carries the provider's latest details such as the search query.

Each message's citations array lists every cited source once. Each entry provides title, url, and host, such as laravel.com, so you can display citations below the reply.

To scroll each new prompt to the top of the transcript as the reply streams in, check out scrolling the transcript.

The chat's status value tracks the current state: ready, submitted, streaming, resuming, or error. For example, show a status message while status is submitted or streaming:

1<Chat chat={chat}>
2 {({ messages, composer, status }) => (
3 <>
4 {/* ... */}
5 
6 {(status === "submitted" || status === "streaming") && <p>Answering...</p>}
7 </>
8 )}
9</Chat>
1<Chat chat={chat}>
2 {({ messages, composer, status }) => (
3 <>
4 {/* ... */}
5 
6 {(status === "submitted" || status === "streaming") && <p>Answering...</p>}
7 </>
8 )}
9</Chat>
1<Chat :chat v-slot="{ messages, composer, status }">
2 <!-- ... -->
3 
4 <p v-if="status === 'submitted' || status === 'streaming'">Answering...</p>
5</Chat>
1<Chat :chat v-slot="{ messages, composer, status }">
2 <!-- ... -->
3 
4 <p v-if="status === 'submitted' || status === 'streaming'">Answering...</p>
5</Chat>

Because messages sent mid-turn are queued automatically, you don't need to disable the input while the bot is replying.

A message's id updates to the persisted database ID once the turn finishes, while key stays constant. Always key rendered messages by message.key so React or Vue doesn't remount them at the end of a turn.

Converse streams Markdown to the browser rather than HTML. While a reply is streaming, its Markdown can be temporarily incomplete, such as an unclosed link. Pass message.content to renderStreamingMarkdown, which escapes unsafe input and returns HTML safe for dangerouslySetInnerHTML in React or v-html in Vue:

1import { renderStreamingMarkdown } from "@laravel/converse-react";
2 
3{messages.map((message) => (
4 <div
5 key={message.key}
6 dangerouslySetInnerHTML={{ __html: renderStreamingMarkdown(message.content) }}
7 />
8))}
1import { renderStreamingMarkdown } from "@laravel/converse-react";
2 
3{messages.map((message) => (
4 <div
5 key={message.key}
6 dangerouslySetInnerHTML={{ __html: renderStreamingMarkdown(message.content) }}
7 />
8))}
1<script setup lang="ts">
2import { renderStreamingMarkdown } from "@laravel/converse-vue";
3</script>
4 
5<template>
6 <div
7 v-for="message in messages"
8 :key="message.key"
9 v-html="renderStreamingMarkdown(message.content)"
10 />
11</template>
1<script setup lang="ts">
2import { renderStreamingMarkdown } from "@laravel/converse-vue";
3</script>
4 
5<template>
6 <div
7 v-for="message in messages"
8 :key="message.key"
9 v-html="renderStreamingMarkdown(message.content)"
10 />
11</template>

Scrolling the Transcript

Like most AI chat interfaces, Chat can scroll each new user prompt to the top of the transcript and anchor it there while the reply streams below it. The user reads the answer from its first line rather than chasing the bottom of the screen.

To enable this behavior, attach composer.container as the ref on your scrollable transcript element, add promptAttribute to every user message element, and place an empty element with composer.spacerStyle at the end of the transcript. The spacer creates enough room at the bottom for the newest prompt to scroll to the top.

Because the transcript container scrolls instead of the page, full-page chats place the scrollable container above the form in a flex column filling the viewport. The chat scaffolded by converse:install already uses this layout:

1import { promptAttribute } from "@laravel/converse-react";
2 
3<div className="flex h-dvh flex-col">
4 <div ref={composer.container} className="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto">
5 {messages.map((message) => (
6 <div key={message.key} {...(message.role === "user" ? { [promptAttribute]: "" } : {})}>
7 {message.content}
8 </div>
9 ))}
10 
11 <div style={composer.spacerStyle} />
12 </div>
13 
14 <form>{/* ... */}</form>
15</div>
1import { promptAttribute } from "@laravel/converse-react";
2 
3<div className="flex h-dvh flex-col">
4 <div ref={composer.container} className="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto">
5 {messages.map((message) => (
6 <div key={message.key} {...(message.role === "user" ? { [promptAttribute]: "" } : {})}>
7 {message.content}
8 </div>
9 ))}
10 
11 <div style={composer.spacerStyle} />
12 </div>
13 
14 <form>{/* ... */}</form>
15</div>
1<script setup lang="ts">
2import { promptAttribute } from "@laravel/converse-vue";
3</script>
4 
5<template>
6 <div class="flex h-dvh flex-col">
7 <div :ref="composer.container" class="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto">
8 <div
9 v-for="message in messages"
10 :key="message.key"
11 v-bind="message.role === 'user' ? { [promptAttribute]: '' } : {}"
12 >
13 {{ message.content }}
14 </div>
15 
16 <div :style="composer.spacerStyle" />
17 </div>
18 
19 <form><!-- ... --></form>
20 </div>
21</template>
1<script setup lang="ts">
2import { promptAttribute } from "@laravel/converse-vue";
3</script>
4 
5<template>
6 <div class="flex h-dvh flex-col">
7 <div :ref="composer.container" class="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto">
8 <div
9 v-for="message in messages"
10 :key="message.key"
11 v-bind="message.role === 'user' ? { [promptAttribute]: '' } : {}"
12 >
13 {{ message.content }}
14 </div>
15 
16 <div :style="composer.spacerStyle" />
17 </div>
18 
19 <form><!-- ... --></form>
20 </div>
21</template>

Inside a layout that renders a header, such as a starter kit's app layout, size the column to fill the space below the header instead of the full viewport.

By default, Chat anchors each new prompt 24 pixels below the top of the scrollable container. Change that offset with scroll-padding-top on the scrollable element. Because Chat reads the property for each new prompt, the offset can respond to breakpoints:

1<div ref={composer.container} className="overflow-y-auto scroll-pt-6 md:scroll-pt-12">
1<div ref={composer.container} className="overflow-y-auto scroll-pt-6 md:scroll-pt-12">
1<div :ref="composer.container" class="overflow-y-auto scroll-pt-6 md:scroll-pt-12">
1<div :ref="composer.container" class="overflow-y-auto scroll-pt-6 md:scroll-pt-12">

You may also pass a pixel number to the anchorOffset prop on Chat, which overrides the CSS property:

1<Chat chat={chat} anchorOffset={48}>
1<Chat chat={chat} anchorOffset={48}>
1<Chat :chat :anchor-offset="48">
1<Chat :chat :anchor-offset="48">

Whether you use scroll-padding-top or anchorOffset, leave at least that much gap between messages so the previous message stays out of view. The gap-6 utility above matches the default 24-pixel offset.

To disable prompt anchoring altogether, such as in a compact sidebar chat, pass false to the anchorPrompts prop on Chat.

Running Web Turns

The web connection is configured in config/converse.php:

1'web' => [
2 'driver' => 'web',
3 'middleware' => ['web'],
4 'guard' => env('CONVERSE_WEB_GUARD'),
5 'guests' => env('CONVERSE_WEB_GUESTS', false),
6 'transport' => env('CONVERSE_WEB_TRANSPORT', 'stream'),
7],
1'web' => [
2 'driver' => 'web',
3 'middleware' => ['web'],
4 'guard' => env('CONVERSE_WEB_GUARD'),
5 'guests' => env('CONVERSE_WEB_GUESTS', false),
6 'transport' => env('CONVERSE_WEB_TRANSPORT', 'stream'),
7],

By default, Converse dispatches each web turn to your queue, so a queue worker must be running. Each turn can run for up to CONVERSE_TURN_TIMEOUT seconds, unless you override it per connection with run_timeout.

Your queue connection's retry_after value must be greater than this timeout. Otherwise, Converse throws an exception when a user sends a message.

When your application uses the sync queue driver, Converse runs the turn after sending the HTTP response, so no queue worker is required. That doesn't work under php artisan serve, because the built-in PHP server can't finish a response early. Locally, use Laravel Herd instead. The turn timeout isn't enforced for turns running after the response.

Streaming and Polling

By default, the browser reads each turn's events over a server-sent event stream, holding a PHP worker open while the turn runs. To avoid tying up PHP workers during long turns, switch to polling with CONVERSE_WEB_TRANSPORT:

1CONVERSE_WEB_TRANSPORT=poll
1CONVERSE_WEB_TRANSPORT=poll

With polling, the browser checks for new events every 2 seconds, or every poll_interval seconds if configured on the connection, so answers arrive in short chunks instead of token by token. You can also set the transport for a single bot in routes/bot.php with poll or stream, passing an optional interval in seconds:

1use App\Ai\Agents\Assistant;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::agent('assistant', Assistant::class)
5 ->connection('web')
6 ->poll(5);
1use App\Ai\Agents\Assistant;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::agent('assistant', Assistant::class)
5 ->connection('web')
6 ->poll(5);

Converse limits each user to following a thread's stream 10 times per minute so one visitor can't tie up workers by repeatedly reopening streams. Polling and catch-up requests aren't rate-limited. To adjust this limit, define the converse-stream rate limiter in the boot method of AppServiceProvider:

1use Illuminate\Cache\RateLimiting\Limit;
2use Illuminate\Http\Request;
3use Illuminate\Support\Facades\RateLimiter;
4 
5RateLimiter::for('converse-stream', function (Request $request) {
6 return $request->boolean('follow', true)
7 ? Limit::perMinute(5)->by(($request->user()?->id ?: $request->ip()).'|'.$request->route('thread'))
8 : Limit::none();
9});
1use Illuminate\Cache\RateLimiting\Limit;
2use Illuminate\Http\Request;
3use Illuminate\Support\Facades\RateLimiter;
4 
5RateLimiter::for('converse-stream', function (Request $request) {
6 return $request->boolean('follow', true)
7 ? Limit::perMinute(5)->by(($request->user()?->id ?: $request->ip()).'|'.$request->route('thread'))
8 : Limit::none();
9});

Your limiter runs on every stream request, so return Limit::none() for catch-up requests where follow is false.

Limiting Turns

Because every turn can call your AI provider, Converse limits each user to 10 turns per minute per bot across all of their threads. Because a guest could start a new session to reset their per-session counter, Converse also caps all guests sharing an IP address at 30 turns per minute per bot. Rejected requests, such as duplicates or messages sent while a thread is locked, don't count against this limit. To customize the limit, define the converse-send rate limiter in the boot method of AppServiceProvider:

1use Illuminate\Cache\RateLimiting\Limit;
2use Illuminate\Http\Request;
3use Illuminate\Support\Facades\RateLimiter;
4 
5RateLimiter::for('converse-send', function (Request $request) {
6 return Limit::perMinute(30)->by(($request->user()?->id ?: $request->ip()).'|'.$request->route('bot'));
7});
1use Illuminate\Cache\RateLimiting\Limit;
2use Illuminate\Http\Request;
3use Illuminate\Support\Facades\RateLimiter;
4 
5RateLimiter::for('converse-send', function (Request $request) {
6 return Limit::perMinute(30)->by(($request->user()?->id ?: $request->ip()).'|'.$request->route('bot'));
7});

Keying the limit by user and bot gives each bot a separate quota. If your web connection uses a custom guard, read the user from that guard, such as $request->user('admin'). Return Limit::none() to disable turn rate limiting. Because Converse checks the limit before a turn produces a response, converse-send doesn't support after limits.

You may also return multiple limits together. For example, combine a per-minute limit to stop bursts with a daily limit to cap per-user AI spend:

1RateLimiter::for('converse-send', function (Request $request) {
2 $key = ($request->user()?->id ?: $request->ip()).'|'.$request->route('bot');
3 
4 return [
5 Limit::perMinute(10)->by($key),
6 Limit::perDay(200)->by($key),
7 ];
8});
1RateLimiter::for('converse-send', function (Request $request) {
2 $key = ($request->user()?->id ?: $request->ip()).'|'.$request->route('bot');
3 
4 return [
5 Limit::perMinute(10)->by($key),
6 Limit::perDay(200)->by($key),
7 ];
8});

When a user exceeds the limit, Converse responds with 429. The chat sets errorCode to rate_limited and populates error with how many seconds to wait. Chat automatically re-queues that message along with any messages sent while waiting, then sends them once the cooldown ends. waitingUntil holds the end timestamp in epoch milliseconds, and waitingSeconds counts down each second so you can display a live countdown:

1{waitingSeconds !== null && <p>Sending again in {waitingSeconds}s.</p>}
1{waitingSeconds !== null && <p>Sending again in {waitingSeconds}s.</p>}
1<p v-if="waitingSeconds !== null">Sending again in {{ waitingSeconds }}s.</p>
1<p v-if="waitingSeconds !== null">Sending again in {{ waitingSeconds }}s.</p>

Converse also caps each user at 3 concurrent running turns per bot across all of their threads, responding with 429 and the concurrent_turn_limit error code beyond that cap. Change the cap with concurrent_turns on your web connection in config/converse.php:

1'web' => [
2 'driver' => 'web',
3 // ...
4 'concurrent_turns' => 5,
5],
1'web' => [
2 'driver' => 'web',
3 // ...
4 'concurrent_turns' => 5,
5],

Set concurrent_turns to 0 to allow unlimited concurrent turns. Don't add Laravel's throttle middleware to the web connection's middleware array, because it would also throttle stream, cancellation, and file download requests.

Paginating Messages

In an Inertia application, Converse::chat loads the newest 50 messages as an Inertia scroll prop. Change the page size with perPage:

1'chat' => Converse::chat('assistant')->perPage(20),
1'chat' => Converse::chat('assistant')->perPage(20),

To load older messages as the user scrolls up, spread infiniteScrollProps onto Inertia's InfiniteScroll component, wrapping only the messages inside it:

1import { InfiniteScroll } from "@inertiajs/react";
2 
3<Chat chat={chat}>
4 {({ messages, infiniteScrollProps }) => (
5 <InfiniteScroll {...infiniteScrollProps!}>
6 {messages.map((message) => (
7 <article key={message.key}>{message.content}</article>
8 ))}
9 </InfiniteScroll>
10 )}
11</Chat>
1import { InfiniteScroll } from "@inertiajs/react";
2 
3<Chat chat={chat}>
4 {({ messages, infiniteScrollProps }) => (
5 <InfiniteScroll {...infiniteScrollProps!}>
6 {messages.map((message) => (
7 <article key={message.key}>{message.content}</article>
8 ))}
9 </InfiniteScroll>
10 )}
11</Chat>
1<script setup lang="ts">
2import { InfiniteScroll } from "@inertiajs/vue3";
3</script>
4 
5<template>
6 <Chat :chat v-slot="{ messages, infiniteScrollProps }">
7 <InfiniteScroll v-bind="infiniteScrollProps!">
8 <article v-for="message in messages" :key="message.key">
9 {{ message.content }}
10 </article>
11 </InfiniteScroll>
12 </Chat>
13</template>
1<script setup lang="ts">
2import { InfiniteScroll } from "@inertiajs/vue3";
3</script>
4 
5<template>
6 <Chat :chat v-slot="{ messages, infiniteScrollProps }">
7 <InfiniteScroll v-bind="infiniteScrollProps!">
8 <article v-for="message in messages" :key="message.key">
9 {{ message.content }}
10 </article>
11 </InfiniteScroll>
12 </Chat>
13</template>

Outside Inertia, infiniteScrollProps is null and the chat props include only the newest page of messages. Because the ChatProps object returned by Converse::chat implements Arrayable and Jsonable, you can also pass it to a Blade view or return it as JSON from a route.

Starting New Threads

Pass new: true to Converse::chat to start a fresh thread instead of resuming the user's latest one. To build a "New conversation" button, add a POST route that flashes new_conversation to the session and redirects back to the chat, then forward that session flag to Converse::chat:

1use Illuminate\Http\Request;
2use Illuminate\Support\Facades\Route;
3use Inertia\Inertia;
4use Laravel\Converse\Facades\Converse;
5 
6Route::get('/chat', function (Request $request) {
7 return Inertia::render('Chat', [
8 'chat' => Converse::chat('assistant', new: $request->session()->has('new_conversation')),
9 ]);
10})->middleware('auth')->name('chat');
11 
12Route::post('/chat/new', function () {
13 return to_route('chat')->with('new_conversation', true);
14})->middleware('auth')->name('chat.new');
1use Illuminate\Http\Request;
2use Illuminate\Support\Facades\Route;
3use Inertia\Inertia;
4use Laravel\Converse\Facades\Converse;
5 
6Route::get('/chat', function (Request $request) {
7 return Inertia::render('Chat', [
8 'chat' => Converse::chat('assistant', new: $request->session()->has('new_conversation')),
9 ]);
10})->middleware('auth')->name('chat');
11 
12Route::post('/chat/new', function () {
13 return to_route('chat')->with('new_conversation', true);
14})->middleware('auth')->name('chat.new');

Because the flashed value lasts for one request, the redirect opens a single new thread. Once the user sends a message in it, reloading the page resumes that new thread.

On Inertia pages, wrap the button in Inertia's Form component and reset chat.messages on submission. Otherwise, InfiniteScroll retains its scroll state across same-page visits and shows older messages from the previous thread:

1import { Form } from "@inertiajs/react";
2 
3<Form action="/chat/new" method="post" options={{ reset: ["chat.messages"] }}>
4 <button type="submit">New conversation</button>
5</Form>
1import { Form } from "@inertiajs/react";
2 
3<Form action="/chat/new" method="post" options={{ reset: ["chat.messages"] }}>
4 <button type="submit">New conversation</button>
5</Form>
1<script setup lang="ts">
2import { Form } from "@inertiajs/vue3";
3</script>
4 
5<template>
6 <Form action="/chat/new" method="post" :options="{ reset: ['chat.messages'] }">
7 <button type="submit">New conversation</button>
8 </Form>
9</template>
1<script setup lang="ts">
2import { Form } from "@inertiajs/vue3";
3</script>
4 
5<template>
6 <Form action="/chat/new" method="post" :options="{ reset: ['chat.messages'] }">
7 <button type="submit">New conversation</button>
8 </Form>
9</template>

Sending Messages From the Browser

Besides using composer, you can send a message programmatically with the chat's send function. By default, messages sent while a turn is running wait in the browser until that turn finishes. queued exposes those pending messages, and reloading the page discards them because they live only in browser memory.

Control how mid-turn messages behave with the queue prop on Chat:

  • queue: Hold the message until the current turn finishes. This is the default.
  • drop: Discard the message.
  • interrupt: Stop the current turn and send the new message.

For example, to interrupt an in-progress reply whenever the user sends a new message:

1<Chat chat={chat} queue="interrupt">
1<Chat chat={chat} queue="interrupt">
1<Chat :chat queue="interrupt">
1<Chat :chat queue="interrupt">

send resolves to false when a message is dropped. Interrupted turns stop at the next streamed event, though your AI provider still bills for tokens already generated.

To let users stop a reply manually, call cancel. Any partial answer already streamed stays visible on screen.

A web chat reads updates from the server only while a turn is running, so messages sent from another browser tab or device normally appear on the next send or reload. To pull updates sooner, call sync through a ref on Chat, such as when a broadcast event arrives:

1import { Chat, type ChatPayload, type ChatRef } from "@laravel/converse-react";
2import { useRef } from "react";
3 
4export default function ChatPage({ chat }: { chat: ChatPayload }) {
5 const conversation = useRef<ChatRef>(null);
6 
7 function onThreadChanged() {
8 conversation.current?.sync();
9 }
10 
11 return <Chat chat={chat} ref={conversation}>{/* ... */}</Chat>;
12}
1import { Chat, type ChatPayload, type ChatRef } from "@laravel/converse-react";
2import { useRef } from "react";
3 
4export default function ChatPage({ chat }: { chat: ChatPayload }) {
5 const conversation = useRef<ChatRef>(null);
6 
7 function onThreadChanged() {
8 conversation.current?.sync();
9 }
10 
11 return <Chat chat={chat} ref={conversation}>{/* ... */}</Chat>;
12}
1<script setup lang="ts">
2import { Chat, type ChatPayload } from "@laravel/converse-vue";
3import { useTemplateRef } from "vue";
4 
5defineProps<{ chat: ChatPayload }>();
6 
7const conversation = useTemplateRef("conversation");
8 
9function onThreadChanged() {
10 conversation.value?.sync();
11}
12</script>
13 
14<template>
15 <Chat ref="conversation" :chat>
16 <!-- ... -->
17 </Chat>
18</template>
1<script setup lang="ts">
2import { Chat, type ChatPayload } from "@laravel/converse-vue";
3import { useTemplateRef } from "vue";
4 
5defineProps<{ chat: ChatPayload }>();
6 
7const conversation = useTemplateRef("conversation");
8 
9function onThreadChanged() {
10 conversation.value?.sync();
11}
12</script>
13 
14<template>
15 <Chat ref="conversation" :chat>
16 <!-- ... -->
17 </Chat>
18</template>

Converse dispatches WebTurnAccepted and WebTurnFinished as turns start and complete. Both events expose thread and owner, so you can broadcast a lightweight ping on the owner's private channel without sending any payload, since sync fetches the new events directly from the thread stream:

1use App\Models\User;
2use Illuminate\Support\Facades\Broadcast;
3use Illuminate\Support\Facades\Event;
4use Laravel\Converse\Events\WebTurnAccepted;
5use Laravel\Converse\Events\WebTurnFinished;
6 
7Event::listen(function (WebTurnAccepted|WebTurnFinished $event) {
8 $owner = $event->owner();
9 
10 if ($owner instanceof User) {
11 Broadcast::private("App.Models.User.{$owner->id}")->as('ChatUpdated')->send();
12 }
13});
1use App\Models\User;
2use Illuminate\Support\Facades\Broadcast;
3use Illuminate\Support\Facades\Event;
4use Laravel\Converse\Events\WebTurnAccepted;
5use Laravel\Converse\Events\WebTurnFinished;
6 
7Event::listen(function (WebTurnAccepted|WebTurnFinished $event) {
8 $owner = $event->owner();
9 
10 if ($owner instanceof User) {
11 Broadcast::private("App.Models.User.{$owner->id}")->as('ChatUpdated')->send();
12 }
13});

Listen for .ChatUpdated with Laravel Echo on your page and call onThreadChanged. Because $event->owner() returns null for guests, this example broadcasts only to signed-in users.

On WebTurnAccepted, isFirstTurn() returns true for the first message in a brand-new thread, which is useful when you want to refresh a sidebar list of conversations.

Sending Files From the Browser

The composer can attach files alongside a message draft. Call composer.addFiles when the user picks or pastes files, composer.removeFile to detach one, and read composer.files to render the pending attachments. Submitting the composer sends the attached files with the draft:

1<form
2 onSubmit={(event) => {
3 event.preventDefault();
4 composer.submit();
5 }}
6>
7 <input
8 type="file"
9 multiple
10 accept={composer.accept}
11 onChange={(event) => {
12 composer.addFiles(event.target.files ?? []);
13 event.target.value = "";
14 }}
15 />
16 
17 {composer.files.map((file, index) => (
18 <button
19 key={`${file.name}-${index}`}
20 type="button"
21 onClick={() => composer.removeFile(file)}
22 >
23 Remove {file.name}
24 </button>
25 ))}
26 
27 <input
28 value={composer.draft}
29 onChange={(event) => composer.setDraft(event.target.value)}
30 />
31 
32 <button type="submit">Send</button>
33</form>
1<form
2 onSubmit={(event) => {
3 event.preventDefault();
4 composer.submit();
5 }}
6>
7 <input
8 type="file"
9 multiple
10 accept={composer.accept}
11 onChange={(event) => {
12 composer.addFiles(event.target.files ?? []);
13 event.target.value = "";
14 }}
15 />
16 
17 {composer.files.map((file, index) => (
18 <button
19 key={`${file.name}-${index}`}
20 type="button"
21 onClick={() => composer.removeFile(file)}
22 >
23 Remove {file.name}
24 </button>
25 ))}
26 
27 <input
28 value={composer.draft}
29 onChange={(event) => composer.setDraft(event.target.value)}
30 />
31 
32 <button type="submit">Send</button>
33</form>
1<script setup lang="ts">
2function pickedFiles(event: Event): File[] {
3 const input = event.target as HTMLInputElement;
4 const files = Array.from(input.files ?? []);
5 
6 input.value = "";
7 
8 return files;
9}
10</script>
11 
12<template>
13 <form @submit.prevent="composer.submit()">
14 <input
15 type="file"
16 multiple
17 :accept="composer.accept"
18 @change="composer.addFiles(pickedFiles($event))"
19 />
20 
21 <button
22 v-for="(file, index) in composer.files"
23 :key="`${file.name}-${index}`"
24 type="button"
25 @click="composer.removeFile(file)"
26 >
27 Remove {{ file.name }}
28 </button>
29 
30 <input v-model="composer.draft" />
31 
32 <button type="submit">Send</button>
33 </form>
34</template>
1<script setup lang="ts">
2function pickedFiles(event: Event): File[] {
3 const input = event.target as HTMLInputElement;
4 const files = Array.from(input.files ?? []);
5 
6 input.value = "";
7 
8 return files;
9}
10</script>
11 
12<template>
13 <form @submit.prevent="composer.submit()">
14 <input
15 type="file"
16 multiple
17 :accept="composer.accept"
18 @change="composer.addFiles(pickedFiles($event))"
19 />
20 
21 <button
22 v-for="(file, index) in composer.files"
23 :key="`${file.name}-${index}`"
24 type="button"
25 @click="composer.removeFile(file)"
26 >
27 Remove {{ file.name }}
28 </button>
29 
30 <input v-model="composer.draft" />
31 
32 <button type="submit">Send</button>
33 </form>
34</template>

Clearing the file input after each selection lets the user pick the same file again.

composer.accept provides the allowed MIME types for the file input's accept attribute. The composer also validates files against your attachment limits as they're added so invalid files are caught before upload, listing rejected files and their reasons in composer.rejectedFiles:

1{composer.rejectedFiles.map(({ file, reason }, index) => (
2 <p key={`${file.name}-${index}`}>
3 {file.name}: {reason}
4 </p>
5))}
1{composer.rejectedFiles.map(({ file, reason }, index) => (
2 <p key={`${file.name}-${index}`}>
3 {file.name}: {reason}
4 </p>
5))}
1<p
2 v-for="({ file, reason }, index) in composer.rejectedFiles"
3 :key="`${file.name}-${index}`"
4>
5 {{ file.name }}: {{ reason }}
6</p>
1<p
2 v-for="({ file, reason }, index) in composer.rejectedFiles"
3 :key="`${file.name}-${index}`"
4>
5 {{ file.name }}: {{ reason }}
6</p>

Because browsers infer MIME types from filenames alone, the composer lets text files and files without a reported MIME type pass to the server, where Converse inspects the file contents.

You may also pass files directly to send, and a message may contain files with no text:

1send("Here is the receipt.", { files: [file] });
1send("Here is the receipt.", { files: [file] });

Attached files appear immediately on the user's message as file parts. Their url property holds a browser object URL for newly sent files and a signed download URL for stored files. Signed URLs are accessible only to the thread's owner and expire after one day by default, or after url_ttl seconds in the attachments array of config/converse.php. Browsers display images, audio, and video inline and download other file types.

Converse saves browser uploads to your attachment disk alongside attachments from other platforms. Handlers read them via $message->attachments(), and agents receive them as prompt attachments. Because your queue worker writes each file while your web server serves it back to the browser, configure object storage such as S3 when they run on separate servers.

The server enforces your attachment limits as well, rejecting invalid uploads with a 422 response. validationErrors lists per-file errors under files.0, files.1, and so on, and whole-upload errors such as exceeding the file count under files. Because only regular messages may carry files, attaching files to an approval response or slash command fails validation with a 422 response too.

The browser submits messages with files as multipart requests. PHP drops files larger than upload_max_filesize, while PHP's post_max_size and your web server's body limit, such as Nginx's client_max_body_size, reject oversized requests with 413. Make sure those server limits are at least as large as the maximum file and message size you allow in config/converse.php.

Approving Tools in the Browser

When an agent pauses for tool approval, its message status becomes awaiting_approval and message.approvals lists every waiting tool call. Render the pending approvals on that message and wire Approve and Reject buttons to approve and reject:

1<Chat chat={chat}>
2 {({ messages, can, approve, reject, streaming }) =>
3 messages.map((message) => (
4 <article key={message.key}>
5 <p>{message.content}</p>
6 
7 {can.approve &&
8 message.approvals.map((approval) => (
9 <div key={approval.id}>
10 <p>{approval.tool}</p>
11 {approval.reason && <p>{approval.reason}</p>}
12 
13 <button disabled={streaming} onClick={() => approve(approval.id)}>
14 Approve
15 </button>
16 
17 <button disabled={streaming} onClick={() => reject(approval.id)}>
18 Reject
19 </button>
20 </div>
21 ))}
22 </article>
23 ))
24 }
25</Chat>
1<Chat chat={chat}>
2 {({ messages, can, approve, reject, streaming }) =>
3 messages.map((message) => (
4 <article key={message.key}>
5 <p>{message.content}</p>
6 
7 {can.approve &&
8 message.approvals.map((approval) => (
9 <div key={approval.id}>
10 <p>{approval.tool}</p>
11 {approval.reason && <p>{approval.reason}</p>}
12 
13 <button disabled={streaming} onClick={() => approve(approval.id)}>
14 Approve
15 </button>
16 
17 <button disabled={streaming} onClick={() => reject(approval.id)}>
18 Reject
19 </button>
20 </div>
21 ))}
22 </article>
23 ))
24 }
25</Chat>
1<Chat :chat v-slot="{ messages, can, approve, reject, streaming }">
2 <article v-for="message in messages" :key="message.key">
3 <p>{{ message.content }}</p>
4 
5 <template v-if="can.approve">
6 <div v-for="approval in message.approvals" :key="approval.id">
7 <p>{{ approval.tool }}</p>
8 <p v-if="approval.reason">{{ approval.reason }}</p>
9 
10 <button :disabled="streaming" @click="approve(approval.id)">Approve</button>
11 <button :disabled="streaming" @click="reject(approval.id)">Reject</button>
12 </div>
13 </template>
14 </article>
15</Chat>
1<Chat :chat v-slot="{ messages, can, approve, reject, streaming }">
2 <article v-for="message in messages" :key="message.key">
3 <p>{{ message.content }}</p>
4 
5 <template v-if="can.approve">
6 <div v-for="approval in message.approvals" :key="approval.id">
7 <p>{{ approval.tool }}</p>
8 <p v-if="approval.reason">{{ approval.reason }}</p>
9 
10 <button :disabled="streaming" @click="approve(approval.id)">Approve</button>
11 <button :disabled="streaming" @click="reject(approval.id)">Reject</button>
12 </div>
13 </template>
14 </article>
15</Chat>

Because handler bots never pause for tool approval, can.approve is false for handler bots.

The chat's pendingApprovals value also exposes the approvals on the newest awaiting message, so you can render an approval prompt outside the transcript, such as above the message form.

When a turn pauses on multiple tool calls at once, approve and reject collect each decision in decisions keyed by approval ID and send all decisions together once every tool call has an answer. Use decisions to show which items the user has already answered:

1{decisions[approval.id] && <p>Waiting for the other approvals...</p>}
1{decisions[approval.id] && <p>Waiting for the other approvals...</p>}
1<p v-if="decisions[approval.id]">Waiting for the other approvals...</p>
1<p v-if="decisions[approval.id]">Waiting for the other approvals...</p>

To submit every decision in a single call, pass a map of approval IDs to respond:

1await respond({
2 "call-1": { action: "approve" },
3 "call-2": { action: "reject" },
4});
1await respond({
2 "call-1": { action: "approve" },
3 "call-2": { action: "reject" },
4});

Converse dispatches WebApprovalRequested when a web turn pauses for approval and WebApprovalResolved when the browser submits its decisions. Both events expose thread and approvals, and WebApprovalResolved provides decisionFor to inspect the decision for a specific approval.

Reacting to the Chat

The onToolResult callback on Chat fires as soon as a tool call returns its result. When an agent's tool modifies application data, use onToolResult to refresh the affected Inertia props:

1<Chat chat={chat} onToolResult={() => router.reload({ only: ["todos"] })}>
1<Chat chat={chat} onToolResult={() => router.reload({ only: ["todos"] })}>
1<Chat :chat :on-tool-result="() => router.reload({ only: ['todos'] })">
1<Chat :chat :on-tool-result="() => router.reload({ only: ['todos'] })">

The callback receives the tool call part with toolName, input, output, errorText, and state, which is complete, error, or denied. For tools that require approval, onToolResult runs after the user resolves the approval.

The onFinish callback receives the bot's message at the end of each turn. Because pausing for approval also ends the current turn, message.status may be awaiting_approval:

1<Chat chat={chat} onFinish={(message) => console.log(message.content)}>
1<Chat chat={chat} onFinish={(message) => console.log(message.content)}>
1<Chat :chat :on-finish="(message) => console.log(message.content)">
1<Chat :chat :on-finish="(message) => console.log(message.content)">

Both callbacks also fire for turns sent from another tab or device once the chat reads them, such as after calling sync. If a tab reconnects after those events were pruned, the chat catches up from the stored transcript without invoking either callback.

For lower-level integrations, onEvent receives every raw AG-UI event as it streams in.

Handling Errors

When a request fails, the user's message stays on screen and error holds the error message. Call retry to resend the failed request or clearError to dismiss it. Because handler bots don't replay failed turns, check can.retry before rendering a retry button:

1<Chat chat={chat}>
2 {({ messages, composer, error, can, retry, clearError }) => (
3 <>
4 {/* ... */}
5 
6 {error && (
7 <div>
8 <p>{error}</p>
9 
10 {can.retry && <button onClick={() => retry()}>Retry</button>}
11 
12 <button onClick={() => clearError()}>Dismiss</button>
13 </div>
14 )}
15 </>
16 )}
17</Chat>
1<Chat chat={chat}>
2 {({ messages, composer, error, can, retry, clearError }) => (
3 <>
4 {/* ... */}
5 
6 {error && (
7 <div>
8 <p>{error}</p>
9 
10 {can.retry && <button onClick={() => retry()}>Retry</button>}
11 
12 <button onClick={() => clearError()}>Dismiss</button>
13 </div>
14 )}
15 </>
16 )}
17</Chat>
1<Chat :chat v-slot="{ messages, composer, error, can, retry, clearError }">
2 <!-- ... -->
3 
4 <div v-if="error">
5 <p>{{ error }}</p>
6 
7 <button v-if="can.retry" @click="retry()">Retry</button>
8 
9 <button @click="clearError()">Dismiss</button>
10 </div>
11</Chat>
1<Chat :chat v-slot="{ messages, composer, error, can, retry, clearError }">
2 <!-- ... -->
3 
4 <div v-if="error">
5 <p>{{ error }}</p>
6 
7 <button v-if="can.retry" @click="retry()">Retry</button>
8 
9 <button @click="clearError()">Dismiss</button>
10 </div>
11</Chat>

Alongside error, errorCode provides a machine-readable code such as approval_mismatch when a user answers an approval that's no longer pending. When the server rejects a request with 422, such as an upload exceeding your attachment limits, validationErrors holds the errors keyed by field name. Calling clearError resets all three values.

To run side effects whenever a request fails, pass an onError callback to Chat:

1<Chat chat={chat} onError={(error) => console.error(error)}>
1<Chat chat={chat} onError={(error) => console.error(error)}>
1<Chat :chat :on-error="(error) => console.error(error)">
1<Chat :chat :on-error="(error) => console.error(error)">

Identifying Web Users

By default, Converse associates each web chat with the user signed into your application's default authentication guard. To use another guard, such as an admin panel guard, set guard on the web connection in config/converse.php and protect your chat page route with matching middleware such as auth:admin:

1'guard' => 'admin',
1'guard' => 'admin',

If a web chat should be scoped to something other than the User model, such as a TeamMember, register a closure with Converse::resolveUsersUsing in the boot method of AppServiceProvider. The closure receives the incoming Request and the web connection's name:

1use App\Models\TeamMember;
2use Illuminate\Http\Request;
3use Laravel\Converse\Facades\Converse;
4 
5/**
6 * Bootstrap any application services.
7 */
8public function boot(): void
9{
10 Converse::resolveUsersUsing(function (Request $request, string $connection): ?TeamMember {
11 return $request->user()?->currentTeamMember;
12 });
13}
1use App\Models\TeamMember;
2use Illuminate\Http\Request;
3use Laravel\Converse\Facades\Converse;
4 
5/**
6 * Bootstrap any application services.
7 */
8public function boot(): void
9{
10 Converse::resolveUsersUsing(function (Request $request, string $connection): ?TeamMember {
11 return $request->user()?->currentTeamMember;
12 });
13}

Your resolver must return an Eloquent model or an object with an id property, and it should return only a participant the current request is authorized to chat as. Once a resolver is registered, Converse ignores the connection's guard option, so read the user from whichever guard you need inside the closure, such as $request->user('admin').

Your resolver also runs during terminal chat with --user. In that case, Converse passes the terminal connection name and a request whose user method returns the user loaded from that guard.

On the web connection, every bot event's user method returns a Laravel\Converse\User built from the resolved model's key and name attribute. To customize those fields, define toConverseUser on your User model or on the model returned by your resolver:

1use Laravel\Converse\User as ConverseUser;
2 
3/**
4 * Get the Converse representation of the user.
5 */
6public function toConverseUser(): ConverseUser
7{
8 return new ConverseUser(
9 id: (string) $this->getKey(),
10 name: $this->name,
11 username: $this->email,
12 );
13}
1use Laravel\Converse\User as ConverseUser;
2 
3/**
4 * Get the Converse representation of the user.
5 */
6public function toConverseUser(): ConverseUser
7{
8 return new ConverseUser(
9 id: (string) $this->getKey(),
10 name: $this->name,
11 username: $this->email,
12 );
13}

Allowing Guests

By default, Converse blocks web chat requests from visitors who aren't signed in. To allow guests on the web connection, set guests to true in config/converse.php or set CONVERSE_WEB_GUESTS=true in .env:

1'guests' => true,
1'guests' => true,

Because guest chats run your agent for any visitor, Converse automatically applies the converse-send rate limiter at 10 turns per minute per session and 30 turns per minute per IP address. You can tighten those limits in converse-send or lower concurrent_turns on the connection.

Remove auth and verified middleware from your chat page route so guests can load the page. Converse scopes each guest's threads to their session, and every bot event's user method returns an anonymous user.

To allow guests for a single bot without opening the whole connection, call allowGuests in routes/bot.php. This takes precedence over the connection's guests option:

1use App\Ai\Agents\SalesAgent;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::agent('sales', SalesAgent::class)
5 ->connection('web')
6 ->allowGuests();
1use App\Ai\Agents\SalesAgent;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::agent('sales', SalesAgent::class)
5 ->connection('web')
6 ->allowGuests();

Pass false to block guests on a specific bot even when the connection allows them:

1use App\Ai\Agents\BillingAgent;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::agent('billing', BillingAgent::class)
5 ->connection('web')
6 ->allowGuests(false);
1use App\Ai\Agents\BillingAgent;
2use Laravel\Converse\Facades\Converse;
3 
4Converse::agent('billing', BillingAgent::class)
5 ->connection('web')
6 ->allowGuests(false);

Because each web connection registers separate routes and options, you can also define a dedicated guest connection with tighter limits, such as fewer concurrent turns, while signed-in users stay on web:

1'guest' => [
2 'driver' => 'web',
3 'middleware' => ['web'],
4 'guests' => true,
5 'concurrent_turns' => 1,
6],
1'guest' => [
2 'driver' => 'web',
3 'middleware' => ['web'],
4 'guests' => true,
5 'concurrent_turns' => 1,
6],

Register your bot on both connections in routes/bot.php, and pass connection: 'guest' to Converse::chat on public pages:

1Converse::agent('sales', SalesAgent::class)
2 ->connection('web', 'guest');
1Converse::agent('sales', SalesAgent::class)
2 ->connection('web', 'guest');
1'chat' => Converse::chat('sales', connection: 'guest'),
1'chat' => Converse::chat('sales', connection: 'guest'),

Building Your Own Chat

The Chat component is the recommended way to render web chat. Under the hood, it wraps the useChat hook in React and composable in Vue, which expose the same chat state and actions without rendering markup. Call useChat directly when you want full control over your component structure, wiring up the composer and transcript scrolling yourself:

1import { useChat, type ChatPayload } from "@laravel/converse-react";
2 
3export default function ChatPage({ chat }: { chat: ChatPayload }) {
4 const { messages, send, status } = useChat(chat);
5 
6 // ...
7}
1import { useChat, type ChatPayload } from "@laravel/converse-react";
2 
3export default function ChatPage({ chat }: { chat: ChatPayload }) {
4 const { messages, send, status } = useChat(chat);
5 
6 // ...
7}
1<script setup lang="ts">
2import { useChat, type ChatPayload } from "@laravel/converse-vue";
3 
4const props = defineProps<{ chat: ChatPayload }>();
5 
6const { messages, send, status } = useChat(() => props.chat);
7</script>
1<script setup lang="ts">
2import { useChat, type ChatPayload } from "@laravel/converse-vue";
3 
4const props = defineProps<{ chat: ChatPayload }>();
5 
6const { messages, send, status } = useChat(() => props.chat);
7</script>

In Vue, pass the chat payload as a getter so partial Inertia reloads and older message pages update the transcript reactively. To explore every option useChat accepts, check out the React package README or Vue package README.

Custom Drivers

To integrate another chat platform, register a custom driver with Converse::extend in the boot method of AppServiceProvider:

1use App\Bots\Drivers\DiscordDriver;
2use Laravel\Converse\Facades\Converse;
3 
4/**
5 * Bootstrap any application services.
6 */
7public function boot(): void
8{
9 Converse::extend('discord', fn ($app, array $config) => new DiscordDriver($config));
10}
1use App\Bots\Drivers\DiscordDriver;
2use Laravel\Converse\Facades\Converse;
3 
4/**
5 * Bootstrap any application services.
6 */
7public function boot(): void
8{
9 Converse::extend('discord', fn ($app, array $config) => new DiscordDriver($config));
10}

Then configure a connection using that driver in config/converse.php:

1'connections' => [
2 'discord' => [
3 'driver' => 'discord',
4 'bot_token' => env('DISCORD_BOT_TOKEN'),
5 ],
6],
1'connections' => [
2 'discord' => [
3 'driver' => 'discord',
4 'bot_token' => env('DISCORD_BOT_TOKEN'),
5 ],
6],

Extend Laravel\Converse\Drivers\Driver and implement events, which turns an incoming webhook payload into bot events, and sendMessage. To accept webhooks, also implement ReceivesWebhooks and verify request authenticity in verify:

1<?php
2 
3namespace App\Bots\Drivers;
4 
5use Illuminate\Http\Request;
6use Laravel\Converse\Cards\Card;
7use Laravel\Converse\Contracts\Drivers\ReceivesWebhooks;
8use Laravel\Converse\Drivers\Driver;
9use Laravel\Converse\Markdown;
10use Laravel\Converse\SentMessage;
11use Laravel\Converse\Thread;
12 
13class DiscordDriver extends Driver implements ReceivesWebhooks
14{
15 /**
16 * Determine if the incoming webhook is authentic.
17 */
18 public function verify(Request $request): bool
19 {
20 // ...
21 }
22 
23 /**
24 * Convert the webhook payload into bot events.
25 */
26 public function events(array $payload): iterable
27 {
28 // ...
29 }
30 
31 /**
32 * Send a message to the given thread.
33 */
34 public function sendMessage(Thread $thread, Card|Markdown|string $content): SentMessage
35 {
36 // ...
37 }
38}
1<?php
2 
3namespace App\Bots\Drivers;
4 
5use Illuminate\Http\Request;
6use Laravel\Converse\Cards\Card;
7use Laravel\Converse\Contracts\Drivers\ReceivesWebhooks;
8use Laravel\Converse\Drivers\Driver;
9use Laravel\Converse\Markdown;
10use Laravel\Converse\SentMessage;
11use Laravel\Converse\Thread;
12 
13class DiscordDriver extends Driver implements ReceivesWebhooks
14{
15 /**
16 * Determine if the incoming webhook is authentic.
17 */
18 public function verify(Request $request): bool
19 {
20 // ...
21 }
22 
23 /**
24 * Convert the webhook payload into bot events.
25 */
26 public function events(array $payload): iterable
27 {
28 // ...
29 }
30 
31 /**
32 * Send a message to the given thread.
33 */
34 public function sendMessage(Thread $thread, Card|Markdown|string $content): SentMessage
35 {
36 // ...
37 }
38}

The driver's connection configuration is available on $this->config.

In events, yield one bot event per incoming message. Attach the platform's message ID with withId and event ID with withEventId so Converse can deduplicate repeated webhooks, and pass isSelf: true on User for messages sent by the bot itself so Converse ignores them:

1use DateTimeImmutable;
2use Laravel\Converse\BotEvents\Message;
3use Laravel\Converse\Thread;
4use Laravel\Converse\User;
5 
6/**
7 * Convert the webhook payload into bot events.
8 */
9public function events(array $payload): iterable
10{
11 $author = $payload['author'];
12 
13 yield Message::make(
14 new Thread($this->connection(), $payload['channel_id']),
15 $payload['content'],
16 new User($author['id'], name: $author['username'], isSelf: $author['id'] === $this->config['bot_id']),
17 new DateTimeImmutable($payload['timestamp']),
18 )->withId($payload['id'])->withEventId($payload['event_id']);
19}
1use DateTimeImmutable;
2use Laravel\Converse\BotEvents\Message;
3use Laravel\Converse\Thread;
4use Laravel\Converse\User;
5 
6/**
7 * Convert the webhook payload into bot events.
8 */
9public function events(array $payload): iterable
10{
11 $author = $payload['author'];
12 
13 yield Message::make(
14 new Thread($this->connection(), $payload['channel_id']),
15 $payload['content'],
16 new User($author['id'], name: $author['username'], isSelf: $author['id'] === $this->config['bot_id']),
17 new DateTimeImmutable($payload['timestamp']),
18 )->withId($payload['id'])->withEventId($payload['event_id']);
19}

Implement the corresponding interfaces in Laravel\Converse\Contracts\Drivers for every feature your platform supports. Each interface enables its matching capability, such as SupportsEditMessages enabling Capability::EditMessage. Two additional interfaces customize webhook and agent behavior:

  • SupportsCreateInlineResponses: Return an immediate HTTP response from createInlineResponse for webhooks that require one, such as a platform verification challenge.
  • SuppliesAgentHistory: Tell Converse that agents already receive their message history elsewhere, such as from stored conversations, so Converse doesn't register the ListMessages tool.

You may also implement ProvidesSetup so php artisan converse:setup can configure your platform interactively. Its setup method receives a Laravel\Converse\Setup helper and can use Laravel Prompts to collect credentials:

1use Laravel\Converse\Setup;
2 
3use function Laravel\Prompts\password;
4 
5/**
6 * Connect the platform to the bot.
7 */
8public function setup(Setup $setup): void
9{
10 $token = password('Bot token', required: true);
11 
12 $setup->writeEnvironment([
13 'bot_token' => $token,
14 'webhook_secret' => $setup->webhookSecret(),
15 ]);
16 
17 // Register $setup->webhookUrl() with the platform using $token...
18}
1use Laravel\Converse\Setup;
2 
3use function Laravel\Prompts\password;
4 
5/**
6 * Connect the platform to the bot.
7 */
8public function setup(Setup $setup): void
9{
10 $token = password('Bot token', required: true);
11 
12 $setup->writeEnvironment([
13 'bot_token' => $token,
14 'webhook_secret' => $setup->webhookSecret(),
15 ]);
16 
17 // Register $setup->webhookUrl() with the platform using $token...
18}

$setup->webhookUrl() prompts for your application's public URL and returns the bot's webhook URL. $setup->webhookSecret() returns the configured secret or generates a new random one. $setup->writeEnvironment() writes each changed value to .env using the connection and key name, such as DISCORD_BOT_TOKEN, and updates the runtime configuration array, though the current driver instance keeps its original $this->config.

Pruning Threads

Converse retains threads and web chat events for CONVERSE_STORAGE_RETENTION days, defaulting to 60. Any thread with no active subscription and no activity for that many days becomes eligible for pruning along with its messages and stored attachments. Converse doesn't prune the separate conversations stored by the AI SDK.

Both Thread and ThreadEvent are prunable Eloquent models. Because model:prune discovers models only under app/Models, pass Converse's models explicitly when scheduling pruning in routes/console.php. If your application doesn't use web chat, pass only Thread::class:

1use Illuminate\Support\Facades\Schedule;
2use Laravel\Converse\Models\Thread;
3use Laravel\Converse\Models\ThreadEvent;
4 
5Schedule::command('model:prune', [
6 '--model' => [ThreadEvent::class, Thread::class],
7])->daily();
1use Illuminate\Support\Facades\Schedule;
2use Laravel\Converse\Models\Thread;
3use Laravel\Converse\Models\ThreadEvent;
4 
5Schedule::command('model:prune', [
6 '--model' => [ThreadEvent::class, Thread::class],
7])->daily();

Testing

In your test suite, you don't want bots hitting real Slack or Telegram APIs. Call Converse::fake() to capture outgoing messages in memory, dispatch an incoming event with Converse::incoming(), and assert against the fake.

Because Converse persists incoming messages to your database and runs turns on your queue, use RefreshDatabase and the sync queue driver in your tests:

1use Laravel\Converse\BotEvents\Message;
2use Laravel\Converse\Facades\Converse;
3use Laravel\Converse\Thread;
4use Laravel\Converse\User;
5 
6test('the bot replies to a mention', function () {
7 $fake = Converse::fake();
8 
9 Converse::incoming('deploy', Message::make(
10 new Thread('slack', 'C0123456789'),
11 'Hello @deploy',
12 new User('U0000001', name: 'Jane'),
13 now()->toDateTimeImmutable(),
14 )->withMention());
15 
16 $fake->assertSent('Hello, Jane!');
17});
1use Laravel\Converse\BotEvents\Message;
2use Laravel\Converse\Facades\Converse;
3use Laravel\Converse\Thread;
4use Laravel\Converse\User;
5 
6test('the bot replies to a mention', function () {
7 $fake = Converse::fake();
8 
9 Converse::incoming('deploy', Message::make(
10 new Thread('slack', 'C0123456789'),
11 'Hello @deploy',
12 new User('U0000001', name: 'Jane'),
13 now()->toDateTimeImmutable(),
14 )->withMention());
15 
16 $fake->assertSent('Hello, Jane!');
17});
1use Laravel\Converse\BotEvents\Message;
2use Laravel\Converse\Facades\Converse;
3use Laravel\Converse\Thread;
4use Laravel\Converse\User;
5 
6public function test_the_bot_replies_to_a_mention(): void
7{
8 $fake = Converse::fake();
9 
10 Converse::incoming('deploy', Message::make(
11 new Thread('slack', 'C0123456789'),
12 'Hello @deploy',
13 new User('U0000001', name: 'Jane'),
14 now()->toDateTimeImmutable(),
15 )->withMention());
16 
17 $fake->assertSent('Hello, Jane!');
18}
1use Laravel\Converse\BotEvents\Message;
2use Laravel\Converse\Facades\Converse;
3use Laravel\Converse\Thread;
4use Laravel\Converse\User;
5 
6public function test_the_bot_replies_to_a_mention(): void
7{
8 $fake = Converse::fake();
9 
10 Converse::incoming('deploy', Message::make(
11 new Thread('slack', 'C0123456789'),
12 'Hello @deploy',
13 new User('U0000001', name: 'Jane'),
14 now()->toDateTimeImmutable(),
15 )->withMention());
16 
17 $fake->assertSent('Hello, Jane!');
18}

The bot must already be registered on the event's connection. String assertions match any recorded message containing the given text, cards match against their fallback text, attachments match against their caption or filename when there's no caption, and ephemeral messages are recorded as sent messages. The fake provides these assertions:

1use Laravel\Converse\Enums\Emoji;
2 
3// Assert a message was sent...
4$fake->assertSent('Hello, Jane!');
5$fake->assertSentCount(1);
6$fake->assertNothingSent();
7 
8// Assert a message was edited or deleted...
9$fake->assertEdited('approved');
10$fake->assertDeleted();
11 
12// Assert a reaction was added or removed...
13$fake->assertReactionAdded(Emoji::Eyes);
14$fake->assertReactionRemoved(Emoji::Eyes);
15 
16// Assert an attachment or a direct message was sent...
17$fake->assertAttachmentSent();
18$fake->assertDirectMessageSent('slack', 'U0000001');
19 
20// Assert a typing indicator status was shown...
21$fake->assertStatus('Searching the docs...');
22 
23// Assert a tool approval was requested or resolved...
24$fake->assertApprovalRequested();
25$fake->assertApprovalRequested('SendMessage');
26$fake->assertApprovalResolved(approved: true);
1use Laravel\Converse\Enums\Emoji;
2 
3// Assert a message was sent...
4$fake->assertSent('Hello, Jane!');
5$fake->assertSentCount(1);
6$fake->assertNothingSent();
7 
8// Assert a message was edited or deleted...
9$fake->assertEdited('approved');
10$fake->assertDeleted();
11 
12// Assert a reaction was added or removed...
13$fake->assertReactionAdded(Emoji::Eyes);
14$fake->assertReactionRemoved(Emoji::Eyes);
15 
16// Assert an attachment or a direct message was sent...
17$fake->assertAttachmentSent();
18$fake->assertDirectMessageSent('slack', 'U0000001');
19 
20// Assert a typing indicator status was shown...
21$fake->assertStatus('Searching the docs...');
22 
23// Assert a tool approval was requested or resolved...
24$fake->assertApprovalRequested();
25$fake->assertApprovalRequested('SendMessage');
26$fake->assertApprovalResolved(approved: true);

Most assertions also have negated counterparts, including assertNotSent, assertNotEdited, assertNotDeleted, assertReactionNotAdded, assertAttachmentNotSent, and assertNoApprovalRequested.

For finer assertions, pass a closure to assertSent, assertNotSent, assertEdited, assertNotEdited, assertAttachmentSent, assertAttachmentNotSent, or assertDirectMessageSent. The closure receives the message content, which may be a string, Markdown, or Card, along with the target Thread:

1use Laravel\Converse\Cards\Card;
2use Laravel\Converse\Thread;
3 
4$fake->assertSent(function (mixed $content, Thread $thread) {
5 return $content instanceof Card && $thread->channel()->id() === 'C0123456789';
6});
1use Laravel\Converse\Cards\Card;
2use Laravel\Converse\Thread;
3 
4$fake->assertSent(function (mixed $content, Thread $thread) {
5 return $content instanceof Card && $thread->channel()->id() === 'C0123456789';
6});

To test an agent bot without calling your AI provider, fake the agent before sending the event:

1use App\Ai\Agents\SupportAgent;
2use Laravel\Converse\BotEvents\Message;
3use Laravel\Converse\Facades\Converse;
4use Laravel\Converse\Thread;
5use Laravel\Converse\User;
6 
7SupportAgent::fake(['Hello, Jane!']);
8 
9$fake = Converse::fake();
10 
11Converse::incoming('support', Message::make(
12 new Thread('slack', 'C0123456789'),
13 'Hello @support',
14 new User('U0000001', name: 'Jane'),
15 now()->toDateTimeImmutable(),
16)->withMention());
17 
18$fake->assertSent('Hello, Jane!');
1use App\Ai\Agents\SupportAgent;
2use Laravel\Converse\BotEvents\Message;
3use Laravel\Converse\Facades\Converse;
4use Laravel\Converse\Thread;
5use Laravel\Converse\User;
6 
7SupportAgent::fake(['Hello, Jane!']);
8 
9$fake = Converse::fake();
10 
11Converse::incoming('support', Message::make(
12 new Thread('slack', 'C0123456789'),
13 'Hello @support',
14 new User('U0000001', name: 'Jane'),
15 now()->toDateTimeImmutable(),
16)->withMention());
17 
18$fake->assertSent('Hello, Jane!');

To test a button click, send an Action event to a bot whose handler implements HandlesActions, such as SupportBot from the combined agent and handler example:

1use Laravel\Converse\BotEvents\Action;
2use Laravel\Converse\Facades\Converse;
3use Laravel\Converse\Thread;
4use Laravel\Converse\User;
5 
6Converse::incoming('support', new Action(
7 new Thread('slack', 'C0123456789'),
8 'approve-refund',
9 new User('U0000001', name: 'Jane'),
10 value: '1042',
11 messageId: '1712345678.000100',
12));
13 
14$fake->assertEdited('approved');
1use Laravel\Converse\BotEvents\Action;
2use Laravel\Converse\Facades\Converse;
3use Laravel\Converse\Thread;
4use Laravel\Converse\User;
5 
6Converse::incoming('support', new Action(
7 new Thread('slack', 'C0123456789'),
8 'approve-refund',
9 new User('U0000001', name: 'Jane'),
10 value: '1042',
11 messageId: '1712345678.000100',
12));
13 
14$fake->assertEdited('approved');

When an agent's tools look up users or download attachments, seed the fake with withUsers and withAttachmentContents. withUsers and withChannels also supply the @user and #channel destinations resolved by scheduled turns:

1use Laravel\Converse\Channel;
2use Laravel\Converse\Facades\Converse;
3use Laravel\Converse\User;
4 
5$fake = Converse::fake()
6 ->withUsers(new User('U0000001', name: 'Jane', username: 'jane'))
7 ->withChannels(new Channel('C0123456789', '#support'))
8 ->withAttachmentContents('F0000001', 'Invoice contents');
1use Laravel\Converse\Channel;
2use Laravel\Converse\Facades\Converse;
3use Laravel\Converse\User;
4 
5$fake = Converse::fake()
6 ->withUsers(new User('U0000001', name: 'Jane', username: 'jane'))
7 ->withChannels(new Channel('C0123456789', '#support'))
8 ->withAttachmentContents('F0000001', 'Invoice contents');

Testing Web Chats

Because a web chat receives messages over HTTP, test it by posting to the bot's web route as an authenticated user and reading the resulting messages from Converse::chat:

1use App\Ai\Agents\Assistant;
2use App\Models\User;
3use Laravel\Converse\Facades\Converse;
4 
5test('the assistant answers in the web chat', function () {
6 Assistant::fake(['Hello, Jane!']);
7 
8 $this->actingAs(User::factory()->create());
9 
10 $this->postJson('/converse/assistant/web', [
11 'messages' => [['id' => 'message-1', 'role' => 'user', 'content' => 'Hello']],
12 ])->assertAccepted();
13 
14 $messages = collect(Converse::chat('assistant')->toArray()['messages']);
15 
16 expect($messages->firstWhere('role', 'assistant')['content'])->toBe('Hello, Jane!');
17});
1use App\Ai\Agents\Assistant;
2use App\Models\User;
3use Laravel\Converse\Facades\Converse;
4 
5test('the assistant answers in the web chat', function () {
6 Assistant::fake(['Hello, Jane!']);
7 
8 $this->actingAs(User::factory()->create());
9 
10 $this->postJson('/converse/assistant/web', [
11 'messages' => [['id' => 'message-1', 'role' => 'user', 'content' => 'Hello']],
12 ])->assertAccepted();
13 
14 $messages = collect(Converse::chat('assistant')->toArray()['messages']);
15 
16 expect($messages->firstWhere('role', 'assistant')['content'])->toBe('Hello, Jane!');
17});
1use App\Ai\Agents\Assistant;
2use App\Models\User;
3use Laravel\Converse\Facades\Converse;
4 
5public function test_the_assistant_answers_in_the_web_chat(): void
6{
7 Assistant::fake(['Hello, Jane!']);
8 
9 $this->actingAs(User::factory()->create());
10 
11 $this->postJson('/converse/assistant/web', [
12 'messages' => [['id' => 'message-1', 'role' => 'user', 'content' => 'Hello']],
13 ])->assertAccepted();
14 
15 $messages = collect(Converse::chat('assistant')->toArray()['messages']);
16 
17 $this->assertSame('Hello, Jane!', $messages->firstWhere('role', 'assistant')['content']);
18}
1use App\Ai\Agents\Assistant;
2use App\Models\User;
3use Laravel\Converse\Facades\Converse;
4 
5public function test_the_assistant_answers_in_the_web_chat(): void
6{
7 Assistant::fake(['Hello, Jane!']);
8 
9 $this->actingAs(User::factory()->create());
10 
11 $this->postJson('/converse/assistant/web', [
12 'messages' => [['id' => 'message-1', 'role' => 'user', 'content' => 'Hello']],
13 ])->assertAccepted();
14 
15 $messages = collect(Converse::chat('assistant')->toArray()['messages']);
16 
17 $this->assertSame('Hello, Jane!', $messages->firstWhere('role', 'assistant')['content']);
18}

With the sync queue driver, the turn finishes before the HTTP request returns.