Laravel AI SDK 入门指南

摘要

Laravel AI SDK 是 Laravel 13 引入的第一方 AI 集成方案,提供统一的 API 用于与 OpenAI、Anthropic、Google Gemini 等 AI 提供商交互。本文将带您从零开始掌握 Laravel AI SDK,包括:

  • Laravel AI SDK 的安装与配置
  • 支持的 AI 提供商及配置方法
  • 文本生成的基础用法
  • 提供商切换与抽象层
  • 错误处理与重试机制
  • 最佳实践与性能优化

本文适合希望快速上手 Laravel AI SDK 的开发者,为后续深入学习高级功能奠定基础。

1. Laravel AI SDK 简介

1.1 什么是 Laravel AI SDK

Laravel AI SDK 提供了一个统一、表达力强的 API,用于与多个 AI 提供商交互。使用 AI SDK,你可以:

  • 构建具有工具和结构化输出的智能代理
  • 生成图像
  • 合成和转录音频
  • 创建向量嵌入
  • 构建语义搜索功能

所有功能都使用一致、符合 Laravel 风格的接口。

1.2 核心优势

优势描述
提供商无关无需重写代码即可切换 AI 提供商
Laravel 原生与框架深度集成,遵循 Laravel 约定
统一 API相同的接口适用于所有提供商
自动重试内置错误处理和重试逻辑
队列集成支持后台任务处理

1.3 支持的提供商

  • OpenAI:GPT-4、GPT-3.5、DALL-E、Whisper
  • Anthropic:Claude 系列
  • Google Gemini:Gemini Pro、Gemini Ultra
  • 其他:兼容 OpenAI API 的提供商

2. 安装与配置

2.1 安装

1
composer require laravel/ai

2.2 发布配置文件

1
php artisan vendor:publish --tag=laravel-ai-config

2.3 配置文件结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// config/ai.php
return [
'default' => env('AI_PROVIDER', 'openai'),

'providers' => [
'openai' => [
'driver' => 'openai',
'api_key' => env('OPENAI_API_KEY'),
'model' => env('OPENAI_MODEL', 'gpt-4'),
],

'anthropic' => [
'driver' => 'anthropic',
'api_key' => env('ANTHROPIC_API_KEY'),
'model' => env('ANTHROPIC_MODEL', 'claude-3-opus'),
],

'gemini' => [
'driver' => 'gemini',
'api_key' => env('GEMINI_API_KEY'),
'model' => env('GEMINI_MODEL', 'gemini-pro'),
],
],
];

2.4 环境变量配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# .env
AI_PROVIDER=openai

# OpenAI
OPENAI_API_KEY=sk-...
OPENAI_MODEL=gpt-4

# Anthropic
ANTHROPIC_API_KEY=sk-ant-...
ANTHROPIC_MODEL=claude-3-opus

# Gemini
GEMINI_API_KEY=...
GEMINI_MODEL=gemini-pro

3. 文本生成基础

3.1 简单文本生成

1
2
3
4
5
6
use Laravel\Ai\Prompt;
use Laravel\Ai\Facades\Ai;

$response = Ai::prompt('Write a haiku about Laravel');

echo $response;

3.2 使用 Prompt 类

1
2
3
4
5
6
7
8
9
use Laravel\Ai\Prompt;

$response = Prompt::make('Explain quantum computing in simple terms')
->withModel('gpt-4')
->withMaxTokens(500)
->withTemperature(0.7)
->generate();

echo $response;

3.3 系统提示

1
2
3
$response = Prompt::make('What is the capital of France?')
->withSystemMessage('You are a helpful geography teacher.')
->generate();

3.4 对话历史

1
2
3
4
5
6
$response = Prompt::make('Tell me more about Paris')
->withHistory([
['role' => 'user', 'content' => 'What is the capital of France?'],
['role' => 'assistant', 'content' => 'The capital of France is Paris.'],
])
->generate();

4. 提供商切换

4.1 全局切换

1
2
// config/ai.php
'default' => 'anthropic',

4.2 运行时切换

1
2
3
4
5
6
7
8
use Laravel\Ai\Facades\Ai;

$response = Ai::provider('anthropic')
->prompt('Hello, Claude!');

// 或使用门面
$response = Ai::using('gemini')
->prompt('Hello, Gemini!');

4.3 提供商特定配置

1
2
3
4
$response = Prompt::make('Analyze this code')
->usingProvider('openai')
->withModel('gpt-4-turbo')
->generate();

5. 结构化输出

5.1 JSON 输出

1
2
3
4
5
6
7
8
9
10
11
12
use Laravel\Ai\Prompt;

$data = Prompt::make('Generate a user profile')
->expectJson([
'name' => 'string',
'email' => 'string',
'age' => 'integer',
])
->generate();

// 返回解析后的数组
echo $data['name'];

5.2 枚举输出

1
2
3
4
5
6
7
8
9
10
11
enum Sentiment: string {
case Positive = 'positive';
case Negative = 'negative';
case Neutral = 'neutral';
}

