Agent助手
- 作者仓库星标 0
- 作者更新于 实时读取
- 作者仓库 skills-registry
- 领域
- AI 智能
- 兼容 Agent
-
- Claude Code
- Cursor
- Cline
- Codex
- Windsurf
- Gemini CLI
- +20
- 信任分
- 88 / 100 · 社区维护
- 作者 / 版本 / 许可
- @tomevault-io · 未声明 license
- Token 消耗评级
- 低消耗
- 接入复杂程度
- 需手动接入
- 是否需要外部 API Key
- 不需要
- 兼容的系统
- Docker
- 底层运行要求
- Docker
- 文件与系统权限
-
- 只读
- 允许写入 / 修改
- 网络行为
- 仅限本地
- 安装命令数
- 26 条
档案由构建时根据 SKILL.md 与安装命令自动衍生,可能与作者实际意图存在差异。
需要注意: 未限定 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 输出预览
## PART A: 任务判断
- 适用问题:提示词、Agent 工作流、模型评估或自动化推理。
- 输入要求:目标材料、限制条件、期望输出和验收方式。
- 证据边界:围绕“When to Apply / Documentation / Agent Anatomy”读取原文规则,不把推断写成作者承诺。
## PART B: 执行结果
- **01** 任务判断:确认你的需求是否属于提示词、Agent 工作流、模型评估或自动化推理,并标出输入、限制和预期结果。
- **02** 执行计划:优先按“When to Apply / Documentation / Agent Anatomy”拆成步骤,说明每一步会读取什么、修改什么、产出什么。
- **03** 交付结果:给出可复制的命令、文件改动、检查清单或内容草稿,并说明如何继续迭代。
- **04** 风险边界:结合 读取文件、写入/修改文件、主要在本地完成、通常不需要额外 API Key 给出执行前确认项。
## Running Rules
- 读取文件、写入/修改文件;主要在本地完成;通常不需要额外 API Key。
- 先小样例验证,再放大到真实任务。
- 交付时同时给结果、检查口径和下一步迭代建议。 原文没有稳定的斜杠命令要求。安装验证后通常全局生效,直接在对话里点名这个 Skill 并描述任务即可。
告诉 Agent 目标文件或材料、期望结果、不可改范围、是否允许联网或执行命令。本 Skill 的权限画像是:读取文件、写入/修改文件。
先用一个小任务确认它会围绕“When to Apply / Documentation / Agent Anatomy”工作;涉及文件或命令时,先看 diff、日志、预览或测试结果。
检查最终产物是否包含明确结果、必要证据和下一步动作;如果输出泛泛而谈,就补充输入、边界和验收标准后重跑。
---
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
## 什么时候使用
- 把 AI / Agent方向的常用动作沉淀成 Agent 可调用的技能 适合处理AI Agent、提示词、模型评估与自动化推理,核心价值是把输入、判断、执行、验证和交付边界固定下来,避免 Agent 泛泛回答。 把任务拆成可执行、可检查…
- 面向提示词、Agent 工作流、模型评估或自动化推理,优先处理能明确输入、步骤和验收标准的工作。
## 需要提供什么
- 目标材料、目录范围、期望结果和不可改动内容。
- 是否允许联网、执行命令、读写文件或调用外部服务。
## 执行规则
- 围绕「When to Apply / Documentation / Agent Anatomy」组织步骤,不把推断写成作者事实。
- 读取文件、写入/修改文件;主要在本地完成;通常不需要额外 API Key。
- 先跑小样例,确认结果可检查后再扩大任务范围。
## 输出要求
- 给出最终产物、关键证据、验证方式和下一步动作。
- 信息不足时标记 unknown,不编造命令、平台或依赖。 作者原文负责流程事实;仓库文件负责来源和命令;流狐只补充适用场景、限制和质量判断。
skill "ai-agent-patterns" {
输入层 -> 用户目标 + 目标文件 + 禁止范围 + 验收标准
上下文层 -> When to Apply / Documentation / Agent Anatomy
规则层 -> SKILL.md 触发条件 / 执行顺序 / 输出格式
运行层 -> Docker | 读取文件、写入/修改文件 | 主要在本地完成
安全层 -> 通常不需要额外 API Key + 小任务验证 + diff / 日志复核
输出层 -> 可复制结果 + 检查清单 + 下一步迭代
} 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.
先判断是否适合
作者设计意图
作者的方法与取舍
边界和复核