Forging Adventures: Building a D&D Engine with the Laravel AI SDK
The Dungeon Master in the Machine
Building a text-based dungeon crawler isn't just about hardcoding strings and conditional logic. By utilizing the
Prerequisites and Key Tools
To follow along, you need a solid grasp of PHP and the laravel/ai package, which simplifies agent creation and conversational state management.

Building the DM Agent
Start by generating a specialized agent class. An agent is essentially a PHP class that encapsulates the "personality" and rules of your assistant. Run the following command:
php artisan make:agent DDMaster
Inside the generated class, define the instructions() method. This is where you set the ground rules. You must explicitly tell the AI to track health, provide three clear choices per turn, and conclude the game if health reaches zero.
public function instructions(): string
{
return "You are a Dungeon Master. Track player health (start 100). Provide 2-3 choices. If health hits 0, game over.";
}
Solving Persistent State
A common pitfall is the "amnesia" effect, where the AI forgets previous turns. To fix this, use the RemembersConversation trait. This trait automatically hooks into the SDK's database migrations to store and retrieve message history. Critically, you must associate the agent with a specific DDMaster::make($user) to ensure the history persists correctly across different sessions.
Syntax Notes and Best Practices
When building terminal interfaces, utilize the text prompt helper for clean user input. Always remove the default messages() method in your agent if you are using the RemembersConversation trait, as the trait handles that logic internally. This prevents empty arrays from overriding your stored history.