Skip to content

Commit

Permalink
[Security Solution] [AI Assistant] Remove citations feature flag (ela…
Browse files Browse the repository at this point in the history
…stic#212204)

## Summary

Removes the citations feature flag added in this PR:
elastic#206683

#### How to test:
- Add the feature flag to kibana.dev.yaml
`xpack.securitySolution.enableExperimental:
['contentReferencesEnabled']`
- Start Kibana
- You should see the log
```
The following configuration values are no longer supported and should be removed from the kibana configuration file:

    xpack.securitySolution.enableExperimental:
      - contentReferencesEnabled
```
- Remove the feature flag from kibana.dev.yaml
- Restart Kibana
- You should not see the log
- Open the Security AI assistant
- Check "Show citations" exists in the assistant settings menu
<img width="869" alt="image"
src="https://github.com/user-attachments/assets/34a4c812-bccd-4eef-a9f9-7c834faff951"
/>

- Ask the assistant a question about your knowledge base or an alert.
The response should contain a citation. (if it does not, append "include
citations" to your prompt)
- Use the shortcut option + c to toggle citations on and off. Observe if
this works as expected.

### Checklist

Check the PR satisfies following conditions.

Reviewers should verify this PR satisfies this list as well.

- [X] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/src/platform/packages/shared/kbn-i18n/README.md)
- [X]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [X] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [X] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [X] This was checked for breaking HTTP API changes, and any breaking
changes have been approved by the breaking-change committee. The
`release_note:breaking` label should be applied in these situations.
- [X] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [X] The PR description includes the appropriate Release Notes section,
and the correct `release_note:*` label is applied per the
[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

### Identify risks

Does this PR introduce any risks? For example, consider risks like hard
to test bugs, performance regression, potential of data loss.

Describe the risk, its severity, and mitigation for each identified
risk. Invite stakeholders and evaluate how to proceed before merging.

- [ ] [See some risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)
- [ ] ...

---------

Co-authored-by: kibanamachine <[email protected]>
(cherry picked from commit 638ae14)
  • Loading branch information
KDKHD committed Feb 25, 2025
1 parent b04883c commit cc5de3f
Show file tree
Hide file tree
Showing 42 changed files with 151 additions and 386 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,4 @@ export type AssistantFeatureKey = keyof AssistantFeatures;
export const defaultAssistantFeatures = Object.freeze({
assistantModelEvaluation: false,
defendInsights: true,
contentReferencesEnabled: false,
});
Original file line number Diff line number Diff line change
Expand Up @@ -18,27 +18,21 @@ import { ContentReferencesStore, ContentReferenceBlock } from '../types';
export const pruneContentReferences = (
content: string,
contentReferencesStore: ContentReferencesStore
): ContentReferences | undefined => {
): ContentReferences => {
const fullStore = contentReferencesStore.getStore();
const prunedStore: Record<string, ContentReference> = {};
const matches = content.matchAll(/\{reference\([0-9a-zA-Z]+\)\}/g);
let isPrunedStoreEmpty = true;

for (const match of matches) {
const referenceElement = match[0];
const referenceId = getContentReferenceId(referenceElement as ContentReferenceBlock);
if (!(referenceId in prunedStore)) {
const contentReference = fullStore[referenceId];
if (contentReference) {
isPrunedStoreEmpty = false;
prunedStore[referenceId] = contentReference;
}
}
}

if (isPrunedStoreEmpty) {
return undefined;
}

return prunedStore;
};
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,11 @@ export const getContentReferenceId = (
* @returns ContentReferenceBlock
*/
export const contentReferenceBlock = (
contentReference: ContentReference
): ContentReferenceBlock => {
contentReference: ContentReference | undefined
): ContentReferenceBlock | '' => {
if (!contentReference) {
return '';
}
return `{reference(${contentReference.id})}`;
};

Expand All @@ -36,7 +39,10 @@ export const contentReferenceBlock = (
* @param contentReference A ContentReference
* @returns the string: `Reference: <contentReferenceBlock>`
*/
export const contentReferenceString = (contentReference: ContentReference) => {
export const contentReferenceString = (contentReference: ContentReference | undefined) => {
if (!contentReference) {
return '';
}
return `Citation: ${contentReferenceBlock(contentReference)}` as const;
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,5 @@ import { z } from '@kbn/zod';
export type GetCapabilitiesResponse = z.infer<typeof GetCapabilitiesResponse>;
export const GetCapabilitiesResponse = z.object({
assistantModelEvaluation: z.boolean(),
contentReferencesEnabled: z.boolean(),
defendInsights: z.boolean(),
});
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,10 @@ paths:
properties:
assistantModelEvaluation:
type: boolean
contentReferencesEnabled:
type: boolean
defendInsights:
type: boolean
required:
- assistantModelEvaluation
- contentReferencesEnabled
- defendInsights
'400':
description: Generic Error
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ const AssistantComponent: React.FC<Props> = ({
showAnonymizedValues,
setContentReferencesVisible,
setShowAnonymizedValues,
assistantFeatures: { contentReferencesEnabled },
} = useAssistantContext();

const [selectedPromptContexts, setSelectedPromptContexts] = useState<
Expand Down Expand Up @@ -408,7 +407,6 @@ const AssistantComponent: React.FC<Props> = ({
currentUserAvatar,
systemPromptContent: currentSystemPrompt?.content,
contentReferencesVisible,
contentReferencesEnabled,
})}
// Avoid comments going off the flyout
css={css`
Expand Down Expand Up @@ -439,7 +437,6 @@ const AssistantComponent: React.FC<Props> = ({
contentReferencesVisible,
euiTheme.size.l,
selectedPromptContextsCount,
contentReferencesEnabled,
]
);

Expand All @@ -457,9 +454,7 @@ const AssistantComponent: React.FC<Props> = ({

return (
<>
{contentReferencesEnabled && (
<AnonymizedValuesAndCitationsTour conversation={currentConversation} />
)}
<AnonymizedValuesAndCitationsTour conversation={currentConversation} />
<EuiFlexGroup direction={'row'} wrap={false} gutterSize="none">
{chatHistoryVisible && (
<EuiFlexItem
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ export const SettingsContextMenu: React.FC<Params> = React.memo(
contentReferencesVisible,
showAnonymizedValues,
setShowAnonymizedValues,
assistantFeatures: { contentReferencesEnabled },
} = useAssistantContext();

const [isPopoverOpen, setPopover] = useState(false);
Expand Down Expand Up @@ -256,62 +255,60 @@ export const SettingsContextMenu: React.FC<Params> = React.memo(
</EuiFlexItem>
</EuiFlexGroup>
</EuiContextMenuItem>

{contentReferencesEnabled && (
<EuiContextMenuItem
aria-label={'show-citations'}
key={'show-citations'}
data-test-subj={'show-citations'}
>
<EuiFlexGroup direction="row" gutterSize="s" alignItems="center">
<EuiFlexItem grow={false}>
<ConditionalWrap
condition={!selectedConversationHasCitations}
wrap={(children) => (
<EuiToolTip
position="top"
key={'disabled-anonymize-values-tooltip'}
content={
<FormattedMessage
id="xpack.elasticAssistant.assistant.settings.showCitationsLabel.disabled.tooltip"
defaultMessage="This conversation does not contain citations."
/>
}
>
{children}
</EuiToolTip>
)}
>
<EuiSwitch
label={i18n.SHOW_CITATIONS}
checked={contentReferencesVisible}
onChange={onChangeContentReferencesVisible}
compressed
disabled={!selectedConversationHasCitations}
<EuiContextMenuItem
aria-label={'show-citations'}
key={'show-citations'}
data-test-subj={'show-citations'}
>
<EuiFlexGroup direction="row" gutterSize="s" alignItems="center">
<EuiFlexItem grow={false}>
<ConditionalWrap
condition={!selectedConversationHasCitations}
wrap={(children) => (
<EuiToolTip
position="top"
key={'disabled-anonymize-values-tooltip'}
content={
<FormattedMessage
id="xpack.elasticAssistant.assistant.settings.showCitationsLabel.disabled.tooltip"
defaultMessage="This conversation does not contain citations."
/>
}
>
{children}
</EuiToolTip>
)}
>
<EuiSwitch
label={i18n.SHOW_CITATIONS}
checked={contentReferencesVisible}
onChange={onChangeContentReferencesVisible}
compressed
disabled={!selectedConversationHasCitations}
/>
</ConditionalWrap>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiToolTip
position="top"
key={'show-citations-tooltip'}
content={
<FormattedMessage
id="xpack.elasticAssistant.assistant.settings.showCitationsLabel.tooltip"
defaultMessage="Keyboard shortcut: <bold>{keyboardShortcut}</bold>"
values={{
keyboardShortcut: isMac ? '⌥ + c' : 'Alt + c',
bold: (str) => <strong>{str}</strong>,
}}
/>
</ConditionalWrap>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiToolTip
position="top"
key={'show-citations-tooltip'}
content={
<FormattedMessage
id="xpack.elasticAssistant.assistant.settings.showCitationsLabel.tooltip"
defaultMessage="Keyboard shortcut: <bold>{keyboardShortcut}</bold>"
values={{
keyboardShortcut: isMac ? '⌥ + c' : 'Alt + c',
bold: (str) => <strong>{str}</strong>,
}}
/>
}
>
<EuiIcon tabIndex={0} type="iInCircle" />
</EuiToolTip>
</EuiFlexItem>
</EuiFlexGroup>
</EuiContextMenuItem>
)}
}
>
<EuiIcon tabIndex={0} type="iInCircle" />
</EuiToolTip>
</EuiFlexItem>
</EuiFlexGroup>
</EuiContextMenuItem>

<EuiHorizontalRule margin="none" />
<EuiContextMenuItem
aria-label={'clear-chat'}
Expand Down Expand Up @@ -339,7 +336,6 @@ export const SettingsContextMenu: React.FC<Params> = React.memo(
handleShowAlertsModal,
knowledgeBase.latestAlerts,
showDestroyModal,
contentReferencesEnabled,
euiTheme.size.m,
euiTheme.size.xs,
selectedConversationHasCitations,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,5 @@ export type GetAssistantMessages = (commentArgs: {
currentUserAvatar?: UserAvatar;
setIsStreaming: (isStreaming: boolean) => void;
systemPromptContent?: string;
contentReferencesVisible?: boolean;
contentReferencesEnabled?: boolean;
contentReferencesVisible: boolean;
}) => EuiCommentProps[];
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ async function getAssistantGraph(logger: Logger): Promise<Drawable> {
createLlmInstance,
tools: [],
replacements: {},
contentReferencesEnabled: false,
savedObjectsClient: savedObjectsClientMock.create(),
});
return graph.getGraph();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,16 @@ export const conversationsFieldMap: FieldMap = {
array: false,
required: false,
},
'messages.metadata': {
type: 'object',
array: false,
required: false,
},
'messages.metadata.content_references': {
type: 'flattened',
array: false,
required: false,
},
replacements: {
type: 'object',
array: false,
Expand Down Expand Up @@ -168,18 +178,3 @@ export const conversationsFieldMap: FieldMap = {
required: false,
},
} as const;

// Once the `contentReferencesEnabled` feature flag is removed, the properties from the schema bellow should me moved into `conversationsFieldMap`
export const conversationsContentReferencesFieldMap: FieldMap = {
...conversationsFieldMap,
'messages.metadata': {
type: 'object',
array: false,
required: false,
},
'messages.metadata.content_references': {
type: 'flattened',
array: false,
required: false,
},
} as const;
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ export const getStructuredToolForIndexEntry = ({
}: {
indexEntry: IndexEntry;
esClient: ElasticsearchClient;
contentReferencesStore: ContentReferencesStore | undefined;
contentReferencesStore: ContentReferencesStore;
logger: Logger;
}): DynamicStructuredTool => {
const inputSchema = indexEntry.inputSchema?.reduce((prev, input) => {
Expand Down Expand Up @@ -223,22 +223,21 @@ export const getStructuredToolForIndexEntry = ({
const result = await esClient.search(params);

const kbDocs = result.hits.hits.map((hit) => {
const reference =
contentReferencesStore && contentReferencesStore.add((p) => createReference(p.id, hit));
const reference = contentReferencesStore.add((p) => createReference(p.id, hit));

if (indexEntry.outputFields && indexEntry.outputFields.length > 0) {
return indexEntry.outputFields.reduce(
(prev, field) => {
// @ts-expect-error
return { ...prev, [field]: hit._source[field] };
},
reference ? { citation: contentReferenceBlock(reference) } : {}
{ citation: contentReferenceBlock(reference) }
);
}

return {
text: hit.highlight?.[indexEntry.field].join('\n --- \n'),
...(reference ? { citation: contentReferenceBlock(reference) } : {}),
citation: contentReferenceBlock(reference),
};
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -817,7 +817,7 @@ export class AIAssistantKnowledgeBaseDataClient extends AIAssistantDataClient {
contentReferencesStore,
esClient,
}: {
contentReferencesStore: ContentReferencesStore | undefined;
contentReferencesStore: ContentReferencesStore;
esClient: ElasticsearchClient;
}): Promise<StructuredTool[]> => {
const user = this.options.currentUser;
Expand Down
Loading

0 comments on commit cc5de3f

Please sign in to comment.