replicate-javascript

repository·main·Indexed 20 days ago

https://github.com/replicate/replicate-javascript

A JavaScript/TypeScript client for the Replicate API, enabling developers to run machine learning models in the cloud. Supports Node.js >= 18, Bun >= 1.0, and Deno >= 1.28. Key features include synchronous model execution via replicate.run, background predictions, SSE streaming with replicate.stream, and webhook validation using validateWebhook. It provides tools for managing models, handling file inputs up to 100MiB, and integrating with serverless platforms like Cloudflare Workers, Vercel, and AWS Lambda.

Tokens
13.7K
Snippets
69
Records
74
Agent score
69%

What's inside replicate

  1. Configure Webhooks for real-time updates

    main

    Instead of polling for results, you can use Webhooks to receive HTTP POST requests from Replicate when a prediction's status changes.

    To use webhooks:

    1. Provide a webhook URL in replicate.predictions.create.
    2. Specify which events to receive using webhook_events_filter. Supported values are: "start", "output", "logs", and "completed".

    Example setup with a webhook URL:

    await replicate.predictions.create({
      version: "...",
      input: { ... },
      webhook: "https://my.app/webhooks/replicate",
      webhook_events_filter: ["completed"],
    });
    const Replicate = require("replicate");
    const replicate = new Replicate();
    
    const input = {
        image: "https://replicate.delivery/pbxt/KWDkejqLfER3jrroDTUsSvBWFaHtapPxfg4xxZIqYmfh3zXm/Screenshot%202024-02-28%20at%2022.14.00.png",
        denoising_strength: 0.5,
        instant_id_strength: 0.8
    };
    
    const callbackURL = `https://my.app/webhooks/replicate`;
    await replicate.predictions.create({
      version: "19deaef633fd44776c82edf39fd60e95a7250b8ececf11a725229dc75a81f9ca",
      input: input,
      webhook: callbackURL,
      webhook_events_filter: ["completed"],
    });
  2. Use TypeScript with Replicate

    main

    The library provides full TypeScript definitions. You can import types like Prediction directly from the package.

    Requirement: To support the module format, you must set "esModuleInterop": true in your tsconfig.json.

    import Replicate, { type Prediction } from 'replicate';
    
    const replicate = new Replicate();
    const model = "black-forest-labs/flux-schnell";
    
    function onProgress(prediction: Prediction) { 
      console.log({ prediction });
    }
    
    const output = await replicate.run(model, { input: { prompt: "..." } }, onProgress);
    import Replicate, { type Prediction } from 'replicate';
    
    const replicate = new Replicate();
    const model = "black-forest-labs/flux-schnell";
    const prompt = "a 19th century portrait of a raccoon gentleman wearing a suit";
    
    function onProgress(prediction: Prediction) {
      console.log({ prediction });
    }
    
    const output = await replicate.run(model, { input: { prompt } }, onProgress)
    console.log({ output })
  3. Run browser integration tests

    main

    The browser integration tests use playwright to run tests against Firefox, Chromium, and WebKit. The suite exercises the streaming API using the replicate/canary model.

    Prerequisites:

    • A Replicate API token must be available in your environment as REPLICATE_API_TOKEN.

    Setup: Install dependencies using npm:

    npm install

    Execution:

    • Run tests across all browsers:
      npm test
    - Run against the default browser (Chromium):
      ```bash
    npm exec playwright test
    • Run against a specific browser (e.g., Firefox):
      npm exec playwright test --browser firefox
  4. Install the Replicate Node.js client

    main

    Install the replicate package via npm to use the client in your Node.js, Bun, or Deno projects.

    Supported platforms:

    • Node.js >= 18
    • Bun >= 1.0
    • Deno >= 1.28
    • Most serverless platforms (Cloudflare Workers, Vercel functions, AWS Lambda)

    Note: This library cannot be used directly from a browser. For web applications, use a backend or a framework like Next.js.

    ```bash
    npm install replicate
    ```埋
  5. Debug browser integration tests

    main

    To debug the integration tests, run Playwright with the --debug flag. This opens a browser window with a debugging interface and sets a breakpoint at the start of the test. You can also connect this directly to VSCode.

    npm exec playwright test --debug

    Setting breakpoints in injected code: Since browser.js is injected into the page via a script tag, you can set breakpoints by adding a debugger statement within that file and opening the DevTools in the spawned browser window before continuing the test suite.

  6. Pass file inputs to models

    main

    When a model requires a file input, you can provide:

    1. A publicly accessible URL to the file.
    2. A local file handle (e.g., a Buffer from fs.readFile).

    Note: File handle inputs are automatically uploaded to Replicate. The maximum upload size is 100MiB. For files larger than 100MiB, upload them to your own storage provider and pass the public URL instead.

    const fs = require("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 });
  7. Stream prediction output using Server-Sent Events

    main

    If options.stream is set to true during prediction creation, the returned prediction object will contain a urls.stream property. You can use this URL with the EventSource API to listen for real-time updates.

    Event Types:

    • output (plain text): Emitted when the prediction returns new output.
    • error (JSON): Emitted when the prediction returns an error.
    • done (JSON): Emitted when the prediction finishes (successfully, via cancellation, or via error).
    if (prediction && prediction.urls && prediction.urls.stream) {
      const source = new EventSource(prediction.urls.stream, { withCredentials: true });
    
      source.addEventListener("output", (e) => {
        console.log("output", e.data);
      });
    
      source.addEventListener("error", (e) => {
        console.error("error", JSON.parse(e.data));
      });
    
      source.addEventListener("done", (e) => {
        source.close();
        console.log("done", JSON.parse(e.data));
      });
    }
  8. Instantiate the Replicate client

    main

    To interact with the Replicate API, create a new instance of the Replicate class. You can provide an API token via the auth option or by setting the REPLICATE_API_TOKEN environment variable.

    Configuration Options

    • auth (string): API access token. Defaults to process.env.REPLICATE_API_TOKEN.
    • userAgent (string): Identifier of your app.
    • baseUrl (string): Defaults to https://api.replicate.com/v1.
    • fetch (Function): Custom fetch function. Defaults to globalThis.fetch.
    • useFileOutput (boolean): If false, run returns URLs instead of FileOutput objects. Defaults to true.
    • fileEncodingStrategy (string): Determines the file encoding strategy. Options: "default", "upload", or "data-uri".
    const Replicate = require("replicate");
    
    const replicate = new Replicate({
        // get your token from https://replicate.com/account
        auth: process.env.REPLICATE_API_TOKEN,
        userAgent: "my-app/1.2.3"
    });
  9. Fix predictions hanging in Next.js App Router

    main

    Next.js App Router extends the global fetch API to cache responses, which can cause Replicate predictions to hang. To prevent this, you must disable caching by setting the cache option to "no-store" on the Replicate client's fetch property.

    Alternatively, you can use the Next.js noStore function within your component to opt out of caching.

    replicate = new Replicate({/*...*/})
    replicate.fetch = (url, options) => {
      return fetch(url, { ...options, cache: "no-store" });
    };