GA

gamma-sdk-patterns

Provides structure and best practices for interacting with the Gamma REST API.

Install

mkdir -p .claude/skills/gamma-sdk-patterns && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/4240" && unzip -o skill.zip -d .claude/skills/gamma-sdk-patterns && rm skill.zip

Installs to .claude/skills/gamma-sdk-patterns

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Reusable patterns for the Gamma REST API (no SDK exists).
57 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Create a typed client for the Gamma REST API
  • Implement a custom error class for Gamma API responses
  • Develop a polling helper for asynchronous generation tasks
  • Create a convenience function to generate and wait for results
  • Implement template-based generation workflows
  • Add retry logic with exponential backoff for API calls

How it works

This skill provides production-grade patterns for interacting with the Gamma REST API, which lacks an official SDK. It includes typed clients, generation helpers, polling mechanisms, template workflows, and error handling.

Inputs & outputs

You give it
Gamma API key, generation requests with content and output format, template IDs, and polling options.
You get back
Typed API responses, generation IDs, generation results, error objects, and file URLs.

When to use gamma-sdk-patterns

  • Building typed Gamma REST wrappers
  • Handling generation polling logic
  • Structuring presentation factory code
  • Error handling for Gamma API calls

About this skill

Gamma API Patterns

Overview

Gamma has no published SDK — all interaction is via REST at https://public-api.gamma.app/v1.0/. This skill provides production-grade patterns for typed clients, generation helpers, polling, template workflows, and error handling.

Prerequisites

  • Completed gamma-install-auth setup
  • TypeScript project with fetch (Node.js 18+)
  • Understanding of the generate-poll-retrieve workflow

Instructions

Step 1: Typed Client Singleton

// lib/gamma.ts
const GAMMA_BASE = "https://public-api.gamma.app/v1.0";

interface GammaConfig {
  apiKey: string;
  baseUrl?: string;
  timeoutMs?: number;
}

// Types based on actual API responses
interface GenerateRequest {
  content: string;
  outputFormat?: "presentation" | "document" | "webpage" | "social_post";
  themeId?: string;
  exportAs?: "pdf" | "pptx" | "png";
  textMode?: "generate" | "condense" | "preserve";
  textAmount?: "brief" | "medium" | "detailed" | "extensive";
  imageOptions?: { style?: string };
  sharingOptions?: {
    workspaceAccess?: "noAccess" | "view" | "comment" | "edit" | "fullAccess";
    externalAccess?: "noAccess" | "view" | "comment" | "edit" | "fullAccess";
  };
  folderIds?: string[];
}

interface GenerateResult {
  generationId: string;
  status: "in_progress" | "completed" | "failed";
  gammaUrl?: string;
  exportUrl?: string;
  creditsUsed?: number;
}

let instance: ReturnType<typeof createGammaClient> | null = null;

export function getGamma() {
  if (!instance) {
    instance = createGammaClient({
      apiKey: process.env.GAMMA_API_KEY!,
    });
  }
  return instance;
}

export function createGammaClient(config: GammaConfig) {
  const base = config.baseUrl ?? GAMMA_BASE;
  const headers: Record<string, string> = {
    "X-API-KEY": config.apiKey,
    "Content-Type": "application/json",
  };

  async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), config.timeoutMs ?? 30000);
    try {
      const res = await fetch(`${base}${path}`, {
        method,
        headers,
        body: body ? JSON.stringify(body) : undefined,
        signal: controller.signal,
      });
      if (!res.ok) {
        const text = await res.text();
        throw new GammaApiError(res.status, text, path);
      }
      return res.json() as T;
    } finally {
      clearTimeout(timeout);
    }
  }

  return {
    generate: (body: GenerateRequest) =>
      request<{ generationId: string }>("POST", "/generations", body),
    generateFromTemplate: (body: TemplateRequest) =>
      request<{ generationId: string }>("POST", "/generations/from-template", body),
    poll: (id: string) =>
      request<GenerateResult>("GET", `/generations/${id}`),
    getFileUrls: (id: string) =>
      request<{ exportUrl: string }>("GET", `/generations/${id}/files`),
    listThemes: () => request<Theme[]>("GET", "/themes"),
    listFolders: () => request<Folder[]>("GET", "/folders"),
  };
}

Step 2: Custom Error Class

// lib/errors.ts
export class GammaApiError extends Error {
  constructor(
    public status: number,
    public body: string,
    public path: string
  ) {
    super(`Gamma API ${status} on ${path}: ${body}`);
    this.name = "GammaApiError";
  }

  get isRateLimit() { return this.status === 429; }
  get isAuth() { return this.status === 401 || this.status === 403; }
  get isServerError() { return this.status >= 500; }
}

Step 3: Poll-Until-Done Helper

// lib/poll.ts
export async function pollUntilDone(
  gamma: ReturnType<typeof createGammaClient>,
  generationId: string,
  opts = { intervalMs: 5000, timeoutMs: 180000 }
): Promise<GenerateResult> {
  const deadline = Date.now() + opts.timeoutMs;

  while (Date.now() < deadline) {
    const result = await gamma.poll(generationId);

    if (result.status === "completed") return result;
    if (result.status === "failed") {
      throw new Error(`Generation ${generationId} failed`);
    }

    await new Promise((r) => setTimeout(r, opts.intervalMs));
  }

  throw new Error(`Poll timeout for ${generationId} after ${opts.timeoutMs}ms`);
}

Step 4: Generate-and-Wait Convenience

