CORS workaround in browser tests
mainpage.route handler to intercept requests. This allows the tests to run in a browser environment without modifying the actual request or response content.repository·main·Indexed 20 days ago
https://github.com/replicate/replicate-javascriptA 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.
page.route handler to intercept requests. This allows the tests to run in a browser environment without modifying the actual request or response content.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:
webhook URL in replicate.predictions.create.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"],
});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 })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:
REPLICATE_API_TOKEN.Setup: Install dependencies using npm:
npm installExecution:
npm test- Run against the default browser (Chromium):
```bash
npm exec playwright testnpm exec playwright test --browser firefoxInstall the replicate package via npm to use the client in your Node.js, Bun, or Deno projects.
Supported platforms:
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
```埋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 --debugSetting 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.
When a model requires a file input, you can provide:
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 });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));
});
}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.
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"
});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" });
};Retrieve a list of curated model collections using a collection slug.
const response = await replicate.collections.get(collection_slug);Retrieve a paginated list of all predictions created by the user. This method takes no arguments.
const response = await replicate.predictions.list();