Z.AI Laravel 12 SDK
Source: Dev.to
请提供您希望翻译的完整文本内容(除代码块和 URL 之外),我将把它翻译成简体中文并保持原有的格式和 Markdown 语法。
核心特性
在其核心,Z.AI Laravel SDK 提供无缝访问前沿 AI 模型,包括 GLM‑4.7、GLM‑4.6 和 GLM‑4.5 系列。该 SDK 的独特之处在于对高级功能的精细实现,例如:
思考模式用于复杂推理
$response = Zai::chat()
->model('glm-4.7')
->thinking(true) // 启用透明的推理过程
->send('Analyze this Laravel application architecture for scalability improvements');
工具与函数调用
$response = Zai::chat()
->tools(['code_analyzer', 'database_optimizer', 'security_scanner'])
->send('Review my Laravel code and suggest optimizations');
实时流式响应
Zai::chat()
->stream() // 在生成时获取响应
->onChunk(fn ($chunk) => $this->broadcastToClients($chunk))
->send('Generate a comprehensive API documentation');
图像生成
图像生成能力堪称惊人:
$image = Zai::image()
->model('glm-image') // Or `cogview-4-250304` for ultra‑high quality
->quality('high') // `standard`, `high`, or `ultra`
->size('1024x1024') // Custom dimensions supported
->style('photorealistic') // Artistic styles available
->generate('A modern Laravel application dashboard with clean UI and responsive design');
这为动态内容创建、自动图像处理以及提升用户体验打开了令人难以置信的可能性。
高级 OCR 能力
$document = Zai::ocr()
->file($uploadedPdf)
->extractTables(true) // Extract structured data from tables
->parseFormulas(true) // Handle spreadsheet content
->layoutAnalysis(true) // Understand document structure
->process();
返回结构化数据,包括:
- 提取的文本
- 表格数据
- 公式和计算
- 布局信息
这些功能在发票处理、文档分析和数据提取应用中具有革命性意义。
现代 PHP 实践 – 完整类型提示
use ZaiLaravelSdk\DTOs\ChatRequest;
use ZaiLaravelSdk\DTOs\ChatResponse;
function processAIRequest(ChatRequest $request): ChatResponse
{
$response = Zai::chat()
->model($request->model)
->temperature($request->temperature)
->maxTokens($request->maxTokens)
->send($request->message);
return $response; // Fully typed response object
}
为开发者带来乐趣的 API
$response = Zai::chat()
->asUser('system_analyst')
->withContext(['laravel_version' => '12.x', 'php_version' => '8.3'])
->temperature(0.7)
->maxTokens(2000)
->tools(['code_reviewer'])
->thinking(true)
->stream()
->send('Perform a comprehensive code review of this Laravel application');
智能验证
SDK 在请求到达 API 之前进行验证,防止产生代价高昂的错误:
try {
$response = Zai::image()
->validateModelCapabilities() // Auto‑validates model support
->validateImageDimensions() // Ensures valid dimensions
->validateQualityLevel() // Checks quality parameter
->generate('Ultra‑high resolution architectural visualization');
} catch (InvalidModelException $e) {
// Handle specific validation errors
}
错误处理与重试逻辑
use ZaiLaravelSdk\Exceptions\ZaiException;
use ZaiLaravelSdk\Retry\ExponentialBackoff;
try {
$response = Zai::chat()->send('Complex AI request');
} catch (ZaiException $e) {
// Detailed error information
$error = [
'code' => $e->getCode(),
'message' => $e->getMessage(),
'retry_count' => $e->getRetryCount(),
'is_recoverable' => $e->isRecoverable(),
'suggested_action'=> $e->getSuggestedAction(),
];
// Built‑in retry logic with exponential backoff
$retryStrategy = new ExponentialBackoff(maxRetries: 3, baseDelay: 1000);
}
无缝 Laravel 集成
队列集成
dispatch(function () {
$result = Zai::chat()->send('Time‑intensive AI analysis');
})->onQueue('ai-processing');
事件处理
Event::listen(AIRequestProcessed::class, function ($event) {
Log::info('AI request completed', ['duration' => $event->duration]);
});
中间件支持
Route::middleware(['ai.rate.limited'])->group(function () {
Route::post('/ai/chat', [AIController::class, 'chat']);
});
示例服务
代码审查服务
class CodeReviewService
{
public function analyzeCode(string $code): array
{
$analysis = Zai::chat()
->asUser('senior_laravel_developer')
->tools(['code_analyzer', 'security_scanner'])
->thinking(true)
->send(
"Review this Laravel code and provide suggestions for optimization, "
. "security improvements, and best practices:\n\n{$code}"
);
return [
'optimizations' => $analysis->getOptimizations(),
'security_issues' => $analysis->getSecurityIssues(),
'best_practices' => $analysis->getBestPractices(),
'refactored_code' => $analysis->getRefactoredCode(),
];
}
}
内容生成服务
class ContentGenerationService
{
public function generateBlogPost(string $topic, string $style): array
{
$outline = Zai::chat()
->asUser('content_strategist')
->send("Create a detailed blog post outline about: {$topic} in {$style} style");
$title = $outline->getTitle();
$sections = $outline->getSections();
$featuredImage = Zai::image()
->style('professional')
->generate("Modern blog post featured image about: {$title}");
return [
'title' => $title,
'sections' => $sections,
'featured_image' => $featuredImage,
];
}
}
Z.AI Laravel SDK 让开发者能够将最前沿的 AI 直接嵌入 Laravel 应用,从智能聊天、代码分析到高质量图像生成和 OCR。结果是?更快的开发周期、更丰富的用户体验,以及 PHP‑AI 解决方案的全新前沿。 🚀
Z.AI Laravel SDK 概览
不再需要与 Guzzle 请求、手动 JSON 解析或复杂的 API 集成搏斗。
Z.AI Laravel SDK 将 “Laravel 方式” 引入 AI 开发——优雅、直观且经受考验。它将复杂的 AI 交互转化为简洁、富有表现力的代码,让任何 Laravel 开发者都感到自然。
为什么选择 Z.AI SDK?
- 可适配 – 支持多个 AI 提供商和模型,让你的应用能够随 AI 生态的演进保持最新。
- 面向未来 – 投资此 SDK 即是为代码库的长期可用性保驾护航。
- 安全 – 采用安全最佳实践:速率限制、输入消毒以及全面的错误处理,保护你的应用及其用户。
准备好用先进的 AI 能力彻底革新你的 Laravel 应用了吗?
安装
composer require 0xmergen/zai-laravel-sdk
配置 (config/zai.php)
env('ZAI_API_KEY'),
'default_model' => 'glm-4.7',
'timeout' => 30,
'retry_attempts' => 3,
'cache_enabled' => true,
];
基本用法
use ZaiLaravelSdk\Facades\Zai;
// Simple chat
$response = Zai::chat()->send('Hello, AI world!');
高级用法(全部功能)
use ZaiLaravelSdk\Facades\Zai;
$response = Zai::chat()
->model('glm-4.7')
->thinking(true) // Enable “thinking” mode
->tools(['data_analyzer']) // Attach tools
->stream() // Stream response
->send('Analyze this dataset and provide insights');
SDK 带来的价值
- 完整的范式转变 – 不仅仅是另一个包;它重新定义了 PHP 开发者集成 AI 的方式。
- 优雅的设计 – Laravel 为先的理念,提供流畅、富有表现力的 API。
- 强大的功能 – 从聊天机器人到内容生成器、智能自动化以及下一代应用。
智能 Laravel 应用的未来已经到来。你准备好构建它了吗?
开始使用
- 安装:
composer require 0xmergen/zai-laravel-sdk - 加入社区: [GitHub 讨论]
- 浏览文档: [文档]