ai-agent-patterns
- Repo stars 0
- Author updated Live
- Author repo skills-registry
- Domain
- AI
- Compatible agents
-
- Claude Code
- Cursor
- Cline
- Codex
- Windsurf
- Gemini CLI
- +20
- Trust score
- 88 / 100 · community maintained
- Author / version / license
- @tomevault-io · no license declared
- Token usage
- Lean
- Setup complexity
- Manual integration
- External API key
- Not required
- Operating systems
- Docker
- Runtime requirements
- Docker
- Permissions
-
- Read-only
- Write / modify
- Network behavior
- Local-only
- Install commands
- 26 variants
Profile is derived at build time from SKILL.md and install vectors. Subject to drift from author intent.
Heads up: 未限定 allowed-tools,默认拥有全部工具权限。
---
name: ai-agent-patterns
description: >- Use when this capability is needed. Use search-docs for detailed Laravel AI SDK documentation…
category: ai
runtime: Docker
---
# ai-agent-patterns output preview
## PART A: Task fit
- Use case: >- Use when this capability is needed. 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. runs entirely locally; runs on Docker. Works with Claude C….
- Inputs: target material, constraints, expected output, and acceptance criteria.
- Evidence boundary: follow “When to Apply / Documentation / Agent Anatomy” and do not present inference as author intent.
## PART B: Execution result
- **01** The card summarizes the use case; runtime output centers on “>- Use when this capability is needed. 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. runs entirely locally; runs on Docker. Works with Claude C…”.
- **02** When the source has headings, the agent prioritizes “When to Apply / Documentation / Agent Anatomy” so the result follows the author’s structure.
- **03** Typical output includes task judgment, concrete steps, required commands or file edits, validation, and follow-up options.
- **04** Risk context follows the fingerprint: read files, write/modify files; mostly runs locally; usually needs no extra API key.
## Running Rules
- read files, write/modify files; mostly runs locally; usually needs no extra API key.
- Validate with a small sample before expanding scope.
- Return the result, validation criteria, and next iteration options. The source does not require a stable slash command. After installation, invoke the skill by name and describe the task.
Name target files or source material, expected output, forbidden changes, and whether network or shell access is allowed. Permission fingerprint: read files, write/modify files.
Start with a small task and check whether the result follows “When to Apply / Documentation / Agent Anatomy”. Inspect diffs, logs, previews, or tests before expanding scope.
Confirm the final output includes a concrete result, evidence, and next action. If it stays generic, tighten inputs, boundaries, and acceptance criteria.
---
name: ai-agent-patterns
description: >- Use when this capability is needed. Use search-docs for detailed Laravel AI SDK documentation…
category: ai
source: tomevault-io/skills-registry
---
# ai-agent-patterns
## When to use
- >- Use when this capability is needed. Use search-docs for detailed Laravel AI SDK documentation before making changes…
- Use it when the task has clear inputs, repeatable steps, and validation criteria.
## What to provide
- Target material, scope, expected result, and forbidden changes.
- Whether network, commands, file writes, or external services are allowed.
## Execution rules
- Organize steps around “When to Apply / Documentation / Agent Anatomy” and keep inference separate from source facts.
- read files, write/modify files; mostly runs locally; usually needs no extra API key.
- Validate with a small sample before expanding the task.
## Output requirements
- Return the deliverable, key evidence, validation method, and next action.
- Mark missing information as unknown; do not invent commands, platforms, or dependencies. The author source anchors workflow facts; repository files anchor sources and commands; Fluxly only adds fit, limitations, and quality judgment.
skill "ai-agent-patterns" {
input -> user goal + target files + boundaries + acceptance criteria
context -> When to Apply / Documentation / Agent Anatomy
rules -> SKILL.md triggers / order / output contract
runtime -> Docker | read files, write/modify files | mostly runs locally
guardrails -> usually needs no extra API key + small-sample validation + diff/log review
output -> copyable result + checklist + next iteration
} AI Agent Patterns
When to Apply
- Creating a new agent class in
app/Ai/Agents/ - Modifying
AgentResolveraction or prompt mappings - Writing tests for agents (
::fake(),::assertPrompted()) - Working with SSE streaming in
AdminArticleAiController - Adding or changing apply block formats (
:::apply-body,:::apply-excerpt) - Debugging agent responses, conversation linking, or temperature behavior
Documentation
Use search-docs for detailed Laravel AI SDK documentation before making changes.
Agent Anatomy
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.
Content Generation Patterns
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 fromconfig('humanizer.banned_phrases'), sentence variety rules)applyBlockInstructions()— Returns formatting rules for apply blocks
Apply blocks tell the frontend to auto-apply content back to the article editor:
Improved Heading
The 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 Routing
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 (alwaysArticleRefiner)forSelectionChat(array $context)— Freeform instruction on selected text (alwaysArticleRefiner)
To add a new agent:
- Create the class in
app/Ai/Agents/implementingAgent, Conversational - Use
HasArticleContext,Promptable,RemembersConversationstraits - Add to
ACTION_AGENTSand/orINLINE_AGENTSinAgentResolver - Add a prompt template to
ACTION_PROMPTSand/orINLINE_PROMPTS - Update
validActions()orvalidInlineActions()if adding new action names
return 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;
}
Streaming & Conversation
The controller uses two streaming methods depending on whether conversations should persist.
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):
- New conversation:
$agent->forUser($user)→ starts fresh - Resume:
$agent->continue($conversationId, as: $user)→ resumes existing - After streaming:
$agent->currentConversation()→ get conversation ID - Link to article: Update
agent_conversations.article_idvia.then()callback on the streamable - Conversations stored in
agent_conversations+agent_conversation_messagestables (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]);
}
});
Testing
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 tests- Conversation history tests must seed
agent_conversationsandagent_conversation_messagestables directly with all required JSON columns (attachments, tool_calls as empty arrays/objects)
Common Pitfalls
- Thinking-capable models crash the SDK: Avoid models like
qwen3that emitThinkingCompleteEvent— the Laravel AI SDK doesn't handle it and throws an unrecoverable exception. Stick tollama3.2:3bor similar non-thinking models. - Ollama, not OpenAI: Agents use
#[Model('llama3.2:3b')]which runs on the Ollama Docker service. Don't confuse this with the globalconfig('ai.default_provider')which is for different use cases. The model attribute is the Ollama model name. - Temperature mismatches: Using high temperature (0.8) for grammar checking produces inconsistent corrections. Using low temperature (0.3) for content generation produces flat, repetitive output. Match temperature to task precision — see the spectrum table above.
- Missing context fields cause silent failures: The context array has 5 fields (
title,body,excerpt,content_type,category). Thebodyfield 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'] ?? ''. - Forgetting to register in AgentResolver: Creating a new agent class without adding it to
ACTION_AGENTSorINLINE_AGENTSinAgentResolvermeans it's unreachable from the controller. Also add a prompt template toACTION_PROMPTS/INLINE_PROMPTSand updatevalidActions()/validInlineActions().
Source: ABilenduke/copilot-developer — distributed by TomeVault.
Decide Fit First
Design Intent
How To Use It
Boundaries And Review