> ## Documentation Index
> Fetch the complete documentation index at: /llms.txt
> Use this file to discover all available pages before exploring further.

# SDK integration guide

> Integrate Livepeer AI and video APIs via official SDKs in TypeScript, Python, and Go. Covers authentication, error handling, retries, and SDK vs direct REST trade-offs.

> [!TIP]
>
> The Studio SDK covers all Livepeer resources -- streams, assets, and AI inference -- in one package. The AI SDK covers inference only. For production applications, use the Studio SDK.

***

Livepeer provides two SDK families. The **Studio SDK** (`livepeer`) wraps the full Studio API: livestreams, video assets, webhooks, access control, and AI inference. The **AI SDK** (`@livepeer/ai`) wraps AI inference endpoints only. Both authenticate with a Bearer token from the Studio dashboard.

Installation

## Installation and initialisation

> [tab] TypeScript
>
> ```bash theme={null}
> npm install livepeer
> ```
>
> ```typescript theme={null}
> import { Livepeer } from 'livepeer';
>
> const client = new Livepeer({
>   apiKey: process.env.LIVEPEER_API_KEY, // Bearer token from Studio
> });
> ```

> [tab] Python
>
> ```bash theme={null}
> pip install livepeer
> ```
>
> ```python theme={null}
> from livepeer import Livepeer
> import os
>
> client = Livepeer(api_key=os.environ['LIVEPEER_API_KEY'])
> ```

> [tab] Go
>
> ```bash theme={null}
> go get github.com/livepeer/livepeer-go
> ```
>
> ```go theme={null}
> import (
>   "context"
>   livepeer "github.com/livepeer/livepeer-go"
> )
>
> client := livepeer.New(
>   livepeer.WithSecurity(os.Getenv("LIVEPEER_API_KEY")),
> )
> ```

> [tab] AI SDK (TypeScript)
>
> ```bash theme={null}
> npm install @livepeer/ai
> ```
>
> ```typescript theme={null}
> import Livepeer from '@livepeer/ai';
>
> const client = new Livepeer({
>   httpBearer: process.env.LIVEPEER_API_KEY,
> });
> // Default gateway: https://dream-gateway.livepeer.cloud
> // For production: configure Studio gateway URL
> ```

AI Inference

## AI inference calls

All nine batch pipelines share the same pattern: call the generate namespace, pass a request body, receive a typed response.

> [tab] TypeScript
>
> ```typescript theme={null}
> // Text to image
> const result = await client.generate.textToImage({
>   prompt: 'a photorealistic mountain lake at dawn',
>   modelId: 'SG161222/RealVisXL_V4.0_Lightning',
>   width: 1024,
>   height: 1024,
> });
> // result.imageResponse.images[0].url
>
> // Image to image
> const img2img = await client.generate.imageToImage({
>   image: fs.createReadStream('./input.jpg'),
>   prompt: 'convert to oil painting style',
>   modelId: 'timbrooks/instruct-pix2pix',
>   strength: 0.7,
> });
>
> // LLM (OpenAI-compatible format)
> const llmResult = await client.generate.llm({
>   messages: [{ role: 'user', content: 'Explain blockchain in one sentence.' }],
>   model: 'meta-llama/Meta-Llama-3.1-8B-Instruct',
> });
> ```

> [tab] Python
>
> ```python theme={null}
> from livepeer.models import components
>
> # Text to image
> result = client.generate.text_to_image(
>     request=components.TextToImageParams(
>         prompt='a photorealistic mountain lake at dawn',
>         model_id='SG161222/RealVisXL_V4.0_Lightning',
>         width=1024,
>         height=1024,
>     )
> )
> # result.image_response.images[0].url
>
> # Audio to text (Whisper)
> with open('audio.mp3', 'rb') as f:
>     transcription = client.generate.audio_to_text(
>         request=components.BodyGenAudioToText(
>             audio=components.Audio(content=f.read(), file_name='audio.mp3'),
>             model_id='openai/whisper-large-v3',
>         )
>     )
> ```

> [tab] Go
>
> ```go theme={null}
> import "github.com/livepeer/livepeer-go/models/components"
>
> prompt := "a photorealistic mountain lake at dawn"
> modelID := "SG161222/RealVisXL_V4.0_Lightning"
> width := int64(1024)
> height := int64(1024)
>
> result, err := client.Generate.TextToImage(ctx,
>   components.TextToImageParams{
>     Prompt:  prompt,
>     ModelID: &modelID,
>     Width:   &width,
>     Height:  &height,
>   },
> )
> ```

Video Resources

## Video API calls (Studio SDK)

> [tab] TypeScript
>
> ```typescript theme={null}
> // Create a livestream
> const stream = await client.stream.create({
>   name: 'my-livestream',
>   record: true,
> });
> console.log(stream.stream.rtmpIngestUrl);
> console.log(stream.stream.playbackId);
>
> // Upload a video asset
> const asset = await client.asset.create({
>   name: 'my-video.mp4',
> });
> // Use asset.tusEndpoint for resumable upload (tus protocol)
>
> // Create a gated stream (JWT access control)
> const gatedStream = await client.stream.create({
>   name: 'gated-stream',
>   playbackPolicy: { type: 'jwt' },
> });
> ```

