### Install and Test Project Dependencies (npm) Source: https://github.com/replicate/replicate-javascript/blob/main/CONTRIBUTING.md Installs project dependencies using npm and runs the test suite. This is a prerequisite for development and is typically run after cloning the repository. ```bash npm install npm test ``` -------------------------------- ### Replicate Training Job Creation Response Example Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Illustrates the JSON response structure received after successfully creating a training job with the Replicate API. This response includes the unique training ID, the model version used, the current status of the job (e.g., 'starting'), input parameters, and timestamps for creation and completion. ```json { "id": "zz4ibbonubfz7carwiefibzgga", "version": "3ae0799123a1fe11f8c89fd99632f843fc5f7a761630160521c4253149754523", "status": "starting", "input": { "text": "..." }, "output": null, "error": null, "logs": null, "started_at": null, "created_at": "2023-03-28T21:47:58.566434Z", "completed_at": null } ``` -------------------------------- ### Replicate Training Job Status Response Example (Succeeded) Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Presents a sample JSON response for a training job that has successfully completed. It includes the training ID, model version, 'succeeded' status, input parameters, output details (like the new model version), and timestamps for when the job started, was created, and finished. ```json { "id": "zz4ibbonubfz7carwiefibzgga", "version": "3ae0799123a1fe11f8c89fd99632f843fc5f7a761630160521c4253149754523", "status": "succeeded", "input": { "data": "...", "param1": "..." }, "output": { "version": "..." }, "error": null, "logs": null, "webhook_completed": null, "started_at": "2023-03-28T21:48:02.402755Z", "created_at": "2023-03-28T21:47:58.566434Z", "completed_at": "2023-03-28T02:49:48.492023Z" } ``` -------------------------------- ### GET /replicate/hardware/list Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Lists the available hardware options for running models on Replicate. This helps in selecting the appropriate hardware for model creation or execution. ```APIDOC ## GET /replicate/hardware/list ### Description List available hardware for running models on Replicate. ### Method GET ### Endpoint /replicate/hardware/list ### Parameters None ### Request Example ```js const response = await replicate.hardware.list() ``` ### Response #### Success Response (200) - **name** (string) - The human-readable name of the hardware. - **sku** (string) - The SKU identifier for the hardware (used in model creation). #### Response Example ```json [ {"name": "CPU", "sku": "cpu" }, {"name": "Nvidia T4 GPU", "sku": "gpu-t4" }, {"name": "Nvidia A40 GPU", "sku": "gpu-a40-small" }, {"name": "Nvidia A40 (Large) GPU", "sku": "gpu-a40-large" }, ] ``` ``` -------------------------------- ### Run SDXL Model with Text Prompt Input Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Example demonstrating how to run the Stability AI SDXL image generation model with a text prompt. The method awaits completion and returns the generated output directly. This is the simplest usage pattern without progress tracking. ```javascript const model = "stability-ai/sdxl:8beff3369e81422112d93b89ca01426147de542cd4684c244b673b105188fe5f"; const input = { prompt: "a 19th century portrait of a raccoon gentleman wearing a suit" }; const output = await replicate.run(model, { input }); ``` -------------------------------- ### GET /predictions Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Get a paginated list of all the predictions you've created. ```APIDOC ## GET /predictions ### Description Get a paginated list of all the predictions you've created. ### Method GET ### Endpoint `/predictions` ### Parameters *Note: This endpoint takes no arguments.* ### Request Example ```javascript const response = await replicate.predictions.list(); ``` ### Response #### Success Response (200) - **previous** (string/null) - URL for the previous page of results, or null if there are no previous results. - **next** (string) - URL for the next page of results. - **results** (array) - An array of prediction objects. - Each prediction object contains: - **id** (string) - The unique identifier for the prediction. - **version** (string) - The model version used for the prediction. - **urls** (object) - URLs for getting and canceling the prediction. - **get** (string) - URL to get the prediction details. - **cancel** (string) - URL to cancel the prediction. - **source** (string) - The source from which the prediction was initiated (e.g., 'web'). - **status** (string) - The current status of the prediction. - **created_at** (string) - Timestamp when the prediction was created. - **started_at** (string) - Timestamp when the prediction started processing. - **completed_at** (string) - Timestamp when the prediction was completed. #### Response Example ```json { "previous": null, "next": "https://api.replicate.com/v1/predictions?cursor=cD0yMDIyLTAxLTIxKzIzJTNBMTglM0EyNC41MzAzNTclMkIwMCUzQTAw", "results": [ { "id": "jpzd7hm5gfcapbfyt4mqytarku", "version": "b21cbe271e65c1718f2999b038c18b45e21e4fba961181fbfae9342fc53b9e05", "urls": { "get": "https://api.replicate.com/v1/predictions/jpzd7hm5gfcapbfyt4mqytarku", "cancel": "https://api.replicate.com/v1/predictions/jpzd7hm5gfcapbfyt4mqytarku/cancel" }, "source": "web", "status": "succeeded", "created_at": "2022-04-26T20:00:40.658234Z", "started_at": "2022-04-26T20:00:84.583803Z", "completed_at": "2022-04-26T20:02:27.648305Z" } /* ... */ ] } ``` ``` -------------------------------- ### Handle Replicate Webhooks with Hono Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Set up a web server using Hono to receive and process incoming webhook POST requests from Replicate. This example demonstrates how to extract prediction data from the request and acknowledge receipt. ```javascript import { serve } from '@hono/node-server'; import { Hono } from 'hono'; const app = new Hono(); app.get('/webhooks/replicate', async (c) => { // Get the prediction from the request. const prediction = await c.req.json(); console.log(prediction); //=> {"id": "xyz", "status": "successful", ... } // Acknowledge the webhook. c.status(200); c.json({ok: true}); }); serve(app, (info) => { console.log(`Listening on http://localhost:${info.port}`) //=> Listening on http://localhost:3000 }); ``` -------------------------------- ### Import Replicate client - CommonJS and ESM Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Import the Replicate package using either CommonJS or ES module syntax. CommonJS works with default setup or .cjs extension, while ESM requires 'module': true in package.json or .mjs extension. ```JavaScript // CommonJS (default or using .cjs extension) const Replicate = require("replicate"); // ESM (where `"module": true` in package.json or using .mjs extension) import Replicate from "replicate"; ``` -------------------------------- ### Run model synchronously and get output Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Execute a machine learning model with input parameters and await the result. Returns a FileOutput object for file data with .url() and .blob() methods for accessing the output. ```JavaScript const model = "stability-ai/stable-diffusion:27b93a2413e7f36cd83da926f3656280b2931564ff050bf9575f1fdf9bcd7478"; const input = { prompt: "a 19th century portrait of a raccoon gentleman wearing a suit", }; const [output] = await replicate.run(model, { input }); // FileOutput('https://replicate.delivery/pbxt/GtQb3Sgve42ZZyVnt8xjquFk9EX5LP0fF68NTIWlgBMUpguQA/out-0.png') console.log(output.url()); // 'https://replicate.delivery/pbxt/GtQb3Sgve42ZZyVnt8xjquFk9EX5LP0fF68NTIWlgBMUpguQA/out-0.png' console.log(output.blob()); // Blob ``` -------------------------------- ### Stream Model Output in JavaScript Source: https://context7.com/replicate/replicate-javascript/llms.txt Demonstrates how to stream output from models that support it, such as large language models. The example uses `replicate.stream` to process output events, including data, errors, and completion notifications, and aggregates the full output. ```javascript const replicate = new Replicate({ auth: process.env.REPLICATE_API_TOKEN, }); const model = "meta/llama-2-70b-chat"; const input = { prompt: "Write a poem about machine learning in the style of Mary Oliver.", max_tokens: 500, temperature: 0.7, }; const output = []; try { for await (const event of replicate.stream(model, { input })) { if (event.event === "output") { process.stdout.write(event.data); output.push(event.data); } else if (event.event === "error") { console.error("Error:", JSON.parse(event.data)); } else if (event.event === "done") { console.log("\nStream complete"); } } console.log("\nFull output:", output.join("")); } catch (error) { console.error("Streaming failed:", error.message); } ``` -------------------------------- ### Replicate Training Job Response Example (Canceled) Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Shows the JSON response structure for a training job that has been successfully canceled. The response includes the training ID, model version, 'canceled' status, input and output details, error logs (if any), and relevant timestamps. This confirms that the cancellation request was processed. ```json { "id": "zz4ibbonubfz7carwiefibzgga", "version": "3ae0799123a1fe11f8c89fd99632f843fc5f7a761630160521c4253149754523", "status": "canceled", "input": { "data": "...", "param1": "..." }, "output": { "version": "..." }, "error": null, "logs": null, "webhook_completed": null, "started_at": "2023-03-28T21:48:02.402755Z", "created_at": "2023-03-28T21:47:58.566434Z", "completed_at": "2023-03-28T02:49:48.492023Z" } ``` -------------------------------- ### Run a Model and Wait for Result in JavaScript Source: https://context7.com/replicate/replicate-javascript/llms.txt Shows how to execute an AI model using the Replicate client and wait for the prediction to complete. It includes an example of image generation with SDXL, handling the output, accessing URLs, and converting results to Blobs. Error handling for prediction failures is also demonstrated. ```javascript const replicate = new Replicate({ auth: process.env.REPLICATE_API_TOKEN, }); // Run an image generation model const model = "stability-ai/sdxl:8beff3369e81422112d93b89ca01426147de542cd4684c244b673b105188fe5f"; const input = { prompt: "a 19th century portrait of a raccoon gentleman wearing a suit", negative_prompt: "blurry, low quality", num_outputs: 1, }; try { const output = await replicate.run(model, { input }); console.log(output); // Output: [FileOutput instance] // Access the URL console.log(output[0].url()); // 'https://replicate.delivery/pbxt/abc123.../out-0.png' // Get as Blob const blob = await output[0].blob(); } catch (error) { console.error("Prediction failed:", error.message); } ``` -------------------------------- ### Create asynchronous prediction in background Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Start a model prediction asynchronously without waiting for completion. Requires version ID and input parameters. Returns prediction object with an ID for later retrieval. ```JavaScript let prediction = await replicate.predictions.create({ version: "27b93a2413e7f36cd83da926f3656280b2931564ff050bf9575f1fdf9bcd7478", input: { prompt: "painting of a cat by andy warhol", }, }); ``` -------------------------------- ### Get All Published Model Versions (JavaScript) Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Retrieves a list of all published versions for a given model, including their input and output schemas. Requires the model owner and model name as input. Returns a paginated list of version details. ```javascript const response = await replicate.models.versions.list(model_owner, model_name); ``` -------------------------------- ### Provide WebCrypto for Older Node.js Versions Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Addresses compatibility issues with the `validateWebhook` function on Node.js versions 18 and below, which may not have the global `crypto` API. This example shows how to manually provide the `webcrypto` module when calling `validateWebhook`. ```javascript const crypto = require("node:crypto").webcrypto; const webhookIsValid = await valdiateWebhook(requestData, crypto); ``` -------------------------------- ### Initialize Replicate Client (JavaScript) Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Demonstrates how to instantiate the Replicate client. It shows basic initialization and how to provide custom fetch implementations for advanced use cases. ```javascript const replicate = new Replicate(options); ``` ```javascript const Replicate = require("replicate"); const fetch = require("fetch"); // Using ESM: // import Replicate from "replicate"; // import fetch from "cross-fetch"; const replicate = new Replicate({ fetch }); ``` ```javascript const customFetch = (url, options) => { const headers = options && options.headers ? { ...options.headers } : {}; headers["X-Custom-Header"] = "some value"; console.log("fetch", { url, ...options, headers }); return fetch(url, { ...options, headers }); }; const replicate = new Replicate({ fetch: customFetch }); ``` -------------------------------- ### GET /models/{model_owner}/{model_name} Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Get metadata for a public model or a private model that you own. This endpoint retrieves detailed information about a specific model. ```APIDOC ## GET /models/{model_owner}/{model_name} ### Description Get metadata for a public model or a private model that you own. This endpoint retrieves detailed information about a specific model. ### Method GET ### Endpoint /models/{model_owner}/{model_name} ### Parameters #### Path Parameters - **model_owner** (string) - Required - The name of the user or organization that owns the model. - **model_name** (string) - Required - The name of the model. #### Query Parameters None #### Request Body None ### Request Example `GET /models/replicate/hello-world` ### Response #### Success Response (200) - **url** (string) - The URL of the model on Replicate. - **owner** (string) - The owner of the model. - **name** (string) - The name of the model. - **description** (string) - A description of the model. - **visibility** (string) - The visibility of the model (e.g., 'public'). - **github_url** (string) - The URL to the model's GitHub repository. - **paper_url** (string) - The URL to the model's paper, if available. - **license_url** (string) - The URL to the model's license, if available. - **latest_version** (object) - Information about the latest version of the model. #### Response Example ```json { "url": "https://replicate.com/replicate/hello-world", "owner": "replicate", "name": "hello-world", "description": "A tiny model that says hello", "visibility": "public", "github_url": "https://github.com/replicate/cog-examples", "paper_url": null, "license_url": null, "latest_version": { /* ... */ } } ``` ``` -------------------------------- ### Create Custom Model with Hardware Configuration in Replicate Source: https://context7.com/replicate/replicate-javascript/llms.txt Create a new model in your Replicate account with specified visibility, hardware, and metadata. Retrieves available hardware options and configures model details including GitHub URL, paper reference, and cover image. ```javascript const replicate = new Replicate({ auth: process.env.REPLICATE_API_TOKEN, }); // List available hardware const hardwareOptions = await replicate.hardware.list(); console.log("Available hardware:", hardwareOptions); // [{ name: "CPU", sku: "cpu" }, { name: "Nvidia T4 GPU", sku: "gpu-t4" }, ...] // Create a new model const newModel = await replicate.models.create( "my-username", "my-custom-model", { visibility: "private", hardware: "gpu-t4", description: "My custom image generation model", github_url: "https://github.com/my-username/my-model", paper_url: "https://arxiv.org/abs/1234.5678", license_url: "https://opensource.org/licenses/MIT", cover_image_url: "https://example.com/cover.png", } ); console.log("Created model:", newModel.url); console.log("Model name:", `${newModel.owner}/${newModel.name}`); ``` -------------------------------- ### Get Collection Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Retrieves a list of curated model collections available on Replicate. ```APIDOC ## GET /collections/{collection_slug} ### Description Get a list of curated model collections. See [replicate.com/collections](https://replicate.com/collections). ### Method GET ### Endpoint `/collections/{collection_slug}` ### Parameters #### Path Parameters - **collection_slug** (string) - Required - The slug of the collection. See http://replicate.com/collections ### Response #### Success Response (200) - **name** (string) - The name of the collection. - **description** (string) - A description of the collection. - **models** (array) - An array of models belonging to the collection. #### Response Example ```json { "name": "Example Collection", "description": "A curated list of example models.", "models": [ { "owner": "replicate", "name": "example-model" } ] } ``` ``` -------------------------------- ### Create New Replicate Deployment (JavaScript) Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Creates a new deployment for a model, specifying the model name, version, and hardware configuration. The function requires an options object with `name`, `model`, `version`, and `hardware`, and can optionally configure `min_instances` and `max_instances` for scaling. ```javascript const response = await replicate.deployments.create(options); ``` -------------------------------- ### List Available Hardware with Replicate JavaScript Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Fetches a list of all available hardware SKUs that can be used for running models on Replicate. This function takes no arguments and returns an array of hardware objects, each containing a 'name' and 'sku' for identification. This information is crucial for specifying hardware when creating or running models. ```javascript const response = await replicate.hardware.list() ``` -------------------------------- ### GET /predictions/{prediction_id} Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Retrieve the details of a specific prediction using its unique ID. ```APIDOC ## GET /predictions/{prediction_id} ### Description Retrieve the details of a specific prediction using its unique ID. ### Method GET ### Endpoint `/predictions/{prediction_id}` ### Parameters #### Path Parameters - **prediction_id** (number) - Required - The unique identifier for the prediction. ### Request Example ```javascript const response = await replicate.predictions.get(prediction_id); ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the prediction. - **version** (string) - The model version used for the prediction. - **urls** (object) - URLs for getting and canceling the prediction. - **get** (string) - URL to get the prediction details. - **cancel** (string) - URL to cancel the prediction. - **status** (string) - The current status of the prediction (e.g., 'starting', 'processing', 'succeeded', 'canceled', 'error'). - **input** (object) - The input parameters provided for the prediction. - **output** (any) - The output of the prediction, if completed successfully. - **error** (string) - Any error message if the prediction failed. - **logs** (string) - Logs generated during the prediction process. - **metrics** (object) - Metrics related to the prediction execution. - **created_at** (string) - Timestamp when the prediction was created. - **started_at** (string) - Timestamp when the prediction started processing. - **completed_at** (string) - Timestamp when the prediction was completed. #### Response Example ```json { "id": "ufawqhfynnddngldkgtslldrkq", "version": "5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa", "urls": { "get": "https://api.replicate.com/v1/predictions/ufawqhfynnddngldkgtslldrkq", "cancel": "https://api.replicate.com/v1/predictions/ufawqhfynnddngldkgtslldrkq/cancel" }, "status": "starting", "input": { "text": "Alice" }, "output": null, "error": null, "logs": null, "metrics": {}, "created_at": "2022-04-26T22:13:06.224088Z", "started_at": null, "completed_at": null } ``` ``` -------------------------------- ### Manage Deployments with Replicate JavaScript API Source: https://context7.com/replicate/replicate-javascript/llms.txt This snippet shows how to create, retrieve, update, list, and delete deployments for production use with the Replicate API. It also demonstrates running predictions against a deployment. Dependencies include the Replicate client library and Node.js environment variables for authentication. ```javascript const replicate = new Replicate({ auth: process.env.REPLICATE_API_TOKEN, }); // Create a deployment const deployment = await replicate.deployments.create({ name: "my-app-image-generator", model: "stability-ai/sdxl", version: "39ed52f2a78e934b3ba6e2a89f5b1c712de7dfea535525255b1aa35c5565e08b", hardware: "gpu-a40-large", min_instances: 1, max_instances: 5, }); console.log("Deployment created:", deployment.name); console.log("Current release:", deployment.current_release.number); // Get deployment details const retrieved = await replicate.deployments.get("my-username", "my-app-image-generator"); console.log("Deployment:", retrieved); // Update deployment const updated = await replicate.deployments.update( "my-username", "my-app-image-generator", { version: "8beff3369e81422112d93b89ca01426147de542cd4684c244b673b105188fe5f", min_instances: 2, max_instances: 10, } ); console.log("Updated to release:", updated.current_release.number); // Run prediction on deployment const prediction = await replicate.deployments.predictions.create( "my-username", "my-app-image-generator", { input: { prompt: "a beautiful sunset over mountains", }, } ); console.log("Prediction:", prediction.id); // List all deployments const deployments = await replicate.deployments.list(); for (const dep of deployments.results) { console.log(`${dep.owner}/${dep.name}`); } // Delete deployment const deleted = await replicate.deployments.delete("my-username", "my-app-image-generator"); console.log("Deleted:", deleted); ``` -------------------------------- ### Get Model Version Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Retrieves detailed metadata for a specific version of a model, including its schema. ```APIDOC ## GET /models/{model_owner}/{model_name}/versions/{version_id} ### Description Get metadata for a specific version of a model. ### Method GET ### Endpoint `/models/{model_owner}/{model_name}/versions/{version_id}` ### Parameters #### Path Parameters - **model_owner** (string) - Required - The name of the user or organization that owns the model. - **model_name** (string) - Required - The name of the model. - **version_id** (string) - Required - The model version identifier. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the model version. - **created_at** (string) - The timestamp when the version was created. - **cog_version** (string) - The version of Cog used for this model. - **openapi_schema** (object) - The OpenAPI schema defining the model's inputs and outputs. #### Response Example ```json { "id": "5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa", "created_at": "2022-04-26T19:29:04.418669Z", "cog_version": "0.3.0", "openapi_schema": {} } ``` ``` -------------------------------- ### GET /replicate/trainings/get Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Retrieves the metadata and current status of a specific training job using its unique ID. ```APIDOC ## GET /replicate/trainings/get ### Description Retrieves the metadata and current status of a specific training job using its unique ID. ### Method GET ### Endpoint `/replicate/trainings/get` ### Parameters #### Path Parameters None #### Query Parameters - **training_id** (string) - Required. The unique identifier for the training job. #### Request Body None ### Request Example ```bash GET /replicate/trainings/get?training_id=zz4ibbonubfz7carwiefibzgga ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the training job. - **version** (string) - The version of the model used for training. - **status** (string) - The current status of the training job (e.g., `succeeded`, `processing`, `failed`). - **input** (object) - The input parameters provided for the training job. - **output** (object | null) - The output of the training job, if completed successfully. - **error** (string | null) - An error message if the training job failed. - **logs** (string | null) - Logs from the training job. - **started_at** (string | null) - Timestamp when the training job started. - **created_at** (string) - Timestamp when the training job was created. - **completed_at** (string | null) - Timestamp when the training job was completed. #### Response Example ```json { "id": "zz4ibbonubfz7carwiefibzgga", "version": "3ae0799123a1fe11f8c89fd99632f843fc5f7a761630160521c4253149754523", "status": "succeeded", "input": { "data": "...", "param1": "..." }, "output": { "version": "..." }, "error": null, "logs": null, "webhook_completed": null, "started_at": "2023-03-28T21:48:02.402755Z", "created_at": "2023-03-28T21:47:58.566434Z", "completed_at": "2023-03-28T02:49:48.492023Z" } ``` ``` -------------------------------- ### Initialize Replicate Client in JavaScript Source: https://context7.com/replicate/replicate-javascript/llms.txt Demonstrates how to initialize the Replicate client in JavaScript using different authentication methods and custom configurations. This includes using an explicit API token, relying on environment variables, and setting custom base URLs or user agents. ```javascript const Replicate = require("replicate"); // Using explicit token const replicate = new Replicate({ auth: "r8_your_api_token_here", }); // Using environment variable (defaults to REPLICATE_API_TOKEN) const replicate = new Replicate(); // With custom configuration const replicate = new Replicate({ auth: process.env.REPLICATE_API_TOKEN, userAgent: "my-app/1.2.3", baseUrl: "https://api.replicate.com/v1", fileEncodingStrategy: "upload", useFileOutput: true, }); ``` -------------------------------- ### Run model with file input from local filesystem Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Execute a model that accepts file input by reading a local file and passing it as input. File handles are automatically uploaded to Replicate with a 100MiB size limit. ```JavaScript const fs = require("node:fs/promises"); // Or when using ESM. // import fs from "node:fs/promises"; const model = "nightmareai/real-esrgan:42fed1c4974146d4d2414e2be2c5277c7fcf05fcc3a73abf41610695738c1d7b"; const input = { image: await fs.readFile("path/to/image.png"), }; const [output] = await replicate.run(model, { input }); // FileOutput('https://replicate.delivery/mgxm/e7b0e122-9daa-410e-8cde-006c7308ff4d/output.png') ``` -------------------------------- ### GET /replicate/models/list Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Retrieves a paginated list of all public models available on Replicate. This endpoint is useful for discovering existing models. ```APIDOC ## GET /replicate/models/list ### Description Get a paginated list of all public models. ### Method GET ### Endpoint /replicate/models/list ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number to retrieve. - **page_size** (integer) - Optional - The number of results per page. ### Request Example ```js const response = await replicate.models.list(); ``` ### Response #### Success Response (200) - **next** (string) - URL for the next page of results, or null if none. - **previous** (string) - URL for the previous page of results, or null if none. - **results** (array) - An array of model objects. - **url** (string) - The API URL for the model. - **owner** (string) - The owner of the model (user or organization). - **name** (string) - The name of the model. - **description** (string) - A brief description of the model. - **visibility** (string) - The visibility of the model (e.g., "public"). - **github_url** (string) - URL to the model's GitHub repository, or null. - **paper_url** (string) - URL to the model's research paper, or null. - **license_url** (string) - URL to the model's license, or null. - **run_count** (integer) - The number of times the model has been run. - **cover_image_url** (string) - URL to the model's cover image. - **default_example** (object) - Details about the default example for the model. - **latest_version** (object) - Details about the latest version of the model. #### Response Example ```json { "next": null, "previous": null, "results": [ { "url": "https://replicate.com/replicate/hello-world", "owner": "replicate", "name": "hello-world", "description": "A tiny model that says hello", "visibility": "public", "github_url": "https://github.com/replicate/cog-examples", "paper_url": null, "license_url": null, "run_count": 5681081, "cover_image_url": "...", "default_example": { /* ... */ }, "latest_version": { /* ... */ } } ] } ``` ``` -------------------------------- ### POST /replicate/trainings/create Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Initiates a fine-tuning job for a language or image model. You can specify the model owner, name, version, destination for the trained model, input parameters, and webhook settings. ```APIDOC ## POST /replicate/trainings/create ### Description Initiates a fine-tuning job for a language or image model. You can specify the model owner, name, version, destination for the trained model, input parameters, and webhook settings. ### Method POST ### Endpoint `/replicate/trainings/create` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **model_owner** (string) - Required. The name of the user or organization that owns the model. - **model_name** (string) - Required. The name of the model. - **version** (string) - Required. The model version. - **options.destination** (string) - Required. The destination for the trained version in the format `{username}/{model_name}`. - **options.input** (object) - Required. An object with the model's inputs. - **options.webhook** (string) - Optional. An HTTPS URL for receiving a webhook when the training has new output. - **options.webhook_events_filter** (string[]) - Optional. You can change which events trigger webhook requests by specifying webhook events (`start` | `output` | `logs` | `completed`). ### Request Example ```json { "model_owner": "user", "model_name": "model", "version": "version_id", "options": { "destination": "user/new-model", "input": { "text": "..." }, "webhook": "https://example.com/webhook" } } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the training job. - **version** (string) - The version of the model used for training. - **status** (string) - The current status of the training job (e.g., `starting`, `processing`, `succeeded`, `failed`, `canceled`). - **input** (object) - The input parameters provided for the training job. - **output** (object | null) - The output of the training job, if completed successfully. - **error** (string | null) - An error message if the training job failed. - **logs** (string | null) - Logs from the training job. - **started_at** (string | null) - Timestamp when the training job started. - **created_at** (string) - Timestamp when the training job was created. - **completed_at** (string | null) - Timestamp when the training job was completed. #### Response Example ```json { "id": "zz4ibbonubfz7carwiefibzgga", "version": "3ae0799123a1fe11f8c89fd99632f843fc5f7a761630160521c4253149754523", "status": "starting", "input": { "text": "..." }, "output": null, "error": null, "logs": null, "started_at": null, "created_at": "2023-03-28T21:47:58.566434Z", "completed_at": null } ``` > **Warning** > If you try to fine-tune a model that doesn't support training, you'll get a `400 Bad Request` response from the server. ``` -------------------------------- ### Wait for prediction completion and get output Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Poll and wait for an asynchronous prediction to complete, then access the output. The output contains the model results as an array or object depending on the model. ```JavaScript prediction = await replicate.wait(prediction); console.log(prediction.output); // ['https://replicate.delivery/pbxt/RoaxeXqhL0xaYyLm6w3bpGwF5RaNBjADukfFnMbhOyeoWBdhA/out-0.png'] ``` -------------------------------- ### Create Deployment Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Creates a new deployment for a specified model and version. ```APIDOC ## POST /replicate/deployments ### Description Create a new deployment. ### Method POST ### Endpoint /replicate/deployments ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required. Name of the new deployment. - **model** (string) - Required. Name of the model in the format `{username}/{model_name}`. - **version** (string) - Required. ID of the model version. - **hardware** (string) - Required. SKU of the hardware to run the deployment on (e.g., `cpu`, `gpu-a100`). - **min_instances** (number) - Optional. Minimum number of instances to run. Defaults to 0. - **max_instances** (number) - Optional. Maximum number of instances to scale up to based on traffic. Defaults to 1. ### Request Example ```javascript const response = await replicate.deployments.create({ name: "my-app-image-generator", model: "stability-ai/sdxl", version: "da77bc59ee60423279fd632efb4795ab731d9e3ca9705ef3341091fb989b7eaf", hardware: "gpu-a100", min_instances: 1, max_instances: 1 }); ``` ### Response #### Success Response (200) - **owner** (string) - The owner of the deployment. - **name** (string) - The name of the deployment. - **current_release** (object) - Details about the current release of the deployment. - **number** (number) - The release number. - **model** (string) - The model name. - **version** (string) - The model version. - **created_at** (string) - Timestamp when the release was created. - **created_by** (object) - Information about who created the release. - **type** (string) - Type of creator (e.g., 'organization'). - **username** (string) - Username of the creator. - **name** (string) - Name of the creator. - **github_url** (string) - GitHub URL of the creator. - **configuration** (object) - Hardware and scaling configuration. - **hardware** (string) - SKU of the hardware. - **min_instances** (number) - Minimum number of instances. - **max_instances** (number) - Maximum number of instances. #### Response Example ```json { "owner": "acme", "name": "my-app-image-generator", "current_release": { "number": 1, "model": "stability-ai/sdxl", "version": "da77bc59ee60423279fd632efb4795ab731d9e3ca9705ef3341091fb989b7eaf", "created_at": "2024-03-14T11:43:32.049157Z", "created_by": { "type": "organization", "username": "acme", "name": "Acme, Inc.", "github_url": "https://github.com/replicate" }, "configuration": { "hardware": "gpu-a100", "min_instances": 1, "max_instances": 0 } } } ``` ``` -------------------------------- ### Create a Training Job with Replicate JavaScript Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Initiates a fine-tuning job for a language or image model using the Replicate JavaScript client. This function requires the model owner, model name, version ID, and an options object containing the destination, model inputs, and optional webhook configurations. It returns a training object detailing the job's status and ID. ```javascript const response = await replicate.trainings.create(model_owner, model_name, version_id, options); ``` -------------------------------- ### Retrieve File Metadata from Replicate Source: https://github.com/replicate/replicate-javascript/blob/main/README.md Get detailed metadata for a specific uploaded file by its ID, including content type, size, checksums, and expiration timestamp. Useful for verifying file properties before using them in predictions. ```javascript const response = await replicate.files.get(file_id); ``` -------------------------------- ### Train a Model using Replicate JavaScript API Source: https://context7.com/replicate/replicate-javascript/llms.txt This snippet demonstrates how to fine-tune models using the Replicate training API. It covers creating a training job, monitoring its status, and handling success or failure. Dependencies include the Replicate client library and Node.js environment variables for authentication. ```javascript const replicate = new Replicate({ auth: process.env.REPLICATE_API_TOKEN, }); // Create a training job let training = await replicate.trainings.create( "stability-ai", "sdxl", "39ed52f2a78e934b3ba6e2a89f5b1c712de7dfea535525255b1aa35c5565e08b", { destination: "my-username/my-fine-tuned-model", input: { input_images: "https://example.com/training-data.zip", token_string: "TOK", caption_prefix: "a photo of TOK", max_train_steps: 1000, learning_rate: 1e-6, }, webhook: "https://my.app/webhooks/training", webhook_events_filter: ["completed"], } ); console.log("Training ID:", training.id); console.log("Status:", training.status); // Wait for training to complete while (training.status !== "succeeded" && training.status !== "failed") { await new Promise((resolve) => setTimeout(resolve, 5000)); training = await replicate.trainings.get(training.id); console.log("Status:", training.status); if (training.logs) { console.log("Latest logs:", training.logs.split("\n").slice(-5).join("\n")); } } if (training.status === "succeeded") { console.log("Training complete!"); console.log("New version:", training.output.version); } else { console.error("Training failed:", training.error); } // Cancel training if needed const cancelled = await replicate.trainings.cancel(training.id); console.log("Cancelled:", cancelled.status); ```