Tela SDK for JavaScript
    Preparing search index...

    Class Canvas<TInput, TOutput>

    Represents a canvas (prompt template) from the Tela API.

    Canvas instances are retrieved using tela.canvas.get() and provide methods for executing prompts with various modes (sync, async, streaming).

    Type Parameters

    • TInput extends ZodTypeOrRecord

      The input schema type (Zod schema or plain object type)

    • TOutput extends ZodTypeOrRecord

      The output schema type (Zod schema or plain object type)

    Index

    Accessors

    • get applicationId(): string

      Returns string

    • get id(): string

      Gets the unique identifier of this canvas.

      Returns string

      The canvas ID.

    • get isWorkflow(): boolean

      Gets whether this canvas is a workflow.

      Returns boolean

      True if the canvas is a workflow.

    • get isWorkstation(): boolean

      Gets whether this canvas is a workstation. This is true if an application ID is provided.

      Returns boolean

      True if the canvas is a workstation.

    • get name(): string

      Gets the name of this canvas, if provided.

      Returns string

      The canvas name or undefined.

    • get versionId(): string

      Gets the version identifier of this canvas, if specified. When undefined, the latest promoted version is used.

      Returns string

      The version ID or undefined.

    Methods

    • Prepares to execute this canvas in batch.

      Parameters

      • params: BatchParams = {}

        The parameters for the batch.

        Configuration options for batch execution.

        Batch executions are always asynchronous and return results via output file. Unlike single executions, batches do not support streaming or synchronous modes.

        • Optionallabel?: string

          Optional label for this execution when using applicationId. This label can be used to identify or categorize the execution. Note: This field is only applicable when applicationId is provided.

        • Optionalmessages?: { content: string; role: string }[]

          An array of previous messages in the conversation. Each message should have a 'role' (e.g., 'user', 'assistant') and 'content'.

        • Optionaloverride?: {
              functions?: {
                  description?: string;
                  id: string;
                  name: string;
                  parameters?: {
                      properties: Record<string, unknown>;
                      required?: string[];
                      type: "object";
                  };
              }[];
              model?: string;
              temperature?: number;
              type: "chat"
              | "completion";
          }

          Override default settings specified in the canvas. This allows for fine-tuning the completion behavior for this specific request.

          • Optionalfunctions?: {
                description?: string;
                id: string;
                name: string;
                parameters?: {
                    properties: Record<string, unknown>;
                    required?: string[];
                    type: "object";
                };
            }[]

            An array of functions that the model can call. This allows for more structured and interactive completions.

          • Optionalmodel?: string

            The specific model to use for this completion. If not specified, the default model set in the canvas will be used.

          • Optionaltemperature?: number

            Controls randomness in the output. Values between 0 and 1. Lower values make the output more focused and deterministic.

          • type: "chat" | "completion"

            Specifies whether to use a chat or completion model.

        • OptionalpollingInterval?: string | number

          Time (in milliseconds if number) between polling attempts (e.g. "1s", "1m", "1h", "1d"). Controls how frequently the SDK checks batch completion status.

          "1s"
          
        • OptionalpollingTimeout?: string | number

          Maximum time (in milliseconds if number) to wait for completion before timing out (e.g. "1s", "1m", "1h", "1d"). After timeout, polling stops but the batch continues processing on the server.

          "1m"
          
        • Optionaltags?: string[]

          Optional array of tags to associate with this execution. Tags can be used for filtering, categorization, and analytics.

        • Optionalwebhook?: BatchWebhookConfig

          Webhook configuration for batch completion notifications. Supports both URL and custom headers to forward.

          webhook: {
          url: 'https://example.com/webhook',
          headers: {
          'user-id': '12345',
          'session': 'abc-xyz'
          }
          }
        • OptionalwebhookUrl?: string

          Optional webhook URL to receive completion notifications. The server will POST to this URL when the batch completes, fails, or is canceled.

          Use the webhook parameter instead for more configuration options.

          // Old way (deprecated)
          const batch = canvas.createBatch({
          webhookUrl: 'https://example.com/webhook'
          })

          // New way (recommended)
          const batch = canvas.createBatch({
          webhook: {
          url: 'https://example.com/webhook',
          headers: { 'user-id': '12345' }
          }
          })

      Returns Batch<Output<TInput>, Output<TOutput>>

      The batch instance that can be used to manage the batch.

      const batch = canvas.createBatch({
      pollingInterval: '1s',
      pollingTimeout: '1m',
      webhookUrl: 'https://example.com/webhook',
      })

      batch.add({
      referenceId: crypto.randomUUID(), // Optional
      variables: { query: 'Hello' },
      })

      const execution = await batch.execute()
      const result = await execution.result
      const resultFile = await execution.downloadOutputFile()
    • Executes this canvas with the provided input variables. Creates and starts a canvas execution, handling variable validation and schema parsing.

      Returns a promise-like object that allows flexible usage patterns:

      • Await for the execution object: const exec = await canvas.execute(vars)
      • Direct result access: const result = await canvas.execute(vars).result
      • Stream iteration: for await (const chunk of canvas.execute(vars, { stream: true }).result)

      Parameters

      • variables: input<TInput>

        Input variables to pass to the canvas template.

      • Optionalparams: SyncExecutionParams

        Optional execution parameters (sync/async/stream configuration).

      Returns CanvasExecutionPromiseLike<SyncExecutionParams, Output<TInput>, Output<TOutput>>

      A promise-like object with a result property for direct result access.

      // Direct result access (recommended for simple cases)
      const result = await canvas.execute({ query: "Hello" }).result;

      // Get execution object for control (e.g., to abort)
      const execution = await canvas.execute({ query: "Hello" });
      const result = await execution.result;

      // Asynchronous execution with polling
      const result = await canvas.execute(
      { query: "Hello" },
      { async: true, pollingInterval: 500 }
      ).result;

      // Streaming execution
      for await (const chunk of canvas.execute(
      { query: "Hello" },
      { stream: true }
      ).result) {
      console.log(chunk);
      }

      // Execution with tags
      const result = await canvas.execute(
      { query: "Hello" },
      { tags: ["production", "analytics"] }
      ).result;
    • Executes this canvas with the provided input variables. Creates and starts a canvas execution, handling variable validation and schema parsing.

      Returns a promise-like object that allows flexible usage patterns:

      • Await for the execution object: const exec = await canvas.execute(vars)
      • Direct result access: const result = await canvas.execute(vars).result
      • Stream iteration: for await (const chunk of canvas.execute(vars, { stream: true }).result)

      Parameters

      • variables: input<TInput>

        Input variables to pass to the canvas template.

      • Optionalparams: AsyncExecutionParams

        Optional execution parameters (sync/async/stream configuration).

      Returns CanvasExecutionPromiseLike<
          AsyncExecutionParams,
          Output<TInput>,
          Output<TOutput>,
      >

      A promise-like object with a result property for direct result access.

      // Direct result access (recommended for simple cases)
      const result = await canvas.execute({ query: "Hello" }).result;

      // Get execution object for control (e.g., to abort)
      const execution = await canvas.execute({ query: "Hello" });
      const result = await execution.result;

      // Asynchronous execution with polling
      const result = await canvas.execute(
      { query: "Hello" },
      { async: true, pollingInterval: 500 }
      ).result;

      // Streaming execution
      for await (const chunk of canvas.execute(
      { query: "Hello" },
      { stream: true }
      ).result) {
      console.log(chunk);
      }

      // Execution with tags
      const result = await canvas.execute(
      { query: "Hello" },
      { tags: ["production", "analytics"] }
      ).result;
    • Executes this canvas with the provided input variables. Creates and starts a canvas execution, handling variable validation and schema parsing.

      Returns a promise-like object that allows flexible usage patterns:

      • Await for the execution object: const exec = await canvas.execute(vars)
      • Direct result access: const result = await canvas.execute(vars).result
      • Stream iteration: for await (const chunk of canvas.execute(vars, { stream: true }).result)

      Parameters

      • variables: input<TInput>

        Input variables to pass to the canvas template.

      • Optionalparams: StreamExecutionParams

        Optional execution parameters (sync/async/stream configuration).

      Returns CanvasExecutionPromiseLike<
          StreamExecutionParams,
          Output<TInput>,
          Output<TOutput>,
      >

      A promise-like object with a result property for direct result access.

      // Direct result access (recommended for simple cases)
      const result = await canvas.execute({ query: "Hello" }).result;

      // Get execution object for control (e.g., to abort)
      const execution = await canvas.execute({ query: "Hello" });
      const result = await execution.result;

      // Asynchronous execution with polling
      const result = await canvas.execute(
      { query: "Hello" },
      { async: true, pollingInterval: 500 }
      ).result;

      // Streaming execution
      for await (const chunk of canvas.execute(
      { query: "Hello" },
      { stream: true }
      ).result) {
      console.log(chunk);
      }

      // Execution with tags
      const result = await canvas.execute(
      { query: "Hello" },
      { tags: ["production", "analytics"] }
      ).result;
    • Fetches an existing async execution by its ID.

      This method retrieves the current state of an async execution that was previously started on this canvas. Only async executions can be fetched, as they are the only ones with persistent UUIDs on the server.

      Parameters

      • id: string

        The UUID of the async execution to fetch.

      • Optionaloptions: { pollingInterval?: string | number; pollingTimeout?: string | number }

        Optional configuration for polling behavior.

        • OptionalpollingInterval?: string | number

          Time in milliseconds between polling attempts (default: 1000).

        • OptionalpollingTimeout?: string | number

          Maximum time in milliseconds to wait for completion (default: 60000).

      Returns Promise<CanvasExecution<AsyncExecutionParams, unknown, Output<TOutput>>>

      A promise resolving to a CanvasExecution instance with the fetched state.

      If the provided ID is not a valid UUID.

      // Start an async execution
      const execution = await canvas.execute({ query: 'test' }, { async: true })
      const executionId = execution.id

      // Later, fetch the execution by ID
      const fetched = await canvas.getExecution(executionId)
      console.log(fetched.status) // 'running', 'succeeded', or 'failed'

      // Use poll() for event-driven progress tracking
      fetched.on('statusChange', (status) => console.log('Status:', status))
      fetched.poll()
    • Gets a canvas by its ID.

      Type Parameters

      • TInput extends ZodTypeOrRecord
      • TOutput extends ZodTypeOrRecord

      Parameters

      • options: Omit<CanvasOptions<TInput, TOutput>, "variables" | "client" | "isWorkflow"> & {
            skipSchemaValidation?: boolean;
        } & { client: BaseClient }

        The options to use to get the canvas.

        • id

          The ID of the canvas to get.

        • versionId

          The version ID of the canvas to get.

        • applicationId

          The application ID of the canvas to get.

        • client

          The client to use to make the request.

        • input

          The input schema of the canvas to get.

        • output

          The output schema of the canvas to get.

        • OptionalskipSchemaValidation?: boolean

          Whether to skip schema validation warnings during canvas retrieval. When true, no warnings will be logged for schema mismatches.

          false
          
        • client: BaseClient

          The client to use to make the request.

      Returns Promise<Canvas<TInput, TOutput>>

      The canvas.