// lib/generate.ts
export async function generateAndWait(
  gamma: ReturnType<typeof createGammaClient>,
  request: GenerateRequest
): Promise<GenerateResult> {
  const { generationId } = await gamma.generate(request);
  console.log(`Generation started: ${generationId}`);
  return pollUntilDone(gamma, generationId);
}

// Usage
const gamma = getGamma();
const result = await generateAndWait(gamma, {
  content: "Quarterly business review for Q1 2026",
  outputFormat: "presentation",
  themeId: "theme_abc123",
  exportAs: "pptx",
  textAmount: "medium",
  imageOptions: { style: "photorealistic corporate" },
});
console.log(`View: ${result.gammaUrl}`);
console.log(`Download: ${result.exportUrl}`);

Step 5: Template-Based Generation

// lib/templates.ts
// Uses POST /v1.0/generations/from-template
// The template gamma must contain exactly one page

interface TemplateRequest {
  gammaId: string;     // Template gamma ID (one-page template)
  prompt: string;      // Content + instructions for the template
  themeId?: string;
  exportAs?: "pdf" | "pptx" | "png";
  imageOptions?: { style?: string };
  sharingOptions?: object;
  folderIds?: string[];
}

export async function generateFromTemplate(
  gamma: ReturnType<typeof createGammaClient>,
  templateId: string,
  prompt: string,
  options: Partial<TemplateRequest> = {}
): Promise<GenerateResult> {
  const { generationId } = await gamma.generateFromTemplate({
    gammaId: templateId,
    prompt,
    ...options,
  });
  return pollUntilDone(gamma, generationId);
}

Step 6: Retry with Backoff

// lib/retry.ts
export async function withRetry<T>(
  fn: () => Promise<T>,
  maxRetries = 3,
  baseDelayMs = 1000
): Promise<T> {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (err) {
      if (attempt === maxRetries) throw err;
      if (err instanceof GammaApiError && !err.isRateLimit && !err.isServerError) {
        throw err; // Don't retry auth errors or 4xx
      }
      const delay = baseDelayMs * Math.pow(2, attempt);
      console.warn(`Retry ${attempt + 1}/${maxRetries} in ${delay}ms`);
      await new Promise((r) => setTimeout(r, delay));
    }
  }
  throw new Error("Unreachable");
}

// Usage
const result = await withRetry(() =>
  generateAndWait(gamma, { content: "My deck", outputFormat: "presentation" })
);

API Endpoints Reference

MethodEndpointPurpose
POST/v1.0/generationsGenerate from text content
POST/v1.0/generations/from-templateGenerate from a template gamma
GET/v1.0/generations/{id}Poll generation status
GET/v1.0/generations/{id}/filesGet export file URLs
GET/v1.0/themesList workspace themes
GET/v1.0/foldersList workspace folders

Error Handling

PatternUse Case
GammaApiError classTyped error handling with isRateLimit, isAuth, isServerError
withRetry()Auto-retry on 429/5xx with exponential backoff
pollUntilDone()Timeout-aware polling with configurable interval
Singleton getGamma()Consistent config across modules

Resources

Next Steps

Proceed to gamma-core-workflow-a for content generation workflows.

When not to use it

  • When the `gamma-install-auth` setup is not completed
  • When the project is not a TypeScript project with `fetch` (Node.js 18+)
  • When there is no understanding of the generate-poll-retrieve workflow

Prerequisites

Completed `gamma-install-auth` setupTypeScript project with `fetch` (Node.js 18+)Understanding of the generate-poll-retrieve workflow

Limitations

  • Errors like 401 or 403 (authentication) are not retried by the `withRetry` function
  • The `pollUntilDone` helper has a default timeout of 180 seconds for generation tasks
  • Template-based generation requires the template gamma to contain exactly one page

How it compares

This skill provides structured, reusable code patterns for the Gamma API, offering a more reliable approach than direct, untyped REST calls.

Compared to similar skills

gamma-sdk-patterns side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
gamma-sdk-patterns (this skill)125dReviewIntermediate
mcp-builder1363moReviewAdvanced
telegram-mini-app626moReviewAdvanced
stripe-integration482moNo flagsAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

mcp-builder

anthropics

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

136215

telegram-mini-app

davila7

Expert in building Telegram Mini Apps (TWA) - web apps that run inside Telegram with native-like experience. Covers the TON ecosystem, Telegram Web App API, payments, user authentication, and building viral mini apps that monetize. Use when: telegram mini app, TWA, telegram web app, TON app, mini app.

62163

stripe-integration

wshobson

Implement Stripe payment processing for robust, PCI-compliant payment flows including checkout, subscriptions, and webhooks. Use when integrating Stripe payments, building subscription systems, or implementing secure checkout flows.

48165

copilot-sdk

github

Build agentic applications with GitHub Copilot SDK. Use when embedding AI agents in apps, creating custom tools, implementing streaming responses, managing sessions, connecting to MCP servers, or creating custom agents. Triggers on Copilot SDK, GitHub SDK, agentic app, embed Copilot, programmable agent, MCP server, custom agent.

763

nodejs-backend-patterns

wshobson

Build production-ready Node.js backend services with Express/Fastify, implementing middleware patterns, error handling, authentication, database integration, and API design best practices. Use when creating Node.js servers, REST APIs, GraphQL backends, or microservices architectures.

1246

chatgpt-app-builder

mcp-use

Build ChatGPT apps with interactive widgets using mcp-use and OpenAI Apps SDK. Use when creating ChatGPT apps, building MCP servers with widgets, defining React widgets, working with Apps SDK, or when user mentions ChatGPT widgets, mcp-use widgets, or Apps SDK development.

535

Search skills

Search the agent skills registry