ai-dev-guidelines
БесплатноБез исполняемых скриптовНе проверенComprehensive AI/ML development guide for LangChain, LangGraph, and ML model integration in FastAPI. Use when building LLM applications, agents, RAG systems…
от diegosouzapw★ 68 звёзд на GitHubОб этом скилле
AI/ML Development Guidelines (LangChain/LangGraph/FastAPI)
Purpose
Establish best practices for integrating AI/ML capabilities into FastAPI applications, with focus on LangChain, LangGraph, and ML model deployment.
When to Use This Skill
Automatically activates when working on:
- LangChain chains, agents, tools
- LangGraph workflows and state machines
- RAG (Retrieval Augmented Generation)
- Prompt engineering and templates
- Vector stores and embeddings
- ML model integration (sentiment analysis, aspect-based analysis, etc.)
- Streaming LLM responses
- AI service layers
- Model deployment and optimization
Quick Start
New AI Feature Checklist
- Model Selection: Choose appropriate model/API (OpenAI, Anthropic, local)
- Prompt Design: Create prompt templates
- Chain/Graph: Build LangChain chain or LangGraph workflow
- API Endpoint: FastAPI route with streaming support
- Error Handling: Retry logic, fallbacks, timeouts
- Validation: Input/output validation with Pydantic
- Monitoring: Log tokens, latency, errors
- Testing: Unit tests with mocked LLM responses
- Documentation: Document prompts and expected behavior
Architecture for AI Features
Layered AI Architecture
HTTP Request
↓
FastAPI Route (streaming setup)
↓
AI Service (chain/graph orchestration)
↓
LangChain/LangGraph (LLM calls)
↓
Model/API (OpenAI, Anthropic, HuggingFace, local)
Current Project ML Structure:
backend/app/
├── routes/
│ └── ML_Routes.py # ML API endpoints
├── machine_learning/
│ └── mlendpoint.py # Sentiment analysis functions
└── services/ # TO BE CREATED for LangChain/LangGraph
└── ai_services/
├── sentiment.py # Refactored sentiment analysis
├── chains.py # LangChain chains
├── graphs.py # LangGraph workflows
└── prompts.py # Prompt templates
Package Management
This project uses uv for Python package management.
# Add LangChain dependencies
uv add langchain langchain-openai langchain-anthropic langgraph
# Add vector store dependencies (when needed)
uv add faiss-cpu chromadb
# Add other AI dependencies
uv add tiktoken sentence-transformers
# Run Python scripts with uv
uv run python script.py
❌ NEVER use pip install - Always use uv add instead.
Core Principles for AI Development
1. Separate Prompts from Code
# ❌ NEVER: Hardcoded prompts in code
def analyze_text(text: str):
response = llm.invoke(f"Analyze sentiment of: {text}")
return response
# ✅ ALWAYS: Templated prompts
from langchain.prompts import ChatPromptTemplate
SENTIMENT_PROMPT = ChatPromptTemplate.from_messages([
("system", "You are a sentiment analysis expert."),
("user", "Analyze the sentiment of the following text:\n\n{text}\n\nProvide: sentiment (positive/neutral/negative) and confidence (0-1).")
])
def analyze_text(text: str):
chain = SENTIMENT_PROMPT | llm | output_parser
return chain.invoke({"text": text})
2. Use Pydantic for LLM Output Validation
from pydantic import BaseModel, Field
from langchain.output_parsers import PydanticOutputParser
class SentimentResult(BaseModel):
sentiment: str = Field(description="positive, neutral, or negative")
confidence: float = Field(ge=0.0, le=1.0)
reasoning: str = Field(description="Brief explanation")
# Create parser
parser = PydanticOutputParser(pydantic_object=SentimentResult)
# Add format instructions to prompt
prompt = ChatPromptTemplate.from_messages([
("system", "You are a sentiment expert."),
("user", "{text}\n\n{format_instructions}")
])
# Use in chain
chain = prompt | llm | parser
result: SentimentResult = chain.invoke({
"text": "I love this product!",
"format_instructions": parser.get_format_instructions()
})
3. Handle Streaming for Better UX
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
# Setup streaming LLM
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="gpt-4",
streaming=True,
callbacks=[StreamingStdOutCallbackHandler()]
)
@app.post("/ai/generate-stream")
async def generate_stream(request: GenerateRequest):
"""Stream LLM responses for real-time feedback"""
async def event_generator():
async for chunk in chain.astream({"input": request.text}):
if chunk:
yield f"data: {chunk}\n\n"
return StreamingResponse(
event_generator(),
media_type="text/event-stream"
)
4. Implement Retry Logic and Fallbacks
from tenacity import retry, stop_after_attempt, wait_exponential
from langchain.chat_models import ChatOpenAI, ChatAnthropic
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1,
Установить ai-dev-guidelines в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл ai-dev-guidelines?
Comprehensive AI/ML development guide for LangChain, LangGraph, and ML model integration in FastAPI. Use when building LLM applications, agents, RAG systems, sentiment analysis, aspect-based analysis, chain orchestration, prompt engineering, vector stores, embeddings, or integrating ML models with FastAPI endpoints. Covers LangChain patterns, LangGraph state machines, model deployment, API integration, streaming, error handling, and best practices.
Как установить скилл ai-dev-guidelines?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл ai-dev-guidelines запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic