npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

replicate-api

v0.4.5

Published

A typed client library for the replicate.com API

Downloads

1,246

Readme

replicate-api

A typed client library for the replicate.com API.

You can use this to access the prediction API in a type-safe and convenient way.

Install

Just install it with your favorite package manager:

yarn add replicate-api
pnpm add replicate-api
npm install replicate-api

The package should work in the browser and in Node.js versions 18 and up.

Obtain an API token

You need an API token for nearly all operations. You can find the token in your account settings.

Examples

Generate an image with stable-diffusion

You can create a new prediction using the stability-ai/stable-diffusion model and wait for the result with:

const prediction = await predict({
  model: "stability-ai/stable-diffusion", // The model name
  input: { prompt: "multicolor hyperspace" }, // The model specific input
  token: "...", // You need a token from replicate.com
  poll: true, // Wait for the model to finish
})

console.log(prediction.output[0])
// https://replicate.com/api/models/stability-ai/stable-diffusion/files/58a1dcfc-3d5d-4297-bac2-5395294fe463/out-0.png

This does some things for you like resolving the model name to a model version and polling until the prediction is completed.

Create a new prediction

const result = await predict({ model: "replicate/hello-world", input: { prompt: "..." }, token: "..." })

Then you can check result.status to see if it's "starting", "processing" or succeeded. If it's "succeeded" you can get the outputs with result.outputs. If not you can check back later with getPrediction() and the id from result (result.id).

You can also set poll: true in the options of predict() to wait until it has finished. If you don't do that, you can still use .poll() to poll until the prediction is done.

Wait until a prediction is finished

// If you have a PredictionState:
const finishedPrediction = prediction.poll()

// If you only have the prediction ID:
const finishedPrediction = await pollPrediction({ id, token: "..." })

// If you are creating a new prediction anyways:
const finishedPrediction = await predict({ ...otherOptions, poll: true })

Retrieve the current state of a prediction

// If you have a PredictionState:
const currentPrediction = prediction.get()

// If you only have the prediction ID:
const currentPrediction = await getPrediction({ id, token: "..." })

Cancel a running prediction

// If you have a PredictionState:
const currentPrediction = result.cancel()

// If you only have the prediction ID:
const currentPrediction = await cancelPrediction({ id, token: "..." })

Canceling the prediction also returns the state of the prediction after canceling.

Get information about a model

const info = await getModel({ model: "replicate/hello-world", token: "..." })

Get a list of all versions of a model

const info = await listVersions({ model: "replicate/hello-world", token: "..." })

Generate a prediction without using the convenience functions

The first example used a few convenience functions to make it easier to use the API. You can also use the lower-level functions that map the API calls more directly.

const model = await getModel({ model: "stability-ai/stable-diffusion", token: "..." })

let prediction = await predict({
  version: model.version,
  input: { prompt: "multicolor hyperspace" },
  token: "...",
})

// pollPrediction does this a bit smarter, with increasing backoff
while (prediction.status === "starting" || prediction.status === "processing") {
  await new Promise(resolve => setTimeout(resolve, 1000))
  prediction = await getPrediction({ id: prediction.id, token: "..." })
}

console.log(prediction.outputs[0])
// https://replicate.com/api/models/stability-ai/stable-diffusion/files/58a1dcfc-3d5d-4297-bac2-5395294fe463/out-0.png

List your past predictions

const result = await listPredictions({
  token: "...",
})

Returns up to 100 predictions. To get more, use the next function:

const moreResults = await result.next()

You can also set all: true to get all predictions.

Use files in your inputs

To use file inputs you need to pass them as URLs. You can use the loadFile function to convert local files to base64 data URLs:

const testaudioURL = await loadFile("./testaudio.mp3")
//

You can also use an HTTPS URL to load files from the web.

Transcribe audio with whisper

You can create a new prediction for the openai/whisper model and wait for the result with:

const prediction = await predict({
  model: "openai/whisper", // The model name
  input: {
    audio: await loadFile("./testaudio.mp3"), // Load local file as base64 dataurl
    // audio: "https://raw.githubusercontent.com/zebreus/replicate-api/master/testaudio.mp3", // Load from a URL
    model: "base",
  }, // The model specific input
  token: "...", // You need a token from replicate.com
  poll: true, // Wait for the model to finish
})

console.log(prediction.output.transcription)
// Transcribed text

Related projects

Older node versions

This package uses the fetch API which is only supported in Node.js 18 and up. If you need to use an older version of Node.js, you can use node-fetch. It will be detected and used automatically if your node does not provide a native fetch. The Options object supports passing a custom fetch function, you can also try to pass node-fetch there.

Building and testing this package

To run the tests for this package you need an API token from <replicate.com>. Then you create a src/tests/token.ts file that exports the token as a string like export const token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx". Now you can run yarn test to run the tests.