AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Building Native macOS Extensions with Raycast AI API and AI.ask: The Zero-Key Architecture Guide

Eli Kent-Daggett · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Building AI-powered productivity tools on macOS used to require a frustrating architectural compromise. Developers either had to enforce a Bring Your Own Key (BYOK) model—requiring end users to generate, configure, and maintain OpenAI or Anthropic API credentials—or host and pay for a custom proxy backend (such as AWS Lambda or Cloudflare Workers), exposing themselves to security vulnerabilities and runaway infrastructure bills.

The Raycast AI API fundamentally eliminates this operational burden. Through @raycast/api and @raycast/utils, macOS developers can embed state-of-the-art large language models directly into native extensions using AI.ask and the useAI hook. The client application handles LLM routing, user authentication, and provider billing through the user's Raycast Pro subscription.

At 365Finds, our commercial and engineering assessment is definitive: for internal team utilities and commercial macOS workflow tools targeted at knowledge workers, building on the Raycast AI API is vastly superior to maintaining self-hosted proxies or building custom Electron apps with BYOK inputs. Developers trade infrastructure autonomy for instant zero-maintenance distribution, native macOS performance, and friction-free user onboarding.


How Raycast AI Replaces External API Keys

In traditional client-side AI extension development, managing LLM access presents two major bottlenecks:

  1. The BYOK UX Hurdle: Over 85% of non-developer desktop users do not maintain paid API platform accounts with active billing methods. Requiring an OpenAI or Anthropic secret key creates immediate churn during onboarding.
  2. The Backend Maintenance Trap: If the developer hosts a shared API key behind a custom API server, they take on server uptime management, credential rotation, rate-limit defense, and unmetered financial liability for user consumption.

Raycast AI resolves both problems through a delegated runtime model. Raycast operates as the secure local orchestration runtime. When an extension invokes AI.ask:


Pre-flight Authorization: environment.canAccess(AI)

Because the Raycast AI API depends on the user having an active Raycast Pro subscription or enterprise seat, calling AI.ask on an unsupported tier triggers an operating system upgrade dialog. If the user dismisses the prompt, the API call throws an unhandled rejection.

To build robust, store-ready extensions, developers must perform pre-flight permission checks using environment.canAccess(AI).

Graceful Degradation Pattern

import { AI, environment, showToast, Toast, openExtensionPreferences } from "@raycast/api";

export async function verifyAIAccess(): Promise<boolean> {
  const hasAccess = environment.canAccess(AI);

  if (!hasAccess) {
    await showToast({
      style: Toast.Style.Failure,
      title: "Raycast AI Required",
      message: "This command requires an active Raycast Pro subscription.",
      primaryAction: {
        title: "Open Preferences",
        onAction: () => openExtensionPreferences(),
      },
    });
    return false;
  }

  return true;
}

By checking access before initiating network execution, you prevent broken visual states and provide users with actionable recovery paths.


Implementation Pattern 1: Background & No-View Commands with AI.ask

For background utilities, hotkey-driven clipboard transformations, or Finder file actions, the low-level AI.ask method provides direct access to LLM completions without rendering a React UI.

Signature & Execution Lifecycle

async function ask(prompt: string, options?: AskOptions): Promise<string> & EventEmitter;

AI.ask returns a hybrid object: an awaitable Promise<string> combined with Node.js-style EventEmitter mechanics for real-time streaming.

1. One-Shot Awaitable Execution

When processing text in batch operations where intermediate streaming is unnecessary, treat AI.ask as a standard promise:

import { AI, Clipboard, showHUD } from "@raycast/api";

export default async function command() {
  try {
    await showHUD("Analyzing clipboard...");
    const clipboardText = await Clipboard.readText();

    if (!clipboardText) {
      await showHUD("Clipboard is empty");
      return;
    }

    const answer = await AI.ask(`Extract key action items as markdown bullets:\n\n${clipboardText}`, {
      creativity: "low",
      model: AI.Model["OpenAI_GPT-4o"],
    });

    await Clipboard.copy(answer);
    await showHUD("Action items copied!");
  } catch (error) {
    await showHUD("Failed to analyze content");
    console.error(error);
  }
}

2. Real-Time Streaming with Event Listeners

For longer outputs or real-time file updates, attach an event listener to the "data" event before awaiting the completion:

import { AI, getSelectedFinderItems, showHUD } from "@raycast/api";
import fs from "fs";

