원클릭으로
llm-patterns
LLM integration patterns — RAG, embeddings, streaming, tool use. Triggers on rag/embeddings/vector/llm/prompt keywords.
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
메뉴
LLM integration patterns — RAG, embeddings, streaming, tool use. Triggers on rag/embeddings/vector/llm/prompt keywords.
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
SOC 직업 분류 기준
When the user wants help with paid advertising campaigns on Google Ads, Meta (Facebook/Instagram), LinkedIn, Twitter/X, or other ad platforms. Also use when the user mentions 'PPC,' 'paid media,' 'ROAS,' 'CPA,' 'ad campaign,' 'retargeting,' 'audience targeting,' 'Google Ads,' 'Facebook ads,' 'LinkedIn ads,' 'ad budget,' 'cost per click,' 'ad spend,' or 'should I run ads.' Use this for campaign strategy, audience targeting, bidding, and optimization. For bulk ad creative generation and iteration, see ad-creative. For landing page optimization, see cro.
Persistent engineering knowledge vault with semantic search. Save decisions, patterns, debug solutions, and insights as Zettelkasten notes in Obsidian with automatic embedding indexing for semantic retrieval. Use this skill whenever the user says "/memo", "запомни это", "сохрани в базу", "save this", "remember this", "добавь в базу знаний", "log this pattern", or any variation of wanting to persist knowledge. Also trigger for "/memo find", "/memo search", "что я решал по X", "find in vault", "search vault", "найди в базе" to search notes — both keyword and semantic. Trigger for "/memo dedup", "/memo stats", "/memo project", "/memo reindex". This is the bridge between Claude Code sessions and long-term engineering memory across all projects.
Use when starting any new task to select the right GSD mode (fast/quick/plan-phase) and the right model tier (Haiku/Sonnet/Opus) for subagents — prevents 5-10× cost overpay on routine work
Pack the whole repo (or a remote one) into one AI-friendly file via Repomix. Use for architectural reviews, cross-repo handoff, full-codebase audits — not for single-file lookups. Triggers on "pack repo", "feed codebase to AI", "снапшот", "analyze remote repo".
花叔Design(Huashu-Design)——用HTML做高保真原型、交互Demo、幻灯片、动画、设计变体探索+设计方向顾问+专家评审的一体化设计能力。HTML是工具不是媒介,根据任务embody不同专家(UX设计师/动画师/幻灯片设计师/原型师),避免web design tropes。触发词:做原型、设计Demo、交互原型、HTML演示、动画Demo、设计变体、hi-fi设计、UI mockup、prototype、设计探索、做个HTML页面、做个可视化、app原型、iOS原型、移动应用mockup、导出MP4、导出GIF、60fps视频、设计风格、设计方向、设计哲学、配色方案、视觉风格、推荐风格、选个风格、做个好看的、评审、好不好看、review this design、带解说的动画、解说视频、概念解释视频、长视频科普、配音动画、voiceover、narration、TTS+动画、5分钟讲清楚什么是XX。**主干能力**:Junior Designer工作流(先给假设+reasoning+placeholder再迭代)、反AI slop清单、React+Babel最佳实践、Tweaks变体切换、Speaker Notes演示、Starter Components(幻灯片外壳/变体画布/动画引擎/设备边框/解说Stage)、App原型专属守则(默认从Wikimedia/Met/Unsplash取真图、每台iPhone包AppPhone状态管理器可交互、交付前跑Playwright点击测试)、Playwright验证、HTML动画→MP4/GIF视频导出(25fps基础 + 60fps插帧 + palette优化GIF + 6首场景化BGM + 自动fade)、**带解说的长动画pipeline**(豆包TTS生人声+实测时长生timeline.json+NarrationStage驱动画面+ducking混音→交付HTML实播+发布MP4双形态;铁律:整片是一个连续的运动叙事,禁PowerPoint切换)。**需求模糊时的Fallback**:设计方向顾问模式——从5流派×20种设计哲学(Pentagram信息建筑/Field.io运动诗学/Kenya Hara东方极简/Sagmeister实验先锋等)推荐3个差异化方向,展示24个预制showcase(8场景×3风格),并行生成3个视觉Demo让用户选
Use BEFORE coding any new feature, MVP, pricing/billing change, launch, or pivot. Acts as a product validation gate for solo founders — validates target user, JTBD, pain intensity, current alternative, success metric, distribution channel, structural advantage vs competitors, unit economics with SaaS-graveyard gate, cheapest experiment, and top risk. RIGID — do not proceed to technical planning until product context is documented in `.planning/product/<slug>.md` or risk is explicitly accepted. Triggers on "build", "ship", "add feature", "MVP", "launch", "pivot", "pricing", "billing", before /plan, /tdd, /gsd-plan-phase, /gsd-discuss-phase, or when user describes a feature without naming a measurable success metric.
| name | LLM Patterns |
| description | LLM integration patterns — RAG, embeddings, streaming, tool use. Triggers on rag/embeddings/vector/llm/prompt keywords. |
Load this skill when working with LLMs, RAG systems, embeddings, or AI integrations.
LLM INTEGRATIONS MUST BE ROBUST AND COST-EFFECTIVE!
| Task | Model | Why |
|---|---|---|
| Complex reasoning | Claude Opus 4.5 / GPT-4 | Best quality |
| General tasks | Claude Sonnet 4.5 / GPT-4o | Balance |
| Simple tasks | Claude Haiku 4.5 / GPT-4o-mini | Fast & cheap |
| Embeddings | text-embedding-3-small | Cost-effective |
| Classification | Fine-tuned small model | Fastest |
Query → Embed Query → Vector Search → Retrieve Chunks → Augment Prompt → LLM → Response
async function ragQuery(query: string): Promise<string> {
// 1. Embed the query
const queryEmbedding = await embedText(query);
// 2. Vector search for relevant chunks
const chunks = await vectorStore.similaritySearch(queryEmbedding, {
topK: 5,
minScore: 0.7,
});
// 3. Build context from chunks
const context = chunks.map((c) => c.content).join('\n\n---\n\n');
// 4. Augment prompt
const prompt = `Answer based on the following context:
Context:
${context}
Question: ${query}
Answer:`;
// 5. Get LLM response
return await llm.complete(prompt);
}
| Document Type | Chunk Size | Overlap |
|---|---|---|
| Dense text (legal, technical) | 256-512 tokens | 50 tokens |
| General content | 512-1024 tokens | 100 tokens |
| Conversational | 1024-2048 tokens | 200 tokens |
// 1. Fixed size chunking
function fixedChunks(text: string, size: number, overlap: number): string[] {
const chunks = [];
for (let i = 0; i < text.length; i += size - overlap) {
chunks.push(text.slice(i, i + size));
}
return chunks;
}
// 2. Semantic chunking (by paragraph/section)
function semanticChunks(text: string): string[] {
return text
.split(/\n\n+/)
.filter((chunk) => chunk.trim().length > 50);
}
// 3. Recursive character splitting (LangChain style)
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 1000,
chunkOverlap: 200,
separators: ['\n\n', '\n', '. ', ' ', ''],
});
// Server (Express)
app.get('/api/chat', async (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
const stream = await anthropic.messages.stream({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{ role: 'user', content: req.query.message }],
});
for await (const event of stream) {
if (event.type === 'content_block_delta') {
res.write(`data: ${JSON.stringify({ text: event.delta.text })}\n\n`);
}
}
res.write('data: [DONE]\n\n');
res.end();
});
// Client
const eventSource = new EventSource('/api/chat?message=Hello');
eventSource.onmessage = (event) => {
if (event.data === '[DONE]') {
eventSource.close();
return;
}
const { text } = JSON.parse(event.data);
appendToOutput(text);
};
// Server
ws.on('message', async (data) => {
const { message } = JSON.parse(data);
const stream = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: message }],
stream: true,
});
for await (const chunk of stream) {
const text = chunk.choices[0]?.delta?.content || '';
ws.send(JSON.stringify({ type: 'chunk', text }));
}
ws.send(JSON.stringify({ type: 'done' }));
});
import { encoding_for_model } from 'tiktoken';
function countTokens(text: string, model = 'gpt-4'): number {
const enc = encoding_for_model(model);
return enc.encode(text).length;
}
function trimContext(messages: Message[], maxTokens: number): Message[] {
let totalTokens = 0;
const trimmed = [];
// Always keep system message
const systemMsg = messages.find((m) => m.role === 'system');
if (systemMsg) {
totalTokens += countTokens(systemMsg.content);
trimmed.push(systemMsg);
}
// Add messages from most recent
for (const msg of messages.reverse()) {
if (msg.role === 'system') continue;
const tokens = countTokens(msg.content);
if (totalTokens + tokens > maxTokens) break;
totalTokens += tokens;
trimmed.unshift(msg);
}
return trimmed;
}
const tools = [
{
name: 'get_weather',
description: 'Get current weather for a location',
input_schema: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'City name, e.g., "San Francisco, CA"',
},
},
required: ['location'],
},
},
];
const response = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
tools,
messages: [{ role: 'user', content: 'What is the weather in Tokyo?' }],
});
// Handle tool use
if (response.stop_reason === 'tool_use') {
const toolUse = response.content.find((c) => c.type === 'tool_use');
const result = await executeTools(toolUse.name, toolUse.input);
// Continue conversation with tool result
const finalResponse = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
tools,
messages: [
{ role: 'user', content: 'What is the weather in Tokyo?' },
{ role: 'assistant', content: response.content },
{ role: 'user', content: [{ type: 'tool_result', tool_use_id: toolUse.id, content: result }] },
],
});
}
async function llmWithRetry<T>(
fn: () => Promise<T>,
maxRetries = 3
): Promise<T> {
let lastError: Error;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error;
if (error.status === 429) {
// Rate limit - exponential backoff
const delay = Math.min(1000 * Math.pow(2, attempt), 30000);
await sleep(delay);
continue;
}
if (error.status >= 500) {
// Server error - retry
await sleep(1000 * attempt);
continue;
}
// Client error - don't retry
throw error;
}
}
throw lastError;
}
| Code | Meaning | Action |
|---|---|---|
| 400 | Bad request | Fix prompt/parameters |
| 401 | Invalid API key | Check credentials |
| 429 | Rate limited | Backoff and retry |
| 500 | Server error | Retry with backoff |
| 529 | Overloaded | Retry with longer backoff |
const systemPrompt = `You are a helpful assistant that answers questions based on the provided context.
Rules:
1. Only use information from the context
2. If the answer is not in the context, say "I don't have information about that"
3. Be concise but complete
4. Cite relevant parts of the context`;
const response = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [
{
role: 'user',
content: `Extract entities from this text and return as JSON:
Text: "John Smith, CEO of Acme Corp, announced the merger on January 15, 2024."
Return format:
{
"people": [{"name": string, "role": string}],
"organizations": [string],
"dates": [string]
}`,
},
],
});
| Model | Input (1M tokens) | Output (1M tokens) |
|---|---|---|
| GPT-4o | $2.50 | $10.00 |
| GPT-4o-mini | $0.15 | $0.60 |
| Claude Sonnet 4.5 | $3.00 | $15.00 |
| Claude Haiku 4.5 | $0.25 | $1.25 |
function estimateCost(inputTokens: number, outputTokens: number, model: string): number {
const pricing = {
'gpt-4o': { input: 0.0000025, output: 0.00001 },
'claude-sonnet-4-5': { input: 0.000003, output: 0.000015 },
};
const p = pricing[model];
return inputTokens * p.input + outputTokens * p.output;
}