$sentiment = Prompt::make('Analyze the sentiment: "I love Laravel!"')
->expectEnum(Sentiment::class)
->generate();

echo $sentiment->value; // 'positive'

5.3 自定义 Schema

1
2
3
4
5
6
7
8
9
10
11
12
use Laravel\Ai\Schema;

$schema = Schema::object()
->properties([
Schema::string('title')->description('The post title'),
Schema::array('tags')->items(Schema::string()),
Schema::integer('read_time_minutes'),
]);

$result = Prompt::make('Generate a blog post metadata')
->withSchema($schema)
->generate();

6. 错误处理

6.1 异常类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use Laravel\Ai\Exceptions\AiException;
use Laravel\Ai\Exceptions\RateLimitException;
use Laravel\Ai\Exceptions\InvalidResponseException;

try {
$response = Ai::prompt('Hello');
} catch (RateLimitException $e) {
// 处理速率限制
retry(3, fn() => Ai::prompt('Hello'), 1000);
} catch (InvalidResponseException $e) {
// 处理无效响应
Log::error('AI response error', ['error' => $e->getMessage()]);
} catch (AiException $e) {
// 通用 AI 异常
}

6.2 自动重试

1
2
3
4
5
6
// config/ai.php
'retry' => [
'times' => 3,
'sleep' => 1000, // 毫秒
'when' => [RateLimitException::class],
],

7. 队列集成

7.1 后台生成

1
2
3
4
5
6
7
use Laravel\Ai\Jobs\GenerateText;

GenerateText::dispatch('Write a blog post about Laravel')
->onQueue('ai')
->chain([
fn($result) => ProcessBlogPost::dispatch($result),
]);

7.2 任务类示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Laravel\Ai\Prompt;

class GenerateProductDescription implements ShouldQueue
{
use Queueable;

public function __construct(
public array $product
) {}

public function handle(): void
{
$description = Prompt::make(
"Write a product description for: {$this->product['name']}"
)->generate();

$this->product['description'] = $description;
$this->product->save();
}
}

8. 流式响应

8.1 基本流式

1
2
3
4
5
6
7
8
9
10
use Illuminate\Support\Facades\Response;

Route::get('/chat', function () {
return Response::stream(function () {
foreach (Ai::stream('Tell me a story') as $chunk) {
echo $chunk;
flush();
}
});
});

8.2 Livewire 集成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
use Livewire\Component;
use Laravel\Ai\Facades\Ai;

class ChatAssistant extends Component
{
public string $message = '';
public string $response = '';

public function send()
{
$this->response = '';

foreach (Ai::stream($this->message) as $chunk) {
$this->response .= $chunk;
$this->stream('response', $this->response);
}
}

public function render()
{
return view('livewire.chat-assistant');
}
}

9. 成本控制

9.1 Token 统计

1
2
3
4
5
$response = Ai::prompt('Hello');

echo $response->usage()->promptTokens;
echo $response->usage()->completionTokens;
echo $response->usage()->totalTokens;

9.2 成本估算

1
2
3
4
5
6
7
8
9
use Laravel\Ai\Cost;

$cost = Cost::estimate(
tokens: 1000,
model: 'gpt-4',
type: 'input'
);

echo $cost->inDollars(); // 0.03

9.3 预算限制

1
2
3
4
5
// config/ai.php
'budget' => [
'daily_limit' => 10.00, // 美元
'alert_threshold' => 0.8, // 80% 时警告
],

10. 最佳实践

10.1 提示词工程

1
2
3
4
5
6
7
8
9
10
11
12
class PromptTemplates
{
public static function codeReview(string $code): string
{
return <<<PROMPT
Review the following code for:
- Security vulnerabilities
- Performance issues
- Best practices violations
- Potential bugs

Code:
    {$code}
    
1
2
3
4
5
        
Provide specific, actionable feedback.
PROMPT;
}
}

10.2 缓存策略

1
2
3
4
5
6
7
8
9
10
use Illuminate\Support\Facades\Cache;

function getCachedResponse(string $prompt): string
{
$key = 'ai:' . md5($prompt);

return Cache::remember($key, now()->addHours(24), function () use ($prompt) {
return Ai::prompt($prompt);
});
}

10.3 监控与日志

1
2
3
4
5
6
// config/ai.php
'logging' => [
'enabled' => true,
'channel' => 'ai',
'level' => 'info',
],
1
2
3
4
5
6
7
8
// 日志示例
[2026-03-20 10:00:00] ai.INFO: AI Request {
"provider": "openai",
"model": "gpt-4",
"prompt_tokens": 150,
"completion_tokens": 200,
"duration_ms": 1234
}

11. 总结

Laravel AI SDK 为 PHP 开发者提供了一个强大、统一的 AI 集成方案:

  1. 简单安装:一行命令即可开始使用
  2. 提供商无关:轻松切换 AI 提供商
  3. Laravel 原生:与框架深度集成
  4. 生产就绪:内置错误处理、重试和监控

通过本指南,您已经掌握了 Laravel AI SDK 的基础用法,可以开始构建 AI 驱动的 Laravel 应用了。

参考资料