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 Laravel AI SDK, we can transform a standard LLM into a dynamic Dungeon Master. This technique moves away from rigid scripts toward fluid storytelling where the AI manages player health, tracks inventory, and narrates unique encounters. It demonstrates that AI isn't solely for data summarization; it is a powerful engine for procedural generation and interactive logic.
Prerequisites and Key Tools
To follow along, you need a solid grasp of PHP and the Laravel framework. You will also need an API key from a supported provider like Anthropic or OpenAI. The primary tool here is 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 Laravel model using 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.
- Laravel
- 33%· products
- Anthropic
- 17%· companies
- Laravel AI SDK
- 17%· products
- OpenAI
- 17%· companies
- Tinkerwell
- 17%· products

Laravel AI SDK: I Built a D&D Terminal Game with AI as Dungeon Master
WatchLaravel // 12:29
The official YouTube channel of Laravel, the clean stack for Artisans and agents. We will update you on what's new in the world of Laravel, from the framework to our products Cloud, Forge, and Nightwatch.