glitchward/shield
Composer 安装命令:
composer require glitchward/shield
包简介
Official PHP client for Glitchward Shield - LLM Prompt Injection Protection API
README 文档
README
Official PHP client for Glitchward Shield - LLM Prompt Injection Protection API.
Protect your AI agents from prompt injection attacks, jailbreaks, and malicious inputs before they reach your LLM provider.
Requirements
- PHP 8.1 or higher
- JSON extension
Installation
composer require glitchward/shield
Quick Start
<?php use Glitchward\Shield\ShieldClient; // Initialize the client with your API token $shield = new ShieldClient('your_api_token'); // Validate a prompt before sending to your LLM $messages = [ ['role' => 'system', 'content' => 'You are a helpful assistant.'], ['role' => 'user', 'content' => 'Hello, how are you?'] ]; $result = $shield->validate($messages); if ($result->isSafe()) { // Safe to send to your LLM provider $response = $openai->chat()->create([ 'model' => 'gpt-4', 'messages' => $messages ]); } else { echo "Blocked! Risk score: {$result->riskScore}\n"; foreach ($result->matches as $match) { echo " - {$match->category}: {$match->pattern}\n"; } }
Usage with OpenAI PHP
<?php use OpenAI; use Glitchward\Shield\ShieldClient; $openai = OpenAI::client('your-openai-key'); $shield = new ShieldClient('your_shield_token'); function safeChat(array $messages): string { global $openai, $shield; // Validate with Shield first $result = $shield->validate($messages); if (!$result->isSafe()) { throw new RuntimeException("Prompt blocked by Shield. Risk: {$result->riskScore}"); } // Safe to proceed $response = $openai->chat()->create([ 'model' => 'gpt-4', 'messages' => $messages ]); return $response->choices[0]->message->content; } // Usage try { $response = safeChat([ ['role' => 'user', 'content' => "What's the weather like?"] ]); echo $response; } catch (RuntimeException $e) { echo "Request blocked: " . $e->getMessage(); }
Usage in Laravel
<?php namespace App\Services; use Glitchward\Shield\ShieldClient; use Glitchward\Shield\Exceptions\ShieldException; class AIService { private ShieldClient $shield; public function __construct() { $this->shield = new ShieldClient(config('services.shield.token')); } public function chat(array $messages): string { // Validate with Shield $result = $this->shield->validate($messages); if (!$result->isSafe()) { Log::warning('Prompt blocked by Shield', [ 'risk_score' => $result->riskScore, 'matches' => array_map(fn($m) => $m->toArray(), $result->matches) ]); throw new \Exception('Your message was blocked by our security filter.'); } // Proceed with OpenAI call return $this->callOpenAI($messages); } }
Laravel Middleware
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Glitchward\Shield\ShieldClient; class ValidatePrompt { private ShieldClient $shield; public function __construct() { $this->shield = new ShieldClient(config('services.shield.token')); } public function handle(Request $request, Closure $next) { if ($request->has('messages')) { $result = $this->shield->validate($request->input('messages')); if (!$result->isSafe()) { return response()->json([ 'error' => 'Prompt rejected by security filter', 'risk_score' => $result->riskScore, ], 400); } } return $next($request); } }
Batch Validation
Validate multiple prompts efficiently in a single request:
<?php use Glitchward\Shield\ShieldClient; $shield = new ShieldClient('your_api_token'); // Validate up to 100 prompts at once $batchResult = $shield->validateBatch([ ['messages' => [['role' => 'user', 'content' => 'First question']]], ['messages' => [['role' => 'user', 'content' => 'Second question']]], ['messages' => [['role' => 'user', 'content' => 'Third question']]], ]); // Check if all prompts are safe if ($batchResult->allSafe()) { echo "All prompts are safe!\n"; } else { $blocked = $batchResult->getBlockedIndices(); echo "Blocked prompts at indices: " . implode(', ', $blocked) . "\n"; } // Process individual results foreach ($batchResult->results as $i => $result) { echo "Prompt {$i}: safe={$result->safe}, risk={$result->riskScore}\n"; }
Validation Result
The ValidationResult object contains:
| Property | Type | Description |
|---|---|---|
safe |
bool |
Whether the prompt is safe |
blocked |
bool |
Whether the prompt was blocked |
riskScore |
float |
Risk score from 0.0 to 1.0 |
processingTimeMs |
int |
Processing time in milliseconds |
matches |
ValidationMatch[] |
List of detected injection patterns |
Each ValidationMatch contains:
category: Type of injection (e.g., "system_prompt_override", "jailbreak")pattern: The pattern that was matchedseverity: Severity level ("low", "medium", "high", "critical")matchedText: The text that matched (optional)
Error Handling
<?php use Glitchward\Shield\ShieldClient; use Glitchward\Shield\Exceptions\ShieldException; use Glitchward\Shield\Exceptions\ShieldAuthException; use Glitchward\Shield\Exceptions\ShieldRateLimitException; use Glitchward\Shield\Exceptions\ShieldValidationException; $shield = new ShieldClient('your_api_token'); try { $result = $shield->validate($messages); } catch (ShieldAuthException $e) { echo "Invalid API token\n"; } catch (ShieldRateLimitException $e) { echo "Rate limited. Retry after: {$e->getRetryAfter()}s\n"; } catch (ShieldValidationException $e) { echo "Invalid request: {$e->getMessage()}\n"; } catch (ShieldException $e) { echo "API error: {$e->getMessage()}\n"; }
Configuration
<?php use Glitchward\Shield\ShieldClient; // Custom configuration $shield = new ShieldClient( apiToken: 'your_api_token', baseUrl: 'https://custom.endpoint.com/api/shield', // Optional timeout: 30 // Request timeout in seconds );
Environment Variables
GLITCHWARD_SHIELD_TOKEN="your_api_token"
<?php use Glitchward\Shield\ShieldClient; $shield = new ShieldClient(getenv('GLITCHWARD_SHIELD_TOKEN'));
Detection Categories
Shield detects these types of attacks:
- System Prompt Override - Attempts to ignore or override system instructions
- Jailbreak Attempts - DAN prompts, character roleplay exploits
- Data Exfiltration - Attempts to extract system prompts or sensitive data
- Encoding Attacks - Base64, hex, unicode obfuscation
- Invisible Characters - Zero-width chars, control characters
- Code Injection - SQL, shell commands, script injection
Rate Limits
- API Rate Limit: 100 requests per minute
- Batch Size Limit: 100 items per batch request
- Monthly Limit: Based on your plan
Links
License
MIT License - see LICENSE for details.
glitchward/shield 适用场景与选型建议
glitchward/shield 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 0 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 02 月 03 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「security」 「ai」 「machine-learning」 「openai」 「ChatGpt」 「llm」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 glitchward/shield 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 glitchward/shield 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 glitchward/shield 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
PHP 8.0+ OpenAI API client with fully typed/documented requests+responses models, guzzle and symfony/http-client support and async/parallel requests.
Provide a way to secure accesses to all routes of an symfony application.
It's a barebone security class written on PHP
Estimate AI API costs before making expensive calls
A powerful package that seamlessly integrates OpenAI's advanced AI capabilities into your Laravel applications. This package offers quick setup and intuitive configuration to leverage AI models for chat, embeddings, and more.
Simple PHP client for Qdrant vector database. Easy-to-use library for storing, searching, and managing vector embeddings in AI and machine learning applications.
统计信息
- 总下载量: 0
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 39
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-02-03