Skip to Content
OrbixDocs
Block SDK · Guides

Add AI to a block

Generate text, structured JSON, and streaming responses with useOrbixAI from @orbixdocs/sdk/ai.

Import useOrbixAI from @orbixdocs/sdk/ai to generate text, stream tokens incrementally, or request structured JSON inside a block.

Capabilities required

FeatureRequired manifest.capabilitiesIncluded in community default?
Prompt-only generation (generateText, generate, stream)ai: ['generate']Yes
Include current editor selection (context: { selection: true })ai: ['generate', 'context:selection'] and document: ['read']Must add 'context:selection'
Include full current page (context: { page: true })ai: ['generate', 'context:document'] and document: ['read']Must add 'context:document'

Remember that declaring capabilities.ai replaces the community default for ai, so always keep 'generate' in the array when adding context scopes:

manifest.json
{
  "capabilities": {
    "ai": ["generate", "context:selection", "context:document"],
    "document": ["read"]
  }
}

Streaming and cancellation example

useOrbixAI tracks concurrent requests safely and exposes cancel() (backed by an AbortController) so users can stop an in-flight stream cleanly:

src/SummarizerBlock.tsx
import { useState } from 'react';
import { defineBlock, type BlockRenderProps } from '@orbixdocs/sdk';
import { useOrbixAI } from '@orbixdocs/sdk/ai';

export default defineBlock({
  manifest: {
    id: 'acme.selection-tldr',
    name: 'Selection TL;DR',
    version: '1.0.0',
    sdk: '^3.0.0',
    capabilities: {
      ai: ['generate', 'context:selection'],
      document: ['read'],
    },
  },
  component(_props: BlockRenderProps) {
    const [output, setOutput] = useState('');
    const { stream, cancel, isGenerating, error } = useOrbixAI({
      systemPrompt: 'Summarize the provided text in two plain bullet points.',
      temperature: 0.3,
    });

    const runSummary = async () => {
      setOutput('');
      try {
        await stream(
          {
            prompt: 'Summarize the selected text.',
            context: { selection: true },
          },
          (_chunk, fullText) => {
            setOutput(fullText);
          }
        );
      } catch {
        // Error state is also surfaced on `error`
      }
    };

    return (
      <div
        style={{
          padding: 16,
          borderRadius: 12,
          background: 'var(--orbix-card-bg, #16171b)',
          border: '1px solid var(--orbix-surface-border, #2a2b32)',
          color: 'var(--orbix-text-primary, #f4f4f5)',
        }}
      >
        <div style={{ display: 'flex', gap: 8 }}>
          <button type="button" disabled={isGenerating} onClick={() => void runSummary()}>
            {isGenerating ? 'Summarizing...' : 'Summarize selection'}
          </button>
          {isGenerating && (
            <button type="button" onClick={cancel}>
              Stop
            </button>
          )}
        </div>

        {error && <p style={{ color: '#f87171' }}>{error.message}</p>}
        {output && <pre style={{ whiteSpace: 'pre-wrap', marginBottom: 0 }}>{output}</pre>}
      </div>
    );
  },
});

Notice the stream signature

stream takes (optionsOrPrompt, onChunk?), where onChunk receives (chunk: string, fullText: string) and context lives inside the first options object ({ prompt, context: { selection: true } }).

Structured JSON generation (generate<T>)

Use generate<T> with a JSON schema when you need typed fields rather than free-form prose:

src/ExtractTasks.tsx
import { useOrbixAI } from '@orbixdocs/sdk/ai';

interface ActionList {
  tasks: Array<{ owner: string; task: string }>;
}

export function useExtractTasks() {
  const ai = useOrbixAI({ temperature: 0.1 });

  return async (notes: string): Promise<ActionList> => {
    return ai.generate<ActionList>({
      prompt: `Extract action items from these meeting notes:\n\n${notes}`,
      schema: {
        type: 'object',
        properties: {
          tasks: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                owner: { type: 'string' },
                task: { type: 'string' },
              },
              required: ['owner', 'task'],
            },
          },
        },
        required: ['tasks'],
      },
    });
  };
}

How API keys and air-gap tainting work at runtime

  1. useOrbixAI calls the Google Gemini API (generativelanguage.googleapis.com) using the user's configured key from localStorage['orbix_gemini_api_key'] (or VITE_GEMINI_API_KEY in local Vite development). If no key is configured, generate and stream reject with an Error instructing the user to add an AI key in Orbix Settings.
  2. Before sending a prompt, useOrbixAI enforces capabilityEngine.verifyAI('generate', blockId) and scans the prompt through orbixEgressFirewall so stored third-party block secrets cannot be leaked into AI prompts.
  3. Passing context: { page: true } or context: { selection: true } requires document: ['read'] alongside ai: ['generate', 'context:document'] or 'context:selection', and marks a community block as tainted by workspace read (orbixEgressFirewall). Tainted blocks remain permitted to call Gemini through useOrbixAI, while arbitrary external fetch / orbixFetch requests are blocked to prevent exfiltration.
  4. getApiKey() never returns the raw key — it returns '••••••••' when a key is present and '' when unset. Calling setApiKey() from a community block logs a warning and is ignored so third-party blocks cannot overwrite the user's workspace AI key.

On this page