Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Full Markdown AI integration #4069

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/young-eggs-taste.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@udecode/plate-ai': minor
---

Fixed a bug with interpreting markdown output from LLMs
2 changes: 2 additions & 0 deletions apps/www/src/registry/default/components/editor/use-chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,12 @@ const fakeStreamText = ({
} = {}) => {
// Create 3 blocks with different lengths
const blocks = [
[{ delay: 73, texts: '# Hello World' }],
Array.from({ length: chunkCount }, () => ({
delay: faker.number.int({ max: 100, min: 30 }),
texts: faker.lorem.words({ max: 3, min: 1 }) + ' ',
})),
[{ delay: 73, texts: '### Hello World' }],
Array.from({ length: chunkCount + 2 }, () => ({
delay: faker.number.int({ max: 100, min: 30 }),
texts: faker.lorem.words({ max: 3, min: 1 }) + ' ',
Expand Down
28 changes: 25 additions & 3 deletions apps/www/src/registry/default/plate-ui/ai-menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import * as React from 'react';

import { type NodeEntry, isHotkey } from '@udecode/plate';
import { type NodeEntry, type TNode, isHotkey } from '@udecode/plate';
import {
AIChatPlugin,
useEditorChat,
Expand Down Expand Up @@ -41,11 +41,33 @@ export function AIMenu() {
null
);

const updateAnchorElement = (node: TNode) => {
const el = editor.api.toDOMNode(node)!;

if (el) {
setAnchorElement(el);
} else {
// Detect a change to the editor content and update the anchor element
const editorDOM = editor.api.toDOMNode(editor)!;

const callback = () => {
const nodeDOM = editor.api.toDOMNode(node)!;

if (nodeDOM) {
setAnchorElement(nodeDOM);
editorDOM.removeEventListener('DOMNodeInserted', callback);
}
};

editorDOM.addEventListener('DOMNodeInserted', callback);
}
};

const content = useLastAssistantMessage()?.content;

const setOpen = (open: boolean) => {
if (open) {
api.aiChat.show();
api.aiChat.show(updateAnchorElement);
} else {
api.aiChat.hide();
}
Expand Down Expand Up @@ -86,7 +108,7 @@ export function AIMenu() {
useHotkeys(
'meta+j',
() => {
api.aiChat.show();
api.aiChat.show(updateAnchorElement);
},
{ enableOnContentEditable: true, enableOnFormTags: true }
);
Expand Down
21 changes: 14 additions & 7 deletions packages/ai/src/lib/transforms/insertAINodes.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Descendant, Path, SlateEditor } from '@udecode/plate';
import type { Descendant, Path, SlateEditor, TElement } from '@udecode/plate';

export const insertAINodes = (
editor: SlateEditor,
Expand All @@ -11,15 +11,22 @@ export const insertAINodes = (
) => {
if (!target && !editor.selection?.focus.path) return;

const aiNodes = nodes.map((node) => ({
...node,
ai: true,
}));
const addAINodes = (plainNodes: Descendant[]) => {
return plainNodes.map(
(plainNode: Descendant): Descendant => ({
...plainNode,
...(plainNode.children ? {} : { ai: true }),
...(plainNode.children
? { children: addAINodes((plainNode as TElement).children) }
: {}),
})
);
};
const aiNodes = addAINodes(nodes);

editor.tf.withoutNormalizing(() => {
editor.tf.insertNodes(aiNodes, {
editor.tf.insertFragment(aiNodes, {
at: editor.api.end(target || editor.selection!.focus.path),
select: true,
});
editor.tf.collapse({ edge: 'end' });
});
Expand Down
12 changes: 11 additions & 1 deletion packages/ai/src/react/ai-chat/AIChatPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type OmitFirst,
type PluginConfig,
type SlateEditor,
type TNode,
bindFirst,
} from '@udecode/plate';
import { BlockSelectionPlugin } from '@udecode/plate-selection/react';
Expand Down Expand Up @@ -55,6 +56,11 @@ export type AIChatPluginConfig = PluginConfig<
* placeholders as `promptTemplate`.
*/
systemTemplate: (props: EditorPromptParams) => string | void;
/**
* Callback function to update the anchor element when the AI is done
* rendering its answer
*/
anchorUpdate?: (anchor: TNode) => void;
} & TriggerComboboxPluginOptions,
{
aiChat: {
Expand All @@ -80,6 +86,7 @@ export const AIChatPlugin = createTPlatePlugin<AIChatPluginConfig>({
dependencies: ['ai'],
options: {
aiEditor: null,
anchorUpdate: undefined,
chat: { messages: [] } as any,
mode: 'chat',
open: false,
Expand Down Expand Up @@ -138,12 +145,15 @@ export const AIChatPlugin = createTPlatePlugin<AIChatPluginConfig>({
delete lastBatch.ai;
}
},
show: () => {
show: (anchorUpdate?: (anchor: TNode) => void) => {
api.aiChat.reset();

getOptions().chat.setMessages?.([]);

setOption('open', true);
if (anchorUpdate) {
setOption('anchorUpdate', anchorUpdate);
}
},
}))
.extendTransforms(({ editor }) => ({
Expand Down
23 changes: 21 additions & 2 deletions packages/ai/src/react/ai-chat/useAIChatHook.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { deserializeInlineMd } from '@udecode/plate-markdown';
import type { Operation } from '@udecode/plate';

import { deserializeMd } from '@udecode/plate-markdown';
import { useEditorPlugin, usePluginOption } from '@udecode/plate/react';

import type { AIPluginConfig } from '../ai/AIPlugin';
Expand All @@ -10,6 +12,10 @@ import { useChatChunk } from './hooks/useChatChunk';
export const useAIChatHooks = () => {
const { editor, tf } = useEditorPlugin<AIPluginConfig>({ key: 'ai' });
const mode = usePluginOption({ key: 'aiChat' } as AIChatPluginConfig, 'mode');
const anchorUpdate = usePluginOption(
{ key: 'aiChat' } as AIChatPluginConfig,
'anchorUpdate'
);

useChatChunk({
onChunk: ({ isFirst, nodes }) => {
Expand All @@ -33,7 +39,11 @@ export const useAIChatHooks = () => {
editor.undo();
editor.history.redos.pop();

const nodes = deserializeInlineMd(editor, content);
const deserialized = deserializeMd(editor, content);
const nodes =
deserialized.at(0)?.type === 'p'
? [...deserialized[0].children, ...deserialized.slice(1)]
: deserialized;

withAIBatch(
editor,
Expand All @@ -42,6 +52,15 @@ export const useAIChatHooks = () => {
},
{ split: true }
);

const lastAINode = editor.history.undos
.at(-1)
?.operations.findLast(
(op: Operation) => op.type === 'insert_node'
)?.node;
if (lastAINode && anchorUpdate) {
anchorUpdate(lastAINode);
}
},
});
};
12 changes: 6 additions & 6 deletions packages/ai/src/react/copilot/CopilotPlugin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -228,28 +228,28 @@ export const CopilotPlugin = createTPlatePlugin<CopilotPluginConfig>({
shortcuts: {
acceptCopilot: {
keys: [[Key.Tab]],
handler: ({ event }) => {
preventDefault: true,
handler: () => {
if (!getOptions().suggestionText?.length) return;

event.preventDefault();
api.copilot.accept();
},
},
acceptCopilotNextWord: {
keys: [[Key.Meta, Key.ArrowRight]],
handler: ({ event }) => {
preventDefault: true,
handler: () => {
if (!getOptions().suggestionText?.length) return;

event.preventDefault();
api.copilot.acceptNextWord();
},
},
hideCopilot: {
keys: [[Key.Escape]],
handler: ({ event }) => {
preventDefault: true,
handler: () => {
if (!getOptions().suggestionText?.length) return;

event.preventDefault();
api.copilot.reset();
},
},
Expand Down
6 changes: 4 additions & 2 deletions packages/ai/tsconfig.build.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@
"compilerOptions": {
"outDir": "./dist"
},
"include": ["src"]
}
"include": [
"src"
]
}