- Laravel AI SDK: สร้าง AI Agent, Tools และ RAG ด้วย Laravel 13
- 1. สิ่งที่ Laravel AI SDK ทำได้
- 2. ความต้องการเบื้องต้น
- 3. ติดตั้ง Laravel AI SDK
- 4. กำหนด AI Provider
- 5. สร้าง AI Agent ตัวแรก
- 6. Anonymous Agent
- 7. Structured Output
- 8. สร้าง Custom Tool
- 9. Conversation Memory
- 10. Streaming
- 11. Queue สำหรับงาน AI
- 12. Embeddings
- 13. Vector Database ด้วย PostgreSQL + pgvector
- 14. RAG ด้วย Similarity Search
- 15. Provider Vector Stores
- 16. MCP Tools
- 17. Provider Tools
- 18. Sub-Agents และ Agentic Workflow
- 19. Human Tool Approval
- 20. Failover
- 21. Testing
- 22. ตัวอย่าง Architecture: AI Knowledge Assistant
- 23. โครงสร้างโปรเจกต์ที่แนะนำ
- 24. Laravel AI SDK vs Laravel MCP vs Laravel Boost
- Laravel Boost ช่วย coding agents เข้าใจและพัฒนาLaravel project
- 25. Roadmap สำหรับ Workshop
- 26. Best Practices
- 27. สรุป
- เอกสารอ้างอิง
#Laravel AI SDK: สร้าง AI Agent, Tools และ RAG ด้วย Laravel 13
Laravel 13 เพิ่ม Laravel AI SDK ซึ่งเป็น first-party package สำหรับพัฒนา AI-native application ด้วยแนวทางแบบ Laravel โดยมี API กลางสำหรับเชื่อมต่อผู้ให้บริการ AI หลายราย เช่น OpenAI, Anthropic และ Gemini พร้อมความสามารถสำคัญ เช่น Agent, Tool Calling, Structured Output, Streaming, Queue, Embeddings, Vector Store, RAG, MCP Tools, Image และ Audio
แนวคิดสำคัญคือไม่ควรกระจายโค้ดเรียก LLM ไว้ตาม Controller แต่แยกพฤติกรรม AI ออกเป็น Agent ที่กำหนด instructions, context, tools และ output schema ได้อย่างชัดเจน
User / Frontend
|
v
Laravel Route / Controller
|
v
+---------------------------+
| Laravel AI SDK |
| Agent |
| Tools / MCP Tools |
| Structured Output |
| Conversation / Streaming |
| Embeddings / RAG |
+-------------+-------------+
|
+------+------+------+
| | | |
OpenAI Anthropic Gemini ...
เอกสารนี้อ้างอิง Laravel 13.x และ Laravel AI SDK ณ วันที่ 22 กันยายน 2026 ควรตรวจสอบเอกสารทางการเมื่อใช้งานในระบบจริง เนื่องจาก SDK ยังมีการพัฒนาอย่างต่อเนื่อง
#1. สิ่งที่ Laravel AI SDK ทำได้
Laravel AI SDK มี abstraction กลางสำหรับงาน AI หลายประเภท ได้แก่
- Text generation และ AI Agents
- Tool / Function Calling
- Structured Output
- Conversation context
- Streaming และ Broadcasting
- Queueing
- Attachments
- Provider tools เช่น Web Search, Web Fetch และ File Search
- Embeddings และ Similarity Search
- Reranking
- Vector Stores และ RAG
- Image generation
- Text-to-Speech และ Speech-to-Text
- MCP Tools
- Sub-Agents
- Human Tool Approval
- Provider failover
- Testing / Fake AI responses
ดังนั้น SDK นี้ไม่ได้เป็นเพียง wrapper สำหรับ Chat Completion แต่เป็น application layer สำหรับสร้าง AI feature ใน Laravel
#2. ความต้องการเบื้องต้น
Laravel 13 ต้องการ PHP 8.3 ขึ้นไป ตรวจสอบเวอร์ชันด้วย
php -v
composer -V
หากต้องการสร้างโปรเจกต์ใหม่
composer create-project laravel/laravel laravel-ai-demo
cd laravel-ai-demo
หรือใช้ Laravel Installer
laravel new laravel-ai-demo
cd laravel-ai-demo
#3. ติดตั้ง Laravel AI SDK
ติดตั้ง package
composer require laravel/ai
publish configuration และ migrations
php artisan vendor:publish --provider="Laravel\Ai\AiServiceProvider"
จากนั้น migrate
php artisan migrate
SDK จะมีตารางสำหรับ conversation storage เช่น
agent_conversations
agent_conversation_messages
#4. กำหนด AI Provider
กำหนด API key ใน .env ตาม provider ที่ใช้ ตัวอย่างเช่น
OPENAI_API_KEY=your-api-key
ANTHROPIC_API_KEY=your-api-key
GEMINI_API_KEY=your-api-key
อย่า commit .env หรือ API key ขึ้น Git repository
.env
Laravel AI SDK ใช้ config/ai.php เป็นจุดกำหนด provider และ model
configuration ทำให้เปลี่ยน provider ได้โดยไม่ต้องเปลี่ยน application
architecture ทั้งหมด
#5. สร้าง AI Agent ตัวแรก
สร้าง Agent ด้วย Artisan
php artisan make:agent LaravelAssistant
Agent จะอยู่ในโครงสร้างประมาณ
app/
└── Ai/
└── Agents/
└── LaravelAssistant.php
ตัวอย่าง Agent แบบพื้นฐาน
<?php
namespace App\Ai\Agents;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Promptable;
use Stringable;
class LaravelAssistant implements Agent
{
use Promptable;
public function instructions(): Stringable|string
{
return <<<'PROMPT'
You are an expert Laravel software engineer.
Answer clearly and provide secure, maintainable examples.
PROMPT;
}
}
เรียกใช้งานได้จาก Route หรือ Service
use App\Ai\Agents\LaravelAssistant;
use Illuminate\Support\Facades\Route;
Route::post('/ai', function () {
$response = (new LaravelAssistant)
->prompt('อธิบาย Service Container ของ Laravel');
return [
'answer' => $response->text,
];
});
แนวคิดคือ Controller รับผิดชอบ HTTP ส่วน Agent รับผิดชอบ AI behavior
#6. Anonymous Agent
กรณีทดลอง prompt อย่างรวดเร็ว สามารถสร้าง agent โดยไม่ต้องสร้าง class
use function Laravel\Ai\agent;
$response = agent(
instructions: 'You are an expert Laravel developer.',
messages: [],
tools: [],
)->prompt('Explain Laravel middleware.');
return $response->text;
เหมาะกับ prototype แต่ระบบที่มี business logic ชัดเจนควรใช้ dedicated Agent class เพื่อให้ง่ายต่อการทดสอบและดูแลรักษา
#7. Structured Output
Application จำนวนมากไม่ได้ต้องการข้อความอิสระ แต่ต้องการข้อมูลที่มี schema ชัดเจน เช่น
{
"category": "bug",
"priority": "high",
"summary": "..."
}
สร้าง structured agent
php artisan make:agent TicketClassifier --structured
ตัวอย่าง
<?php
namespace App\Ai\Agents;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\HasStructuredOutput;
use Laravel\Ai\Promptable;
class TicketClassifier implements Agent, HasStructuredOutput
{
use Promptable;
public function instructions(): string
{
return 'Classify software support tickets.';
}
public function schema(JsonSchema $schema): array
{
return [
'category' => $schema->string()->required(),
'priority' => $schema->string()->required(),
'summary' => $schema->string()->required(),
];
}
}
เรียกใช้
$result = (new TicketClassifier)
->prompt('ระบบ login ใช้งานไม่ได้หลัง deploy version ใหม่');
return [
'category' => $result['category'],
'priority' => $result['priority'],
'summary' => $result['summary'],
];
Structured Output เหมาะมากสำหรับ API, workflow automation และการบันทึกผลลงฐานข้อมูล
#8. สร้าง Custom Tool
Agent ต่างจาก chatbot ทั่วไปตรงที่สามารถเรียก Tools เพื่อทำงานกับระบบจริงได้
สร้าง tool
php artisan make:tool GetOrderStatus
โครงสร้าง
app/
└── Ai/
├── Agents/
└── Tools/
└── GetOrderStatus.php
แนวคิดของ Tool คือกำหนด input schema และ handle() สำหรับดำเนินการจริง
เช่นค้นฐานข้อมูล เรียก service หรือคำนวณข้อมูล
ตัวอย่างเชิงแนวคิด
public function handle(string $orderId): string
{
$order = Order::where('order_no', $orderId)->first();
if (! $order) {
return 'Order not found';
}
return "Order {$order->order_no}: {$order->status}";
}
จากนั้นให้ Agent implement HasTools
use App\Ai\Tools\GetOrderStatus;
use Laravel\Ai\Contracts\HasTools;
class SupportAgent implements Agent, HasTools
{
use Promptable;
public function instructions(): string
{
return 'Help customers check their orders.';
}
public function tools(): iterable
{
return [
new GetOrderStatus,
];
}
}
flow จะกลายเป็น
User
|
| "Order ORD-1001 ถึงไหนแล้ว?"
v
SupportAgent
|
| decides to call tool
v
GetOrderStatus
|
v
Database
|
v
Tool Result
|
v
LLM generates final answer
#Security ของ Tools
Tool คือจุดที่ AI สามารถกระทำกับระบบจริง จึงควร
- authorize ผู้ใช้ก่อนเข้าถึงข้อมูล
- validate arguments ทุกครั้ง
- ใช้ least privilege
- แยก read-only tools กับ destructive tools
- log tool invocation
- ใช้ Human Tool Approval กับ action ที่มีผลกระทบสูง
- ไม่ส่ง secret หรือข้อมูลส่วนบุคคลที่ไม่จำเป็นไปยัง model
#9. Conversation Memory
AI Assistant มักต้องจำบริบทการสนทนา เช่น
User: ฉันใช้ Laravel 13
AI: ...
User: แล้วตัวอย่างก่อนหน้าต้องแก้อะไร?
Laravel AI SDK รองรับ conversational agents และมี conversation storage ในฐานข้อมูล ทำให้สามารถต่อ conversation เดิมได้
ข้อสำคัญด้าน security คือ application ต้องตรวจสอบสิทธิ์ว่า participant มีสิทธิ์เข้าถึง conversation ก่อน continue conversation เสมอ
#10. Streaming
สำหรับ chatbot การรอให้ model ตอบครบทั้งหมดทำให้ UX ช้า จึงควรใช้ streaming
Without Streaming
Prompt -------- wait --------> Complete Response
With Streaming
Prompt -> token -> token -> token -> token -> done
Streaming เหมาะกับ
- AI Chat
- Coding Assistant
- Document Assistant
- Long-form generation
Laravel AI SDK รองรับ streaming และ broadcasting เพื่อเชื่อมกับ frontend แบบ real-time
#11. Queue สำหรับงาน AI
งานที่ใช้เวลานานไม่ควร block HTTP request เช่น
- วิเคราะห์เอกสารยาว
- สรุปหลายไฟล์
- batch classification
- สร้าง report
- processing pipeline
สามารถ queue agent request แล้วให้ worker ประมวลผล
HTTP Request
|
v
Laravel
|
v
Queue
|
v
Worker
|
v
AI Provider
แนวทางนี้ช่วยเรื่อง timeout, retry และ scalability
#12. Embeddings
Embedding คือการแปลงข้อมูลเป็น vector เพื่อเปรียบเทียบความหมายเชิง semantic
"Laravel authentication"
|
v
Embedding Model
|
v
[0.018, -0.224, 0.731, ...]
Laravel AI SDK มี API สำหรับสร้าง embeddings และรองรับการนำ vector ไปใช้ค้นหา similarity
ตัวอย่างแนวคิด
use Laravel\Ai\Embeddings;
$response = Embeddings::for([
'Laravel is a PHP framework.',
'Laravel supports queues and events.',
])->generate();
API จริงที่ต้องระบุ provider/model อาจแตกต่างตาม configuration และ provider ที่เลือก จึงควรตรวจสอบเอกสาร provider ก่อน deploy
#13. Vector Database ด้วย PostgreSQL + pgvector
Laravel 13 รองรับ vector column บน PostgreSQL ผ่าน pgvector
ตัวอย่าง migration
Schema::ensureVectorExtensionExists();
Schema::create('documents', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->vector('embedding', dimensions: 1536);
$table->timestamps();
});
จำนวน dimensions ต้องตรงกับ embedding model ที่ใช้งานจริง ไม่ควร copy ค่า 1536 ไปใช้โดยไม่ตรวจสอบ model
ข้อมูลจะมีลักษณะ
documents
id | title | content | embedding
---+-------------+----------------+---------------------
1 | Laravel AI | Laravel AI... | [0.12, -0.31, ...]
2 | Queue | Queue allows.. | [0.44, 0.10, ...]
#14. RAG ด้วย Similarity Search
RAG หรือ Retrieval-Augmented Generation คือการค้นข้อมูลที่เกี่ยวข้องก่อนส่ง context ให้ LLM
User Question
|
v
Create Query Embedding
|
v
Similarity Search
|
v
Relevant Documents
|
v
LLM + Context
|
v
Grounded Answer
Laravel AI SDK มี SimilaritySearch tool สำหรับให้ Agent ค้น Eloquent model
ที่มี vector embedding
use App\Models\Document;
use Laravel\Ai\Tools\SimilaritySearch;
public function tools(): iterable
{
return [
SimilaritySearch::usingModel(
Document::class,
'embedding'
),
];
}
ทำให้ RAG สามารถอยู่ใน Agent tool loop ได้โดยไม่ต้องเขียน orchestration ใหม่ทั้งหมด
#15. Provider Vector Stores
นอกจากเก็บ embeddings ในฐานข้อมูลของเราเอง SDK ยังมี Vector Store abstraction
use Laravel\Ai\Stores;
$store = Stores::create(
name: 'Knowledge Base',
description: 'Laravel project documentation.',
);
return $store->id;
เหมาะกับระบบที่ต้องการ upload files และใช้ provider-managed retrieval
#16. MCP Tools
หากติดตั้ง Laravel MCP สามารถนำ tools จาก MCP Server มาให้ Agent ใช้ได้
แนวคิด
Laravel AI Agent
|
+---- Local Tool
|
+---- MCP Client
|
v
MCP Server
|
+------+------+------+
| | |
GitHub Database External API
ตัวอย่าง remote MCP
use Laravel\Mcp\Client;
public function tools(): iterable
{
return [
...Client::web('https://mcp.example.com')
->withToken($token)
->tools(),
];
}
หรือ local MCP server
use Laravel\Mcp\Client;
public function tools(): iterable
{
return [
...Client::local(
'php',
['artisan', 'mcp:start']
)->tools(),
];
}
นี่เป็นจุดเชื่อมสำคัญระหว่าง Laravel AI SDK และ Laravel MCP: AI SDK เป็นฝั่ง agent/orchestration ส่วน MCP เป็น protocol สำหรับนำ tools จากระบบอื่นเข้ามาใช้งาน
#17. Provider Tools
SDK รองรับ tools ที่ provider ดำเนินการให้ เช่น Web Search, Web Fetch และ File Search โดย capability ขึ้นกับ provider
ตัวอย่าง Web Search
use Laravel\Ai\Providers\Tools\WebSearch;
public function tools(): iterable
{
return [
new WebSearch,
];
}
Web Fetch สามารถจำกัด domain ได้ เพื่อลดความเสี่ยงและควบคุมแหล่งข้อมูล
use Laravel\Ai\Providers\Tools\WebFetch;
public function tools(): iterable
{
return [
(new WebFetch)
->max(3)
->allow(['laravel.com']),
];
}
#18. Sub-Agents และ Agentic Workflow
เมื่อระบบซับซ้อน สามารถแยกหน้าที่เป็น specialist agents เช่น
Orchestrator
|
+-------------+-------------+
| | |
v v v
Search Agent SQL Agent Report Agent
| | |
+-------------+-------------+
|
v
Final Answer
หลักการสำคัญคือไม่ควรสร้าง multi-agent เพียงเพราะทำได้ หาก single agent + tools แก้ปัญหาได้ง่ายกว่า ก็ควรเริ่มจาก architecture ที่ง่ายกว่า
#19. Human Tool Approval
Action บางประเภทไม่ควรให้ Agent execute โดยอัตโนมัติ เช่น
delete account
refund payment
send email
deploy production
modify database
ควรใช้ approval flow
Agent
|
v
Request Tool Call
|
v
Human Approval
|
+---- Reject --> Stop
|
+---- Approve
|
v
Execute Tool
นี่เป็น pattern สำคัญสำหรับ production agent เพราะลดความเสี่ยงจาก model error และ prompt injection
#20. Failover
Production AI application ไม่ควร assume ว่า provider จะพร้อมใช้งานตลอดเวลา ปัญหาที่พบได้ เช่น
- rate limit
- provider outage
- model unavailable
- timeout
Laravel AI SDK มีแนวทาง failover ระหว่าง provider/model ช่วยลดการเขียน fallback logic กระจายทั่ว application
#21. Testing
AI feature ต้อง test ได้เช่นเดียวกับ business logic อื่น Laravel AI SDK มี fake/testing APIs สำหรับหลาย capability เช่น Agent, Embeddings, Images, Audio, Files และ Vector Stores
แนวคิดของ test คือไม่เรียก API จริงทุกครั้ง
PHPUnit / Pest
|
v
Fake Agent
|
v
Known Response
|
v
Assertions
ข้อดีคือ
- test เร็ว
- ไม่มี API cost
- deterministic มากขึ้น
- CI/CD ไม่ต้องพึ่ง external provider
- ทดสอบว่า Agent ถูก prompt หรือ workflow ถูกเรียกตามที่คาดหวังได้
#22. ตัวอย่าง Architecture: AI Knowledge Assistant
ตัวอย่างระบบถามตอบเอกสารภายในองค์กร
+----------------+
| React / Blade |
+-------+--------+
|
v
+----------------+
| Laravel API |
+-------+--------+
|
v
+----------------+
| KnowledgeAgent |
+---+---------+--+
| |
+----------+ +----------+
v v
SimilaritySearch MCP Tools
| |
v v
PostgreSQL + pgvector Other Systems
|
v
Documents
workflow
1. User ส่งคำถาม
2. KnowledgeAgent วิเคราะห์คำถาม
3. Agent เรียก SimilaritySearch
4. ระบบค้น document chunks ที่เกี่ยวข้อง
5. context ถูกส่งให้ model
6. model สร้างคำตอบจาก context
7. Laravel ส่งผลกลับ frontend
#23. โครงสร้างโปรเจกต์ที่แนะนำ
app/
├── Ai/
│ ├── Agents/
│ │ ├── KnowledgeAgent.php
│ │ ├── SupportAgent.php
│ │ └── TicketClassifier.php
│ │
│ └── Tools/
│ ├── GetOrderStatus.php
│ ├── SearchKnowledge.php
│ └── CreateTicket.php
│
├── Http/
│ └── Controllers/
│ └── AiController.php
│
├── Models/
│ ├── Document.php
│ └── User.php
│
└── Services/
└── DocumentIngestionService.php
ควรให้ Controller บาง และย้าย AI behavior ไปยัง Agent/Tool ตาม responsibility
#24. Laravel AI SDK vs Laravel MCP vs Laravel Boost
เทคโนโลยี หน้าที่หลัก
Laravel AI SDK สร้าง AI features และ Agents ภายใน Laravel application
Laravel MCP expose/consume tools ผ่าน Model Context Protocol
#Laravel Boost ช่วย coding agents เข้าใจและพัฒนา Laravel project
ทั้งสามสามารถใช้ร่วมกันได้
Developer
|
v
AI Coding Agent
|
Laravel Boost
|
v
Laravel Application
|
+---- Laravel AI SDK ---- AI Agent
|
+---- Laravel MCP ------- MCP Tools
#25. Roadmap สำหรับ Workshop
ลำดับการเรียนที่เหมาะสม
Laravel 13
|
v
Install laravel/ai
|
v
Simple Agent
|
v
Structured Output
|
v
Custom Tool
|
v
Conversation + Streaming
|
v
Embeddings
|
v
pgvector + Similarity Search
|
v
RAG
|
v
MCP Tools
|
v
Sub-Agent / Approval / Testing
|
v
Production AI Application
#26. Best Practices
- เริ่มจาก single agent ก่อน multi-agent
- แยก Agent, Tool และ business service ออกจาก Controller
- ใช้ Structured Output เมื่อต้องส่งข้อมูลให้ application logic
- validate และ authorize ทุก tool call
- ใช้ Human Approval กับ destructive actions
- จำกัด WebFetch/WebSearch และ external access เท่าที่จำเป็น
- ไม่ส่ง secrets หรือข้อมูล sensitive ให้ model โดยไม่จำเป็น
- ใช้ queue กับงาน AI ที่ใช้เวลานาน
- ใช้ streaming สำหรับ interactive UX
- fake AI calls ใน automated tests
- log latency, token/cost และ tool execution ที่จำเป็นต่อ observability
- ออกแบบ fallback/failover สำหรับ production
- สำหรับ RAG ให้ประเมิน retrieval quality แยกจาก generation quality
- ป้องกัน prompt injection โดยถือ retrieved/external content เป็น untrusted input
- ตรวจสอบ model และ embedding dimensions จาก provider configuration เสมอ
#27. สรุป
Laravel AI SDK ทำให้ Laravel 13 มี application abstraction สำหรับ AI ที่ครบกว่าการเรียก REST API ไปยัง LLM โดยตรง จุดเด่นคือ Agent, Tools, Structured Output, Conversation, Streaming, Queue, Embeddings, RAG, MCP integration, Human Approval, Failover และ Testing อยู่ใน ecosystem เดียวกัน
สำหรับระบบจริง architecture ที่เหมาะสมมักเริ่มจาก
Laravel
|
v
AI Agent
|
+---- Structured Output
|
+---- Local Tools
|
+---- Similarity Search / RAG
|
+---- MCP Tools
|
+---- Human Approval
|
v
AI Provider
การออกแบบเช่นนี้ทำให้ AI ไม่ใช่เพียง chatbot แต่เป็นส่วนหนึ่งของ application workflow ที่สามารถควบคุม ทดสอบ และขยายระบบได้ตามแนวทางของ Laravel
#เอกสารอ้างอิง
- Laravel AI SDK Documentation: https://laravel.com/framework/docs/13.x/ai-sdk
- Laravel AI: https://laravel.com/ai
- Laravel AI SDK GitHub: https://github.com/laravel/ai
- Laravel 13 Release Notes: https://laravel.com/framework/docs/releases