> [tab] Python
>
> ```python theme={null}
> # Create a livestream
> stream = client.stream.create(
>     request={'name': 'my-livestream', 'record': True}
> )
> print(stream.stream.rtmp_ingest_url)
>
> # Upload an asset
> asset = client.asset.create(
>     request={'name': 'my-video.mp4'}
> )
> ```

Error Handling

## Error handling

All SDKs surface three error types. Handle them explicitly.

> [tab] TypeScript
>
> ```typescript theme={null}
> import { SDKError } from 'livepeer/models/errors';
>
> try {
>   const result = await client.generate.textToImage({ prompt: 'test' });
> } catch (err) {
>   if (err instanceof SDKError) {
>     if (err.statusCode === 401) {
>       // Invalid or missing API key
>       console.error('Authentication failed -- check LIVEPEER_API_KEY');
>     } else if (err.statusCode === 422) {
>       // Invalid request body -- check model_id, prompt, dimensions
>       console.error('Validation error:', err.body);
>     } else if (err.statusCode === 503) {
>       // Model is cold -- retry after 30-90 seconds
>       console.error('Model loading -- retry in 60s');
>     } else {
>       console.error(`API error ${err.statusCode}:`, err.message);
>     }
>   }
>   throw err;
> }
> ```

> [tab] Python
>
> ```python theme={null}
> from livepeer.models import errors
>
> try:
>     result = client.generate.text_to_image(request=params)
> except errors.HTTPValidationError as e:
>     # 422 -- invalid request body
>     print('Validation error:', e.detail)
> except errors.HTTPError as e:
>     if e.status_code == 401:
>         print('Authentication failed')
>     elif e.status_code == 503:
>         print('Model loading -- retry in 60s')
>     else:
>         raise
> ```

Retry Configuration

## Retry configuration

Both SDKs support configurable retry policies with exponential backoff. Cold model load times range from 30 seconds to several minutes -- configure retries accordingly.

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Livepeer } from 'livepeer';
>
> const client = new Livepeer({
>   apiKey: process.env.LIVEPEER_API_KEY,
>   retryConfig: {
>     strategy: 'backoff',
>     backoff: {
>       initialInterval: 2000,   // 2 seconds
>       maxInterval: 60000,      // 60 seconds max
>       exponent: 1.5,
>       maxElapsedTime: 300000,  // 5 minutes total
>     },
>     retryConnectionErrors: true,
>   },
> });
> ```

> [tab] Python
>
> ```python theme={null}
> from livepeer import Livepeer
> from livepeer.utils import BackoffStrategy, RetryConfig
>
> client = Livepeer(
>     api_key=os.environ['LIVEPEER_API_KEY'],
> )
>
> # Per-request retry override
> result = client.generate.text_to_image(
>     request=params,
>     retries=RetryConfig(
>         strategy='backoff',
>         backoff=BackoffStrategy(
>             initial_interval=2000,
>             max_interval=60000,
>             exponent=1.5,
>             max_elapsed_time=300000,
>         ),
>         retry_connection_errors=True,
>     ),
> )
> ```

Authentication Notes

## API key types

Two API key types exist in Studio. Use the correct type for your deployment context.

<table>
  <thead>
    <tr>
      Type

      Use case

      Security boundary
    </tr>
  </thead>

  <tbody>
    <tr>
      **Backend API key**

      Server-side code, CI/CD, scripts

      Full API access. Never expose in client-side code or committed to version control.
    </tr>

    <tr>
      **CORS-enabled key**

      Browser-side applications making direct API calls

      Scoped to asset and stream IDs. Safe to embed in frontend. Create in Studio dashboard under API Keys.
    </tr>
  </tbody>
</table>

SDK vs Direct REST

## SDK vs direct REST

Use the SDK unless you have a specific reason not to. The SDK adds typed responses, automatic retry logic, request serialisation, and error classification over raw HTTP.

Direct REST is appropriate when you are working in a language without an official SDK, integrating with a platform that already manages HTTP (e.g., curl in a shell pipeline), or need fine-grained control over request headers and serialisation.

## Related pages

> [card] [AI Quickstart](/v2/developers/get-started/ai-quickstart.md)
>
> First AI API call in 10 minutes.

> [card] [SDKs Reference](/v2/developers/resources/sdks.md)
>
> All SDK versions, packages, and links to full API reference.

> [card] [AI Authentication](/v2/developers/guides/ai/authentication.md)
>
> API key types, rotation strategy, and CORS configuration.

> [card] [AI Troubleshooting](/v2/developers/guides/ai/troubleshooting.md)
>
> Error patterns and fixes for common AI inference failures.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.