Developers · SAM 3 & SAM 3.1
SAM API Guide “SAM API” means two different things: hosted HTTP endpoints you call over the internet, and local Python interfaces you run on your own GPU. This guide covers each separately, then shows how to turn local SAM 3 into your own API.
Start here
Hosted API or Local Python?
Meta publishes open checkpoints and code, not a paid API. Pick the path that fits your constraints.
| Hosted API (HTTP) | Local Python interface | |
|---|---|---|
| What you call | An HTTPS endpoint with an API key | Python methods such as set_text_prompt() |
| Hardware | Provider’s GPUs | Your NVIDIA GPU (CUDA 12.6+) |
| Setup time | Minutes: get a key | An hour or more: env, access, install |
| Cost model | Per request or per frames | Your GPU time; no per-call fee |
| Output | JSON with mask URLs, RLE or polygons | Tensors in memory |
| Latency | Network + queue + inference | Inference only |
| Data privacy | Images leave your network | Images stay with you |
| Customisation | Provider’s options only | Full: fine-tuning, video sessions, SAM 3 Agent |
| Best for | Prototypes, low or spiky volume, no GPU | High volume, sensitive data, custom pipelines |
- Authenticate: each provider issues an API key; keep it server-side, never in browser code.
- Submit: POST the image URL (or base64) and prompt fields.
- Wait: short jobs return directly; queued jobs give a request ID to poll, or call your webhook.
- Read results: masks as image URLs, RLE or polygons, plus scores and boxes if requested.
- Pay: per request or per batch of video frames. Compare in the pricing guide.
Hosted · fal
fal: SAM 3 and SAM 3.1 Endpoints
Ready-made endpoints for image, RLE, embeddings, video and SAM 3D. Image segmentation is listed at $0.005 per request.
Python
import fal_client # pip install fal-client · export FAL_KEY=...
result = fal_client.subscribe("fal-ai/sam-3/image", arguments={
"image_url": "https://example.com/street.jpg",
"prompt": "yellow taxi",
"return_multiple_masks": True,
"max_masks": 10, # 1–32
"include_scores": True,
"include_boxes": True, # normalized [cx, cy, w, h]
})
for mask, score in zip(result["masks"], result.get("scores", [])):
print(round(score, 2), mask["url"])cURL (queue)
curl -X POST https://queue.fal.run/fal-ai/sam-3/image \
-H "Authorization: Key $FAL_KEY" \
-H "Content-Type: application/json" \
-d '{"image_url":"https://example.com/street.jpg","prompt":"yellow taxi"}'
# → {request_id, status_url, response_url}: poll status_url, then GET response_url| Input field | Default | What it does |
|---|---|---|
image_url | required | Image to segment |
prompt | “wheel” | Text concept to find |
point_prompts / box_prompts | [] | Clicks or boxes (x_min, y_min, x_max, y_max) |
return_multiple_masks, max_masks | false, 3 | Return up to 32 masks |
include_scores, include_boxes | false | Add scores and normalized boxes |
apply_mask, output_format | true, png | Preview overlay; png, jpeg or webp |
Other endpoints: fal-ai/sam-3/image-rle, fal-ai/sam-3/image/embed, fal-ai/sam-3-1/image (real-time WebSocket mode), fal-ai/sam-3/video-rle ($0.005 per 16 frames), fal-ai/sam-3/3d-objects. Prices change; check before budgeting.
Hosted · Roboflow
Roboflow: Serverless SAM 3 Endpoints
Two raw endpoints: concept_segment for text prompts (find every match) and visual_segment for points or a box (one object, SAM 2 style).
Python · concept segmentation
import os, requests
resp = requests.post(
"https://serverless.roboflow.com/sam3/concept_segment",
headers={"Authorization": f"Bearer {os.environ['ROBOFLOW_API_KEY']}"},
json={
"image": {"type": "url", "value": "https://example.com/street.jpg"},
"prompts": [{"type": "text", "text": "yellow taxi"}],
"output_prob_thresh": 0.5,
"format": "polygon", # or "rle"
},
)
data = resp.json() # prompt_results, time- Auth: API key in an
Authorization: Bearerheader (the olderapi_keyquery parameter still works). - Several prompts per call: add more
{"type": "text", ...}items toprompts. - Outputs: polygons or RLE; easy to chain with Roboflow Workflows for visualisation and logic.
- Self-host option: the same API runs locally in the
roboflow/inference-serverDocker image.
Hosted · Replicate
Replicate: Community SAM 3 Models
Replicate hosts several community-packaged SAM 3 and SAM 3.1 models, billed by GPU time. Inputs differ per model, so read its API tab.
Python
import replicate # pip install replicate · export REPLICATE_API_TOKEN=...
output = replicate.run("visionaix/sam3-1", input={
"image": open("street.jpg", "rb"),
"text_prompt": "yellow taxi",
"confidence_threshold": 0.5,
})
# community model: input names and outputs differ per model pageOne popular SAM 3 model is quoted at about $0.023 per run on an L40S; costs vary with input. Community models aren’t maintained by Meta: pin a version for production.
Hosted · best practice
Hosted API Best Practices
Reliability
- Use queue mode plus webhooks for video and batches.
- Retry 429 and 5xx with exponential back-off.
- Send stable, public image URLs (or signed URLs).
- Pin model versions where the provider allows it.
- Log request IDs so you can trace failures.
Cost & security
- Keep API keys on your server; proxy browser calls.
- Ask for RLE or polygons instead of overlays to save bandwidth.
- Cache results by image hash + prompt.
- Check data-retention terms before sending private images.
- Pass on SAM License terms if you ship results commercially.
- Requirements: Python 3.12+, PyTorch 2.7+, CUDA 12.6+ GPU.
- Access: approved access to
facebook/sam3(andfacebook/sam3.1), thenhf auth login. - Three interfaces: official
sam3, Hugging Face Transformers, Ultralytics. - New here? Start with the Python tutorial.
official sam3 · image
from PIL import Image
from sam3.model_builder import build_sam3_image_model
from sam3.model.sam3_image_processor import Sam3Processor
processor = Sam3Processor(build_sam3_image_model()) # load once
state = processor.set_image(Image.open("street.jpg"))
out = processor.set_text_prompt(state=state, prompt="yellow taxi")
masks, boxes, scores = out["masks"], out["boxes"], out["scores"] # tensorsLocal · reference
Local Interface Method Reference
| Interface | Main entry points | Notes |
|---|---|---|
| sam3 (official) · images | build_sam3_image_model(), Sam3Processor(model), .set_image(img), .set_text_prompt(state=, prompt=) | Returns masks, boxes, scores; points and boxes shown in the repo notebooks |
| sam3 (official) · video | build_sam3_video_predictor(), .handle_request(dict(type="start_session" | "add_prompt", ...)) | MP4 or JPEG folder; object IDs across frames; SAM 3.1 needs latest code |
| Transformers | Sam3Model, Sam3Processor, post_process_instance_segmentation(); Sam3TrackerModel; Sam3VideoModel | Batching, cached vision_embeds / text embeddings |
| Ultralytics | SAM3SemanticPredictor (text, exemplar boxes); SAM("sam3.pt") (points, boxes) | ultralytics 8.3.237+; can load sam3.1_multiplex.pt; AGPL-3.0 wrapper |
| Roboflow Inference (self-hosted) | docker run --gpus=all -p 9001:9001 roboflow/inference-server | Local HTTP server exposing the same SAM 3 modes |
All code for each interface: developer hub · Output formats: mask formats
Local → HTTP
Build Your Own SAM 3 API
Wrap the local interface in a small web service to get a hosted-style API you control.
- Load once: never build the model inside the request handler.
- One request at a time per GPU worker; add a queue (Redis, Celery, cloud tasks) for real traffic.
- Return compact masks: PNG as below, or RLE for large batches.
- Production: auth, size limits, timeouts. See production tips.
server.py
import io, base64
import numpy as np
from fastapi import FastAPI, UploadFile, Form # pip install fastapi uvicorn python-multipart
from PIL import Image
from sam3.model_builder import build_sam3_image_model
from sam3.model.sam3_image_processor import Sam3Processor
app = FastAPI()
processor = Sam3Processor(build_sam3_image_model()) # loaded once at startup
@app.post("/segment")
def segment(file: UploadFile, prompt: str = Form(...)):
image = Image.open(io.BytesIO(file.file.read())).convert("RGB")
out = processor.set_text_prompt(state=processor.set_image(image), prompt=prompt)
objects = []
for i in range(len(out["scores"])):
m = out["masks"][i].squeeze().cpu().numpy().astype(np.uint8) * 255
buf = io.BytesIO()
Image.fromarray(m).save(buf, format="PNG")
objects.append({"score": float(out["scores"][i]),
"box": out["boxes"][i].tolist(),
"mask_png": base64.b64encode(buf.getvalue()).decode()})
return {"prompt": prompt, "objects": objects}
# run: uvicorn server:app --port 8000 (one GPU worker per process)Formats and gotchas
Response Formats and Gotchas
Most integration bugs come from coordinates and mask encodings.
- Boxes: fal returns normalized
[cx, cy, w, h]; local and most box inputs use pixel[x0, y0, x1, y1]. - Masks: local = tensors; fal = image URLs; Roboflow = polygons or RLE.
- Thresholds: named differently:
output_prob_thresh,confidence_threshold,threshold. - Multiple masks: some endpoints return 1 by default; ask for more.
- Prompt names:
prompt,text_promptor apromptslist, depending on provider. - Errors: model access · empty masks
Questions
SAM API FAQ
Does Meta offer an official SAM 3 API?
No public paid API from Meta. You either call a hosted provider such as fal, Roboflow or a Replicate model, or run Meta’s open checkpoints locally through the sam3 package, Transformers or Ultralytics.
What is the difference between a hosted SAM API and a local Python interface?
A hosted API is an HTTP endpoint on someone else’s GPUs: you send an image URL and prompt, pay per call, and get JSON back. A local interface is a Python library on your own GPU: you call methods like set_text_prompt() and get tensors back, with no per-call fee.
How much does a hosted SAM 3 API cost?
fal lists SAM 3 image segmentation at $0.005 per request and video at $0.005 per 16 frames. Replicate community models are billed by GPU time. Check each provider’s current pricing.
Can I send a text prompt to a hosted SAM 3 API?
Yes. fal uses a prompt field, Roboflow’s concept_segment endpoint takes a prompts list with text items, and Replicate models usually expose a prompt or text_prompt input.
Why are the boxes from fal different from my local boxes?
fal returns normalized [cx, cy, w, h] boxes when include_boxes is on, while local interfaces typically return pixel coordinates. Convert before comparing.
How do I turn local SAM 3 into my own API?
Load the model once at startup in a web framework such as FastAPI, accept an image and prompt, run set_image and set_text_prompt, and return masks as PNG, RLE or polygons. Put a queue in front for heavy traffic.
Is it safe to send images to a hosted API?
Images leave your network, so check the provider’s data retention and security terms. For sensitive images, run SAM 3 locally or in your own cloud.