[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6CTC2CE8Q5QMAW8CMY0YY6C":3,"skill-same:01M6CTC2CE8Q5QMAW8CMY0YY6C":67},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":28,"linkOnly":29,"markdownContent":30,"markdownBody":31,"frontMatter":32,"refName":35,"commitSha":36,"skillDirectory":37,"forksCount":38,"repositoryHtmlUrl":39,"repositoryHomepageUrl":6,"ownerHtmlUrl":40,"ownerBlogUrl":6,"ownerDescription":41,"updatedAt":42,"install":43,"resources":56},"01M6CTC2CE8Q5QMAW8CMY0YY6C","ai-engineering",null,"Designs AI features: LLM integration, retrieval-augmented generation (RAG) over your own data, prompts, and AI cost control. Use when building a feature that calls an AI model.","vibbs\u002Fcompany-os","vibbs","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F7379149?v=4","01M6CT6M03CAS1H7RA89F3965B","Vibbs Dod","01M6CT6M4MY60C9FFQ3AAR2RSK",6,"MIT","https:\u002F\u002Fgithub.com\u002Fvibbs\u002Fcompany-os\u002Fblob\u002Fmain\u002Fos\u002Fskills\u002Fai-engineering\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27],"ai engineering","engineering","rag","integration","data","model","use","prompts","cost","2026-11-10 10:12:30",false,"---\nname: ai-engineering\ndescription: \"Designs AI features: LLM integration, retrieval-augmented generation (RAG) over your own data, prompts, and AI cost control. Use when building a feature that calls an AI model.\"\nruntimes:\n  claude:\n    user-invocable: false\n---\n\n# AI Engineering\n\n## Reference\n- **ID**: S-ENG-13\n- **Category**: Engineering\n- **Inputs**: approved PRD, company.config.yaml (ai.* section), existing RFCs, standards\u002Fengineering\u002Fai-patterns.md\n- **Outputs**: AI architecture section → artifacts\u002Frfcs\u002F (as section within RFC)\n- **Used by**: Engineering Agent (Staff Engineer level — not delegated to sub-agents)\n- **Tool scripts**: .\u002Ftools\u002Fartifact\u002Fvalidate.sh\n\n## Purpose\n\nDesign the AI\u002FML architecture for features that involve language models, retrieval-augmented generation, agent systems, or other AI components. This skill produces the AI-specific section of an RFC, covering model selection, integration patterns, prompt engineering, cost modeling, evaluation strategy, and ethical safeguards.\n\nAI architecture is a cross-cutting concern that affects backend (API design, data pipelines), frontend (streaming UX, latency handling), and infrastructure (model hosting, vector databases, cost management). The Staff Engineer owns this skill directly rather than delegating to a sub-agent, ensuring architectural coherence across all domains.\n\n## When to Use\n\n- PRD or feature involves LLM integration (chat, summarization, classification, generation)\n- Feature requires retrieval-augmented generation (RAG) with a knowledge base\n- Building an agent system with tool use, multi-step reasoning, or orchestration\n- Feature involves embeddings, semantic search, or vector databases\n- Prompt engineering or structured output design is needed\n- AI cost estimation or optimization is required for budgeting\n- Feature needs AI safety review (guardrails, bias assessment, PII handling)\n\n## AI Engineering Procedure\n\n### Step 1: Load Context\n\nBefore designing any AI architecture:\n\n1. **Read `company.config.yaml`** — extract `ai.*` section (llm_provider, llm_model, embedding_provider, vector_db, guardrails, cost_budget_monthly)\n2. **Read the PRD** — identify all AI-related acceptance criteria and user-facing AI behaviors\n3. **Read existing RFCs** in `artifacts\u002Frfcs\u002F` — check for prior AI architecture decisions, existing model integrations, or shared AI infrastructure\n4. **Read `standards\u002Fengineering\u002Fai-patterns.md`** — load reference patterns for LLM integration, RAG, cost optimization, and safety\n5. **Check tech stack compatibility** — verify that the configured database, queue, and hosting can support the AI workload (e.g., pgvector requires PostgreSQL, streaming requires WebSocket or SSE support)\n\n### Step 2: Classify AI Pattern\n\nDetermine which AI pattern(s) the feature requires. A feature may combine multiple patterns.\n\n| Pattern | Description | Key Concerns |\n|---------|-------------|--------------|\n| **LLM API Call** | Direct call to a language model API (chat, completion, classification) | Latency, cost, fallback, streaming |\n| **RAG Pipeline** | Retrieval-augmented generation with external knowledge | Chunking, embedding, retrieval quality, freshness |\n| **Agent System** | Multi-step reasoning with tool use and orchestration | State management, tool design, loop control, cost caps |\n| **Fine-tuning** | Custom model training on domain-specific data | Data pipeline, evaluation, versioning, cost |\n| **Computer Vision** | Image\u002Fvideo analysis, OCR, visual understanding | Multimodal models, preprocessing, latency |\n| **Recommendation** | Personalized content or action suggestions | Embedding similarity, feedback loops, cold start |\n\nDocument which patterns apply and why. If the pattern is unclear, default to the simplest option (LLM API Call) and note the uncertainty.\n\n### Step 3: Design AI Architecture\n\nFor each classified pattern, produce the architecture design following these guidelines.\n\n#### LLM Integration\n\n1. **API Wrapper Design** — define the abstraction layer between your application and the LLM provider\n   - Provider-agnostic interface (swap Anthropic\u002FOpenAI\u002FGoogle without code changes)\n   - Request\u002Fresponse types with structured validation\n   - Configuration: model name, temperature, max tokens, stop sequences\n2. **Streaming vs Batch** — determine the delivery mode\n   - Streaming (SSE\u002FWebSocket): use for user-facing generation where perceived latency matters\n   - Batch: use for background processing, classification, or bulk operations\n   - Hybrid: stream to user, batch for internal processing\n3. **Fallback Chains** — define behavior when the primary model fails\n   - Primary model → fallback model → cached response → graceful error\n   - Timeout thresholds per model tier (e.g., 30s for opus, 15s for sonnet, 5s for haiku)\n   - Circuit breaker pattern for sustained failures\n4. **Model Routing** — select the right model for the task\n   - Simple tasks (classification, extraction) → smaller\u002Ffaster model\n   - Complex tasks (reasoning, generation) → larger model\n   - Route based on: task complexity, latency requirement, cost sensitivity\n\n#### RAG Pipeline\n\n1. **Chunking Strategy** — how to split source documents\n   - Chunk size: 512-1024 tokens for most use cases; smaller for precise retrieval, larger for context-heavy\n   - Overlap: 10-20% overlap between chunks to preserve context boundaries\n   - Strategy: semantic chunking (by heading\u002Fparagraph) preferred over fixed-size\n2. **Embedding Model Selection** — choose based on configured `ai.embedding_provider`\n   - Define embedding dimensions and distance metric (cosine similarity standard)\n   - Plan for embedding model upgrades (versioned embedding collections)\n3. **Vector Database Schema** — design based on configured `ai.vector_db`\n   - Collection\u002Findex design: namespace by tenant (if multi-tenant), partition by document type\n   - Metadata schema: source_id, chunk_index, created_at, tenant_id, document_type\n   - Index configuration: HNSW parameters, quantization if needed\n4. **Retrieval and Re-ranking** — define the retrieval pipeline\n   - Initial retrieval: top-K (typically K=10-20) from vector search\n   - Re-ranking: cross-encoder or LLM-based re-ranking for top results\n   - Hybrid search: combine vector similarity with keyword search (BM25) when available\n   - Context window assembly: order chunks, deduplicate, fit within token budget\n\n#### Agent Systems\n\n1. **Tool Design** — define the tools the agent can use\n   - Each tool: name, description, input schema (JSON Schema), output format\n   - Tool categories: read-only (safe to retry) vs write (idempotent or not)\n   - Error handling: tool failure should not crash the agent loop\n2. **Orchestration Patterns** — define how the agent operates\n   - Single-turn: one tool call per request (simplest)\n   - Multi-turn: iterative tool use with intermediate reasoning (ReAct pattern)\n   - Multi-agent: specialized agents coordinated by an orchestrator\n3. **State Management** — define how agent state is tracked\n   - Conversation history: full vs windowed vs summarized\n   - Tool call history: log all calls for debugging and audit\n   - Checkpointing: save state at key decision points for recovery\n4. **Safety Controls** — prevent runaway agent behavior\n   - Maximum iterations per request (hard cap)\n   - Maximum total tokens per request (cost cap)\n   - Human-in-the-loop for destructive actions\n   - Timeout per agent execution\n\n### Step 4: Prompt Engineering\n\nDesign the prompt architecture for each AI interaction.\n\n1. **System Prompt Design**\n   - Define the role, capabilities, and constraints\n   - Include output format specification (especially for structured outputs)\n   - Specify what the model should NOT do (negative constraints)\n   - Keep system prompts version-controlled and testable\n2. **Few-Shot Examples**\n   - Include 2-5 representative examples for classification or extraction tasks\n   - Examples should cover: typical case, edge case, and negative case\n   - Store examples alongside prompt templates for easy iteration\n3. **Chain-of-Thought**\n   - Use for complex reasoning tasks (multi-step math, logic, analysis)\n   - Request explicit reasoning before the final answer\n   - Consider whether reasoning should be visible to end users or hidden\n4. **Structured Outputs**\n   - Define JSON Schema for all machine-consumed outputs\n   - Use constrained generation when available (tool_use, response_format)\n   - Validate outputs against schema before processing downstream\n   - Define fallback behavior for malformed outputs\n\n### Step 5: Cost Model\n\nEstimate and plan for AI operational costs.\n\n1. **Token Estimation Per Request**\n   - Input tokens: system prompt + user input + context (RAG chunks, history)\n   - Output tokens: expected response length (cap with max_tokens)\n   - Calculate per-request cost at current provider pricing\n2. **Monthly Budget Projection**\n   - Estimate requests per day\u002Fmonth based on expected usage patterns\n   - Multiply by per-request cost for baseline monthly spend\n   - Add buffer (2-3x) for growth and retries\n   - Compare against `ai.cost_budget_monthly` from config\n3. **Cost Optimization Strategies**\n   - **Semantic caching**: cache responses for semantically similar inputs (embedding similarity > threshold)\n   - **Model tier routing**: route simple tasks to cheaper models, reserve expensive models for complex tasks\n   - **Batching**: group multiple small requests into batch API calls where latency allows\n   - **Prompt optimization**: minimize system prompt tokens, compress context, use efficient few-shot formats\n   - **Token budgets**: set per-request and per-user token limits to prevent cost spikes\n   - **Response caching**: cache deterministic outputs (classification, extraction) with TTL\n\n### Step 6: Evaluation Plan\n\nDefine how to measure AI feature quality.\n\n1. **Accuracy Metrics**\n   - Define task-specific metrics: precision\u002Frecall (classification), BLEU\u002FROUGE (generation), MRR\u002FnDCG (retrieval)\n   - Establish baseline from manual evaluation or existing system\n   - Set target thresholds for production readiness\n2. **Latency SLOs**\n   - Define acceptable latency for each AI operation (p50, p95, p99)\n   - Streaming: time to first token (TTFT) and tokens per second (TPS)\n   - End-to-end: total request time including retrieval, generation, and post-processing\n3. **Regression Testing**\n   - Build an evaluation dataset (golden set) of input-output pairs\n   - Run regression tests on prompt changes, model upgrades, or pipeline modifications\n   - Automate evaluation in CI where possible (deterministic checks first, LLM-as-judge for subjective quality)\n4. **A\u002FB Testing**\n   - Define the experiment: which AI variation to test (model, prompt, retrieval strategy)\n   - Define the success metric: user satisfaction, task completion, accuracy\n   - Plan the rollout: feature flag with percentage-based allocation\n\n### Eval Framework Selection\n\nRecommend an eval framework based on the AI architecture:\n- **PromptFoo**: Best for prompt engineering and LLM output evaluation (Claude, GPT). Supports assertions, model comparison, red teaming.\n- **RAGAS**: Best for RAG pipeline evaluation. Measures faithfulness, relevance, context recall.\n- **Custom evals via batch API**: For domain-specific evaluation. Use Anthropic's batch API for cost-efficient bulk evaluation runs.\n- **DeepEval**: General-purpose LLM evaluation with built-in metrics.\n\nFor all approaches: define eval datasets early, run evals in CI, track scores over time.\n\n### Step 7: Ethical AI Checklist\n\nAssess and mitigate AI-specific risks.\n\n1. **Prompt Injection Protection**\n   - Input validation: sanitize user inputs before including in prompts\n   - System\u002Fuser message separation: never concatenate user input into system prompts\n   - Output validation: verify outputs match expected format and constraints\n   - Indirect injection: assess risk from RAG content containing adversarial instructions\n2. **Content Filtering**\n   - Define output filtering rules: no harmful content, no PII generation, no hallucinated citations\n   - Implement pre-response filtering (keyword blocklist, classifier, or LLM-based filter)\n   - Configure guardrails based on `ai.guardrails` config setting\n3. **Transparency and Explainability**\n   - Clearly indicate AI-generated content to users (labeling requirement)\n   - Provide source attribution for RAG-based answers when possible\n   - Allow users to provide feedback on AI outputs (thumbs up\u002Fdown, corrections)\n4. **PII Handling in Prompts**\n   - Audit all data flows: what user\u002Fcustomer data enters the LLM prompt?\n   - Apply PII redaction before sending to external LLM providers\n   - If PII must be sent: verify DPA (Data Processing Agreement) with provider\n   - Log what data was sent to which model for compliance auditing\n5. **Output Guardrails**\n   - Define acceptable output boundaries (topic, format, length, tone)\n   - Implement response validation before returning to users\n   - Define fallback responses for when guardrails are triggered\n   - Monitor guardrail trigger rate for threshold anomalies\n\n### Step 8: Produce AI Architecture Section for RFC\n\nIntegrate the above into the RFC being produced by the architecture-draft skill. The AI architecture should appear as a dedicated section within the RFC, containing:\n\n1. **AI Pattern Classification** — which patterns apply and why\n2. **Architecture Diagram** — showing data flow through the AI pipeline\n3. **Model Selection and Routing** — which models for which tasks, fallback chains\n4. **Data Pipeline** — how data flows from source to embedding to retrieval to generation\n5. **Prompt Specifications** — system prompts, structured output schemas (reference versioned prompt files)\n6. **Cost Projection** — per-request and monthly cost estimates with optimization plan\n7. **Evaluation Strategy** — metrics, baselines, targets, regression test plan\n8. **AI Safety Measures** — prompt injection protection, guardrails, PII handling, bias assessment\n9. **Infrastructure Requirements** — vector database, model hosting, caching layer, queue for async AI tasks\n\nThis section should be self-contained enough that a backend engineer can implement the AI pipeline without additional context.\n\n### Step 9: Validate\n\nRun artifact validation on the RFC containing the AI architecture section.\n\n- [ ] AI pattern classification is explicit and justified\n- [ ] Model selection matches `ai.llm_provider` and `ai.llm_model` from config (or deviation is documented)\n- [ ] RAG pipeline design includes chunking, embedding, retrieval, and re-ranking (if RAG pattern)\n- [ ] Prompt specifications are detailed enough to implement (system prompt, output schema)\n- [ ] Cost model includes per-request and monthly estimates\n- [ ] Cost stays within `ai.cost_budget_monthly` (or overrun is flagged with justification)\n- [ ] Evaluation plan has concrete metrics and targets\n- [ ] Ethical AI checklist is addressed (all 5 areas: injection, filtering, transparency, PII, guardrails)\n- [ ] Infrastructure requirements are compatible with configured tech stack\n- [ ] Artifact frontmatter is complete (`.\u002Ftools\u002Fartifact\u002Fvalidate.sh`)\n\n## Quality Checklist\n\n- [ ] `company.config.yaml` `ai.*` section was read and respected\n- [ ] `standards\u002Fengineering\u002Fai-patterns.md` was consulted for reference patterns\n- [ ] AI pattern correctly classified (not over-engineered for the use case)\n- [ ] Architecture supports provider swapping (not locked to one LLM vendor)\n- [ ] Streaming vs batch decision is justified by UX requirements\n- [ ] Fallback chain handles provider outages gracefully\n- [ ] Cost model is realistic and within budget (or overrun explicitly flagged)\n- [ ] Prompt engineering follows best practices (structured outputs, few-shot, CoT where appropriate)\n- [ ] Evaluation plan includes both automated and human assessment\n- [ ] All ethical AI checklist items are addressed (not skipped)\n- [ ] PII handling is documented and compliant\n- [ ] AI architecture section integrates cleanly into the RFC structure\n","# AI Engineering\n\n## Reference\n- **ID**: S-ENG-13\n- **Category**: Engineering\n- **Inputs**: approved PRD, company.config.yaml (ai.* section), existing RFCs, standards\u002Fengineering\u002Fai-patterns.md\n- **Outputs**: AI architecture section → artifacts\u002Frfcs\u002F (as section within RFC)\n- **Used by**: Engineering Agent (Staff Engineer level — not delegated to sub-agents)\n- **Tool scripts**: .\u002Ftools\u002Fartifact\u002Fvalidate.sh\n\n## Purpose\n\nDesign the AI\u002FML architecture for features that involve language models, retrieval-augmented generation, agent systems, or other AI components. This skill produces the AI-specific section of an RFC, covering model selection, integration patterns, prompt engineering, cost modeling, evaluation strategy, and ethical safeguards.\n\nAI architecture is a cross-cutting concern that affects backend (API design, data pipelines), frontend (streaming UX, latency handling), and infrastructure (model hosting, vector databases, cost management). The Staff Engineer owns this skill directly rather than delegating to a sub-agent, ensuring architectural coherence across all domains.\n\n## When to Use\n\n- PRD or feature involves LLM integration (chat, summarization, classification, generation)\n- Feature requires retrieval-augmented generation (RAG) with a knowledge base\n- Building an agent system with tool use, multi-step reasoning, or orchestration\n- Feature involves embeddings, semantic search, or vector databases\n- Prompt engineering or structured output design is needed\n- AI cost estimation or optimization is required for budgeting\n- Feature needs AI safety review (guardrails, bias assessment, PII handling)\n\n## AI Engineering Procedure\n\n### Step 1: Load Context\n\nBefore designing any AI architecture:\n\n1. **Read `company.config.yaml`** — extract `ai.*` section (llm_provider, llm_model, embedding_provider, vector_db, guardrails, cost_budget_monthly)\n2. **Read the PRD** — identify all AI-related acceptance criteria and user-facing AI behaviors\n3. **Read existing RFCs** in `artifacts\u002Frfcs\u002F` — check for prior AI architecture decisions, existing model integrations, or shared AI infrastructure\n4. **Read `standards\u002Fengineering\u002Fai-patterns.md`** — load reference patterns for LLM integration, RAG, cost optimization, and safety\n5. **Check tech stack compatibility** — verify that the configured database, queue, and hosting can support the AI workload (e.g., pgvector requires PostgreSQL, streaming requires WebSocket or SSE support)\n\n### Step 2: Classify AI Pattern\n\nDetermine which AI pattern(s) the feature requires. A feature may combine multiple patterns.\n\n| Pattern | Description | Key Concerns |\n|---------|-------------|--------------|\n| **LLM API Call** | Direct call to a language model API (chat, completion, classification) | Latency, cost, fallback, streaming |\n| **RAG Pipeline** | Retrieval-augmented generation with external knowledge | Chunking, embedding, retrieval quality, freshness |\n| **Agent System** | Multi-step reasoning with tool use and orchestration | State management, tool design, loop control, cost caps |\n| **Fine-tuning** | Custom model training on domain-specific data | Data pipeline, evaluation, versioning, cost |\n| **Computer Vision** | Image\u002Fvideo analysis, OCR, visual understanding | Multimodal models, preprocessing, latency |\n| **Recommendation** | Personalized content or action suggestions | Embedding similarity, feedback loops, cold start |\n\nDocument which patterns apply and why. If the pattern is unclear, default to the simplest option (LLM API Call) and note the uncertainty.\n\n### Step 3: Design AI Architecture\n\nFor each classified pattern, produce the architecture design following these guidelines.\n\n#### LLM Integration\n\n1. **API Wrapper Design** — define the abstraction layer between your application and the LLM provider\n   - Provider-agnostic interface (swap Anthropic\u002FOpenAI\u002FGoogle without code changes)\n   - Request\u002Fresponse types with structured validation\n   - Configuration: model name, temperature, max tokens, stop sequences\n2. **Streaming vs Batch** — determine the delivery mode\n   - Streaming (SSE\u002FWebSocket): use for user-facing generation where perceived latency matters\n   - Batch: use for background processing, classification, or bulk operations\n   - Hybrid: stream to user, batch for internal processing\n3. **Fallback Chains** — define behavior when the primary model fails\n   - Primary model → fallback model → cached response → graceful error\n   - Timeout thresholds per model tier (e.g., 30s for opus, 15s for sonnet, 5s for haiku)\n   - Circuit breaker pattern for sustained failures\n4. **Model Routing** — select the right model for the task\n   - Simple tasks (classification, extraction) → smaller\u002Ffaster model\n   - Complex tasks (reasoning, generation) → larger model\n   - Route based on: task complexity, latency requirement, cost sensitivity\n\n#### RAG Pipeline\n\n1. **Chunking Strategy** — how to split source documents\n   - Chunk size: 512-1024 tokens for most use cases; smaller for precise retrieval, larger for context-heavy\n   - Overlap: 10-20% overlap between chunks to preserve context boundaries\n   - Strategy: semantic chunking (by heading\u002Fparagraph) preferred over fixed-size\n2. **Embedding Model Selection** — choose based on configured `ai.embedding_provider`\n   - Define embedding dimensions and distance metric (cosine similarity standard)\n   - Plan for embedding model upgrades (versioned embedding collections)\n3. **Vector Database Schema** — design based on configured `ai.vector_db`\n   - Collection\u002Findex design: namespace by tenant (if multi-tenant), partition by document type\n   - Metadata schema: source_id, chunk_index, created_at, tenant_id, document_type\n   - Index configuration: HNSW parameters, quantization if needed\n4. **Retrieval and Re-ranking** — define the retrieval pipeline\n   - Initial retrieval: top-K (typically K=10-20) from vector search\n   - Re-ranking: cross-encoder or LLM-based re-ranking for top results\n   - Hybrid search: combine vector similarity with keyword search (BM25) when available\n   - Context window assembly: order chunks, deduplicate, fit within token budget\n\n#### Agent Systems\n\n1. **Tool Design** — define the tools the agent can use\n   - Each tool: name, description, input schema (JSON Schema), output format\n   - Tool categories: read-only (safe to retry) vs write (idempotent or not)\n   - Error handling: tool failure should not crash the agent loop\n2. **Orchestration Patterns** — define how the agent operates\n   - Single-turn: one tool call per request (simplest)\n   - Multi-turn: iterative tool use with intermediate reasoning (ReAct pattern)\n   - Multi-agent: specialized agents coordinated by an orchestrator\n3. **State Management** — define how agent state is tracked\n   - Conversation history: full vs windowed vs summarized\n   - Tool call history: log all calls for debugging and audit\n   - Checkpointing: save state at key decision points for recovery\n4. **Safety Controls** — prevent runaway agent behavior\n   - Maximum iterations per request (hard cap)\n   - Maximum total tokens per request (cost cap)\n   - Human-in-the-loop for destructive actions\n   - Timeout per agent execution\n\n### Step 4: Prompt Engineering\n\nDesign the prompt architecture for each AI interaction.\n\n1. **System Prompt Design**\n   - Define the role, capabilities, and constraints\n   - Include output format specification (especially for structured outputs)\n   - Specify what the model should NOT do (negative constraints)\n   - Keep system prompts version-controlled and testable\n2. **Few-Shot Examples**\n   - Include 2-5 representative examples for classification or extraction tasks\n   - Examples should cover: typical case, edge case, and negative case\n   - Store examples alongside prompt templates for easy iteration\n3. **Chain-of-Thought**\n   - Use for complex reasoning tasks (multi-step math, logic, analysis)\n   - Request explicit reasoning before the final answer\n   - Consider whether reasoning should be visible to end users or hidden\n4. **Structured Outputs**\n   - Define JSON Schema for all machine-consumed outputs\n   - Use constrained generation when available (tool_use, response_format)\n   - Validate outputs against schema before processing downstream\n   - Define fallback behavior for malformed outputs\n\n### Step 5: Cost Model\n\nEstimate and plan for AI operational costs.\n\n1. **Token Estimation Per Request**\n   - Input tokens: system prompt + user input + context (RAG chunks, history)\n   - Output tokens: expected response length (cap with max_tokens)\n   - Calculate per-request cost at current provider pricing\n2. **Monthly Budget Projection**\n   - Estimate requests per day\u002Fmonth based on expected usage patterns\n   - Multiply by per-request cost for baseline monthly spend\n   - Add buffer (2-3x) for growth and retries\n   - Compare against `ai.cost_budget_monthly` from config\n3. **Cost Optimization Strategies**\n   - **Semantic caching**: cache responses for semantically similar inputs (embedding similarity > threshold)\n   - **Model tier routing**: route simple tasks to cheaper models, reserve expensive models for complex tasks\n   - **Batching**: group multiple small requests into batch API calls where latency allows\n   - **Prompt optimization**: minimize system prompt tokens, compress context, use efficient few-shot formats\n   - **Token budgets**: set per-request and per-user token limits to prevent cost spikes\n   - **Response caching**: cache deterministic outputs (classification, extraction) with TTL\n\n### Step 6: Evaluation Plan\n\nDefine how to measure AI feature quality.\n\n1. **Accuracy Metrics**\n   - Define task-specific metrics: precision\u002Frecall (classification), BLEU\u002FROUGE (generation), MRR\u002FnDCG (retrieval)\n   - Establish baseline from manual evaluation or existing system\n   - Set target thresholds for production readiness\n2. **Latency SLOs**\n   - Define acceptable latency for each AI operation (p50, p95, p99)\n   - Streaming: time to first token (TTFT) and tokens per second (TPS)\n   - End-to-end: total request time including retrieval, generation, and post-processing\n3. **Regression Testing**\n   - Build an evaluation dataset (golden set) of input-output pairs\n   - Run regression tests on prompt changes, model upgrades, or pipeline modifications\n   - Automate evaluation in CI where possible (deterministic checks first, LLM-as-judge for subjective quality)\n4. **A\u002FB Testing**\n   - Define the experiment: which AI variation to test (model, prompt, retrieval strategy)\n   - Define the success metric: user satisfaction, task completion, accuracy\n   - Plan the rollout: feature flag with percentage-based allocation\n\n### Eval Framework Selection\n\nRecommend an eval framework based on the AI architecture:\n- **PromptFoo**: Best for prompt engineering and LLM output evaluation (Claude, GPT). Supports assertions, model comparison, red teaming.\n- **RAGAS**: Best for RAG pipeline evaluation. Measures faithfulness, relevance, context recall.\n- **Custom evals via batch API**: For domain-specific evaluation. Use Anthropic's batch API for cost-efficient bulk evaluation runs.\n- **DeepEval**: General-purpose LLM evaluation with built-in metrics.\n\nFor all approaches: define eval datasets early, run evals in CI, track scores over time.\n\n### Step 7: Ethical AI Checklist\n\nAssess and mitigate AI-specific risks.\n\n1. **Prompt Injection Protection**\n   - Input validation: sanitize user inputs before including in prompts\n   - System\u002Fuser message separation: never concatenate user input into system prompts\n   - Output validation: verify outputs match expected format and constraints\n   - Indirect injection: assess risk from RAG content containing adversarial instructions\n2. **Content Filtering**\n   - Define output filtering rules: no harmful content, no PII generation, no hallucinated citations\n   - Implement pre-response filtering (keyword blocklist, classifier, or LLM-based filter)\n   - Configure guardrails based on `ai.guardrails` config setting\n3. **Transparency and Explainability**\n   - Clearly indicate AI-generated content to users (labeling requirement)\n   - Provide source attribution for RAG-based answers when possible\n   - Allow users to provide feedback on AI outputs (thumbs up\u002Fdown, corrections)\n4. **PII Handling in Prompts**\n   - Audit all data flows: what user\u002Fcustomer data enters the LLM prompt?\n   - Apply PII redaction before sending to external LLM providers\n   - If PII must be sent: verify DPA (Data Processing Agreement) with provider\n   - Log what data was sent to which model for compliance auditing\n5. **Output Guardrails**\n   - Define acceptable output boundaries (topic, format, length, tone)\n   - Implement response validation before returning to users\n   - Define fallback responses for when guardrails are triggered\n   - Monitor guardrail trigger rate for threshold anomalies\n\n### Step 8: Produce AI Architecture Section for RFC\n\nIntegrate the above into the RFC being produced by the architecture-draft skill. The AI architecture should appear as a dedicated section within the RFC, containing:\n\n1. **AI Pattern Classification** — which patterns apply and why\n2. **Architecture Diagram** — showing data flow through the AI pipeline\n3. **Model Selection and Routing** — which models for which tasks, fallback chains\n4. **Data Pipeline** — how data flows from source to embedding to retrieval to generation\n5. **Prompt Specifications** — system prompts, structured output schemas (reference versioned prompt files)\n6. **Cost Projection** — per-request and monthly cost estimates with optimization plan\n7. **Evaluation Strategy** — metrics, baselines, targets, regression test plan\n8. **AI Safety Measures** — prompt injection protection, guardrails, PII handling, bias assessment\n9. **Infrastructure Requirements** — vector database, model hosting, caching layer, queue for async AI tasks\n\nThis section should be self-contained enough that a backend engineer can implement the AI pipeline without additional context.\n\n### Step 9: Validate\n\nRun artifact validation on the RFC containing the AI architecture section.\n\n- [ ] AI pattern classification is explicit and justified\n- [ ] Model selection matches `ai.llm_provider` and `ai.llm_model` from config (or deviation is documented)\n- [ ] RAG pipeline design includes chunking, embedding, retrieval, and re-ranking (if RAG pattern)\n- [ ] Prompt specifications are detailed enough to implement (system prompt, output schema)\n- [ ] Cost model includes per-request and monthly estimates\n- [ ] Cost stays within `ai.cost_budget_monthly` (or overrun is flagged with justification)\n- [ ] Evaluation plan has concrete metrics and targets\n- [ ] Ethical AI checklist is addressed (all 5 areas: injection, filtering, transparency, PII, guardrails)\n- [ ] Infrastructure requirements are compatible with configured tech stack\n- [ ] Artifact frontmatter is complete (`.\u002Ftools\u002Fartifact\u002Fvalidate.sh`)\n\n## Quality Checklist\n\n- [ ] `company.config.yaml` `ai.*` section was read and respected\n- [ ] `standards\u002Fengineering\u002Fai-patterns.md` was consulted for reference patterns\n- [ ] AI pattern correctly classified (not over-engineered for the use case)\n- [ ] Architecture supports provider swapping (not locked to one LLM vendor)\n- [ ] Streaming vs batch decision is justified by UX requirements\n- [ ] Fallback chain handles provider outages gracefully\n- [ ] Cost model is realistic and within budget (or overrun explicitly flagged)\n- [ ] Prompt engineering follows best practices (structured outputs, few-shot, CoT where appropriate)\n- [ ] Evaluation plan includes both automated and human assessment\n- [ ] All ethical AI checklist items are addressed (not skipped)\n- [ ] PII handling is documented and compliant\n- [ ] AI architecture section integrates cleanly into the RFC structure\n",{"name":5,"runtimes":33,"description":7},{"claude":34},{"user-invocable":29},"main","e842fb6d0e04360c47db78bc2e2e2987314d64d4","os\u002Fskills\u002Fai-engineering",2,"https:\u002F\u002Fgithub.com\u002Fvibbs\u002Fcompany-os","https:\u002F\u002Fgithub.com\u002Fvibbs","Principal Engineer · Applied AI · building ArcAI @ GrowthArc","2026-10-21 02:08:08",{"source":8,"skillName":5,"commands":44,"prompt":54,"zipAvailable":55},[45,48,51],{"tool":46,"command":47},"npx","npx skills add vibbs\u002Fcompany-os --skill ai-engineering",{"tool":49,"command":50},"bunx","bunx skills add vibbs\u002Fcompany-os --skill ai-engineering",{"tool":52,"command":53},"pnpm","pnpm dlx skills add vibbs\u002Fcompany-os --skill ai-engineering","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fvibbs\u002Fcompany-os\u002Fblob\u002Fmain\u002Fos\u002Fskills\u002Fai-engineering\u002FSKILL.md",true,[57,63],{"path":58,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":61,"sourceHtmlUrl":62},"checklist.md","REFERENCE","参考文档",11638,"https:\u002F\u002Fgithub.com\u002Fcodeasice\u002Fagentcore-presentation\u002Fblob\u002Fmaster\u002F.claude\u002Fskills\u002Fbmad-correct-course\u002Fchecklist.md",{"path":64,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":65,"sourceHtmlUrl":66},"workflow.md",11348,"https:\u002F\u002Fgithub.com\u002Fcodeasice\u002Fagentcore-presentation\u002Fblob\u002Fmaster\u002F.claude\u002Fskills\u002Fbmad-correct-course\u002Fworkflow.md",[68,77,85,95,111,129],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":28},"01M6CTHBW1E64ECYGD105N4S5E","typo-field","Fixture skill with a misspelled top-level field.","https:\u002F\u002Fgithub.com\u002Fvibbs\u002Fcompany-os\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskills\u002Ftypo-field\u002FSKILL.md",[],[75,76],"typo field","fixture skill",{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":28},"01M6CTHABTV8FKVDHFMMKPAV51","spaced-comments","Fixture skill with comments and spaces after block keys.","https:\u002F\u002Fgithub.com\u002Fvibbs\u002Fcompany-os\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskills\u002Fspaced-comments\u002FSKILL.md",[],[84,76],"spaced comments",{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":28},"01M6CTH8MHC14KB65ZDHYBJW1N","crlf-comments","Fixture skill with Windows line endings.","https:\u002F\u002Fgithub.com\u002Fvibbs\u002Fcompany-os\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskills\u002Fcrlf-comments\u002FSKILL.md",[],[92,93,94,76],"crlf comments","CRLF","windows",{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":28},"01M6CTH6TBKTDP9G8QB1Z2K0TY","claude-fields","Fixture skill using top-level fields Claude Code documents.","https:\u002F\u002Fgithub.com\u002Fvibbs\u002Fcompany-os\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskills\u002Fclaude-fields\u002FSKILL.md",[],[102,103,104,105,106,107,76,108,109,110],"claude fields","explore","documents","src","grep","read","Bash","code","testing",{"skillNo":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":122,"publishedAt":28},"01M6CTH46BGKXH80RWS876Y2CW","workflow-router","Maps an objective to the artifacts, stages and agents it needs. Use when deciding what happens next or which agents to involve.","https:\u002F\u002Fgithub.com\u002Fvibbs\u002Fcompany-os\u002Fblob\u002Fmain\u002Fos\u002Fskills\u002Fworkflow-router\u002FSKILL.md",[117],{"categoryNo":118,"categoryName":119,"taxonomyType":120,"taxonomyTypeDesc":121},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[123,124,125,126,127,25,128],"workflow","router","workflow router","next","maps","artifacts",{"skillNo":130,"name":131,"nameZh":6,"description":132,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":133,"categories":134,"keywords":135,"publishedAt":28},"01M6CTH27653SRVP2FMEQN3J5B","weekly-review","Summarizes your week: what shipped, AI spend, support themes, security health and next priorities. Use at the end of each week.","https:\u002F\u002Fgithub.com\u002Fvibbs\u002Fcompany-os\u002Fblob\u002Fmain\u002Fos\u002Fskills\u002Fweekly-review\u002FSKILL.md",[],[136,137,138,126,25,139,140,141,142],"weekly review","review","priorities","health","save","support","security"]