export default async function command() {
  const [selectedFile] = await getSelectedFinderItems();
  if (!selectedFile) {
    await showHUD("No file selected in Finder");
    return;
  }

  await showHUD("Streaming code refactor...");
  const rawCode = await fs.promises.readFile(selectedFile.path, "utf-8");

  let accumulatedContent = "";
  const request = AI.ask(`Refactor this code for readability and type safety:\n\n${rawCode}`, {
    creativity: "none",
  });

  request.on("data", async (chunk: string) => {
    accumulatedContent += chunk;
    // Stream chunks directly into the destination file
    await fs.promises.writeFile(`${selectedFile.path}.refactored.ts`, accumulatedContent, "utf-8");
  });

  await request;
  await showHUD("Refactoring complete!");
}

Configuration Options: Fine-Tuning AI.ask

The options parameter accepts an AI.AskOptions object:

creativity

Controls model temperature and sampling diversity:

model

Selects the underlying LLM. Developers can pass strongly typed enum keys from AI.Model or reference a local model ID provided via an ai.modelProvider extension.

Supported models within the Raycast ecosystem include:

If a user lacks permission for a premium frontier model or disables a specific provider in Raycast Settings, Raycast automatically falls back to an equivalent active model, ensuring command execution does not fail.

signal

Pass a standard Web API AbortSignal to cancel long-running or stranded requests:

const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 15000); // 15s timeout

const response = await AI.ask("Summarize the logs", {
  signal: controller.signal,
});
clearTimeout(timeoutId);

Implementation Pattern 2: Interactive Views with the useAI Hook

When building interactive commands using Raycast's React renderer (Detail, List, or Form), manually managing stream buffers, loading spinners, and abort controllers creates unnecessary boilerplate.

The @raycast/utils package provides the specialized useAI hook, which wraps AI.ask into a reactive state machine.

Interactive Code Explainer Example

import { Detail, ActionPanel, Action, Icon } from "@raycast/api";
import { useAI } from "@raycast/utils";

interface CommandProps {
  arguments: {
    snippet?: string;
  };
}

export default function Command(props: CommandProps) {
  const targetCode = props.arguments.snippet || "const x = () => { return 42; };";

  const { data, isLoading, revalidate, error } = useAI(
    `Explain the time complexity, edge cases, and architecture of this code:\n\`\`\`typescript\n${targetCode}\n\`\`\``,
    {
      creativity: "low",
      stream: true, // Enabled by default; streams data into the view
    }
  );

  return (
    <Detail
      isLoading={isLoading}
      markdown={data || (isLoading ? "*Analyzing snippet...*" : "*No output generated.*")}
      actions={
        <ActionPanel>
          <Action.CopyToClipboard title="Copy Explanation" content={data || ""} />
          <Action title="Regenerate" icon={Icon.ArrowClockwise} onAction={revalidate} />
        </ActionPanel>
      }
    />
  );
}

State Properties of useAI


Architectural Comparison: Raycast AI API vs. Alternative Patterns

DimensionRaycast AI API (@raycast/api)Bring Your Own Key (BYOK)Self-Hosted Proxy Backend
API Key ProvisioningZero; managed by Raycast clientHigh; user generates personal keysDeveloper provisions and funds keys
Onboarding FrictionInstant for Raycast Pro usersSevere; requires developer platform setupInstant; transparent to user
Infrastructure OverheadNone; zero server hostingNone; direct client-to-API callsHigh; Lambda, edge functions, DBs
Developer Cost Risk$0; covered by user subscription$0; user pays their providerHigh; runaway abuse or bill spikes
Rate Limit ManagementBuilt-in (10/min, 100/hr)Bound to individual user key tierDeveloper must enforce rate limiters
Model FlexibilityMulti-vendor (OpenAI, Claude, Gemini)Tied to single configured providerFully customizable
UI Integration SpeedNative React hooks (useAI, Detail)Manual streaming and state plumbingManual websocket / SSE handling

Rate Limits and Production Guardrails

To prevent runaway loops from exhausting subscriber quotas, Raycast enforces programmatic rate limits on extension calls:

Best Practices for Extension Developers

  1. Avoid Automated Polling: Never call AI.ask inside setInterval or unbounded file-watcher callbacks. All AI calls should be triggered by deliberate user actions.
  2. Handle Rejections Cleanly: Always wrap standalone AI.ask calls in try...catch blocks to capture quota exhaustion (Rate limit exceeded) or network disconnections.
  3. Keep Prompts Compact: Provide concise system instructions and clean input text to minimize latency and token expenditure against the user's monthly credits.

365Finds Research Verdict

The Raycast AI API is an exceptional engineering design for developers building macOS-native software. By decoupling AI capabilities from raw API key management and custom backend proxies, it shifts the operational burden to Raycast while giving developers instantaneous access to top-tier models.

The trade-off is platform scope: your extension requires Raycast Pro ($8–$10/month) for end users. However, for internal developer workflows, macOS power users, and team productivity tooling, this constraint is negligible compared to the massive reduction in engineering maintenance, security exposure, and infrastructure overhead.

References