replicate
Run machine learning models in the cloud via API. Access thousands of open-source models for image generation, language, audio, and video. Fine-tune models on custom data and deploy custom models with Cog packaging format.
What this skill does
# Replicate
## Installation
```bash
# Install Python client
pip install replicate
# Set API token
export REPLICATE_API_TOKEN="r8_xxxxxxxxxxxx"
```
## Run a Model
```python
# run_model.py — Run a model and get the output
import replicate
# Run Stable Diffusion XL
output = replicate.run(
"stability-ai/sdxl:7762fd07cf82c948538e41f63f77d685e02b063e37e496e96eefd46c929f9bdc",
input={
"prompt": "A futuristic cityscape at sunset, digital art",
"negative_prompt": "blurry, low quality",
"width": 1024,
"height": 1024,
"num_outputs": 1,
},
)
# Output is a list of URLs
for url in output:
print(url)
```
## Run Language Models
```python
# run_llm.py — Run open-source LLMs via Replicate
import replicate
# Run Llama with streaming
for event in replicate.stream(
"meta/llama-2-70b-chat",
input={
"prompt": "Explain machine learning to a 5-year-old",
"system_prompt": "You are a friendly teacher.",
"max_new_tokens": 500,
"temperature": 0.7,
},
):
print(str(event), end="", flush=True)
```
## Async Predictions
```python
# async_prediction.py — Submit a prediction and poll for results
import replicate
import time
# Create prediction without waiting
prediction = replicate.predictions.create(
model="stability-ai/sdxl",
input={"prompt": "A cat in space"},
)
print(f"Prediction ID: {prediction.id}")
print(f"Status: {prediction.status}")
# Poll for completion
while prediction.status not in ("succeeded", "failed", "canceled"):
time.sleep(2)
prediction.reload()
print(f"Status: {prediction.status}")
if prediction.status == "succeeded":
print(f"Output: {prediction.output}")
```
## Webhooks
```python
# webhook_prediction.py — Get notified when a prediction completes via webhook
import replicate
prediction = replicate.predictions.create(
model="stability-ai/sdxl",
input={"prompt": "A mountain landscape"},
webhook="https://myapp.com/api/replicate-webhook",
webhook_events_filter=["completed"],
)
print(f"Prediction started: {prediction.id}")
```
## Fine-Tuning
```python
# fine_tune.py — Fine-tune SDXL on custom images
import replicate
# Create a fine-tune training
training = replicate.trainings.create(
version="stability-ai/sdxl:7762fd07cf82c948538e41f63f77d685e02b063e37e496e96eefd46c929f9bdc",
input={
"input_images": "https://my-bucket.s3.amazonaws.com/training-images.zip",
"token_string": "TOK",
"caption_prefix": "a photo of TOK, ",
"max_train_steps": 1000,
"use_face_detection_instead": False,
},
destination="my-username/my-sdxl-model",
)
print(f"Training ID: {training.id}")
print(f"Status: {training.status}")
# Check training status
training.reload()
print(f"Status: {training.status}")
print(f"Model version: {training.output.get('version')}")
```
## Deploy Custom Models with Cog
```dockerfile
# cog.yaml — Define model environment for Cog packaging
build:
python_version: "3.11"
python_packages:
- torch==2.1.0
- transformers==4.36.0
gpu: true
predict: "predict.py:Predictor"
```
```python
# predict.py — Cog predictor class for custom model deployment
from cog import BasePredictor, Input, Path
from transformers import pipeline
class Predictor(BasePredictor):
def setup(self):
"""Load model into memory during container startup"""
self.pipe = pipeline("text-generation", model="./model", device=0)
def predict(
self,
prompt: str = Input(description="Input text prompt"),
max_tokens: int = Input(description="Max tokens to generate", default=100, ge=1, le=1000),
temperature: float = Input(description="Sampling temperature", default=0.7, ge=0, le=2),
) -> str:
"""Run a single prediction"""
output = self.pipe(prompt, max_new_tokens=max_tokens, temperature=temperature)
return output[0]["generated_text"]
```
```bash
# Build and push a custom model with Cog
pip install cog
# Test locally
cog predict -i prompt="Hello world"
# Push to Replicate
cog login
cog push r8.im/my-username/my-model
```
## Node.js Client
```typescript
// replicate_node.ts — Use Replicate from Node.js
import Replicate from "replicate";
const replicate = new Replicate({ auth: process.env.REPLICATE_API_TOKEN });
const output = await replicate.run("stability-ai/sdxl", {
input: {
prompt: "A watercolor painting of a robot",
width: 1024,
height: 1024,
},
});
console.log(output);
```
## Key Concepts
- **Version pinning**: Models are versioned by SHA — pin versions for reproducibility
- **Cold starts**: First request to a model may take 10-60s to boot; subsequent calls are faster
- **Streaming**: Use `replicate.stream()` for real-time token output from language models
- **Cog**: Open-source tool to package ML models as Docker containers for Replicate
- **Webhooks**: Avoid polling by receiving HTTP callbacks when predictions complete
- **Pricing**: Pay per second of compute; GPU type depends on the model
Related in Image & Video
watch
IncludedWatch a video (URL or local path). Downloads with yt-dlp, extracts auto-scaled frames with ffmpeg, pulls the transcript from captions (or Whisper API fallback), and hands the result to Claude so it can answer questions about what's in the video.
physical-ai-defect-image-generation
IncludedUse when the user wants to orchestrate defect image generation, run associated setup, or handle outputs on OSMO. The Day 0 path handles cold-start with USD-to-ROI, image-edit augmentation, and AnomalyGen to create initial PCBA datasets. The Day 1 path performs inference and labeling on real images. This skill helps with first-time asset setup, creation of finetuning checkpoints, and configuring deployment. Trigger keywords: defect image generation, dig workflow, dig pipeline, defect image detection workflow, aoi pipeline, aoi anomalygen, usd2roi anomalygen, day 0 pcba, day 1 pcba, day 1 real-photo alignment, day 1 manual roi, metal surface anomaly, glass defect, anomalygen finetune, setup_pcb, setup_metal, setup_glass, setup_pretrained, dig setup, dig datasets, dig pretrained checkpoint, dig image-edit endpoint.
accelint-react-best-practices
IncludedReact performance optimization and best practices. ALWAYS use this skill when working with any React code - writing components, hooks, JSX; refactoring; optimizing re-renders, memoization, state management; reviewing for performance; fixing hydration mismatches; debugging infinite re-renders, stale closures, input focus loss, animations restarting; preventing remounting; implementing transitions, lazy initialization, effect dependencies. Even simple React tasks benefit from these patterns. Covers React 19+ (useEffectEvent, Activity, ref props). Triggers - useEffect, useState, useMemo, useCallback, memo, inline components, nested components, components inside components, re-render, performance, hydration, SSR, Next.js, useDeferredValue, combined hooks.
elevenlabs-agents
IncludedBuild conversational AI voice agents with ElevenLabs Platform using React, JavaScript, React Native, or Swift SDKs. Configure agents, tools (client/server/MCP), RAG knowledge bases, multi-voice, and Scribe real-time STT. Use when: building voice chat interfaces, implementing AI phone agents with Twilio, configuring agent workflows or tools, adding RAG knowledge bases, testing with CLI "agents as code", or troubleshooting deprecated @11labs packages, Android audio cutoff, CSP violations, dynamic variables, or WebRTC config. Keywords: ElevenLabs Agents, ElevenLabs voice agents, AI voice agents, conversational AI, @elevenlabs/react, @elevenlabs/client, @elevenlabs/react-native, @elevenlabs/elevenlabs-js, @elevenlabs/agents-cli, elevenlabs SDK, voice AI, TTS, text-to-speech, ASR, speech recognition, turn-taking model, WebRTC voice, WebSocket voice, ElevenLabs conversation, agent system prompt, agent tools, agent knowledge base, RAG voice agents, multi-voice agents, pronunciation dictionary, voice speed control, elevenlabs scribe, @11labs deprecated, Android audio cutoff, CSP violation elevenlabs, dynamic variables elevenlabs, case-sensitive tool names, webhook authentication
humanizer
IncludedHumanize AI-generated text by detecting and removing patterns typical of LLM output. Rewrites text to sound natural, specific, and human. Uses 28 pattern detectors, 560+ AI vocabulary terms across 3 tiers, and statistical analysis (burstiness, type-token ratio, readability) for comprehensive detection. Use when asked to humanize text, de-AI writing, make content sound more natural/human, review writing for AI patterns, score text for AI detection, or improve AI-generated drafts. Covers content, language, style, communication, and filler categories.
generating-mermaid-diagrams
IncludedSalesforce architecture diagrams using Mermaid with ASCII fallback. Use this skill when generating text-based diagrams for Salesforce architecture, OAuth flows, ERDs, integration sequences, or Agentforce structure. TRIGGER when: user says "diagram", "visualize", "ERD", or asks for sequence diagrams, flowcharts, class diagrams, or architecture visualizations in Mermaid. DO NOT TRIGGER when: user wants PNG/SVG image output (use generating-visual-diagrams), or asks about non-Salesforce systems.