@ckeditor/ckeditor5-ai
Version:
AI features for CKEditor 5.
343 lines (342 loc) • 13.5 kB
TypeScript
/**
* @license Copyright (c) 2003-2025, CKSource Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
*/
import { type AIConnector, type AIUserMessage } from '../../aicore/aiconnector.js';
import { AIContextItemType, AIContextTextResourceType, type AIContextItem, type AIContextItemRequestData } from '../../aicore/model/aicontext.js';
export declare const AI_CONTEXT_MODEL_EVENT_NAMES: readonly ["contextItemAdded", "contextItemRemoved", "contextItemLoadingEnded", "contextSent", "error", "addContextOptionsChanged", "sourceResourcesLoaded", "resourceStateChanged", "uploadProgressChanged"];
declare const AIChatContext_base: {
new (): import("ckeditor5/src/utils.js").Observable;
prototype: import("ckeditor5/src/utils.js").Observable;
};
/**
* Manages the context of the current conversation.
*/
export declare class AIChatContext extends /* #__PURE__ */ AIChatContext_base {
constructor({ connector, config, ownerId }: {
connector: AIConnector;
config?: AIChatContextConfig;
ownerId: string;
});
/**
* Initializes the context.
*/
init(): void;
/**
* Returns the pending context items that will be sent to the AI endpoint in the next interaction.
*
* @returns Map of pending context items keyed by their uiId
*/
getPendingContextItems(): Map<string, AIContextItem>;
/**
* Populates context items from message data.
* This method converts user message content to context items and adds them to the conversation context.
*/
populateFromMessage(content: AIUserMessage['content'][0]): Promise<AIContextItem>;
/**
* Creates a context item from conversation content.
*/
private _createContextItemFromContent;
/**
* Returns all context items that have been sent to the AI endpoint in the current conversation.
*
* @returns Map of sent context items keyed by their uiId
*/
getSentContextItems(): Map<string, AIContextItem>;
/**
* Removes a context item from the pending context.
* Read-only items cannot be removed and the method returns early.
*
* @param uiId The unique identifier of the context item to remove
*/
removeFromContext(uiId: string): void;
/**
* Clears all pending context items and adds the current document to the conversation context if it exists.
*/
clearPendingContextItems(): void;
/**
* Adds context items to the conversation context and clears the pending context items.
*/
addToConversationContext(contextItems: Map<string, AIContextItem>): void;
/**
* Checks if the current document is in the pending context.
*
* @returns True if the current document is in pending context, false otherwise
*/
isCurrentDocumentInContext(): boolean;
isSelectionInContext(): boolean;
/**
* Checks if the current document is in the conversation context.
*
* @returns True if the current document is in conversation context, false otherwise
*/
isCurrentDocumentInConversation(): boolean;
/**
* Converts context items to request data format for API endpoint.
* This static method transforms the internal context item format to the format expected by the AI connector.
*
* @param contextItems Map of context items to convert
* @returns Array of context items in API request format
*/
static mapContextItemsToRequestData(contextItems: Map<string, AIContextItem>): Array<AIContextItemRequestData>;
/**
* Adds files to the context by uploading them and creating context items.
* This method handles multiple files concurrently and tracks upload progress.
*
* @param files Array of File objects to upload and add to context
* @param [attributes] Optional attributes object containing resourceId and label for tracking purposes and context chips
* @param [type] Context item type, defaults to AIContextItemType.FILE to indicate that the file is being added as a file or text
* @returns Promise that resolves when all files are processed
*/
addFilesToContext(files: Array<File>, attributes?: {
resourceId: string;
label: string;
}, type?: AIContextItemType.FILE | AIContextItemType.TEXT): Promise<void>;
/**
* Adds the current document to the pending context.
* If the document is already in context, this method returns early without changes.
*
* @param label Display label for the current document
*/
addCurrentDocumentToContext(label: string): void;
/**
* Updates the current document in the pending context with new content and version.
* This method uploads the document content and updates the context item accordingly.
*
* @param content The document content to upload, or undefined to skip
* @param version Version number of the document for change tracking
* @returns Promise that resolves when the document is updated
*/
updateCurrentDocument(content: string | undefined, version: number, sessionId: string | null, selections: Array<{
start: number;
end: number;
htmlFragment: string;
}>): Promise<void>;
addSelectionToContext(selection: string): void;
removeSelectionFromContext(): void;
/**
* Adds a URL to the context by uploading it and creating a context item.
* This method handles URL upload with proper error handling and progress tracking.
*
* @param url The URL to upload and add to context
* @param [attributes] Optional attributes object containing resourceId and label for tracking purposes and context chips
* @returns Promise that resolves when the URL is processed
*/
addUrlToContext(url: string, attributes?: {
resourceId: string;
label: string;
}): Promise<void>;
/**
* Loads resources for a given source provider with the specified query.
* This method calls the source's getResources callback and updates resource states.
*
* @param sourceId The unique identifier of the source provider
* @param query Search query to filter resources
* @param uid Unique identifier for the request to prevent race conditions
* @returns Promise resolving to array of resources with context state
*/
loadSourceResources(sourceId: string, query: string, uid: string): Promise<Array<AIContextResourceState>>;
addResourceToContext(source: AIContextProvider, resource: AIContextResource): Promise<void>;
}
export type AIChatContextItemAddedEvent = {
name: 'contextItemAdded';
args: [
{
contextItem: AIContextItem;
isLoading: boolean;
}
];
};
export type AIChatContextItemRemovedEvent = {
name: 'contextItemRemoved';
args: [
{
uiId: string;
type?: AIContextItemType;
}
];
};
export type AIChatContextSentEvent = {
name: 'contextSent';
args: [
{
contextItems: Array<AIContextItem>;
}
];
};
export type AIChatContextAddContextOptionsChangedEvent = {
name: 'addContextOptionsChanged';
args: [
{
options: AIAddContextOptionsState;
}
];
};
export type AIChatContextUploadProgressChangedEvent = {
name: 'uploadProgressChanged';
args: [
{
isUploadInProgress: boolean;
}
];
};
export type AIAddContextOptionsState = {
document: {
enabled: boolean;
isHidden: boolean;
};
urls: {
enabled: boolean;
};
files: {
enabled: boolean;
};
sources: Array<AIContextProviderState>;
};
export type AIContextProviderState = AIContextProvider & {
resources: Array<AIContextResourceState>;
};
export type AIContextResourceState = AIContextResource & {
isInContext?: boolean;
};
/**
* The configuration of the AI Chat menu for adding resources to the prompt context.
*
* This menu allows users to attach additional resources (files, documents, URLs) to their AI chat prompts,
* providing the AI with more context for generating responses. The properties defined in this config are set
* in the `config.ai.chat.context` namespace.
*
* It also allows to change the minimal number of items in the context adding menu required to show the search input
* using `config.ai.chat.context.searchInputVisibleFrom` option.
*
* ```ts
* ClassicEditor
* .create( editorElement, {
* ai: {
* chat: {
* context: {
* document: { enabled: true },
* urls: { enabled: false },
* files: { enabled: true },
* sources: [
* {
* id: 'my-docs',
* label: 'My Documents',
* getResources: ( query?: string ) => fetchMyDocuments( query ),
* getData: ( id ) => fetchDocumentContent( id )
* }
* ],
* searchInputVisibleFrom: 5
* }
* }
* }
* } )
* .then( ... )
* .catch( ... );
* ```
*
* The `document`, `urls`, and `files` properties control the built-in options in the context menu.
* Each option can be enabled or disabled using the `enabled` boolean property.
*
* The `sources` property is an array where each element represents a custom option in the context menu.
* When a user clicks on a custom source option, it will display a list of available resources returned by the
* `getResources` callback. If a resource doesn't have content provided in the `getResources` response, the content
* will be retrieved using the `getData` callback when the resource is selected. If the list of resources is long enough,
* the search input will be shown to filter the resources. The minimal number of resources required to show the search input
* can be configured using `searchInputVisibleFrom` option.
*
* See {@link module:ai/aichat/model/aichatcontext~AIContextProvider} and
* {@link module:ai/aichat/model/aichatcontext~AIContextResource}.
*/
export type AIChatContextConfig = {
document?: {
enabled: boolean;
};
urls?: {
enabled: boolean;
};
files?: {
enabled: boolean;
};
sources?: Array<AIContextProvider>;
/**
* The minimum number of resources to show the search input.
*
* @default 7
*/
searchInputVisibleFrom?: number;
};
/**
* The configuration of a custom option in the AI Chat menu for adding resources to the prompt context.
*
* Each `AIContextProvider` represents a single menu option that, when clicked, displays a list of available
* resources that can be attached to the AI prompt. The `label` is displayed as the menu option text, and the
* optional `icon` can be used to provide a visual representation.
*
* The `getResources` callback is called when the user clicks on the menu option and should return an array of
* available resources. If a resource doesn't have content provided in the `getResources` response (i.e., the `data`
* property is undefined), the content will be retrieved using the `getData` callback when the resource is selected
* to be included in the prompt context.
*
* The optional `useDefaultFiltering` property controls whether the built-in search filtering should be applied
* to the resources returned by `getResources`. When set to `true`, the resources will be filtered
* based on the user's search query. When set to `false`, all resources will be displayed regardless of the search query,
* allowing the provider to handle filtering internally within the `getResources` callback.
*
* ```ts
* {
* id: 'knowledge-base',
* label: 'Knowledge Base',
* icon: 'book',
* useDefaultFiltering: false,
* getResources: async ( query?: string ) => [
* { id: 'doc1', type: AIContextItemType.DOCUMENT, label: 'User Guide' },
* { id: 'doc2', type: AIContextItemType.DOCUMENT, label: 'API Reference', data: 'content...' }
* ],
* getData: async ( id ) => fetchDocumentContent( id )
* }
* ```
*/
export type AIContextProvider = {
id: string;
icon?: string;
label: string;
useDefaultFiltering?: boolean;
getResources: (query?: string) => Promise<Array<AIContextResource>>;
getData?: (id: string) => Promise<string>;
};
/**
* An individual resource item within a {@link module:ai/aichat/model/aichatcontext~AIContextProvider}.
*
* Represents a single selectable item in the resources list displayed when a user clicks on a custom
* context menu option. The `label` is displayed to the user as the resource name, and the `type`
* indicates what kind of context item this represents (file, document, or URL).
*
* When selected, the resource will be attached to the AI prompt to provide additional context for
* generating responses. If the `data` property is provided, it contains the content of the resource.
* If `data` is undefined, the content will be retrieved using the `getData` callback from the parent
* `AIContextProvider` when the resource is selected.
*
* ```ts
* {
* id: 'user-guide-intro',
* type: AIContextItemType.DOCUMENT,
* label: 'User Guide - Introduction',
* data: 'This is the introduction to our user guide...'
* }
* ```
*/
export type AIContextResource = {
id: string;
type: AIContextItemType;
label: string;
data?: string | File | AIContextTextResource;
};
/**
* A text resource that can be used as a context item.
*/
export type AIContextTextResource = {
content: string;
type: AIContextTextResourceType;
};
export {};