Light Logo
Go SDK (v0.49.0)Guides

Predictions

A guide on how to work with predictions using the WriftAI Go client

This section demonstrates common prediction operations you can perform with the WriftAI Go client. These examples are not exhaustive — check the client reference for all options.

Get a Prediction by ID

prediction, err := client.Predictions.Get(context.TODO(), "your-prediction-id")

Cancel a Prediction by ID

err := client.Predictions.Cancel(context.TODO(), "your-prediction-id")

Create a Prediction

Pass the prediction input as a wriftai.PredictionInput, a map of input names to values. Any value that encoding/json can marshal is allowed, and a plain map[string]any also works.

With the latest version of a model

prediction, err := client.Predictions.Create(
	context.TODO(),
	wriftai.CreatePredictionParams{
		Model: "hexgrad/kokoro-82m",
		Input: wriftai.PredictionInput{
			"text": "Good morning! Here's your daily summary.",
		},
	},
)

With a specific version of a model

prediction, err := client.Predictions.Create(
	context.TODO(),
	wriftai.CreatePredictionParams{
		Model: "hexgrad/kokoro-82m:1",
		Input: wriftai.PredictionInput{
			"text": "Good morning! Here's your daily summary.",
		},
	},
)

With raw JSON values

Values that are already encoded can be passed as json.RawMessage. They are sent as-is and can be mixed with regular Go values.

prediction, err := client.Predictions.Create(
	context.TODO(),
	wriftai.CreatePredictionParams{
		Model: "hexgrad/kokoro-82m",
		Input: wriftai.PredictionInput{
			"text":  "Good morning! Here's your daily summary.",
			"speed": json.RawMessage(`1.2`),
		},
	},
)

With a webhook for prediction updates

webhookSecret := "top-secret"

prediction, err := client.Predictions.Create(
	context.TODO(),
	wriftai.CreatePredictionParams{
		Model: "hexgrad/kokoro-82m",
		Input: wriftai.PredictionInput{
			"text": "Good morning! Here's your daily summary.",
		},
		Webhook: &wriftai.Webhook{
			URL:    "https://example.com/webhooks/wriftai",
			Secret: &webhookSecret, // This is optional
		},
	},
)

With file inputs

File inputs are automatically uploaded when you create a prediction. Wrap your file content in a wriftai.File created with wriftai.NewFile, and there is no need to call client.Files.Upload() separately.

Files can be nested at any depth in input, inside map[string]any, []any, map[string]*wriftai.File or []*wriftai.File, and you can include as many as you need. Other container types are not scanned for files. All files are uploaded concurrently before the prediction is created.

With a file from disk:

file, err := os.Open("audio.wav")
if err != nil {
	log.Fatal(err)
}
defer file.Close()

prediction, err := client.Predictions.Create(
	context.TODO(),
	wriftai.CreatePredictionParams{
		Model: "pyannote/speaker-diarization-community-1",
		Input: wriftai.PredictionInput{
			"audio": wriftai.NewFile(file, ""),
		},
	},
)

With raw bytes:

prediction, err := client.Predictions.Create(
	context.TODO(),
	wriftai.CreatePredictionParams{
		Model: "pyannote/speaker-diarization-community-1",
		Input: wriftai.PredictionInput{
			"audio": wriftai.NewFile(
				bytes.NewReader([]byte("audio content")),
				"",
			),
		},
	},
)

With a file-like object:

prediction, err := client.Predictions.Create(
	context.TODO(),
	wriftai.CreatePredictionParams{
		Model: "pyannote/speaker-diarization-community-1",
		Input: wriftai.PredictionInput{
			"audio": wriftai.NewFile(strings.NewReader("audio content"), ""),
		},
	},
)

With upload progress:

prediction, err := client.Predictions.Create(
	context.TODO(),
	wriftai.CreatePredictionParams{
		Model: "pyannote/speaker-diarization-community-1",
		Input: wriftai.PredictionInput{
			"audio": wriftai.NewFile(file, ""),
		},
		OnUploadProgress: func(*wriftai.File) wriftai.ProgressFunc {
			return func(delta, total int64) error {
				fmt.Printf("read %d more bytes (file size: %d)\n", delta, total)
				return nil
			}
		},
	},
)

OnUploadProgress is called once for each file and receives that file, so you can track files separately. It returns the progress function for that file, or nil to skip it. The returned function works like FileUploadOptions.OnProgress in the Files guide and is called concurrently, so synchronize any shared state it updates.

For more details on working with files, see the Files guide.

With input validation enabled

Enable early input validation against the model’s input schema before a prediction is created. This catches invalid inputs upfront and prevents unnecessary model execution and cost.

validate := true
prediction, err := client.Predictions.Create(
	context.TODO(),
	wriftai.CreatePredictionParams{
		Model: "hexgrad/kokoro-82m",
		Input: wriftai.PredictionInput{
			"text": "Good morning! Here's your daily summary.",
		},
		ValidateInput: &validate,
	},
)

Create and wait for completion

