Laravel AI SDK
📝 此頁面為 Laravel 官方文檔的繁體中文翻譯。查看原始英文版本
Laravel AI SDK
簡介
Laravel AI SDK 提供了一個統一的、表達力強的介面,用於與各種 AI 提供商(如 OpenAI、Anthropic、Ollama 和 Gemini)互動。該 SDK 圍繞提示詞(prompts)、工具(tools)、代理(agents)和執行緒(threads)等核心概念建立,使您能夠輕鬆建立 AI 驅動的應用程式。
[!NOTE] Laravel AI SDK 是透過 Laravel Boost 套件提供的,該套件包含 AI SDK、MCP 整合以及 MCP 應用開發工具。
安裝
要安裝 AI SDK,請使用 Composer 安裝 Laravel Boost:
composer require laravel/boost
配置
安裝後,發佈 AI SDK 配置:
php artisan install:ai
此命令將建立 config/ai.php 配置檔,您可以在其中配置 AI 提供商和模型。在您的 .env 檔案中設定 API 金鑰:
AI_OPENAI_API_KEY=sk-...
AI_ANTHROPIC_API_KEY=sk-ant-...
AI_GEMINI_API_KEY=...
快速入門
配置完成後,您可以開始使用 AI SDK 生成文字:
use Illuminate\Support\Facades\AI;
$result = AI::chat('What is Laravel?');
echo $result->content();
提示詞
提供上下文
您可以為 AI 模型提供系統提示詞來設定上下文:
use Illuminate\Support\Facades\AI;
$result = AI::chat('Explain queues in Laravel', [
'system' => 'You are a Laravel expert. Keep explanations concise and include code examples.',
]);
echo $result->content();
對話歷史
要維護對話歷史,可以將消息陣列傳遞給 chat 方法:
use Illuminate\Support\Facades\AI;
$messages = [
['role' => 'user', 'content' => 'What is Eloquent?'],
['role' => 'assistant', 'content' => 'Eloquent is Laravel's ORM...'],
['role' => 'user', 'content' => 'How do I define relationships?'],
];
$result = AI::chat($messages);
結構化輸出
您可以請求結構化輸出(如 JSON):
use Illuminate\Support\Facades\AI;
$result = AI::chat('List 3 Laravel features', [
'schema' => [
'type' => 'object',
'properties' => [
'features' => [
'type' => 'array',
'items' => ['type' => 'string'],
],
],
],
]);
$data = $result->json();
模型
選擇模型
您可以指定使用哪個 AI 模型:
use Illuminate\Support\Facades\AI;
$result = AI::chat('Hello!', ['model' => 'gpt-4o']);
模型選項
每個提供商支援特定的選項,如溫度、最大令牌數等:
$result = AI::chat('Hello!', [
'model' => 'gpt-4o',
'temperature' => 0.7,
'maxTokens' => 1000,
]);
自訂模型
您可以在 config/ai.php 中配置自訂模型或提供商。
工具
工具允許 AI 模型執行操作,例如查詢資料庫或呼叫 API。
定義工具
工具使用 PHP 類別定義,並包含名稱、描述和處理方法:
use Illuminate\AI\Tool;
class GetWeather extends Tool
{
public function __construct()
{
parent::__construct(
name: 'get_weather',
description: 'Get the current weather for a location',
parameters: [
'location' => ['type' => 'string', 'description' => 'City name'],
],
);
}
public function handle(array $parameters): string
{
$location = $parameters['location'];
return "The weather in {$location} is sunny, 72°F.";
}
}
工具呼叫
將工具傳遞給 AI 聊天方法,模型可以在需要時呼叫它們:
use Illuminate\Support\Facades\AI;
$result = AI::chat("What's the weather in Paris?", [
'tools' => [new GetWeather],
]);
echo $result->content();
MCP 工具
您還可以從 MCP 伺服器提供工具。這些工具會自動被 AI 模型發現和呼叫:
use Illuminate\Support\Facades\AI;
use Laravel\Mcp\Facades\Mcp;
$client = Mcp::client('weather-server');
$tools = $client->tools();
$result = AI::chat("What's the weather in Tokyo?", [
'tools' => $tools,
]);
代理
代理是具有工具存取權限的 AI 模型,可以在執行緒上下文中自主處理多步驟任務。
建立代理
使用 Agent 類別建立代理:
use Illuminate\AI\Agent;
use Illuminate\Support\Facades\AI;
$agent = new Agent(
model: 'gpt-4o',
instructions: 'You are a helpful assistant.',
tools: [new GetWeather],
);
$result = $agent->run("What's the weather in London?");
代理工具
代理可以存取多個工具來完成複雜任務。當代理需要工具時,它會自動呼叫該工具並使用結果繼續處理。
指令
代理指令定義了 AI 的行為和知識界限。指令在代理的整個生命週期中保持一致。
代理生命週期
代理可以使用 run 方法處理單個查詢,也可以維護一個持續的執行緒來處理多輪對話。
執行緒
執行緒維護 AI 代理和使用者之間的對話歷史,允許多輪互動。
建立執行緒
use Illuminate\AI\Thread;
$thread = new Thread;
$agent = new Agent(
model: 'gpt-4o',
instructions: 'You are a helpful assistant.',
);
$response = $agent->run('What is the capital of France?', $thread);
$response = $agent->run('What is its population?', $thread);
管理執行緒
執行緒可以序列化並儲存以便之後恢復對話。
串流
AI SDK 支援串流回應,允許您即時顯示產生的文字:
use Illuminate\Support\Facades\AI;
$stream = AI::chat('Write a poem about Laravel', ['stream' => true]);
foreach ($stream as $chunk) {
echo $chunk->content;
}
錯誤處理
AI SDK 在所有提供商之上提供了統一的錯誤處理。常見例外包括速率限制、認證錯誤和超時。
測試
AI SDK 包含用於測試的 fake 驅動程式,允許您在不實際呼叫 AI API 的情況下斷言 AI 互動:
use Illuminate\Support\Facades\AI;
AI::fake();
$result = AI::chat('Hello!');
$result->assertContentContains('...');