{"id":13570039,"url":"https://github.com/replicate/replicate-javascript","last_synced_at":"2025-05-14T01:05:37.154Z","repository":{"id":72243129,"uuid":"567870467","full_name":"replicate/replicate-javascript","owner":"replicate","description":"Node.js client for Replicate","archived":false,"fork":false,"pushed_at":"2025-03-26T17:43:49.000Z","size":819,"stargazers_count":535,"open_issues_count":6,"forks_count":219,"subscribers_count":27,"default_branch":"main","last_synced_at":"2025-04-03T06:53:08.280Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://replicate.com/docs/get-started/nodejs","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/replicate.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-11-18T19:28:10.000Z","updated_at":"2025-03-28T13:46:38.000Z","dependencies_parsed_at":"2023-12-15T14:30:00.911Z","dependency_job_id":"d947c457-814d-4e38-aebb-7eb5e7371d83","html_url":"https://github.com/replicate/replicate-javascript","commit_stats":{"total_commits":286,"total_committers":24,"mean_commits":"11.916666666666666","dds":"0.44405594405594406","last_synced_commit":"0b7c8ebd9adb30f84ab420d1288e2ce1dac349cf"},"previous_names":[],"tags_count":65,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/replicate%2Freplicate-javascript","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/replicate%2Freplicate-javascript/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/replicate%2Freplicate-javascript/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/replicate%2Freplicate-javascript/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/replicate","download_url":"https://codeload.github.com/replicate/replicate-javascript/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248208688,"owners_count":21065205,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T14:00:47.516Z","updated_at":"2025-04-10T11:37:15.921Z","avatar_url":"https://github.com/replicate.png","language":"TypeScript","funding_links":[],"categories":["JavaScript SDKs for general AI APIs","TypeScript","Client libraries"],"sub_categories":[],"readme":"# Replicate Node.js client\n\nA Node.js client for [Replicate](https://replicate.com).\nIt lets you run models from your Node.js code,\nand everything else you can do with\n[Replicate's HTTP API](https://replicate.com/docs/reference/http).\n\n\u003e [!IMPORTANT]\n\u003e This library can't interact with Replicate's API directly from a browser.\n\u003e For more information about how to build a web application\n\u003e check out our [\"Build a website with Next.js\"](https://replicate.com/docs/get-started/nextjs) guide.\n\n## Supported platforms\n\n- [Node.js](https://nodejs.org) \u003e= 18\n- [Bun](https://bun.sh) \u003e= 1.0\n- [Deno](https://deno.com) \u003e= 1.28\n\nYou can also use this client library on most serverless platforms, including\n[Cloudflare Workers](https://developers.cloudflare.com/workers/),\n[Vercel functions](https://vercel.com/docs/functions), and\n[AWS Lambda](https://aws.amazon.com/lambda/).\n\n## Installation\n\nInstall it from npm:\n\n```bash\nnpm install replicate\n```\n\n## Usage\n\nImport or require the package:\n\n```js\n// CommonJS (default or using .cjs extension)\nconst Replicate = require(\"replicate\");\n\n// ESM (where `\"module\": true` in package.json or using .mjs extension)\nimport Replicate from \"replicate\";\n```\n\nInstantiate the client:\n\n```js\nconst replicate = new Replicate({\n  // get your token from https://replicate.com/account/api-tokens\n  auth: \"my api token\", // defaults to process.env.REPLICATE_API_TOKEN\n});\n```\n\nRun a model and await the result:\n\n```js\nconst model = \"stability-ai/stable-diffusion:27b93a2413e7f36cd83da926f3656280b2931564ff050bf9575f1fdf9bcd7478\";\nconst input = {\n  prompt: \"a 19th century portrait of a raccoon gentleman wearing a suit\",\n};\nconst [output] = await replicate.run(model, { input });\n// FileOutput('https://replicate.delivery/pbxt/GtQb3Sgve42ZZyVnt8xjquFk9EX5LP0fF68NTIWlgBMUpguQA/out-0.png')\n\nconsole.log(output.url()); // 'https://replicate.delivery/pbxt/GtQb3Sgve42ZZyVnt8xjquFk9EX5LP0fF68NTIWlgBMUpguQA/out-0.png'\nconsole.log(output.blob()); // Blob\n```\n\n\u003e [!NOTE]\n\u003e A model that outputs file data returns a `FileOutput` object by default. This is an implementation\n\u003e of `ReadableStream` that returns the file contents. It has a `.blob()` method for accessing a\n\u003e `Blob` representation and a `.url()` method that will return the underlying data-source.\n\u003e\n\u003e We recommend accessing file data directly either as readable stream or via `.blob()` as the\n\u003e `.url()` property may not always return a HTTP URL in future.\n\nYou can also run a model in the background:\n\n```js\nlet prediction = await replicate.predictions.create({\n  version: \"27b93a2413e7f36cd83da926f3656280b2931564ff050bf9575f1fdf9bcd7478\",\n  input: {\n    prompt: \"painting of a cat by andy warhol\",\n  },\n});\n```\n\nThen fetch the prediction result later:\n\n```js\nprediction = await replicate.predictions.get(prediction.id);\n```\n\nOr wait for the prediction to finish:\n\n```js\nprediction = await replicate.wait(prediction);\nconsole.log(prediction.output);\n// ['https://replicate.delivery/pbxt/RoaxeXqhL0xaYyLm6w3bpGwF5RaNBjADukfFnMbhOyeoWBdhA/out-0.png']\n```\n\nTo run a model that takes a file input you can pass either\na URL to a publicly accessible file on the Internet\nor a handle to a file on your local device.\n\n```js\nconst fs = require(\"node:fs/promises\");\n\n// Or when using ESM.\n// import fs from \"node:fs/promises\";\n\nconst model = \"nightmareai/real-esrgan:42fed1c4974146d4d2414e2be2c5277c7fcf05fcc3a73abf41610695738c1d7b\";\nconst input = {\n  image: await fs.readFile(\"path/to/image.png\"),\n};\nconst [output] = await replicate.run(model, { input });\n// FileOutput('https://replicate.delivery/mgxm/e7b0e122-9daa-410e-8cde-006c7308ff4d/output.png')\n```\n\n\u003e [!NOTE]\n\u003e File handle inputs are automatically uploaded to Replicate.\n\u003e See [`replicate.files.create`](#replicatefilescreate) for more information.\n\u003e The maximum size for uploaded files is 100MiB.\n\u003e To run a model with a larger file as an input,\n\u003e upload the file to your own storage provider\n\u003e and pass a publicly accessible URL.\n\n## TypeScript usage\n\nThis library exports TypeScript definitions. You can import them like this:\n\n```ts\nimport Replicate, { type Prediction } from 'replicate';\n```\n\nHere's an example that uses the `Prediction` type with a custom `onProgress` callback:\n\n```ts\nimport Replicate, { type Prediction } from 'replicate';\n\nconst replicate = new Replicate();\nconst model = \"black-forest-labs/flux-schnell\";\nconst prompt = \"a 19th century portrait of a raccoon gentleman wearing a suit\";\nfunction onProgress(prediction: Prediction) {\n  console.log({ prediction });\n}\n\nconst output = await replicate.run(model, { input: { prompt } }, onProgress)\nconsole.log({ output })\n```\n\nSee the full list of exported types in [index.d.ts](./index.d.ts).\n\n### Webhooks\n\nWebhooks provide real-time updates about your prediction. Specify an endpoint when you create a prediction, and Replicate will send HTTP POST requests to that URL when the prediction is created, updated, and finished.\n\nIt is possible to provide a URL to the predictions.create() function that will be requested by Replicate when the prediction status changes. This is an alternative to polling.\n\nTo receive webhooks you’ll need a web server. The following example uses Hono, a web standards based server, but this pattern applies to most frameworks.\n\n\u003cdetails\u003e\n  \u003csummary\u003eSee example\u003c/summary\u003e\n\n```js\nimport { serve } from '@hono/node-server';\nimport { Hono } from 'hono';\n\nconst app = new Hono();\napp.get('/webhooks/replicate', async (c) =\u003e {\n  // Get the prediction from the request.\n  const prediction = await c.req.json();\n  console.log(prediction);\n  //=\u003e {\"id\": \"xyz\", \"status\": \"successful\", ... }\n\n  // Acknowledge the webhook.\n  c.status(200);\n  c.json({ok: true});\n}));\n\nserve(app, (info) =\u003e {\n  console.log(`Listening on http://localhost:${info.port}`)\n  //=\u003e Listening on http://localhost:3000\n});\n```\n\n\u003c/details\u003e\n\nCreate the prediction passing in the webhook URL to `webhook` and specify which events you want to receive in `webhook_events_filter` out of \"start\", \"output\", ”logs” and \"completed\":\n\n```js\nconst Replicate = require(\"replicate\");\nconst replicate = new Replicate();\n\nconst input = {\n    image: \"https://replicate.delivery/pbxt/KWDkejqLfER3jrroDTUsSvBWFaHtapPxfg4xxZIqYmfh3zXm/Screenshot%202024-02-28%20at%2022.14.00.png\",\n    denoising_strength: 0.5,\n    instant_id_strength: 0.8\n};\n\nconst callbackURL = `https://my.app/webhooks/replicate`;\nawait replicate.predictions.create({\n  version: \"19deaef633fd44776c82edf39fd60e95a7250b8ececf11a725229dc75a81f9ca\",\n  input: input,\n  webhook: callbackURL,\n  webhook_events_filter: [\"completed\"],\n});\n\n// The server will now handle the event and log:\n// =\u003e {\"id\": \"xyz\", \"status\": \"successful\", ... }\n```\n\n## Verifying webhooks\n\nTo prevent unauthorized requests, Replicate signs every webhook and its metadata with a unique key for each user or organization. You can use this signature to verify the webhook indeed comes from Replicate before you process it.\n\nThis client includes a `validateWebhook` convenience function that you can use to validate webhooks.\n\nTo validate webhooks:\n\n1. Check out the [webhooks guide](https://replicate.com/docs/webhooks) to get started.\n1. [Retrieve your webhook signing secret](https://replicate.com/docs/webhooks#retrieving-the-webhook-signing-key) and store it in your enviroment.\n1. Update your webhook handler to call `validateWebhook(request, secret)`, where `request` is an instance of a [web-standard `Request` object](https://developer.mozilla.org/en-US/docs/Web/API/object), and `secret` is the signing secret for your environment.\n\nHere's an example of how to validate webhooks using Next.js:\n\n```js\nimport { NextResponse } from 'next/server';\nimport { validateWebhook } from 'replicate';\n\nexport async function POST(request) {\n  const secret = process.env.REPLICATE_WEBHOOK_SIGNING_SECRET;\n\n  if (!secret) {\n    console.log(\"Skipping webhook validation. To validate webhooks, set REPLICATE_WEBHOOK_SIGNING_SECRET\")\n    const body = await request.json();\n    console.log(body);\n    return NextResponse.json({ detail: \"Webhook received (but not validated)\" }, { status: 200 });\n  }\n\n  const webhookIsValid = await validateWebhook(request.clone(), secret);\n\n  if (!webhookIsValid) {\n    return NextResponse.json({ detail: \"Webhook is invalid\" }, { status: 401 });\n  }\n\n  // process validated webhook here...\n  console.log(\"Webhook is valid!\");\n  const body = await request.json();\n  console.log(body);\n\n  return NextResponse.json({ detail: \"Webhook is valid\" }, { status: 200 });\n}\n```\n\nIf your environment doesn't support `Request` objects, you can pass the required information to `validateWebhook` directly:\n\n```js\nconst requestData = {\n  id: \"123\",            // the `Webhook-Id` header\n  timestamp: \"0123456\", // the `Webhook-Timestamp` header\n  signature: \"xyz\",     // the `Webhook-Signature` header\n  body: \"{...}\",        // the request body as a string, ArrayBuffer or ReadableStream\n  secret: \"shhh\",       // the webhook secret, obtained from the `replicate.webhooks.defaul.secret` endpoint\n};\nconst webhookIsValid = await validateWebhook(requestData);\n```\n\n\u003e [!NOTE]\n\u003e The `validateWebhook` function uses the global `crypto` API available in most JavaScript runtimes. Node \u003c= 18 does not provide this global so in this case you need to either call node with the `--no-experimental-global-webcrypto` or provide the `webcrypto` module manually.\n\u003e ```js\n\u003e const crypto = require(\"node:crypto\").webcrypto;\n\u003e const webhookIsValid = await valdiateWebhook(requestData, crypto);\n\u003e ```\n\n## TypeScript\n\nThe `Replicate` constructor and all `replicate.*` methods are fully typed.\n\nCurrently in order to support the module format used by `replicate` you'll need to set `esModuleInterop` to `true` in your tsconfig.json.\n\n## API\n\n### Constructor\n\n```js\nconst replicate = new Replicate(options);\n```\n\n| name                           | type     | description                                                                                                                      |\n| ------------------------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------- |\n| `options.auth`                 | string   | **Required**. API access token                                                                                                   |\n| `options.userAgent`            | string   | Identifier of your app. Defaults to `replicate-javascript/${packageJSON.version}`                                                |\n| `options.baseUrl`              | string   | Defaults to https://api.replicate.com/v1                                                                                         |\n| `options.fetch`                | function | Fetch function to use. Defaults to `globalThis.fetch`                                                                            |\n| `options.fileEncodingStrategy` | string   | Determines the file encoding strategy to use. Possible values: `\"default\"`, `\"upload\"`, or `\"data-uri\"`. Defaults to `\"default\"` |\n| `options.useFileOutput`        | boolean  | Determines if the `replicate.run()` method should convert file output into `FileOutput` objects |\n\n\nThe client makes requests to Replicate's API using\n[fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch).\nBy default, the `globalThis.fetch` function is used,\nwhich is available on [Node.js 18](https://nodejs.org/en/blog/announcements/v18-release-announce#fetch-experimental) and later,\nas well as\n[Cloudflare Workers](https://developers.cloudflare.com/workers/runtime-apis/fetch/),\n[Vercel Functions](https://vercel.com/docs/functions),\nand other environments.\n\nOn earlier versions of Node.js\nand other environments where global fetch isn't available,\nyou can install a fetch function from an external package like\n[cross-fetch](https://www.npmjs.com/package/cross-fetch)\nand pass it to the `fetch` option in the constructor.\n\n```js\nconst Replicate = require(\"replicate\");\nconst fetch = require(\"fetch\");\n\n// Using ESM:\n// import Replicate from \"replicate\";\n// import fetch from \"cross-fetch\";\n\nconst replicate = new Replicate({ fetch });\n```\n\nYou can also use the `fetch` option to add custom behavior to client requests,\nsuch as injecting headers or adding log statements.\n\n```js\nconst customFetch = (url, options) =\u003e {\n  const headers = options \u0026\u0026 options.headers ? { ...options.headers } : {};\n  headers[\"X-Custom-Header\"] = \"some value\";\n\n  console.log(\"fetch\", { url, ...options, headers });\n\n  return fetch(url, { ...options, headers });\n};\n\nconst replicate = new Replicate({ fetch: customFetch });\n```\n\n### `replicate.run`\n\nRun a model and await the result. Unlike [`replicate.prediction.create`](#replicatepredictionscreate), this method returns only the prediction output rather than the entire prediction object.\n\n```js\nconst output = await replicate.run(identifier, options, progress);\n```\n\n| name                            | type     | description                                                                                                                                                                                                 |\n| ------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `identifier`                    | string   | **Required**. The model version identifier in the format `{owner}/{name}:{version}`, for example `stability-ai/sdxl:8beff3369e81422112d93b89ca01426147de542cd4684c244b673b105188fe5f`                       |\n| `options.input`                 | object   | **Required**. An object with the model inputs.                                                                                                                                                              |\n| `options.wait`                  | object   | Options for waiting for the prediction to finish                        | \n| `options.wait.mode`             | `\"poll\" \\| \"block\"`   | `\"block\"` holds the request open, `\"poll\"` makes repeated requests to fetch the prediction. Defaults to `\"block\"`  |\n| `options.wait.interval`         | number   | Polling interval in milliseconds. Defaults to 500 |\n| `options.wait.timeout`          | number   | In `\"block\"` mode determines how long the request will be held open until falling back to polling. Defaults to 60 |\n| `options.webhook`               | string   | An HTTPS URL for receiving a webhook when the prediction has new output                                                                                                                                     |\n| `options.webhook_events_filter` | string[] | An array of events which should trigger [webhooks](https://replicate.com/docs/webhooks). Allowable values are `start`, `output`, `logs`, and `completed`                                                    |\n| `options.signal`                | object   | An [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) to cancel the prediction                                                                                                     |\n| `progress`                      | function | Callback function that receives the prediction object as it's updated. The function is called when the prediction is created, each time it's updated while polling for completion, and when it's completed. |\n\nThrows `Error` if the prediction failed.\n\nReturns `Promise\u003cunknown\u003e` which resolves with the output of running the model.\n\n\u003e [!NOTE]\n\u003e Currently the TypeScript return type of `replicate.run()` is `Promise\u003cobject\u003e` this is\n\u003e misleading as a model can return array types as well as primative types like strings,\n\u003e numbers and booleans.\n\nExample:\n\n```js\nconst model = \"stability-ai/sdxl:8beff3369e81422112d93b89ca01426147de542cd4684c244b673b105188fe5f\";\nconst input = { prompt: \"a 19th century portrait of a raccoon gentleman wearing a suit\" };\nconst output = await replicate.run(model, { input });\n```\n\nExample that logs progress as the model is running:\n\n```js\nconst model = \"stability-ai/sdxl:8beff3369e81422112d93b89ca01426147de542cd4684c244b673b105188fe5f\";\nconst input = { prompt: \"a 19th century portrait of a raccoon gentleman wearing a suit\" };\nconst onProgress = (prediction) =\u003e {\n   const last_log_line = prediction.logs.split(\"\\n\").pop()\n   console.log({id: prediction.id, log: last_log_line})\n}\nconst output = await replicate.run(model, { input }, onProgress)\n```\n\n#### Sync vs. Async API (`\"poll\"` vs. `\"block\"`)\n\nThe `replicate.run()` API takes advantage of the [Replicate sync API](https://replicate.com/docs/topics/predictions/create-a-prediction)\nwhich is optimized for low latency requests to file models like `black-forest-labs/flux-dev` and \n`black-forest-labs/flux-schnell`. When creating a prediction this will hold a connection open to the\nserver and return a `FileObject` containing the generated file as quickly as possible.\n\n### `replicate.stream`\n\nRun a model and stream its output. Unlike [`replicate.prediction.create`](#replicatepredictionscreate), this method returns only the prediction output rather than the entire prediction object.\n\n```js\nfor await (const event of replicate.stream(identifier, options)) { /* ... */ }\n```\n\n| name                            | type     | description                                                                                                                                              |\n| ------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `identifier`                    | string   | **Required**. The model version identifier in the format `{owner}/{name}` or `{owner}/{name}:{version}`, for example `meta/llama-2-70b-chat`             |\n| `options.input`                 | object   | **Required**. An object with the model inputs.                                                                                                           |\n| `options.webhook`               | string   | An HTTPS URL for receiving a webhook when the prediction has new output                                                                                  |\n| `options.webhook_events_filter` | string[] | An array of events which should trigger [webhooks](https://replicate.com/docs/webhooks). Allowable values are `start`, `output`, `logs`, and `completed` |\n| `options.signal`                | object   | An [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) to cancel the prediction                                                  |\n\nThrows `Error` if the prediction failed.\n\nReturns `AsyncGenerator\u003cServerSentEvent\u003e` which yields the events of running the model.\n\nExample:\n\n```js\nconst model = \"meta/llama-2-70b-chat\";\nconst options = {\n  input: {\n    prompt: \"Write a poem about machine learning in the style of Mary Oliver.\",\n  },\n  // webhook: \"https://smee.io/dMUlmOMkzeyRGjW\" // optional\n};\nconst output = [];\n\nfor await (const { event, data } of replicate.stream(model, options)) {\n  if (event === \"output\") {\n    output.push(data);\n  }\n}\n\nconsole.log(output.join(\"\").trim());\n```\n\n### Server-sent events\n\nA stream generates server-sent events with the following properties:\n\n| name    | type   | description                                                                  |\n| ------- | ------ | ---------------------------------------------------------------------------- |\n| `event` | string | The type of event. Possible values are `output`, `logs`, `error`, and `done` |\n| `data`  | string | The event data                                                               |\n| `id`    | string | The event id                                                                 |\n| `retry` | number | The number of milliseconds to wait before reconnecting to the server         |\n\nAs the prediction runs, the generator yields `output` and `logs` events. If an error occurs, the generator yields an `error` event with a JSON object containing the error message set to the `data` property. When the prediction is done, the generator yields a `done` event with an empty JSON object set to the `data` property.\n\nEvents with the `output` event type have their `toString()` method overridden to return the event data as a string. Other event types return an empty string.\n\n### `replicate.models.get`\n\nGet metadata for a public model or a private model that you own.\n\n```js\nconst response = await replicate.models.get(model_owner, model_name);\n```\n\n| name          | type   | description                                                             |\n| ------------- | ------ | ----------------------------------------------------------------------- |\n| `model_owner` | string | **Required**. The name of the user or organization that owns the model. |\n| `model_name`  | string | **Required**. The name of the model.                                    |\n\n```jsonc\n{\n  \"url\": \"https://replicate.com/replicate/hello-world\",\n  \"owner\": \"replicate\",\n  \"name\": \"hello-world\",\n  \"description\": \"A tiny model that says hello\",\n  \"visibility\": \"public\",\n  \"github_url\": \"https://github.com/replicate/cog-examples\",\n  \"paper_url\": null,\n  \"license_url\": null,\n  \"latest_version\": {\n    /* ... */\n  }\n}\n```\n\n### `replicate.models.list`\n\nGet a paginated list of all public models.\n\n```js\nconst response = await replicate.models.list();\n```\n\n```jsonc\n{\n  \"next\": null,\n  \"previous\": null,\n  \"results\": [\n    {\n      \"url\": \"https://replicate.com/replicate/hello-world\",\n      \"owner\": \"replicate\",\n      \"name\": \"hello-world\",\n      \"description\": \"A tiny model that says hello\",\n      \"visibility\": \"public\",\n      \"github_url\": \"https://github.com/replicate/cog-examples\",\n      \"paper_url\": null,\n      \"license_url\": null,\n      \"run_count\": 5681081,\n      \"cover_image_url\": \"...\",\n      \"default_example\": {\n        /* ... */\n      },\n      \"latest_version\": {\n        /* ... */\n      }\n    }\n  ]\n}\n```\n\n### `replicate.models.search`\n\nSearch for public models on Replicate.\n\n```js\nconst response = await replicate.models.search(query);\n```\n\n| name    | type   | description                            |\n| ------- | ------ | -------------------------------------- |\n| `query` | string | **Required**. The search query string. |\n\n### `replicate.models.create`\n\nCreate a new public or private model.\n\n```js\nconst response = await replicate.models.create(model_owner, model_name, options);\n```\n\n| name                      | type   | description                                                                                                                                                                                                                                               |\n| ------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `model_owner`             | string | **Required**. The name of the user or organization that will own the model. This must be the same as the user or organization that is making the API request. In other words, the API token used in the request must belong to this user or organization. |\n| `model_name`              | string | **Required**. The name of the model. This must be unique among all models owned by the user or organization.                                                                                                                                              |\n| `options.visibility`      | string | **Required**. Whether the model should be public or private. A public model can be viewed and run by anyone, whereas a private model can be viewed and run only by the user or organization members that own the model.                                   |\n| `options.hardware`        | string | **Required**. The SKU for the hardware used to run the model. Possible values can be found by calling [`replicate.hardware.list()`](#replicatehardwarelist).                                                                                              |\n| `options.description`     | string | A description of the model.                                                                                                                                                                                                                               |\n| `options.github_url`      | string | A URL for the model's source code on GitHub.                                                                                                                                                                                                              |\n| `options.paper_url`       | string | A URL for the model's paper.                                                                                                                                                                                                                              |\n| `options.license_url`     | string | A URL for the model's license.                                                                                                                                                                                                                            |\n| `options.cover_image_url` | string | A URL for the model's cover image. This should be an image file.                                                                                                                                                                                          |\n\n### `replicate.hardware.list`\n\nList available hardware for running models on Replicate.\n\n```js\nconst response = await replicate.hardware.list()\n```\n\n```jsonc\n[\n  {\"name\": \"CPU\", \"sku\": \"cpu\" },\n  {\"name\": \"Nvidia T4 GPU\", \"sku\": \"gpu-t4\" },\n  {\"name\": \"Nvidia A40 GPU\", \"sku\": \"gpu-a40-small\" },\n  {\"name\": \"Nvidia A40 (Large) GPU\", \"sku\": \"gpu-a40-large\" },\n]\n```\n\n### `replicate.models.versions.list`\n\nGet a list of all published versions of a model, including input and output schemas for each version.\n\n```js\nconst response = await replicate.models.versions.list(model_owner, model_name);\n```\n\n| name          | type   | description                                                             |\n| ------------- | ------ | ----------------------------------------------------------------------- |\n| `model_owner` | string | **Required**. The name of the user or organization that owns the model. |\n| `model_name`  | string | **Required**. The name of the model.                                    |\n\n```jsonc\n{\n  \"previous\": null,\n  \"next\": null,\n  \"results\": [\n    {\n      \"id\": \"5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa\",\n      \"created_at\": \"2022-04-26T19:29:04.418669Z\",\n      \"cog_version\": \"0.3.0\",\n      \"openapi_schema\": {\n        /* ... */\n      }\n    },\n    {\n      \"id\": \"e2e8c39e0f77177381177ba8c4025421ec2d7e7d3c389a9b3d364f8de560024f\",\n      \"created_at\": \"2022-03-21T13:01:04.418669Z\",\n      \"cog_version\": \"0.3.0\",\n      \"openapi_schema\": {\n        /* ... */\n      }\n    }\n  ]\n}\n```\n\n### `replicate.models.versions.get`\n\nGet metadata for a specific version of a model.\n\n```js\nconst response = await replicate.models.versions.get(model_owner, model_name, version_id);\n```\n\n| name          | type   | description                                                             |\n| ------------- | ------ | ----------------------------------------------------------------------- |\n| `model_owner` | string | **Required**. The name of the user or organization that owns the model. |\n| `model_name`  | string | **Required**. The name of the model.                                    |\n| `version_id`  | string | **Required**. The model version                                         |\n\n```jsonc\n{\n  \"id\": \"5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa\",\n  \"created_at\": \"2022-04-26T19:29:04.418669Z\",\n  \"cog_version\": \"0.3.0\",\n  \"openapi_schema\": {\n    /* ... */\n  }\n}\n```\n\n### `replicate.collections.get`\n\nGet a list of curated model collections. See [replicate.com/collections](https://replicate.com/collections).\n\n```js\nconst response = await replicate.collections.get(collection_slug);\n```\n\n| name              | type   | description                                                                    |\n| ----------------- | ------ | ------------------------------------------------------------------------------ |\n| `collection_slug` | string | **Required**. The slug of the collection. See http://replicate.com/collections |\n\n### `replicate.predictions.create`\n\nRun a model with inputs you provide.\n\n```js\nconst response = await replicate.predictions.create(options);\n```\n\n| name                            | type     | description                                                                                                                      |\n| ------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------- |\n| `options.input`                 | object   | **Required**. An object with the model's inputs                                                                                  |\n| `options.model`                 | string   | The name of the model, e.g. `black-forest-labs/flux-schnell`. This is required if you're running an [official model](https://replicate.com/explore#official-models).                                                                                                   |\n| `options.version`               | string   | The 64-character [model version id](https://replicate.com/docs/topics/models/versions), e.g. `80537f9eead1a5bfa72d5ac6ea6414379be41d4d4f6679fd776e9535d1eb58bb`. This is required if you're not specifying a `model`.                                                                                                  |\n| `options.wait`                  | number   | Wait up to 60s for the prediction to finish before returning. Disabled by default. See [Synchronous predictions](https://replicate.com/docs/topics/predictions/create-a-prediction#sync-mode) for more information.                                                           |\n| `options.stream`                | boolean  | Requests a URL for streaming output output                                                                                       |\n| `options.webhook`               | string   | An HTTPS URL for receiving a webhook when the prediction has new output                                                          |\n| `options.webhook_events_filter` | string[] | You can change which events trigger webhook requests by specifying webhook events (`start` \\| `output` \\| `logs` \\| `completed`) |\n\n```jsonc\n{\n  \"id\": \"ufawqhfynnddngldkgtslldrkq\",\n  \"version\": \"5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa\",\n  \"status\": \"succeeded\",\n  \"input\": {\n    \"text\": \"Alice\"\n  },\n  \"output\": null,\n  \"error\": null,\n  \"logs\": null,\n  \"metrics\": {},\n  \"created_at\": \"2022-04-26T22:13:06.224088Z\",\n  \"started_at\": null,\n  \"completed_at\": null,\n  \"urls\": {\n    \"get\": \"https://api.replicate.com/v1/predictions/ufawqhfynnddngldkgtslldrkq\",\n    \"cancel\": \"https://api.replicate.com/v1/predictions/ufawqhfynnddngldkgtslldrkq/cancel\",\n    \"stream\": \"https://streaming.api.replicate.com/v1/predictions/ufawqhfynnddngldkgtslldrkq\" // Present only if `options.stream` is `true`\n  }\n}\n```\n\n#### Streaming\n\nSpecify the `stream` option when creating a prediction\nto request a URL to receive streaming output using\n[server-sent events (SSE)](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events).\n\nIf the requested model version supports streaming,\nthen the returned prediction will have a `stream` entry in its `urls` property\nwith a URL that you can use to construct an\n[`EventSource`](https://developer.mozilla.org/en-US/docs/Web/API/EventSource).\n\n```js\nif (prediction \u0026\u0026 prediction.urls \u0026\u0026 prediction.urls.stream) {\n  const source = new EventSource(prediction.urls.stream, { withCredentials: true });\n\n  source.addEventListener(\"output\", (e) =\u003e {\n    console.log(\"output\", e.data);\n  });\n\n  source.addEventListener(\"error\", (e) =\u003e {\n    console.error(\"error\", JSON.parse(e.data));\n  });\n\n  source.addEventListener(\"done\", (e) =\u003e {\n    source.close();\n    console.log(\"done\", JSON.parse(e.data));\n  });\n}\n```\n\nA prediction's event stream consists of the following event types:\n\n| event    | format     | description                                    |\n| -------- | ---------- | ---------------------------------------------- |\n| `output` | plain text | Emitted when the prediction returns new output |\n| `error`  | JSON       | Emitted when the prediction returns an error   |\n| `done`   | JSON       | Emitted when the prediction finishes           |\n\nA `done` event is emitted when a prediction finishes successfully,\nis cancelled, or produces an error.\n\n### `replicate.predictions.get`\n\n```js\nconst response = await replicate.predictions.get(prediction_id);\n```\n\n| name            | type   | description                     |\n| --------------- | ------ | ------------------------------- |\n| `prediction_id` | number | **Required**. The prediction id |\n\n```jsonc\n{\n  \"id\": \"ufawqhfynnddngldkgtslldrkq\",\n  \"version\": \"5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa\",\n  \"urls\": {\n    \"get\": \"https://api.replicate.com/v1/predictions/ufawqhfynnddngldkgtslldrkq\",\n    \"cancel\": \"https://api.replicate.com/v1/predictions/ufawqhfynnddngldkgtslldrkq/cancel\"\n  },\n  \"status\": \"starting\",\n  \"input\": {\n    \"text\": \"Alice\"\n  },\n  \"output\": null,\n  \"error\": null,\n  \"logs\": null,\n  \"metrics\": {},\n  \"created_at\": \"2022-04-26T22:13:06.224088Z\",\n  \"started_at\": null,\n  \"completed_at\": null\n}\n```\n\n### `replicate.predictions.cancel`\n\nStop a running prediction before it finishes.\n\n```js\nconst response = await replicate.predictions.cancel(prediction_id);\n```\n\n| name            | type   | description                     |\n| --------------- | ------ | ------------------------------- |\n| `prediction_id` | number | **Required**. The prediction id |\n\n```jsonc\n{\n  \"id\": \"ufawqhfynnddngldkgtslldrkq\",\n  \"version\": \"5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa\",\n  \"urls\": {\n    \"get\": \"https://api.replicate.com/v1/predictions/ufawqhfynnddngldkgtslldrkq\",\n    \"cancel\": \"https://api.replicate.com/v1/predictions/ufawqhfynnddngldkgtslldrkq/cancel\"\n  },\n  \"status\": \"canceled\",\n  \"input\": {\n    \"text\": \"Alice\"\n  },\n  \"output\": null,\n  \"error\": null,\n  \"logs\": null,\n  \"metrics\": {},\n  \"created_at\": \"2022-04-26T22:13:06.224088Z\",\n  \"started_at\": \"2022-04-26T22:13:06.224088Z\",\n  \"completed_at\": \"2022-04-26T22:13:06.224088Z\"\n}\n```\n\n### `replicate.predictions.list`\n\nGet a paginated list of all the predictions you've created.\n\n```js\nconst response = await replicate.predictions.list();\n```\n\n`replicate.predictions.list()` takes no arguments.\n\n```jsonc\n{\n  \"previous\": null,\n  \"next\": \"https://api.replicate.com/v1/predictions?cursor=cD0yMDIyLTAxLTIxKzIzJTNBMTglM0EyNC41MzAzNTclMkIwMCUzQTAw\",\n  \"results\": [\n    {\n      \"id\": \"jpzd7hm5gfcapbfyt4mqytarku\",\n      \"version\": \"b21cbe271e65c1718f2999b038c18b45e21e4fba961181fbfae9342fc53b9e05\",\n      \"urls\": {\n        \"get\": \"https://api.replicate.com/v1/predictions/jpzd7hm5gfcapbfyt4mqytarku\",\n        \"cancel\": \"https://api.replicate.com/v1/predictions/jpzd7hm5gfcapbfyt4mqytarku/cancel\"\n      },\n      \"source\": \"web\",\n      \"status\": \"succeeded\",\n      \"created_at\": \"2022-04-26T20:00:40.658234Z\",\n      \"started_at\": \"2022-04-26T20:00:84.583803Z\",\n      \"completed_at\": \"2022-04-26T20:02:27.648305Z\"\n    }\n    /* ... */\n  ]\n}\n```\n\n### `replicate.trainings.create`\n\nUse the [training API](https://replicate.com/docs/fine-tuning) to fine-tune language models\nto make them better at a particular task.\nTo see what **language models** currently support fine-tuning,\ncheck out Replicate's [collection of trainable language models](https://replicate.com/collections/trainable-language-models).\n\nIf you're looking to fine-tune **image models**,\ncheck out Replicate's [guide to fine-tuning image models](https://replicate.com/docs/guides/fine-tune-an-image-model).\n\n```js\nconst response = await replicate.trainings.create(model_owner, model_name, version_id, options);\n```\n\n| name                            | type     | description                                                                                                                      |\n| ------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------- |\n| `model_owner`                   | string   | **Required**. The name of the user or organization that owns the model.                                                          |\n| `model_name`                    | string   | **Required**. The name of the model.                                                                                             |\n| `version`                       | string   | **Required**. The model version                                                                                                  |\n| `options.destination`           | string   | **Required**. The destination for the trained version in the form `{username}/{model_name}`                                      |\n| `options.input`                 | object   | **Required**. An object with the model's inputs                                                                                  |\n| `options.webhook`               | string   | An HTTPS URL for receiving a webhook when the training has new output                                                            |\n| `options.webhook_events_filter` | string[] | You can change which events trigger webhook requests by specifying webhook events (`start` \\| `output` \\| `logs` \\| `completed`) |\n\n```jsonc\n{\n  \"id\": \"zz4ibbonubfz7carwiefibzgga\",\n  \"version\": \"3ae0799123a1fe11f8c89fd99632f843fc5f7a761630160521c4253149754523\",\n  \"status\": \"starting\",\n  \"input\": {\n    \"text\": \"...\"\n  },\n  \"output\": null,\n  \"error\": null,\n  \"logs\": null,\n  \"started_at\": null,\n  \"created_at\": \"2023-03-28T21:47:58.566434Z\",\n  \"completed_at\": null\n}\n```\n\n\u003e **Warning**\n\u003e If you try to fine-tune a model that doesn't support training,\n\u003e you'll get a `400 Bad Request` response from the server.\n\n### `replicate.trainings.get`\n\nGet metadata and status of a training.\n\n```js\nconst response = await replicate.trainings.get(training_id);\n```\n\n| name          | type   | description                   |\n| ------------- | ------ | ----------------------------- |\n| `training_id` | number | **Required**. The training id |\n\n```jsonc\n{\n  \"id\": \"zz4ibbonubfz7carwiefibzgga\",\n  \"version\": \"3ae0799123a1fe11f8c89fd99632f843fc5f7a761630160521c4253149754523\",\n  \"status\": \"succeeded\",\n  \"input\": {\n    \"data\": \"...\"\n    \"param1\": \"...\"\n  },\n  \"output\": {\n    \"version\": \"...\"\n  },\n  \"error\": null,\n  \"logs\": null,\n  \"webhook_completed\": null,\n  \"started_at\": \"2023-03-28T21:48:02.402755Z\",\n  \"created_at\": \"2023-03-28T21:47:58.566434Z\",\n  \"completed_at\": \"2023-03-28T02:49:48.492023Z\"\n}\n```\n\n### `replicate.trainings.cancel`\n\nStop a running training job before it finishes.\n\n```js\nconst response = await replicate.trainings.cancel(training_id);\n```\n\n| name          | type   | description                   |\n| ------------- | ------ | ----------------------------- |\n| `training_id` | number | **Required**. The training id |\n\n```jsonc\n{\n  \"id\": \"zz4ibbonubfz7carwiefibzgga\",\n  \"version\": \"3ae0799123a1fe11f8c89fd99632f843fc5f7a761630160521c4253149754523\",\n  \"status\": \"canceled\",\n  \"input\": {\n    \"data\": \"...\"\n    \"param1\": \"...\"\n  },\n  \"output\": {\n    \"version\": \"...\"\n  },\n  \"error\": null,\n  \"logs\": null,\n  \"webhook_completed\": null,\n  \"started_at\": \"2023-03-28T21:48:02.402755Z\",\n  \"created_at\": \"2023-03-28T21:47:58.566434Z\",\n  \"completed_at\": \"2023-03-28T02:49:48.492023Z\"\n}\n```\n\n### `replicate.trainings.list`\n\nGet a paginated list of all the trainings you've run.\n\n```js\nconst response = await replicate.trainings.list();\n```\n\n`replicate.trainings.list()` takes no arguments.\n\n```jsonc\n{\n  \"previous\": null,\n  \"next\": \"https://api.replicate.com/v1/trainings?cursor=cD0yMDIyLTAxLTIxKzIzJTNBMTglM0EyNC41MzAzNTclMkIwMCUzQTAw\",\n  \"results\": [\n    {\n      \"id\": \"jpzd7hm5gfcapbfyt4mqytarku\",\n      \"version\": \"b21cbe271e65c1718f2999b038c18b45e21e4fba961181fbfae9342fc53b9e05\",\n      \"urls\": {\n        \"get\": \"https://api.replicate.com/v1/trainings/jpzd7hm5gfcapbfyt4mqytarku\",\n        \"cancel\": \"https://api.replicate.com/v1/trainings/jpzd7hm5gfcapbfyt4mqytarku/cancel\"\n      },\n      \"source\": \"web\",\n      \"status\": \"succeeded\",\n      \"created_at\": \"2022-04-26T20:00:40.658234Z\",\n      \"started_at\": \"2022-04-26T20:00:84.583803Z\",\n      \"completed_at\": \"2022-04-26T20:02:27.648305Z\"\n    }\n    /* ... */\n  ]\n}\n```\n\n### `replicate.deployments.predictions.create`\n\nRun a model using your own custom deployment.\n\nDeployments allow you to run a model with a private, fixed API endpoint. You can configure the version of the model, the hardware it runs on, and how it scales. See the [deployments guide](https://replicate.com/docs/deployments) to learn more and get started.\n\n```js\nconst response = await replicate.deployments.predictions.create(deployment_owner, deployment_name, options);\n```\n\n| name                            | type     | description                                                                                                                      |\n| ------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------- |\n| `deployment_owner`              | string   | **Required**. The name of the user or organization that owns the deployment                                                      |\n| `deployment_name`               | string   | **Required**. The name of the deployment                                                                                         |\n| `options.input`                 | object   | **Required**. An object with the model's inputs                                                                                  |\n| `options.webhook`               | string   | An HTTPS URL for receiving a webhook when the prediction has new output                                                          |\n| `options.webhook_events_filter` | string[] | You can change which events trigger webhook requests by specifying webhook events (`start` \\| `output` \\| `logs` \\| `completed`) |\n\nUse `replicate.wait` to wait for a prediction to finish,\nor `replicate.predictions.cancel` to cancel a prediction before it finishes.\n\n### `replicate.deployments.list`\n\nList your deployments.\n\n```js\nconst response = await replicate.deployments.list();\n```\n\n```jsonc\n{\n  \"next\": null,\n  \"previous\": null,\n  \"results\": [\n    {\n      \"owner\": \"acme\",\n      \"name\": \"my-app-image-generator\",\n      \"current_release\": { /* ... */ }\n    }\n    /* ... */\n  ]\n}\n```\n\n### `replicate.deployments.create`\n\nCreate a new deployment.\n\n```js\nconst response = await replicate.deployments.create(options);\n```\n\n| name                    | type   | description                                                                      |\n| ----------------------- | ------ | -------------------------------------------------------------------------------- |\n| `options.name`          | string | Required. Name of the new deployment                                             |\n| `options.model`         | string | Required. Name of the model in the format `{username}/{model_name}`              |\n| `options.version`       | string | Required. ID of the model version                                                |\n| `options.hardware`      | string | Required. SKU of the hardware to run the deployment on (`cpu`, `gpu-a100`, etc.) |\n| `options.min_instances` | number | Minimum number of instances to run. Defaults to 0                                |\n| `options.max_instances` | number | Maximum number of instances to scale up to based on traffic. Defaults to 1       |\n\n```jsonc\n{\n  \"owner\": \"acme\",\n  \"name\": \"my-app-image-generator\",\n  \"current_release\": {\n    \"number\": 1,\n    \"model\": \"stability-ai/sdxl\",\n    \"version\": \"da77bc59ee60423279fd632efb4795ab731d9e3ca9705ef3341091fb989b7eaf\",\n    \"created_at\": \"2024-03-14T11:43:32.049157Z\",\n    \"created_by\": {\n       \"type\": \"organization\",\n       \"username\": \"acme\",\n       \"name\": \"Acme, Inc.\",\n       \"github_url\": \"https://github.com/replicate\"\n    },\n    \"configuration\": {\n      \"hardware\": \"gpu-a100\",\n      \"min_instances\": 1,\n      \"max_instances\": 0\n    }\n  }\n}\n```\n\n### `replicate.deployments.update`\n\nUpdate an existing deployment.\n\n```js\nconst response = await replicate.deployments.update(deploymentOwner, deploymentName, options);\n```\n\n| name                    | type   | description                                                                      |\n| ----------------------- | ------ | -------------------------------------------------------------------------------- |\n| `deploymentOwner`       | string | Required. Owner of the deployment                                                |\n| `deploymentName`        | string | Required. Name of the deployment to update                                       |\n| `options.model`         | string | Name of the model in the format `{username}/{model_name}`                        |\n| `options.version`       | string | ID of the model version                                                          |\n| `options.hardware`      | string | Required. SKU of the hardware to run the deployment on (`cpu`, `gpu-a100`, etc.) |\n| `options.min_instances` | number | Minimum number of instances to run                                               |\n| `options.max_instances` | number | Maximum number of instances to scale up to                                       |\n\n```jsonc\n{\n  \"owner\": \"acme\",\n  \"name\": \"my-app-image-generator\",\n  \"current_release\": {\n    \"number\": 2,\n    \"model\": \"stability-ai/sdxl\",\n    \"version\": \"39ed52f2a78e934b3ba6e2a89f5b1c712de7dfea535525255b1aa35c5565e08b\",\n    \"created_at\": \"2024-03-14T11:43:32.049157Z\",\n    \"created_by\": {\n       \"type\": \"organization\",\n       \"username\": \"acme\",\n       \"name\": \"Acme, Inc.\",\n       \"github_url\": \"https://github.com/replicate\"\n    },\n    \"configuration\": {\n      \"hardware\": \"gpu-a100\",\n      \"min_instances\": 1,\n      \"max_instances\": 0\n    }\n  }\n}\n```\n\n### `replicate.files.create`\n\nUpload a file to Replicate.\n\n\u003e [!TIP]\n\u003e The client library calls this endpoint automatically to upload the contents of\n\u003e file handles provided as prediction and training inputs.\n\u003e You don't need to call this method directly unless you want more control.\n\u003e For example, you might want to reuse a file across multiple predictions\n\u003e without re-uploading it each time,\n\u003e or you may want to set custom metadata on the file resource.\n\u003e\n\u003e You can configure how a client handles file handle inputs\n\u003e by setting the `fileEncodingStrategy` option in the\n\u003e [client constructor](#constructor).\n\n```js\nconst response = await replicate.files.create(file, metadata);\n```\n\n| name       | type                  | description                                                |\n| ---------- | --------------------- | ---------------------------------------------------------- |\n| `file`     | Blob, File, or Buffer | **Required**. The file to upload.                          |\n| `metadata` | object                | Optional. User-provided metadata associated with the file. |\n\n```jsonc\n{\n    \"id\": \"MTQzODcyMDct0YjZkLWE1ZGYtMmRjZTViNWIwOGEyNjNhNS0\",\n    \"name\": \"photo.webp\",\n    \"content_type\": \"image/webp\",\n    \"size\": 96936,\n    \"etag\": \"f211779ff7502705bbf42e9874a17ab3\",\n    \"checksums\": {\n        \"sha256\": \"7282eb6991fa4f38d80c312dc207d938c156d714c94681623aedac846488e7d3\",\n        \"md5\": \"f211779ff7502705bbf42e9874a17ab3\"\n    },\n    \"metadata\": {\n        \"customer_reference_id\": \"123\"\n    },\n    \"created_at\": \"2024-06-28T10:16:04.062Z\",\n    \"expires_at\": \"2024-06-29T10:16:04.062Z\",\n    \"urls\": {\n        \"get\": \"https://api.replicate.com/v1/files/MTQzODcyMDct0YjZkLWE1ZGYtMmRjZTViNWIwOGEyNjNhNS0\"\n    }\n}\n```\n\nFiles uploaded to Replicate using this endpoint expire after 24 hours.\n\nPass the `urls.get` property of a file resource\nto use it as an input when running a model on Replicate.\nThe value of `urls.get` is opaque,\nand shouldn't be inferred from other attributes.\n\nThe contents of a file are only made accessible to a model running on Replicate,\nand only when passed as a prediction or training input\nby the user or organization who created the file.\n\n### `replicate.files.list`\n\nList all files you've uploaded.\n\n```js\nconst response = await replicate.files.list();\n```\n\n### `replicate.files.get`\n\nGet metadata for a specific file.\n\n```js\nconst response = await replicate.files.get(file_id);\n```\n\n| name      | type   | description                       |\n| --------- | ------ | --------------------------------- |\n| `file_id` | string | **Required**. The ID of the file. |\n\n### `replicate.files.delete`\n\nDelete a file.\n\nFiles uploaded using the `replicate.files.create` method expire after 24 hours.\nYou can use this method to delete them sooner.\n\n```js\nconst response = await replicate.files.delete(file_id);\n```\n\n| name      | type   | description                       |\n| --------- | ------ | --------------------------------- |\n| `file_id` | string | **Required**. The ID of the file. |\n\n### `replicate.paginate`\n\nPass another method as an argument to iterate over results\nthat are spread across multiple pages.\n\nThis method is implemented as an\n[async generator function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator),\nwhich you can use in a for loop or iterate over manually.\n\n```js\n// iterate over paginated results in a for loop\nfor await (const page of replicate.paginate(replicate.predictions.list)) {\n  /* do something with page of results */\n}\n\n// iterate over paginated results one at a time\nlet paginator = replicate.paginate(replicate.predictions.list);\nconst page1 = await paginator.next();\nconst page2 = await paginator.next();\n// etc.\n```\n\n### `replicate.request`\n\nLow-level method used by the Replicate client to interact with API endpoints.\n\n```js\nconst response = await replicate.request(route, parameters);\n```\n\n| name                 | type                | description |\n| -------------------- | ------------------- | ----------- |\n| `options.route`      | `string`            | Required. REST API endpoint path.\n| `options.params`     | `object`            | URL query parameters for the given route. |\n| `options.method`     | `string`            | HTTP method for the given route. |\n| `options.headers`    | `object`            | Additional HTTP headers for the given route. |\n| `options.data`       | `object \\| FormData` | Request body. |\n| `options.signal`     | `AbortSignal`       | Optional `AbortSignal`. |\n\nThe `replicate.request()` method is used by the other methods\nto interact with the Replicate API.\nYou can call this method directly to make other requests to the API.\n\nThe method accepts an `AbortSignal` which can be used to cancel the request in flight.\n\n### `FileOutput`\n\n`FileOutput` is a `ReadableStream` instance that represents a model file output. It can be used to stream file data to disk or as a `Response` body to an HTTP request.\n\n```javascript\nconst [output] = await replicate.run(\"black-forest-labs/flux-schnell\", { \n  input: { prompt: \"astronaut riding a rocket like a horse\" }\n});\n\n// To access the file URL:\nconsole.log(output.url()); //=\u003e \"http://example.com\"\n\n// To write the file to disk:\nfs.writeFile(\"my-image.png\", output);\n\n// To stream the file back to a browser:\nreturn new Response(output);\n\n// To read the file in chunks:\nfor await (const chunk of output) {\n  console.log(chunk); // UInt8Array\n}\n```\n\nYou can opt out of FileOutput by passing `useFileOutput: false` to the `Replicate` constructor:\n\n```javascript\nconst replicate = new Replicate({ useFileOutput: false });\n```\n\n| method               | returns   | description                                                  |\n| -------------------- | ------    | ------------------------------------------------------------ |\n| `blob()`             | object    | A `Blob` instance containing the binary file                 |\n| `url()`              | string    | A `URL` object pointing to the underlying data source. Please note that this may not always be an HTTP URL in future.       |\n\n## Troubleshooting\n\n### Predictions hanging in Next.js\n\nNext.js App Router adds some extensions to `fetch` to make it cache responses. To disable this behavior, set the `cache` option to `\"no-store\"` on the Replicate client's fetch object:\n\n```js\nreplicate = new Replicate({/*...*/})\nreplicate.fetch = (url, options) =\u003e {\n  return fetch(url, { ...options, cache: \"no-store\" });\n};\n```\n\nAlternatively you can use Next.js [`noStore`](https://github.com/replicate/replicate-javascript/issues/136#issuecomment-1847442879) to opt out of caching for your component.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Freplicate%2Freplicate-javascript","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Freplicate%2Freplicate-javascript","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Freplicate%2Freplicate-javascript/lists"}