🚀 BlockNote AI is here! Access the early preview.

AI Integration with ClientSideTransport

The standard setup is to have BlockNote AI call your server, which then calls an LLM of your choice. In this example, we show how you can use the ClientSideTransport to make calls directly to your LLM provider.

To hide API keys of our LLM provider, we do still route calls through a proxy server using fetchViaProxy (this is optional).

import { createGroq } from "@ai-sdk/groq";
import { BlockNoteEditor, filterSuggestionItems } from "@blocknote/core";
import "@blocknote/core/fonts/inter.css";
import { en } from "@blocknote/core/locales";
import { BlockNoteView } from "@blocknote/mantine";
import "@blocknote/mantine/style.css";
import {
  FormattingToolbar,
  FormattingToolbarController,
  getDefaultReactSlashMenuItems,
  getFormattingToolbarItems,
  SuggestionMenuController,
  useCreateBlockNote,
} from "@blocknote/react";
import {
  AIMenuController,
  AIToolbarButton,
  ClientSideTransport,
  createAIExtension,
  fetchViaProxy,
  getAISlashMenuItems,
} from "@blocknote/xl-ai";
import { en as aiEn } from "@blocknote/xl-ai/locales";
import "@blocknote/xl-ai/style.css";
import { getEnv } from "./getEnv";

const BASE_URL =
  getEnv("BLOCKNOTE_AI_SERVER_BASE_URL") || "https://localhost:3000/ai";

// We define the model directly in our app using the Vercel AI SDK
const model = createGroq({
  // We supply a custom fetch function so that requests are routed through our proxy server
  // (see `packages/xl-ai-server/src/routes/proxy.ts`)
  // this is needed to hide the API key of our LLM provider from the client,
  // and to prevent CORS issues
  fetch: fetchViaProxy(
    (url) => `${BASE_URL}/proxy?provider=groq&url=${encodeURIComponent(url)}`,
  ),
  apiKey: "fake-api-key", // the API key is not used as it's actually added in the proxy server
})("llama-3.3-70b-versatile");

export default function App() {
  // Creates a new editor instance.
  const editor = useCreateBlockNote({
    dictionary: {
      ...en,
      ai: aiEn, // add default translations for the AI extension
    },
    // Register the AI extension
    extensions: [
      createAIExtension({
        // The ClientSideTransport is used so the client makes calls directly to `streamText`
        // (whereas normally in the Vercel AI SDK, the client makes calls to your server, which then calls these methods)
        // (see https://github.com/vercel/ai/issues/5140 for background info)
        transport: new ClientSideTransport({
          model,
        }),
      }),
    ],
    // We set some initial content for demo purposes
    initialContent: [
      {
        type: "heading",
        props: {
          level: 1,
        },
        content: "Open source software",
      },
      {
        type: "paragraph",
        content:
          "Open source software refers to computer programs whose source code is made available to the public, allowing anyone to view, modify, and distribute the code. This model stands in contrast to proprietary software, where the source code is kept secret and only the original creators have the right to make changes. Open projects are developed collaboratively, often by communities of developers from around the world, and are typically distributed under licenses that promote sharing and openness.",
      },
      {
        type: "paragraph",
        content:
          "One of the primary benefits of open source is the promotion of digital autonomy. By providing access to the source code, these programs empower users to control their own technology, customize software to fit their needs, and avoid vendor lock-in. This level of transparency also allows for greater security, as anyone can inspect the code for vulnerabilities or malicious elements. As a result, users are not solely dependent on a single company for updates, bug fixes, or continued support.",
      },
      {
        type: "paragraph",
        content:
          "Additionally, open development fosters innovation and collaboration. Developers can build upon existing projects, share improvements, and learn from each other, accelerating the pace of technological advancement. The open nature of these projects often leads to higher quality software, as bugs are identified and fixed more quickly by a diverse group of contributors. Furthermore, using open source can reduce costs for individuals, businesses, and governments, as it is often available for free and can be tailored to specific requirements without expensive licensing fees.",
      },
    ],
  });

  // Renders the editor instance using a React component.
  return (
    <div>
      <BlockNoteView
        editor={editor}
        // We're disabling some default UI elements
        formattingToolbar={false}
        slashMenu={false}
      >
        {/* Add the AI Command menu to the editor */}
        <AIMenuController />

        {/* We disabled the default formatting toolbar with `formattingToolbar=false` 
        and replace it for one with an "AI button" (defined below). 
        (See "Formatting Toolbar" in docs)
        */}
        <FormattingToolbarWithAI />

        {/* We disabled the default SlashMenu with `slashMenu=false` 
        and replace it for one with an AI option (defined below). 
        (See "Suggestion Menus" in docs)
        */}
        <SuggestionMenuWithAI editor={editor} />
      </BlockNoteView>
    </div>
  );
}

// Formatting toolbar with the `AIToolbarButton` added
function FormattingToolbarWithAI() {
  return (
    <FormattingToolbarController
      formattingToolbar={() => (
        <FormattingToolbar>
          {...getFormattingToolbarItems()}
          {/* Add the AI button */}
          <AIToolbarButton />
        </FormattingToolbar>
      )}
    />
  );
}

// Slash menu with the AI option added
function SuggestionMenuWithAI(props: {
  editor: BlockNoteEditor<any, any, any>;
}) {
  return (
    <SuggestionMenuController
      triggerCharacter="/"
      getItems={async (query) =>
        filterSuggestionItems(
          [
            ...getDefaultReactSlashMenuItems(props.editor),
            // add the default AI slash menu items, or define your own
            ...getAISlashMenuItems(props.editor),
          ],
          query,
        )
      }
    />
  );
}
// helper function to get env variables across next / vite
// only needed so this example works in BlockNote demos and docs
export function getEnv(key: string) {
  const env = (import.meta as any).env
    ? {
        BLOCKNOTE_AI_SERVER_API_KEY: (import.meta as any).env
          .VITE_BLOCKNOTE_AI_SERVER_API_KEY,
        BLOCKNOTE_AI_SERVER_BASE_URL: (import.meta as any).env
          .VITE_BLOCKNOTE_AI_SERVER_BASE_URL,
      }
    : {
        BLOCKNOTE_AI_SERVER_API_KEY:
          process.env.NEXT_PUBLIC_BLOCKNOTE_AI_SERVER_API_KEY,
        BLOCKNOTE_AI_SERVER_BASE_URL:
          process.env.NEXT_PUBLIC_BLOCKNOTE_AI_SERVER_BASE_URL,
      };

  const value = env[key as keyof typeof env];
  return value;
}