Skip to content

Commit af2ef14

Browse files
authored
feat(guardrails): add Contextual grounding (#660)
* feat(guardrails): add contextual grounding
1 parent 78e3ed2 commit af2ef14

17 files changed

+234
-11
lines changed

.projen/deps.json

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.projenrc.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import {
3030
const GITHUB_USER = 'awslabs';
3131
const PUBLICATION_NAMESPACE = 'cdklabs';
3232
const PROJECT_NAME = 'generative-ai-cdk-constructs';
33-
const CDK_VERSION: string = '2.149.0';
33+
const CDK_VERSION: string = '2.154.1';
3434

3535
function camelCaseIt(input: string): string {
3636
// Hypens and dashes to spaces and then CamelCase...

CHANGELOG.md

+4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
# CDK Generative AI Constructs V0.1.258 (2024-08-26)
2+
3+
Based on CDK library version 2.154.1
4+
15
# CDK Generative AI Constructs V0.1.213 (2024-07-18)
26

37
Based on CDK library version 2.149.0

DEVELOPER_GUIDE.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Default output format [None]: json
1616
```
1717

1818
- [Node](https://nodejs.org/en) >= v20.9.0
19-
- [AWS CDK](https://github.com/aws/aws-cdk/releases/tag/v2.141.0) >= 2.141.0
19+
- [AWS CDK](https://github.com/aws/aws-cdk/releases/tag/v2.154.1) >= 2.154.1
2020
- [Python](https://www.python.org/downloads/) >=3.9
2121
- [Projen](https://github.com/projen/projen) >= 0.78.8
2222
- [Yarn](https://classic.yarnpkg.com/lang/en/docs/cli/install/) >= 1.22.19

apidocs/interfaces/DockerLambdaCustomProps.md

+19
Original file line numberDiff line numberDiff line change
@@ -565,6 +565,25 @@ stable
565565

566566
***
567567

568+
### recursiveLoop?
569+
570+
> `readonly` `optional` **recursiveLoop**: `RecursiveLoop`
571+
572+
Sets the Recursive Loop Protection for Lambda Function.
573+
It lets Lambda detect and terminate unintended recusrive loops.
574+
575+
#### Default
576+
577+
```ts
578+
RecursiveLoop.Terminate
579+
```
580+
581+
#### Stability
582+
583+
stable
584+
585+
***
586+
568587
### reservedConcurrentExecutions?
569588

570589
> `readonly` `optional` **reservedConcurrentExecutions**: `number`

apidocs/namespaces/bedrock/README.md

+2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
- [CanadaSpecific](enumerations/CanadaSpecific.md)
1414
- [ChunkingStrategy](enumerations/ChunkingStrategy.md)
15+
- [ContextualGroundingFilterConfigType](enumerations/ContextualGroundingFilterConfigType.md)
1516
- [FiltersConfigStrength](enumerations/FiltersConfigStrength.md)
1617
- [FiltersConfigType](enumerations/FiltersConfigType.md)
1718
- [Finance](enumerations/Finance.md)
@@ -52,6 +53,7 @@
5253
- [ApiSchemaConfig](interfaces/ApiSchemaConfig.md)
5354
- [BedrockFoundationModelProps](interfaces/BedrockFoundationModelProps.md)
5455
- [ContentPolicyConfigProps](interfaces/ContentPolicyConfigProps.md)
56+
- [ContextualGroundingPolicyConfigProps](interfaces/ContextualGroundingPolicyConfigProps.md)
5557
- [GuardrailConfiguration](interfaces/GuardrailConfiguration.md)
5658
- [GuardrailProps](interfaces/GuardrailProps.md)
5759
- [InferenceConfiguration](interfaces/InferenceConfiguration.md)

apidocs/namespaces/bedrock/classes/Guardrail.md

+14
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,20 @@ The tree node.
106106

107107
## Methods
108108

109+
### addContextualGroundingPolicyConfig()
110+
111+
> **addContextualGroundingPolicyConfig**(`props`): `void`
112+
113+
#### Parameters
114+
115+
**props**: [`ContextualGroundingPolicyConfigProps`](../interfaces/ContextualGroundingPolicyConfigProps.md)[]
116+
117+
#### Returns
118+
119+
`void`
120+
121+
***
122+
109123
### addSensitiveInformationPolicyConfig()
110124

111125
> **addSensitiveInformationPolicyConfig**(`props`, `guardrailRegexesConfig`): `void`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
[**@cdklabs/generative-ai-cdk-constructs**](../../../README.md)**Docs**
2+
3+
***
4+
5+
[@cdklabs/generative-ai-cdk-constructs](../../../README.md) / [bedrock](../README.md) / ContextualGroundingFilterConfigType
6+
7+
# Enumeration: ContextualGroundingFilterConfigType
8+
9+
## Enumeration Members
10+
11+
### GROUNDING
12+
13+
> **GROUNDING**: `"GROUNDING"`
14+
15+
Grounding score represents the confidence that the model response is factually correct and grounded in the source.
16+
If the model response has a lower score than the defined threshold, the response will be blocked and the configured
17+
blocked message will be returned to the user. A higher threshold level blocks more responses.
18+
19+
***
20+
21+
### RELEVANCE
22+
23+
> **RELEVANCE**: `"RELEVANCE"`
24+
25+
Relevance score represents the confidence that the model response is relevant to the user's query.
26+
If the model response has a lower score than the defined threshold, the response will be blocked and
27+
the configured blocked message will be returned to the user. A higher threshold level blocks more responses
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
[**@cdklabs/generative-ai-cdk-constructs**](../../../README.md)**Docs**
2+
3+
***
4+
5+
[@cdklabs/generative-ai-cdk-constructs](../../../README.md) / [bedrock](../README.md) / ContextualGroundingPolicyConfigProps
6+
7+
# Interface: ContextualGroundingPolicyConfigProps
8+
9+
## Properties
10+
11+
### filtersConfigType
12+
13+
> `readonly` **filtersConfigType**: [`ContextualGroundingFilterConfigType`](../enumerations/ContextualGroundingFilterConfigType.md)
14+
15+
The filter details for the guardrails contextual grounding filter.
16+
GROUNDING: Validate if the model responses are grounded and factually correct based on the information provided in the reference source,
17+
and block responses that are below the defined threshold of grounding.
18+
RELEVANCE: Validate if the model responses are relevant to the user's query and block responses
19+
that are below the defined threshold of relevance.
20+
21+
***
22+
23+
### threshold
24+
25+
> `readonly` **threshold**: `number`
26+
27+
The threshold details for the guardrails contextual grounding filter.
28+
0 blocks nothing, 0.99 blocks almost everything

apidocs/namespaces/bedrock/interfaces/GuardrailProps.md

+8
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,14 @@ The message to return when the guardrail blocks a model response.
2626

2727
***
2828

29+
### contextualGroundingfiltersConfig?
30+
31+
> `readonly` `optional` **contextualGroundingfiltersConfig**: [`ContextualGroundingPolicyConfigProps`](ContextualGroundingPolicyConfigProps.md)[]
32+
33+
Contextual grounding policy config for a guardrail.
34+
35+
***
36+
2937
### description?
3038

3139
> `readonly` `optional` **description**: `string`

package.json

+2-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/cdk-lib/bedrock/README.md

+28
Original file line numberDiff line numberDiff line change
@@ -597,6 +597,19 @@ const guardrails = new bedrock.Guardrail(this,'bedrockGuardrails',{
597597
action: "BLOCK",
598598
});
599599

600+
// Optional - Add contextual grounding
601+
602+
guardrails.addContextualGroundingPolicyConfig([
603+
{
604+
threshold: 0.5,
605+
filtersConfigType: bedrock.ContextualGroundingFilterConfigType.GROUNDING,
606+
},
607+
{
608+
threshold: 0.9,
609+
filtersConfigType: bedrock.ContextualGroundingFilterConfigType.RELEVANCE,
610+
},
611+
]);
612+
600613
// Optional - Add Denied topics . You can use default Topic or create your custom Topic with createTopic function. The default Topics can also be overwritten.
601614

602615
const topic = new Topic(this,'topic');
@@ -641,6 +654,21 @@ Python
641654
action= "BLOCK"
642655
)
643656

657+
# Optional - Add contextual grounding
658+
659+
guardrails.add_contextual_grounding_policy_config(
660+
props= [
661+
bedrock.ContextualGroundingPolicyConfigProps(
662+
threshold= 0.5,
663+
filters_config_type= bedrock.ContextualGroundingFilterConfigType.GROUNDING
664+
),
665+
bedrock.ContextualGroundingPolicyConfigProps(
666+
threshold= 0.5,
667+
filters_config_type= bedrock.ContextualGroundingFilterConfigType.RELEVANCE
668+
),
669+
],
670+
)
671+
644672
#Optional - Add Denied topics . You can use default Topic or create your custom Topic with createTopic function. The default Topics can also be overwritten.
645673

646674
topic = bedrock.Topic(self,'topic')

src/cdk-lib/bedrock/content-policy.ts

+25
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,37 @@ export enum FiltersConfigStrength {
3131
HIGH = 'HIGH',
3232
}
3333

34+
export enum ContextualGroundingFilterConfigType {
35+
/**Grounding score represents the confidence that the model response is factually correct and grounded in the source.
36+
* If the model response has a lower score than the defined threshold, the response will be blocked and the configured
37+
* blocked message will be returned to the user. A higher threshold level blocks more responses. */
38+
GROUNDING = 'GROUNDING',
39+
/**Relevance score represents the confidence that the model response is relevant to the user's query.
40+
* If the model response has a lower score than the defined threshold, the response will be blocked and
41+
* the configured blocked message will be returned to the user. A higher threshold level blocks more responses */
42+
RELEVANCE = 'RELEVANCE'
43+
}
44+
3445
export interface ContentPolicyConfigProps{
3546
readonly filtersConfigType: FiltersConfigType;
3647
readonly inputStrength?: FiltersConfigStrength;
3748
readonly outputStrength?: FiltersConfigStrength;
3849
}
3950

51+
export interface ContextualGroundingPolicyConfigProps {
52+
/**The filter details for the guardrails contextual grounding filter.
53+
* GROUNDING: Validate if the model responses are grounded and factually correct based on the information provided in the reference source,
54+
* and block responses that are below the defined threshold of grounding.
55+
* RELEVANCE: Validate if the model responses are relevant to the user's query and block responses
56+
* that are below the defined threshold of relevance.
57+
*/
58+
readonly filtersConfigType: ContextualGroundingFilterConfigType;
59+
/** The threshold details for the guardrails contextual grounding filter.
60+
* 0 blocks nothing, 0.99 blocks almost everything
61+
*/
62+
readonly threshold: number;
63+
}
64+
4065
export class ContentPolicyConfig extends Construct {
4166
readonly contentPolicyConfigList: bedrock.CfnGuardrail.ContentFilterConfigProperty[];
4267

src/cdk-lib/bedrock/guardrails.ts

+30-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import { CfnTag, aws_bedrock as bedrock } from 'aws-cdk-lib';
1717
import * as kms from 'aws-cdk-lib/aws-kms';
1818
import { Construct } from 'constructs';
1919

20-
import { ContentPolicyConfig, ContentPolicyConfigProps } from './content-policy';
20+
import { ContentPolicyConfig, ContentPolicyConfigProps, ContextualGroundingPolicyConfigProps } from './content-policy';
2121
import { GuardrailVersion } from './guardrail-version';
2222
import { SensitiveInformationPolicyConfig, SensitiveInformationPolicyConfigProps } from './pii-list';
2323
import { Topic } from './topic-list';
@@ -46,6 +46,11 @@ export interface GuardrailProps {
4646
*/
4747
readonly filtersConfig?: ContentPolicyConfigProps[];
4848

49+
/**
50+
* Contextual grounding policy config for a guardrail.
51+
*/
52+
readonly contextualGroundingfiltersConfig?: ContextualGroundingPolicyConfigProps[];
53+
4954
/**
5055
* PII fields which needs to be masked.
5156
*/
@@ -132,6 +137,16 @@ export class Guardrail extends Construct {
132137
},
133138
});
134139

140+
if (props.contextualGroundingfiltersConfig) {
141+
this.guardrailInstance.contextualGroundingPolicyConfig={
142+
filtersConfig:
143+
props.contextualGroundingfiltersConfig.map((prop) => ({
144+
type: prop.filtersConfigType,
145+
threshold: prop.threshold,
146+
})),
147+
};
148+
}
149+
135150
this.guardrailVersion = this.guardrailInstance.attrVersion;
136151
this.guardrailId = this.guardrailInstance.attrGuardrailId;
137152

@@ -153,6 +168,20 @@ export class Guardrail extends Construct {
153168
}
154169
}
155170

171+
public addContextualGroundingPolicyConfig( props: ContextualGroundingPolicyConfigProps[]) {
172+
if (props) {
173+
this.guardrailInstance.contextualGroundingPolicyConfig={
174+
filtersConfig:
175+
props.map((prop) => ({
176+
type: prop.filtersConfigType,
177+
threshold: prop.threshold,
178+
})),
179+
};
180+
} else {
181+
throw new Error('No ContextualGroundingPolicyConfig is set in GuardrailProps.');
182+
}
183+
}
184+
156185

157186
public async uploadWordPolicyFromFile(filePath: string) {
158187
try {

src/common/props/DockerLambdaCustomProps.ts

+7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

test/cdk-lib/bedrock/guardrails.test.ts

+24-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import { expect as cdkExpect, haveResource } from '@aws-cdk/assert';
1515
import * as cdk from 'aws-cdk-lib';
1616
import { AwsSolutionsChecks } from 'cdk-nag';
17-
import { FiltersConfigStrength, FiltersConfigType } from '../../../src/cdk-lib/bedrock/content-policy';
17+
import { FiltersConfigStrength, FiltersConfigType, ContextualGroundingFilterConfigType } from '../../../src/cdk-lib/bedrock/content-policy';
1818
import { Guardrail, GuardrailProps } from '../../../src/cdk-lib/bedrock/guardrails';
1919
import { General, PiiEntitiesConfigAction } from '../../../src/cdk-lib/bedrock/pii-list';
2020
import { Topic } from '../../../src/cdk-lib/bedrock/topic-list';
@@ -73,6 +73,17 @@ describe('Guardrail', () => {
7373
action: 'BLOCK',
7474
});
7575

76+
guardrail.addContextualGroundingPolicyConfig([
77+
{
78+
threshold: 0.5,
79+
filtersConfigType: ContextualGroundingFilterConfigType.GROUNDING,
80+
},
81+
{
82+
threshold: 0.9,
83+
filtersConfigType: ContextualGroundingFilterConfigType.RELEVANCE,
84+
},
85+
]);
86+
7687
const topic = new Topic(stack, 'my-topic');
7788
topic.financialAdviceTopic();
7889

@@ -117,6 +128,18 @@ describe('Guardrail', () => {
117128
},
118129
],
119130
},
131+
ContextualGroundingPolicyConfig: {
132+
FiltersConfig: [
133+
{
134+
Threshold: 0.5,
135+
Type: 'GROUNDING',
136+
},
137+
{
138+
Threshold: 0.9,
139+
Type: 'RELEVANCE',
140+
},
141+
],
142+
},
120143
TopicPolicyConfig: {
121144
TopicsConfig: [
122145
{

0 commit comments

Comments
 (0)