Leanpub Header

Skip to main content

Building AI Applications with PHP

A Practical Guide Using PapiAI, Laravel, and Symfony

Build real AI agents in PHP — no Python required. Two complete projects, ten LLM providers, and every production concern covered.

Minimum price

$19.00

$29.00

You pay

$29.00

Author earns

$23.20
$

...Or Buy With Credits!

You can get credits with a paid monthly or annual Reader Membership, or you can buy them here.

Buying multiple copies for your team? See below for a discount!

PDF
EPUB
About

About

About the Book

PHP developers build ambitious applications with Laravel and Symfony every day — but the moment AI enters the picture, they're told to reach for Python. This book proves that's unnecessary.

Building AI Applications with PHP walks you through creating two complete, production-grade AI applications from scratch: an intelligent customer support agent with Laravel and an AI content generation pipeline with Symfony. Both use PapiAI, an open-source PHP library with zero runtime dependencies, support for 10 LLM providers, and a proper agentic runtime.

You'll learn every aspect of AI application development that matters in production: streaming responses in real time, giving agents tools that query your database, managing conversation memory across requests, validating structured output with schemas, building RAG pipelines with embeddings and vector search, processing tasks asynchronously with queues, defending against prompt injection, controlling costs, and deploying with confidence.

This isn't a tour of API endpoints. It's a guide to the architecture, patterns, and hard-won lessons that separate a demo from a deployable product — written entirely in the language you already know.

Team Discounts

Team Discounts

Get a team discount on this book!

  • Up to 3 members

    Minimum price
    $47.00
    Suggested price
    $72.00
  • Up to 5 members

    Minimum price
    $76.00
    Suggested price
    $116.00
  • Up to 10 members

    Minimum price
    $133.00
    Suggested price
    $203.00
  • Up to 15 members

    Minimum price
    $190.00
    Suggested price
    $290.00
  • Up to 25 members

    Minimum price
    $285.00
    Suggested price
    $435.00

Author

About the Author

Marcello Duarte

Marcello Duarte has been awarded best UK Agile coach in 2014. He has helped many teams in many organisations across Europe into Agile processes and development practices like Scrum, TDD, Refactoring, Collaborative Product Ownership and Software Quality. He is also the co-creator of PhpSpec, a tool for TDD/SpecBDD in PHP, and heads the Learning & Development at Inviqa, a leading PHP consultancy business in Europe.

Contents

Table of Contents

Building AI Applications with PHP

  1. A Practical Guide Using PapiAI, Laravel, and Symfony

Part I: Foundations

Chapter 1: The AI-Native PHP Application

  1. What You’ll Build
  2. Who This Book Is For
  3. What You Need
  4. The Anatomy of an AI Application
  5. Installing PapiAI

Chapter 2: Your First Agent

  1. The Provider
  2. The Agent
  3. The Response
  4. Streaming
  5. Swapping Providers
  6. Failover

Chapter 3: Tools — Giving the AI Hands

  1. How Tool Calling Works
  2. Creating Tools with Closures
  3. Creating Tools with PHP Attributes
  4. Tool Design Principles
  5. The Agentic Loop and maxTurns

Chapter 4: Conversations and Memory

  1. The Conversation Object
  2. Messages
  3. Why Context Management Matters
  4. Context Window Strategies
  5. Persisting Conversations

Chapter 5: Structured Output

  1. The Schema System
  2. Schema Types
  3. Constraints and Modifiers
  4. Validation

Chapter 6: Retrieval-Augmented Generation (RAG)

  1. How RAG Works
  2. Embeddings with PapiAI
  3. The Vector Store
  4. Building a RAG Pipeline
  5. RAG as a Tool
  6. Tuning RAG Quality
  7. Production Considerations

Chapter 7: Middleware

  1. The Middleware Interface
  2. Built-in Middleware
  3. Stacking Middleware
  4. Custom Middleware

Part II: Building the Laravel Project

Chapter 8: Project Setup — The Support Agent

  1. Scaffolding
  2. Configuration
  3. Database Setup
  4. The System Prompt

Chapter 9: Building the Tools

  1. OrderLookup
  2. KnowledgeBase
  3. InventoryCheck
  4. Registering Tools in the Service Provider

Chapter 10: The Chat Controller and Streaming

  1. The Controller
  2. Routes
  3. The Frontend
  4. Testing the Flow

Chapter 11: Security

  1. Prompt Injection
  2. Tool Security
  3. API Key Management
  4. Rate Limiting
  5. Cost Controls

Part III: Building the Symfony Project

Chapter 12: Project Setup — The Content Pipeline

  1. Scaffolding
  2. Bundle Configuration
  3. Database Schema
  4. The Article Schema

Chapter 13: The Content Generation Pipeline

  1. The Pipeline Orchestrator
  2. Async Processing with Messenger
  3. The Controller
  4. Running the Worker

Chapter 14: Performance

  1. Streaming
  2. Caching
  3. Model Selection
  4. Async Processing
  5. Token Optimization
  6. Connection Reuse

Chapter 15: Architecture Patterns

  1. The Agent as a Service
  2. Separate Concerns
  3. Prompt Management
  4. The Router Pattern
  5. Observability

Chapter 16: Testing AI Applications

  1. Testing Tools
  2. Testing with Mock Providers
  3. Testing Schemas
  4. Integration Tests

Chapter 17: Deployment and Production Concerns

  1. Environment Configuration
  2. Health Checks
  3. Monitoring
  4. Timeouts
  5. Scaling

Appendix A: Provider Reference

  1. Provider Capabilities Matrix
  2. Provider Constructor Parameters

Appendix B: Schema Reference

  1. Types
  2. Constraints
  3. Validation Methods

Appendix C: Middleware Reference

  1. RetryMiddleware
  2. RateLimitMiddleware
  3. CacheMiddleware
  4. LoggingMiddleware
  5. Custom Middleware

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

Now, this is technically risky for us, since you'll have the book or course files either way. But we're so confident in our products and services, and in our authors and readers, that we're happy to offer a full money back guarantee for everything we sell.

You can only find out how good something is by trying it, and because of our 100% money back guarantee there's literally no risk to do so!

So, there's no reason not to click the Add to Cart button, is there?

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earned over $14 million writing, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub