Meta SAM 3 Playground

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.

two kinds of API
Animation of hosted API versus local PythonTwo lanes. Top lane, hosted API: your app sends an HTTPS request over the internet to a provider’s GPU and gets JSON with mask links back. Bottom lane, local Python: your script calls the sam3 library, which runs on your own GPU and returns tensors in memory. HOSTED API · HTTPLOCAL PYTHON · in-process your app internet · API key providerGPU POST JSON your machine your script sam3 / HF / YOLO your GPU
Illustration: an HTTP round trip versus an in-process call.

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 callAn HTTPS endpoint with an API keyPython methods such as set_text_prompt()
HardwareProvider’s GPUsYour NVIDIA GPU (CUDA 12.6+)
Setup timeMinutes: get a keyAn hour or more: env, access, install
Cost modelPer request or per framesYour GPU time; no per-call fee
OutputJSON with mask URLs, RLE or polygonsTensors in memory
LatencyNetwork + queue + inferenceInference only
Data privacyImages leave your networkImages stay with you
CustomisationProvider’s options onlyFull: fine-tuning, video sessions, SAM 3 Agent
Best forPrototypes, low or spiky volume, no GPUHigh volume, sensitive data, custom pipelines
request lifecycle
Animation of a hosted API request lifecycleA request is submitted and gets a request ID. Its status badge cycles from in queue to in progress to completed, then the result returns JSON with mask image URLs, scores and boxes. submitPOST /queuepoll / webhookstatus_urlGPU runsSAM 3resultresponse_url status IN_QUEUEIN_PROGRESSCOMPLETED { "masks": [ { "url": "https://…/mask_0.png" }, … ], "scores": [0.94, 0.91], "boxes": [[0.41, 0.55, 0.18, 0.22], …] } illustrative fal-style response
Illustration of a queued hosted request.
  • 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 fieldDefaultWhat it does
image_urlrequiredImage 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_masksfalse, 3Return up to 32 masks
include_scores, include_boxesfalseAdd scores and normalized boxes
apply_mask, output_formattrue, pngPreview 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: Bearer header (the older api_key query parameter still works).
  • Several prompts per call: add more {"type": "text", ...} items to prompts.
  • 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-server Docker 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 page

One 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.
local stack
Animated stack of the local Python interfaceFour layers stack up: your Python code at the top, then the interface library such as sam3, Transformers or Ultralytics, then PyTorch with CUDA on your GPU, and at the bottom the gated checkpoint file. A pulse travels down and back up, showing a call returning tensors. your Python codecalls methodssam3 · Transformers · UltralyticsPython interfacePyTorch + CUDAtensors on GPUcheckpoint (gated)facebook/sam3 · sam3.1 no network hop · no per-call fee · you manage the GPU
Illustration of the local software stack.
  • Requirements: Python 3.12+, PyTorch 2.7+, CUDA 12.6+ GPU.
  • Access: approved access to facebook/sam3 (and facebook/sam3.1), then hf 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"]   # tensors

Local · reference

Local Interface Method Reference

InterfaceMain entry pointsNotes
sam3 (official) · imagesbuild_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) · videobuild_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
TransformersSam3Model, Sam3Processor, post_process_instance_segmentation(); Sam3TrackerModel; Sam3VideoModelBatching, cached vision_embeds / text embeddings
UltralyticsSAM3SemanticPredictor (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-serverLocal 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.

your own endpoint
Animation of wrapping local SAM 3 in your own APIClients send requests to your FastAPI server. The SAM 3 model is loaded once and stays in GPU memory. Each request runs set_image and set_text_prompt and returns JSON with scores, boxes and PNG masks. client 1client 2client 3 FastAPIPOST /segmentimage + prompt SAM 3 in VRAMloaded onceat startup your endpoint, your rules: auth, limits, formats, data stays in-house
Illustration of a self-hosted SAM 3 service.
  • 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.

box formats
Animation comparing pixel and normalized box formatsThe same box on a 1000 by 600 image is shown in two formats. Pixel corners: x0 300, y0 180, x1 500, y1 420. Normalized centre format: cx 0.40, cy 0.50, w 0.20, h 0.40. The display alternates between the two. image 1000 × 600 px (shown at 30%) (300,180)(500,420) xyxy · pixels[300, 180, 500, 420]local sam3 · RoboflowReplicate box inputs w .20h .40 cx,cy,w,h · 0–1[0.40, 0.50, 0.20, 0.40]fal output boxes always check each provider’s box format before drawing
Illustration: the same box in two formats.
  • 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_prompt or a prompts list, 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.

Keep reading