llm-chat-interface
Guide for building full-stack LLM applications with Warren's preferred tech stack. Use when building chat interfaces, LLM-powered apps, or any application using claude-agent-sdk. Covers tech stack (React + TypeScript + Vite + Tailwind frontend, FastAPI + uv backend), SDK usage patterns, structured logging, and Makefile conventions. Load references as needed - chat-interface.md for chat UI patterns, realtime-streaming.md for SSE/activity streaming, storage-patterns.md for backend persistence. Keywords - LLM app, claude-agent-sdk, FastAPI, React, chat interface.
What this skill does
## Tech Stack
### Frontend
- React + TypeScript + Vite
- **Tailwind CSS** preferred over plain CSS files
- **Text editor**: CodeMirror or TipTap recommended over plain textarea
- react-markdown for LLM response rendering
- vitest + @testing-library/react for testing
### Backend
- FastAPI + uv + sse-starlette (for real-time streaming)
- Use pyproject.toml (modern, consolidates config)
- CORS: Include all potential dev ports (5173, 5174, 3000) - Vite bounces to alternate ports
- pytest + pytest-asyncio for testing
- Ruff for linting
### LLM Integration
- claude-agent-sdk (Anthropic's official agent SDK)
- Simple HTTP request/response preferred over WebSocket streaming
- Client-side history management - frontend stores conversation, sends full history, backend stays stateless
- Models: haiku (speed), opus (quality)
---
## Makefile Conventions
Provide a Makefile with standardized commands:
```makefile
.PHONY: help serve kill restart test lint
help: ## Show this help message
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-15s\033[0m %s\n", $$1, $$2}'
serve: ## Start both frontend and backend
@echo "Starting backend..."
cd backend && uv run uvicorn main:app --port 8000 &
@echo "Starting frontend..."
cd frontend && npm run dev &
@echo "Services started. Use 'make kill' to stop."
kill: ## Stop all services
@pkill -f "uvicorn main:app" 2>/dev/null || true
@pkill -f "vite" 2>/dev/null || true
@echo "Services stopped."
restart: kill serve ## Restart all services
test: ## Run all tests
cd backend && uv run pytest
cd frontend && npm test
lint: ## Run linters
cd backend && uv run ruff check .
cd frontend && npm run lint
```
**Key principles:**
- `make help` as the default/documented entry point - shows all available commands
- `make serve` starts full stack with single command
- `make kill` cleanly stops services - no orphan processes
- Disable hot reload during development - prevents test flakiness
- Health endpoints return service identification for debugging:
```python
@router.get("/health")
async def health():
return {"status": "healthy", "service": "your-service-name"}
```
---
## SDK Gotchas (claude-agent-sdk)
### Authentication
- **Local auth works automatically** - no API key needed when running locally
- Don't use raw `anthropic.Anthropic()` - it requires explicit API key
- Import: `from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage`
### Two Usage Patterns
**Pattern 1: Text-Only Mode** (for simple completions)
```python
options = ClaudeAgentOptions(
model="claude-sonnet-4-20250514",
system_prompt=system_prompt,
max_turns=1,
allowed_tools=[], # Disables tools, forces text output
)
result_text = ""
async for message in query(prompt=prompt, options=options):
if isinstance(message, ResultMessage):
result_text = message.result or ""
```
**Pattern 2: Agent Mode** (for file operations, testing, iteration)
```python
options = ClaudeAgentOptions(
model="claude-sonnet-4-20250514",
system_prompt=system_prompt,
max_turns=None, # Unlimited turns
cwd=str(working_dir),
permission_mode="acceptEdits",
allowed_tools=["Read", "Glob", "Grep", "Write", "Edit", "WebFetch", "Bash"],
add_dirs=[str(working_dir)],
)
```
### Tool Behavior (CRITICAL)
- **Tools enabled = different output**: When tools are available, Claude may USE them rather than OUTPUT text
- Example: "Create index.html" → Claude writes the file via Write tool, `ResultMessage.result` is empty
- To get text output, use `allowed_tools=[]`
- To let Claude create files, enable tools + set `cwd` and `permission_mode`
### Message Type Checking
```python
from claude_agent_sdk import (
AssistantMessage, ResultMessage,
TextBlock, ToolUseBlock, ToolResultBlock
)
async for message in query(prompt=prompt, options=options):
if isinstance(message, AssistantMessage):
for block in message.content:
if isinstance(block, ToolUseBlock):
tool_name = block.name
tool_input = block.input or {}
elif isinstance(block, TextBlock):
text = block.text
elif isinstance(message, ResultMessage):
result = message.result
```
**NEVER use attribute-based type checking** like `block.type == 'tool_use'` - fails silently.
### General Gotchas
1. **Never break early** from async generator - causes cancel scope errors
2. **Consume entire generator** even if you have the result
3. **Empty result with tools** - If `ResultMessage.result` is empty, Claude likely completed an action via tools
---
## LLM Output Validation (Early Return Pattern)
When LLM output requires parsing, validate before proceeding:
```python
# Parse structured output from LLM
analysis = await self._analyze_codebase(session_id, path, question)
# Log raw output for debugging
logger.info(
"Analysis complete",
session_id=session_id,
analysis_length=len(analysis),
analysis_preview=analysis[:500] if analysis else "EMPTY",
)
# Parse and validate
variants = parse_xml_tags(analysis, "variant")
logger.info("Parsed results", num_variants=len(variants))
# CRITICAL: Early return on validation failure
if len(variants) == 0:
logger.error("No variants found", analysis_output=analysis[:1000])
await activity_stream.emit(session_id, "session_error",
"Analysis failed to produce results. Check logs.")
return LaunchResponse(session_id=session_id, variants=[],
error="Analysis produced no results")
# Only proceed if validation passed
await activity_stream.emit(session_id, "analysis_complete",
f"Found {len(variants)} variants")
```
**Key principle:** Emit error event, then return early. Never continue a workflow with empty/invalid LLM output.
---
## Parsing Structured LLM Output
When LLMs output structured formats (XML, JSON), use proper parsing libraries:
### XML Output - Use ElementTree
**DON'T** use regex for XML parsing:
```python
# Fragile - breaks on whitespace, special chars, nested tags
for match in re.finditer(r'<(\w+)>(.*?)</\1>', response):
axis = match.group(1)
content = match.group(2)
```
**DO** use xml.etree.ElementTree:
```python
import xml.etree.ElementTree as ET
# Extract XML block from LLM response (may have surrounding text)
xml_match = re.search(r'<root>(.*?)</root>', response, re.DOTALL)
if not xml_match:
logger.warning("No XML block found")
return []
try:
root = ET.fromstring(f"<wrapper>{xml_match.group(1)}</wrapper>")
for item in root.findall('item'):
data = {
"id": item.get('id'), # Attributes
"name": item.findtext('name'), # Child element text
}
# Dynamic child parsing
for child in item:
if child.text:
data[child.tag] = child.text
except ET.ParseError as e:
logger.warning(f"XML parse error: {e}")
# Fallback to basic regex if needed
```
**Benefits:**
- Proper tree traversal for nested structures
- Automatic whitespace handling
- Clear errors on malformed XML
- Dynamic element discovery (no hardcoded tag names)
### JSON Output
```python
import json
# Clean markdown code blocks if present
clean = response.strip()
if clean.startswith("```"):
clean = re.sub(r"^```(?:json)?\n?", "", clean)
clean = re.sub(r"\n?```$", "", clean)
try:
data = json.loads(clean)
except json.JSONDecodeError as e:
logger.error(f"JSON parse error: {e}", raw_response=response[:500])
return None
```
**Key principle:** LLMs produce text, not data structures. Always parse with proper libraries, log raw output on failure.
---
## Parallel Agent Operations
When running multiple agents in parallel with `asyncio.gather`:
```python
results = await asyncio.gather(*build_tasks, return_exceptions=True)
successful = 0
failed = 0
for i, result in enumerate(results):
if isinstance(result, Exception):
failed += 1
Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.