用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/tomevault-io/skills-registry --skill ai-agent-patterns命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
基于 SOC 职业分类
正在显示 SKILL.md
| name | ai-agent-patterns |
| description | >- Use when this capability is needed. |
app/Ai/Agents/AgentResolver action or prompt mappings::fake(), ::assertPrompted())AdminArticleAiController:::apply-body, :::apply-excerpt)Use search-docs for detailed Laravel AI SDK documentation before making changes.
Every agent implements Agent & Conversational (intersection type), uses three traits, and is configured via PHP attributes. All agents run on Ollama (Docker service), not OpenAI.
use App\Ai\Agents\Concerns\HasArticleContext; use Laravel\Ai\Attributes\MaxTokens; use Laravel\Ai\Attributes\Model; use Laravel\Ai\Attributes\Temperature; use Laravel\Ai\Attributes\Timeout; use Laravel\Ai\Concerns\RemembersConversations; use Laravel\Ai\Contracts\Agent; use Laravel\Ai\Contracts\Conversational; use Stringable;
#[Model('llama3.2:3b')] // Ollama model — NOT OpenAI #[Temperature(0.6)] // 0.3 (precise) to 0.8 (creative) #[MaxTokens(4096)] // Fixed for all agents #[Timeout(120)] // Fixed for all agents class ArticleRefiner implements Agent, Conversational { use HasArticleContext, Promptable, RemembersConversations;
public function instructions(): Stringable|string
{
return <<<INSTRUCTIONS
You are an expert content editor...
{$this->articleContextBlock()}
{$this->applyBlockInstructions()}
INSTRUCTIONS;
}
}
Temperature spectrum — choose based on the agent's task precision:
| Temperature | Agent | Rationale |
|---|---|---|
| 0.3 | GrammarChecker | Deterministic corrections, no creativity needed |
| 0.4 | Proofreader | Slight variation in feedback phrasing |
| 0.5 | SeoOptimizer | Balanced analysis with structured output |
| 0.6 | ArticleRefiner | Creative improvement while preserving voice |
| 0.8 | ArticleGenerator | Maximum creativity for original content |
Non-conversational agents: HumanizerAgent implements only Agent (NOT Conversational) because it processes text in a single pass without conversation memory. It does NOT use HasArticleContext — it has its own constructor signature.
The HasArticleContext trait provides the constructor, context accessors, and prompt-building methods shared by all conversational agents.
protected function contextTitle(): string { return $this->context['title'] ?? ''; }
protected function contextBody(): string { return $this->context['body'] ?? ''; }
protected function contextExcerpt(): string { return $this->context['excerpt'] ?? ''; }
protected function contextContentType(): string { return $this->context['content_type'] ?? ''; }
protected function contextCategory(): string { return $this->context['category'] ?? ''; }
protected function estimateWordCount(string $body): int { return str_word_count(strip_tags($body)); }
}
Prompt-building methods (called in instructions()):
articleContextBlock() — Returns article metadata (title, type, category, word count) + writing quality standards (banned phrases from config('humanizer.banned_phrases'), sentence variety rules)applyBlockInstructions() — Returns formatting rules for apply blocksApply blocks tell the frontend to auto-apply content back to the article editor:
// For replacing article body: :::apply-bodyThe revised content goes here...
:::// For replacing article excerpt: :::apply-excerpt A compelling 1-2 sentence summary under 160 characters. :::
When to use apply blocks: Only when the agent generates or rewrites replacement content. For feedback, suggestions, and analysis, agents respond in plain markdown without apply blocks. This distinction is enforced in each agent's instructions() prompt.
AgentResolver is the single routing layer between HTTP endpoints and agent classes. All agent instantiation goes through it — never new Agent() directly.
protected const INLINE_AGENTS = [
'proofread' => Proofreader::class,
'grammar' => GrammarChecker::class,
];
// Each constant also has matching prompt templates:
// ACTION_PROMPTS and INLINE_PROMPTS
}
Factory methods — all return Agent&Conversational intersection type:
forAction(string $action, array $context) — Quick actions (proofread, grammar, generate, refine, seo, excerpt)forInlineReview(string $action, array $context) — Inline editor actions (proofread, grammar only)forChat(array $context) — Conversational chat (always ArticleRefiner)forSelectionChat(array $context) — Freeform instruction on selected text (always ArticleRefiner)To add a new agent:
app/Ai/Agents/ implementing Agent, ConversationalHasArticleContext, Promptable, RemembersConversations traitsACTION_AGENTS and/or INLINE_AGENTS in AgentResolverACTION_PROMPTS and/or INLINE_PROMPTSvalidActions() or validInlineActions() if adding new action namesreturn new $class($context);
}
// Prompt includes body context appended to the template public static function actionPrompt(string $action, array $context): string { $prompt = self::ACTION_PROMPTS[$action];
if ($action === 'generate') {
$prompt .= "\n\nArticle body to base generation on:\n".substr(strip_tags($context['body'] ?? ''), 0, 500);
} elseif (in_array($action, ['proofread', 'grammar', 'seo', 'refine'])) {
$prompt .= "\n\nArticle body:\n".($context['body'] ?? '');
} elseif ($action === 'excerpt') {
$prompt .= "\n\nArticle body:\n".substr(strip_tags($context['body'] ?? ''), 0, 2000);
}
return $prompt;
}
The controller uses two streaming methods depending on whether conversations should persist.
// AdminArticleAiController::streamDirect() private function streamDirect(Agent&Conversational $agent, string $prompt, User $user): StreamedResponse { $agent->forUser($user); $streamable = $agent->stream($prompt);return response()->stream(function () use ($streamable) {
try {
foreach ($streamable as $event) {
echo 'data: '.((string) $event)."\n\n";
if (ob_get_level() > 0) { ob_flush(); }
flush();
}
} catch (\Throwable $e) {
echo 'data: '.json_encode(['type' => 'error', 'message' => $e->getMessage()])."\n\n";
flush();
report($e);
}
echo "data: [DONE]\n\n";
flush();
}, 200, [
'Content-Type' => 'text/event-stream',
'X-Accel-Buffering' => 'no',
'Cache-Control' => 'no-cache',
'Connection' => 'keep-alive',
]);
}
Conversation linking (for chat, not inline actions):
$agent->forUser($user) → starts fresh$agent->continue($conversationId, as: $user) → resumes existing$agent->currentConversation() → get conversation IDagent_conversations.article_id via .then() callback on the streamableagent_conversations + agent_conversation_messages tables (UUID PKs)Generate action is special: Dispatches ProcessArticle job instead of streaming. Returns 202 Accepted with JSON. The job runs generation server-side, humanizes via TextHumanizer, and broadcasts progress via Reverb.
$streamable = $agent->stream($prompt); $articleId = $validated['article_id'] ?? null;
$streamable->then(function () use ($agent, $articleId) { $conversationId = $agent->currentConversation();
if ($conversationId && $articleId) {
DB::table('agent_conversations')
->where('id', $conversationId)
->whereNull('article_id')
->update(['article_id' => $articleId]);
}
});
Each agent class has its own ::fake() and ::assertPrompted() static methods provided by the Laravel AI SDK. Always fake the specific agent class, not a generic mock.
// Helper function for valid context (reuse across tests) function validContext(): array { return [ 'title' => 'Test Article', 'body' => '
Test article body with enough content.
', 'excerpt' => 'A test excerpt', 'content_type' => 'general', 'category' => 'Technology', ]; }// Fake an agent with a canned response test('chat endpoint streams response', function () { $admin = User::factory()->admin()->create(); ArticleRefiner::fake(['Improved content here']);
$this->actingAs($admin)
->postJson('/admin/articles/ai/chat', [
'message' => 'Improve this article',
'context' => validContext(),
])->assertOk();
ArticleRefiner::assertPrompted('Improve this article');
});
// Fake an agent for quick actions test('action endpoint resolves correct agent', function () { $admin = User::factory()->admin()->create(); Proofreader::fake(['Feedback here']);
$this->actingAs($admin)
->postJson('/admin/articles/ai/action', [
'action' => 'proofread',
'context' => validContext(),
])->assertOk();
Proofreader::assertPrompted(fn ($prompt) =>
str_contains($prompt->prompt, 'Review the current article')
);
});
// Generate action uses Queue::fake() instead test('generate action dispatches job', function () { Queue::fake(); $admin = User::factory()->admin()->create(); $article = Article::factory()->create();
$this->actingAs($admin)
->postJson('/admin/articles/ai/action', [
'action' => 'generate',
'article_id' => $article->id,
'context' => validContext(),
])->assertAccepted();
Queue::assertPushed(ProcessArticle::class);
});
Key testing patterns:
AgentName::fake(['response text']) — Synchronous fake with canned responseAgentName::fake() — Empty response fake (for validation tests)AgentName::assertPrompted('substring') — Assert the prompt contained textAgentName::assertPrompted(fn ($prompt) => ...) — Assert with closure for complex matchingQueue::fake() + Queue::assertPushed(ProcessArticle::class) — For the generate action$this->withoutMiddleware(ValidateCsrfToken::class) — For JSON API testsagent_conversations and agent_conversation_messages tables directly with all required JSON columns (attachments, tool_calls as empty arrays/objects)qwen3 that emit ThinkingCompleteEvent — the Laravel AI SDK doesn't handle it and throws an unrecoverable exception. Stick to llama3.2:3b or similar non-thinking models.#[Model('llama3.2:3b')] which runs on the Ollama Docker service. Don't confuse this with the global config('ai.default_provider') which is for different use cases. The model attribute is the Ollama model name.title, body, excerpt, content_type, category). The body field uses ['present', 'nullable'] validation — it must be present in the request even if null. Controllers coerce null to empty string: $validated['context']['body'] = $validated['context']['body'] ?? ''.ACTION_AGENTS or INLINE_AGENTS in AgentResolver means it's unreachable from the controller. Also add a prompt template to ACTION_PROMPTS/INLINE_PROMPTS and update validActions()/validInlineActions().Source: ABilenduke/copilot-developer — distributed by TomeVault.