# Context library

The Context Library stores reusable knowledge on the CKEditor AI service, so the AI features work with your organization’s own rules and reference material instead of generic instructions. A **context** is a named container that can hold reusable prompts, reference files, or both:

* **Prompts** – reusable instruction text, such as a tone-of-voice rule, an editorial standard, or a compliance requirement.
* **Files** – reference documents, such as a brand guidelines PDF, a product glossary, or a policy handbook.

> **Unlock this feature with selected CKEditor Plans**
>
> Try all premium features – no credit card needed.
>
> [Sign up for a free trial ](https://portal.ckeditor.com/checkout?plan=free)[Select a Plan](https://ckeditor.com/pricing/)

> **Note**
>
> The word “context” appears in several meanings across the documentation. This guide is about the Context Library. It is not related to the [`Context` class](../collaboration/context-and-collaboration-features.md) that shares plugins between editors, nor is it the same thing as the [resources a user attaches](ckeditor-ai-chat.md#attaching-resources-to-conversations) to an AI Chat conversation – although the [picker](#offering-contexts-in-the-ai-chat-picker) can offer library contexts among those resources.

<a id="how-it-works">

## How it works

1. An administrator creates a context on the AI service, adds prompts to it, and uploads files – directly or from a URL. See [Creating a context](https://ckeditor.com/docs/cs/latest/guides/ckeditor-ai/context-library.html#creating-a-context) in the Cloud Services documentation for the how-to.
2. An AI request references the context – either the editor sends the reference, or the service applies the context automatically.
3. The service expands the reference before the model sees the request: the context’s prompts are added to the instructions and its files are attached as reference material.

> **Important**
>
> Referencing a context requires the user token to grant access to it, and each reference sent with a request is authorized on its own. Read more about the `ai:contexts` permissions in the [permissions guide](../../../../cs/latest/guides/ckeditor-ai/permissions.md).

Resolution happens per call, so a request always uses the current content of the context. Updating a prompt or replacing a file in the library changes the behavior of every request that references it, with no deployment.

A context attached this way stays invisible to the user.

<a id="choosing-the-right-mechanism">

## Choosing the right mechanism

A context can reach a request at four levels of scope. Pick the one that matches how universal the knowledge is:

| Scope                  | Mechanism                                                                       | Managed by                                         | Typical case                                                                                                |
| ---------------------- | ------------------------------------------------------------------------------- | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| Whole environment      | [Automatic application](#applying-contexts-automatically)                       | Administrator, on the AI service                   | Rules that must hold everywhere – house style, compliance.                                                  |
| Editor instance        | [`config.ai.defaultContext`](#attaching-contexts-from-the-editor-configuration) | Integrator, in the editor configuration            | Knowledge that depends on the application state – the document type, its workflow status, the current user. |
| Single conversation    | [The AI Chat context picker](#offering-contexts-in-the-ai-chat-picker)          | User, in AI Chat                                   | Knowledge the user decides to bring in – a project brief, a product glossary.                               |
| Single command or call | [A per-invocation reference](#attaching-contexts-in-programmatic-flows)         | Integrator, per custom command or programmatic run | Material needed by one specific operation.                                                                  |

<a id="applying-contexts-automatically">

## Applying contexts automatically

Some knowledge should shape every AI response in your environment, no matter which feature produced it and who asked. The typical case is a house style: a context holding the style guide file plus a prompt describing when and how the guide applies. With it in place, every conversation, review, action, and translation follows the style guide – and neither the users nor the editor manage anything.

This is what the `autoApply` setting of a context does. An administrator enables it on the AI service and the service injects the context into every matching call. No editor configuration is involved, and the editor sends nothing. See [Applying a context automatically](https://ckeditor.com/docs/cs/latest/guides/ckeditor-ai/context-library.html#applying-a-context-automatically) in the Cloud Services documentation to set it up.

> **Note**
>
> Automatic application is global – it affects every matching call in the environment. Note also that it targets the AI service features (`conversations`, `actions.*`, `reviews.*`, `document-processing`), which are named differently than the editor features used in this guide.

Use the mechanisms below when the environment-wide scope is too broad and the editor – or the user – should decide which contexts apply.

<a id="attaching-contexts-from-the-editor-configuration">

## Attaching contexts from the editor configuration

The [`config.ai.defaultContext`](../../api/module_ai_aiconfig-AIConfig.md#member-defaultContext) option holds a list of context references that CKEditor AI attaches automatically to the requests made by its features. It is set per editor instance, so the attached knowledge can follow the application state – the type of the edited document, its workflow status, or the current user:

```js
// Every document gets the house style guide.
const defaultContext = [ { id: 'style-guide' } ];

// Clinical reports additionally get the medical terminology context.
if ( documentType === 'clinical-report' ) {
	defaultContext.push( { id: 'medical-terminology' } );
}

ClassicEditor
	.create( {
		/* ... */
		ai: {
			defaultContext
		}
	} )
	.then( /* ... */ )
	.catch( /* ... */ );
```

An entry without a `features` property is attached to every AI feature: [AI Chat](ckeditor-ai-chat.md), [AI Quick Actions](ckeditor-ai-actions.md), [AI Review](ckeditor-ai-review.md), and [AI Translate](ckeditor-ai-translate.md).

<a id="context-references">

### Context references

A context reference points either at a whole context or at a single item inside it:

| Reference                                                  | Attaches                                    |
| ---------------------------------------------------------- | ------------------------------------------- |
| `{ id: 'style-guide' }`                                    | Every prompt and every file in the context. |
| `{ id: 'style-guide', promptId: 'V1StGXR8_Z5jdHi6B-myT' }` | A single prompt from the context.           |
| `{ id: 'style-guide', fileId: 'k7Qk2Anpd9WjU7scF3xVv' }`   | A single file from the context.             |

The `promptId` and `fileId` properties are mutually exclusive.

All three shapes go into the same `config.ai.defaultContext` list:

```js
ClassicEditor
	.create( {
		/* ... */
		// ... Other configuration options ...
		ai: {
			defaultContext: [
				// The whole context: every prompt and every file it holds.
				{ id: 'style-guide' },

				// A single prompt from another context.
				{ id: 'brand-voice', promptId: 'V1StGXR8_Z5jdHi6B-myT' },

				// A single file from another context.
				{ id: 'legal-rules', fileId: 'k7Qk2Anpd9WjU7scF3xVv' }
			]
		}
	} )
	.then( /* ... */ )
	.catch( /* ... */ );
```

The `id` of a context is chosen by whoever creates it, so it can be a readable name such as `style-guide`. The `promptId` and `fileId` values are generated by the service when a prompt or a file is added to a context. Read them from the context itself before referencing a single item.

<a id="targeting-specific-features">

### Targeting specific features

Add a [`features`](../../api/module_ai_aicore_model_aidefaultcontext-AIDefaultContextFeatures.md) property to an entry to narrow down where it applies. Each key targets one AI feature. A key set to `true` attaches the entry to every invocation of that feature. A key set to a `RegExp` attaches it only when one of the invocation IDs matches. A key that is omitted, or set to `false`, excludes the feature:

```js
ClassicEditor
	.create( {
		/* ... */
		// ... Other configuration options ...
		ai: {
			defaultContext: [
				// Attached to every AI feature.
				{ id: 'style-guide' },

				// Attached to every review command, and only to the translate quick actions.
				{
					id: 'glossary',
					features: {
						review: true,
						quickActions: /^translate/
					}
				}
			]
		}
	} )
	.then( /* ... */ )
	.catch( /* ... */ );
```

The table below lists the keys and the IDs a `RegExp` is matched against:

| Key            | Feature                                  | IDs matched by a `RegExp`                                     |
| -------------- | ---------------------------------------- | ------------------------------------------------------------- |
| `chat`         | [AI Chat](ckeditor-ai-chat.md)           | The ID of the AI Chat shortcut that started the conversation. |
| `quickActions` | [Quick Actions](ckeditor-ai-actions.md)  | The ID of the action and the ID of the group it belongs to.   |
| `review`       | [AI Review](ckeditor-ai-review.md)       | The ID of the review command.                                 |
| `translate`    | [AI Translate](ckeditor-ai-translate.md) | The ID of the target language.                                |

The `quickActions`, `review`, and `translate` entries are selected separately for each run. The `chat` entries are selected once, when a conversation is initialized, and then attached to every message of that conversation – so an entry with a `RegExp` matched by the starting chat shortcut applies to the whole conversation, while a conversation started in any other way receives only the entries set to `true`. Each feature guide covers its own configuration, with examples, in detail.

<a id="how-references-combine">

### How references combine

References reach a request in a fixed order: first the matching `ai.defaultContext` entries, in configuration order, then any reference the invocation itself carries, such as the `context` of a custom quick action or of an extra review command, or a context the user attached to an AI Chat conversation.

<a id="offering-contexts-in-the-ai-chat-picker">

## Offering contexts in the AI Chat picker

Every mechanism above is set up by an administrator or an integrator, and the attached contexts stay invisible to users. The [`config.ai.chat.context.contextLibrary`](../../api/module_ai_aichat_model_aichatcontext-AIChatContextConfig.md#member-contextLibrary) option puts the choice in the hands of the user instead: it adds the library to the “Add context” menu of [AI Chat](ckeditor-ai-chat.md), where the user attaches a context to the conversation like any other resource.

The option is disabled by default:

```js
ClassicEditor
	.create( {
		/* ... */
		// ... Other configuration options ...
		ai: {
			chat: {
				context: {
					contextLibrary: {
						enabled: true
					}
				}
			}
		}
	} )
	.then( /* ... */ )
	.catch( /* ... */ );
```

When it is enabled, the menu shows a “Context library” item that lists the contexts available to the user by name, falling back to the context ID when a context has no name. Attaching one attaches the whole context – every prompt and every file it holds. Once a message is sent, the reference stays with the conversation and is sent with every following message. Its chip appears only on the message it was sent with: from then on the reference is attached silently, with no way for the user to see or remove it.

Two rules decide what the picker offers:

* **Access follows the token.** The list contains only the contexts the user token grants access to, so different users can be offered different contexts. Read more about the [`ai:contexts` permissions](../../../../cs/latest/guides/ckeditor-ai/permissions.md#context-library-permissions).
* **Default contexts are excluded.** A context referenced by `config.ai.defaultContext` never appears in the picker, even when the entry references a single item or targets only other features. Default contexts are owned by the configuration – to make a context user-selectable, leave it out of `config.ai.defaultContext`.

The list is fetched once, when the AI plugins initialize, and is not refreshed during the session. Changes in the library reach the picker after the page is reloaded.

The “Add context” menu offers more than the library – see [attaching resources to conversations](ckeditor-ai-chat.md#attaching-resources-to-conversations) in the AI Chat guide for the document, URL, file, and custom sources.

<a id="using-prompts-and-files-in-custom-actions-and-reviews">

## Using prompts and files in custom actions and reviews

A custom quick action or an extra review command can reference a context instead of carrying an inline `prompt` string, so the instruction and its reference material live in the library. This keeps them maintained in one place – they change without a deployment – and out of the frontend: the curated prompt text is not stored in the editor configuration and does not show up in the network traffic of the request. See [custom quick actions](ckeditor-ai-actions.md#prompt-from-a-context) and [extra review commands](ckeditor-ai-review.md#prompt-from-a-context) for the configuration.

<a id="attaching-contexts-in-programmatic-flows">

## Attaching contexts in programmatic flows

Driving a feature from code does not change how the mechanisms above apply. A method that starts the user interface flow of a feature attaches the matching `ai.defaultContext` entries, just like the user interface does. A headless run bypasses the user interface, and with it the editor configuration, so it works only with the references the call carries in its `contexts` option. The [programmatic usage guide](ckeditor-ai-programmatic.md) documents that option for every flow that accepts it: [chat conversations](ckeditor-ai-programmatic.md#chat) – where the passed references are merged with the configured ones rather than replacing them – [quick actions](ckeditor-ai-programmatic.md#quick-actions), [reviews](ckeditor-ai-programmatic.md#review), [translations](ckeditor-ai-programmatic.md#translate), and [document processing](ckeditor-ai-programmatic.md#document-processing).

<a id="removing-a-context">

## Removing a context

Deleting a context from the library is immediate, but references to it can outlive it – in the editor configuration, in the picker, and in the AI Chat conversations that attached it. Since references resolve per call, every new request that still carries a reference to a deleted context fails.

We recommend removing a context in the following order:

1. **Stop referencing the context.** Remove its entries from `config.ai.defaultContext`, from the custom quick actions and extra review commands that use it, and from programmatic calls. If the context is applied automatically, disable its `autoApply` setting on the AI service.
2. **Revoke access.** Stop granting the context in the [`ai:contexts` permissions](../../../../cs/latest/guides/ckeditor-ai/permissions.md#context-library-permissions) of the user tokens. Without access, the context disappears from the AI Chat picker and the service rejects any request that still references it. Allow for a transition window: tokens issued earlier keep their access until they are refreshed, and an editor that is already open keeps showing the context in the picker until the page is reloaded.
3. **Delete the context.** Remove it from the AI service. See the [API reference](https://ckeditor.com/docs/cs/latest/guides/ckeditor-ai/context-library.html#api-reference) in the Cloud Services documentation for the management call.

Deletion does not touch the stored conversation history, so conversations that used the context remain readable. Writing is a different matter: a conversation sends its attached context references with every message and they cannot be detached, so the next prompt in such a conversation is rejected. The user continues in a new conversation.

<a id="common-api">

## Common API

The Context Library is configured through `config.ai.defaultContext` and can be inspected from code – read the contexts available to the current token and build your own user interface around them.

| API                                                                                                                                              | Description                                                                                                          |
| ------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- |
| [`config.ai.defaultContext`](../../api/module_ai_aiconfig-AIConfig.md#member-defaultContext)                                                     | The list of context references attached automatically to the AI features.                                            |
| [`config.ai.chat.context.contextLibrary`](../../api/module_ai_aichat_model_aichatcontext-AIChatContextConfig.md#member-contextLibrary)           | Offers the library in the AI Chat context picker.                                                                    |
| [`AIContextRef`](../../api/module_ai_aicore_model_aicontextref-AIContextRef.md)                                                                  | The shape of a single context reference.                                                                             |
| [`AIDefaultContextEntry`](../../api/module_ai_aicore_model_aidefaultcontext-AIDefaultContextEntry.md)                                            | A context reference with an optional `features` narrowing.                                                           |
| [`AICore#contextLibrary`](../../api/module_ai_aicore_aicore-AICore.md#member-contextLibrary)                                                     | The shared context library instance, fetched once for all AI features.                                               |
| [`AIContextLibrary#getAllContexts()`](../../api/module_ai_aicore_model_aicontextlibrary-AIContextLibrary.md#function-getAllContexts)             | Returns every context the current token can access, for building your own context user interface.                    |
| [`AIContextLibrary#getAvailableContexts()`](../../api/module_ai_aicore_model_aicontextlibrary-AIContextLibrary.md#function-getAvailableContexts) | Returns the contexts offered as user-selectable – all contexts minus those referenced by `config.ai.defaultContext`. |

<a id="related-resources">

## Related resources

* [Using CKEditor AI programmatically](ckeditor-ai-programmatic.md) – drive the AI features and gateways from code.
* [Context Library in Cloud Services](https://ckeditor.com/docs/cs/latest/guides/ckeditor-ai/context-library.html) – creating and managing contexts, automatic application, and the REST API details.
* [Permissions](../../../../cs/latest/guides/ckeditor-ai/permissions.md) – the `ai:contexts` scopes that control access to contexts.

---

Full index of the CKEditor 5 documentation: [llms.txt](../../../llms.txt)
