Puck AI beta
Read docs
API ReferenceAICloud ClientpuckHandler

puckHandler

Handle all endpoints for the /api/puck/* path (used by the AI plugin) and fine-tune behavior.

// app/api/puck/[...all]/route.ts

import { puckHandler } from "@puckeditor/cloud-client";

export const POST = (request) => {
  return puckHandler(request, {
    ai: {
      context: "We are Google. You create Google landing pages.",
    },
  });
};

Args

ParamExampleTypeStatus
requestnew Request()RequestRequired
cloudOptions{ ai: {} }CloudOptions-

Cloud Options

ParamExampleTypeStatus
ai.context"We are Google"String-
ai.onFinish({ totalCost }) => {}Function-
ai.tools{}Object-
apiKey"SECRET"String-
host"https://www.example.com/api/"String-

ai.context

Provide system context and instructions to the agent.

const handler = puckHandler({
  ai: {
    context: "We are Google. You create Google landing pages.",
  },
});

ai.onFinish

A callback triggered when the request is complete. Provides usage information.

const handler = puckHandler({
  ai: {
    onFinish: ({ totalCost, tokenUsage }) => {
      console.log(`Used ${totalCost} credit`);
    },
  },
});

OnFinish Params

ParamExampleType
totalCost0.2number
tokenUsage{}Object
totalCost

A number representing the total cost of the request.

tokenUsage

An object containing a breakdown of token consumption:

  • inputTokens
  • outputTokens
  • totalTokens
  • reasoningTokens
  • cachedInputTokens

ai.tools

Define tools that enable the agent to execute functions on your server and retrieve data. The result of the tool will be factored into the request.

import { tool } from "@puckeditor/cloud-client";
 
const handler = puckHandler({
  ai: {
    tools: {
      getProducts: tool({
        description: "Get a list of product codes",
        inputSchema: z.object(),
        execute: async () => {
          return [
            {
              name: "Google Maps",
              product_code: "maps",
            },
            {
              name: "Google Calendar",
              product_code: "calendar",
            },
          ];
        },
      }),
    },
  },
});

apiKey

Set your API key. Will use the PUCK_API_KEY environment variable by default.

const handler = puckHandler({
  apiKey: process.env.MY_PUCK_KEY,
});

host

Set a custom Puck Cloud host.

const handler = puckHandler({
  host: "https://www.example.com/api",
});