prediction, err := client.Predictions.Create(
	context.TODO(),
	wriftai.CreatePredictionParams{
		Model: "hexgrad/kokoro-82m",
		Input: wriftai.PredictionInput{
			"text": "Good morning! Here's your daily summary.",
		},
		Wait: &wriftai.CreatePredictionWaitOptions{},
	},
)

This returns a finished prediction. The server holds the connection open for its default wait time, and if the prediction hasn't finished by then, the client polls until it reaches a terminal state.

Create and wait with a custom duration

Set how long the server holds the initial request open before the client falls back to polling:

prediction, err := client.Predictions.Create(
	context.TODO(),
	wriftai.CreatePredictionParams{
		Model: "hexgrad/kokoro-82m",
		Input: wriftai.PredictionInput{
			"text": "Good morning! Here's your daily summary.",
		},
		Wait: &wriftai.CreatePredictionWaitOptions{
			Duration: 30 * time.Second,
		},
	},
)

This still returns a finished prediction. Duration only changes how long the initial request stays open before polling starts. Use a lower value if your environment has a short HTTP timeout, or a higher one (up to the server's maximum) to get the result as soon as it's ready with fewer polling requests.

Create and wait without polling

Set DisablePoll to true to return as soon as the server's wait ends, even if the prediction is still running:

prediction, err := client.Predictions.Create(
	context.TODO(),
	wriftai.CreatePredictionParams{
		Model: "hexgrad/kokoro-82m",
		Input: wriftai.PredictionInput{
			"text": "Good morning! Here's your daily summary.",
		},
		Wait: &wriftai.CreatePredictionWaitOptions{
			DisablePoll: true,
		},
	},
)

The returned prediction may not be in a terminal state, so check its Status.

Create and wait with progress updates

onPoll := func(pred *wriftai.PredictionWithDetails) error {
	// your custom logic
	return nil
}

prediction, err := client.Predictions.Create(
	context.TODO(),
	wriftai.CreatePredictionParams{
		Model: "hexgrad/kokoro-82m",
		Input: wriftai.PredictionInput{
			"text": "Good morning! Here's your daily summary.",
		},
		Wait: &wriftai.CreatePredictionWaitOptions{
			PredictionWaitOptions: wriftai.PredictionWaitOptions{
				PollInterval: 2 * time.Second,
				OnPoll:       onPoll,
			},
		},
	},
)

PollInterval and OnPoll belong to PredictionWaitOptions, which is embedded in CreatePredictionWaitOptions. They only take effect while the client is polling and do not affect the initial wait.

Wait for an existing prediction to complete

prediction, err := client.Predictions.Wait(
	context.TODO(),
	"your-prediction-id",
	nil, // no custom wait options
)

This is also what Create with Wait set uses to poll when the prediction hasn't finished after the server's wait, so calling it directly is useful when you want to skip straight to polling, or you already have a prediction ID from somewhere else.

It takes the same PollInterval and OnPoll options shown above, passed as PredictionWaitOptions:

onPoll := func(pred *wriftai.PredictionWithDetails) error {
	// your custom logic
	return nil
}

prediction, err := client.Predictions.Wait(
	context.TODO(),
	"your-prediction-id",
	&wriftai.PredictionWaitOptions{
		PollInterval: 2 * time.Second,
		OnPoll:       onPoll,
	},
)

Stream a Prediction's events

A prediction's events can be streamed while it runs. You can either create and stream the prediction in one call with CreateStream, or create the prediction first and stream its events later by ID with Stream.

To stream a prediction's events later with the Stream method, the prediction must be created with the Stream field of CreatePredictionParams set to true.

Streaming stops on its own once the prediction sends a terminal event, so there's nothing extra to handle. If the server closes an idle connection before then, the client reconnects automatically from the last event it received, so you don't miss or repeat events.

Create a prediction and stream its events in one call

CreateStream works like Create, but returns the prediction's events from the create request instead of returning the prediction. Streaming is always enabled, so it takes CreatePredictionStreamParams, which has no Stream field:

for event, err := range client.Predictions.CreateStream(
	context.TODO(),
	wriftai.CreatePredictionStreamParams{
		Model: "openai/privacy-filter",
		Input: wriftai.PredictionInput{
			"text": "My name is Alice Smith and my email is alice@example.com.",
		},
	},
) {
	fmt.Println(event)
}

The iterator returned by CreateStream can only be ranged over once. Ranging over it again yields an error. To read the same prediction's events again, use Stream with its ID.

Create a prediction, then stream its events by ID

With the Stream field set to true but without waiting, Create returns the prediction as usual, and you stream its events afterwards with the Stream method, which takes the prediction's ID:

prediction, err := client.Predictions.Create(
	context.TODO(),
	wriftai.CreatePredictionParams{
		Model: "openai/privacy-filter",
		Input: wriftai.PredictionInput{
			"text": "My name is Alice Smith and my email is alice@example.com.",
		},
		Stream: true,
	},
)
if err != nil {
	log.Fatal(err)
}

for event, err := range client.Predictions.Stream(
	context.TODO(),
	prediction.ID,
	nil, // no extra options
) {
	fmt.Println(event)
}

Create returns an error if the Wait field is set while the Stream field is true, because the API then responds with an event stream instead of the prediction. Use CreateStream to stream from the create call.

The sections below use Stream, which takes a prediction's ID. The same applies to CreateStream, apart from the differences noted in each section.

Handle events by type

for event, err := range client.Predictions.Stream(
	context.TODO(),
	"your-prediction-id",
	nil,
) {
	if event.Event == wriftai.PredictionStreamEventTypeOutput {
		fmt.Println(event)
	}
}

Start from a specific event

Pass AfterID in PredictionStreamOptions to only receive events after a given event ID. Without it, the stream starts from the first event.

for event, err := range client.Predictions.Stream(
	context.TODO(),
	"your-prediction-id",
	&wriftai.PredictionStreamOptions{
		AfterID: "event-id",
	},
) {
	fmt.Println(event)
}

CreateStream has no AfterID, since it starts from the first event.

Set how long the server waits for events

By default, the server decides how long an idle connection stays open between events before closing it, and the client reconnects automatically when that happens. This is usually fine, but you can set it with the Wait option of PredictionStreamOptions, as a time.Duration (sent to the server in seconds). Use a lower value if something in your environment, like a proxy or load balancer, closes idle connections sooner than the server does, or a higher one to reconnect less often when there are long gaps between events:

for event, err := range client.Predictions.Stream(
	context.TODO(),
	"your-prediction-id",
	&wriftai.PredictionStreamOptions{
		Wait: 10 * time.Second,
	},
) {
	fmt.Println(event)
}

This is the longest the server waits between events, not how long to wait for the prediction to finish. After an idle close, the client reconnects with the same value.

CreateStream takes the same setting as the Wait field of CreatePredictionStreamParams:

for event, err := range client.Predictions.CreateStream(
	context.TODO(),
	wriftai.CreatePredictionStreamParams{
		Model: "openai/privacy-filter",
		Input: wriftai.PredictionInput{
			"text": "My name is Alice Smith and my email is alice@example.com.",
		},
		Wait: 10 * time.Second,
	},
) {
	fmt.Println(event)
}

Resume after a network error

Streaming connections can stay open for a long time, so they can drop before the stream ends, for example because of a network issue on your side. Opening the connection is retried on transient errors, like any other request, but if the connection drops after events have started arriving, the error is raised rather than retried. To pick up where you left off, call Stream again with AfterID, set to the ID of the last event you received:

var (
	lastID    string
	streamErr error
)

// Try once, then retry once more if the connection drops mid-stream.
for attempt := 0; attempt < 2; attempt++ {
	streamErr = nil
	gotEvent := false

	for event, err := range client.Predictions.Stream(
		context.TODO(),
		"your-prediction-id",
		&wriftai.PredictionStreamOptions{
			AfterID: lastID,
		},
	) {
		if err != nil {
			streamErr = err
			break
		}

		gotEvent = true
		lastID = event.ID
		fmt.Println(event)
	}

	// An error before any event means the stream could not be opened, which
	// retrying won't fix.
	if streamErr == nil || !gotEvent {
		break
	}
}

if streamErr != nil {
	log.Fatal(streamErr)
}

The first event in a prediction's stream has type PredictionStreamEventTypeInit and its Data contains the prediction ID. When streaming from CreateStream, that's how you get the ID to resume with Stream the same way. If the error is raised before the first event, there is no ID yet, so there is nothing to resume from.

var (
	predictionID string
	lastID       string
	streamErr    error
)

for event, err := range client.Predictions.CreateStream(
	context.TODO(),
	wriftai.CreatePredictionStreamParams{
		Model: "deepseek-ai/deepseek-r1",
		Input: map[string]any{
			"prompt": "Summarize quantum computing.",
		},
	},
) {
	if err != nil {
		streamErr = err
		break
	}

	if event.Event == wriftai.PredictionStreamEventTypeInit {
		data, _ := event.Data.(map[string]any)
		predictionID, _ = data["id"].(string)
	}

	lastID = event.ID
	fmt.Println(event)
}

// No prediction ID yet, so there is nothing to resume from.
if streamErr != nil && predictionID == "" {
	log.Fatal(streamErr)
}

// Continue from the last event received.
if streamErr != nil {
	for event, err := range client.Predictions.Stream(
		context.TODO(),
		predictionID,
		&wriftai.PredictionStreamOptions{
			AfterID: lastID,
		},
	) {
		if err != nil {
			log.Fatal(err)
		}

		fmt.Println(event)
	}
}

Stop streaming early

To stop streaming early, stop ranging over the events, for example with break. The client immediately stops consuming the stream and closes the underlying connection. This works the same way for CreateStream.

for event, err := range client.Predictions.Stream(
	context.TODO(),
	"your-prediction-id",
	nil,
) {
	fmt.Println(event)
	break // Stop after the first event.
}

List Predictions

predictions, err := client.Predictions.List(
	context.TODO(),
	nil, // default options
)

Predictions filtered by status

statuses := []wriftai.Status{wriftai.StatusFailed}
predictions, err := client.Predictions.List(
	context.TODO(),
	&wriftai.PredictionListOptions{
		Statuses: &statuses,
	},
)