diff --git a/appconfig-ai-model-lambda-bedrock/typescript/cdk/.gitignore b/appconfig-ai-model-lambda-bedrock/typescript/cdk/.gitignore
new file mode 100644
index 000000000..81344fc85
--- /dev/null
+++ b/appconfig-ai-model-lambda-bedrock/typescript/cdk/.gitignore
@@ -0,0 +1,5 @@
+node_modules/
+cdk.out/
+build/
+cdk.context.json
+package-lock.json
diff --git a/appconfig-ai-model-lambda-bedrock/typescript/cdk/README.md b/appconfig-ai-model-lambda-bedrock/typescript/cdk/README.md
new file mode 100644
index 000000000..98675a347
--- /dev/null
+++ b/appconfig-ai-model-lambda-bedrock/typescript/cdk/README.md
@@ -0,0 +1,125 @@
+# Roll out Amazon Bedrock model settings with AWS AppConfig and AWS Lambda
+
+This pattern keeps the Amazon Bedrock model ID, inference parameters and system prompt in an AWS AppConfig AI model invocation configuration profile (type `AWS.AppConfig.AIModelInvocation`). An AWS Lambda function reads the deployed configuration through the AWS AppConfig Agent Lambda extension and maps it onto an Amazon Bedrock Converse request. A model or prompt change is a configuration deployment with a gradual strategy, and an Amazon CloudWatch alarm on the function's errors makes AWS AppConfig roll a bad change back automatically.
+
+Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/appconfig-ai-model-lambda-bedrock-typescript-cdk
+
+Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. The stack has no resources that bill per hour: the CloudWatch alarm is billed per alarm per month while it exists, Amazon Bedrock bills per token, AWS AppConfig bills per configuration request received, AWS Lambda bills per request and duration, and Amazon CloudWatch Logs bills per GB ingested and stored. You are responsible for any AWS costs incurred. No warranty is implied in this example.
+
+## Requirements
+
+* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
+* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
+* [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) installed
+* [Node.js](https://nodejs.org/en/download/) installed
+* [AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html), with your account and Region bootstrapped (`npx cdk bootstrap`). The commands below use `npx cdk`, which runs the CDK CLI version this project installs, so no global install is needed.
+* Access to Amazon Nova 2 Lite and Amazon Nova Micro in [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) in your Region
+
+## Supported Regions
+
+The stack supports us-east-1, us-east-2, us-west-2, eu-central-1, eu-north-1, eu-west-1 and eu-west-3, and `cdk synth` stops with an error in any other Region. These are source Regions of the `us.` and `eu.` geo inference profiles on the [Nova 2 Lite](https://docs.aws.amazon.com/bedrock/latest/userguide/model-card-amazon-nova-2-lite.html) and [Nova Micro](https://docs.aws.amazon.com/bedrock/latest/userguide/model-card-amazon-nova-micro.html) model cards, and the stack maps each one to the arm64 layer ARN of the AWS AppConfig Agent Lambda extension from the [extension versions page](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-integration-lambda-extensions-versions.html). Both tables are in `lib/appconfig-ai-model-lambda-bedrock-stack.ts`.
+
+## How it works
+
+1. Each hosted version of the profile is a JSON document with `schemaVersion`, `model`, `inferenceParameters` and `messages`. AWS AppConfig checks it against the [AI model invocation schema](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-ai-model-configuration.html) when the version is created: out-of-range inference parameters, a missing `schemaVersion` and a message without `role` are rejected. In our tests a document without `model` was accepted; calls with such a version fail as function errors, so the alarm rolls it back like any other bad version. The stack creates version 1 (Nova 2 Lite, temperature 0.2, a two-sentence system prompt) and deploys it at once.
+2. The function calls the agent on `localhost:2772`, sends the `system` messages as `system`, the other messages as earlier turns, `inferenceParameters` as `inferenceConfig` and `customParameters` (when present) as `additionalModelRequestFields`, then appends the caller's prompt. It returns the model, the inference parameters and the answer.
+3. Later versions are deployed with the rollout strategy: 50 percent of the targets, then 100 percent, over 4 minutes, then a 5 minute bake time. The percentage applies to the clients that poll AWS AppConfig (each execution environment runs its own agent), not to individual requests.
+4. The environment monitors the alarm. If it goes to `ALARM` (or `INSUFFICIENT_DATA`) during the deployment or the bake time, AWS AppConfig rolls back to the previous version and the deployment ends in `ROLLED_BACK`.
+5. The function role may invoke only the two Nova models (inference profile and destination Region model ARNs), so the AWS Identity and Access Management (IAM) policy is the list of models a configuration can switch to. Any other model fails with `AccessDeniedException`, which is a function error.
+
+## Important Notes
+
+* This pattern uses the AI model invocation profile only. To version prompts separately from the model settings, AWS AppConfig also has [AI prompt configuration profiles](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-ai-prompt-configuration.html).
+* The profile is an L1 `CfnConfigurationProfile` because the aws-cdk-lib `ConfigurationType` enum has no AI model invocation value. Hosted versions here use the content type `application/json; type=AWS.AppConfig.AIModelInvocation`: AWS CloudFormation rejects plain `application/json` for this profile type, although the user guide CLI example shows plain `application/json`.
+* An invalid prompt is answered with an `error` field instead of an exception, so caller mistakes cannot roll back a configuration. A failed Converse call is rethrown.
+* The environment and profile set `DeletionProtectionCheck` to `BYPASS` so `cdk destroy` works right after a test. Remove it for long-lived environments.
+
+## Deployment Instructions
+
+1. Clone the repository:
+ ```bash
+ git clone https://github.com/aws-samples/serverless-patterns
+ cd serverless-patterns/appconfig-ai-model-lambda-bedrock/typescript/cdk
+ ```
+
+2. Install dependencies and type-check:
+ ```bash
+ npm install
+ npm run build
+ ```
+
+3. If the account and Region have never been used with the AWS CDK, bootstrap them once:
+ ```bash
+ npx cdk bootstrap
+ ```
+
+4. Deploy the stack:
+ ```bash
+ npx cdk deploy
+ ```
+
+5. Note the stack outputs: `FunctionName`, `LogGroupName`, `ApplicationId`, `EnvironmentId`, `ConfigurationProfileId`, `RolloutStrategyId`, `AlarmName` and `GeoPrefix`.
+
+## Testing
+
+Use the AWS CLI configured for the Region you deployed to. Start every new shell with these variables and helpers:
+
+```bash
+STACK=AppconfigAiModelLambdaBedrockStack
+out() { aws cloudformation describe-stacks --stack-name "$STACK" --query "Stacks[0].Outputs[?OutputKey=='$1'].OutputValue" --output text; }
+FN=$(out FunctionName); APP=$(out ApplicationId); ENV=$(out EnvironmentId); CFG=$(out ConfigurationProfileId)
+ROLLOUT=$(out RolloutStrategyId); ALARM=$(out AlarmName); GEO=$(out GeoPrefix)
+ask() { aws lambda invoke --function-name "$FN" --cli-binary-format raw-in-base64-out --payload "{\"prompt\":\"$1\"}" /tmp/answer.json >/dev/null; cat /tmp/answer.json; echo; }
+new_version() { aws appconfig create-hosted-configuration-version --application-id "$APP" --configuration-profile-id "$CFG" --content-type 'application/json; type=AWS.AppConfig.AIModelInvocation' --content "fileb://$1" --query VersionNumber --output text /tmp/version-out.json; }
+wait_alarm_ok() { until [ "$(aws cloudwatch describe-alarms --alarm-names "$ALARM" --query 'MetricAlarms[0].StateValue' --output text)" = OK ]; do sleep 15; done; }
+deploy() { wait_alarm_ok; aws appconfig start-deployment --application-id "$APP" --environment-id "$ENV" --configuration-profile-id "$CFG" --deployment-strategy-id "$ROLLOUT" --configuration-version "$1" --query DeploymentNumber --output text; }
+watch_deployment() { [ -n "$1" ] || { echo "no deployment number"; return 1; }; while true; do S=$(aws appconfig get-deployment --application-id "$APP" --environment-id "$ENV" --deployment-number "$1" --query '[State,PercentageComplete]' --output text); echo "$(date -u +%H:%M:%S) $S"; ask "Name one AWS Region in Europe."; case "$S" in COMPLETE*|ROLLED_BACK*|REVERTED*) break ;; esac; sleep 20; done; }
+```
+
+1. Ask a question. Expected: a JSON object with `model` set to `us.amazon.nova-2-lite-v1:0` (or `eu.` in Europe), `temperature` 0.2 and an answer of at most two sentences.
+ ```bash
+ ask "What does AWS AppConfig do?"
+ ```
+
+2. Create version 2, which switches to Nova Micro with a one-sentence prompt, and roll it out. `deploy` first waits until the alarm is `OK`: a new alarm stays `INSUFFICIENT_DATA` for a few minutes after the stack is created, and AWS AppConfig rolls back a deployment that starts in that state (our first test did, within 24 seconds). The helper then prints the deployment state and an answer every 20 seconds until the deployment ends (about 9 minutes). Expected: the `model` in the answers changes to the Nova Micro profile during the rollout, and the last state is `COMPLETE 100.0`.
+ ```bash
+ printf '{"schemaVersion":"1","model":"%s.amazon.nova-micro-v1:0","inferenceParameters":{"temperature":0.5,"maxTokens":200},"messages":[{"role":"system","content":"Answer in one sentence."}]}' "$GEO" > /tmp/model-v2.json
+ V2=$(new_version /tmp/model-v2.json); echo "version $V2"
+ watch_deployment "$(deploy "$V2")"
+ ```
+
+3. Schema validation. A document with `topP` above 1 is rejected when it is created. Expected: `BadRequestException ... Configuration content did not adhere to json schema: [message: "numeric instance is greater than the required maximum (maximum: 1, found: 2)" - parent node: /inferenceParameters/topP]`, and no version is created.
+ ```bash
+ echo '{"schemaVersion":"1","model":"any","inferenceParameters":{"topP":2}}' > /tmp/model-invalid.json
+ new_version /tmp/model-invalid.json
+ ```
+
+4. Automatic rollback. Version 3 passes the schema but names a model the function role may not invoke. `deploy` waits until the alarm is `OK` again, then rolls the version out. Expected: answers turn into `"errorType":"AccessDeniedException"` once the execution environment receives version 3, the alarm goes to `ALARM` and the state reaches `ROLLED_BACK`. The last answer of the loop can still be an error, because the agent polls every 15 seconds; the `ask` about 20 seconds later is answered by the Nova Micro profile (version 2) again.
+ ```bash
+ printf '{"schemaVersion":"1","model":"%s.amazon.nova-pro-v1:0","messages":[{"role":"system","content":"Answer in one sentence."}]}' "$GEO" > /tmp/model-v3.json
+ V3=$(new_version /tmp/model-v3.json); DEP=$(deploy "$V3"); watch_deployment "$DEP"
+ sleep 20; ask "Name one AWS Region in Europe."
+ aws appconfig get-deployment --application-id "$APP" --environment-id "$ENV" --deployment-number "$DEP" --query 'EventLog[].[EventType,TriggeredBy]' --output text
+ ```
+ Expected in the event log (newest first): `ROLLBACK_COMPLETED CLOUDWATCH_ALARM`, then `BAKE_TIME_STARTED` if the rollback came during the bake, `PERCENTAGE_UPDATED APPCONFIG` and `DEPLOYMENT_STARTED USER`. The test calls reach one execution environment, which receives version 3 either at 50 percent or at 100 percent: in our runs the first error came at 50 percent (twice in us-west-2) or during the bake (eu-central-1), and the rollback 1.5 to 2 minutes after the first error. The alarm returns to `OK` a few minutes after the errors stop; the next `deploy` waits for that. The function logs each failure: `aws logs tail "$(out LogGroupName)" --since 30m`.
+
+## Cleanup
+
+1. Make sure no deployment is still running (the last `watch_deployment` ended). In a new shell, paste the variable block from Testing first. Then delete the versions that the Testing section created:
+ ```bash
+ for v in $(aws appconfig list-hosted-configuration-versions --application-id "$APP" --configuration-profile-id "$CFG" --query 'Items[?VersionNumber>`1`].VersionNumber' --output text); do
+ aws appconfig delete-hosted-configuration-version --application-id "$APP" --configuration-profile-id "$CFG" --version-number "$v"
+ done
+ ```
+
+2. Delete the stack. This deletes the AWS AppConfig application with its environment, profile, version 1 and deployment strategies, the function, its log group with the logs, the alarm and the IAM roles:
+ ```bash
+ npx cdk destroy
+ ```
+
+3. Delete the local test files: `rm -f /tmp/answer.json /tmp/version-out.json /tmp/model-*.json`
+
+----
+Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved.
+
+SPDX-License-Identifier: MIT-0
diff --git a/appconfig-ai-model-lambda-bedrock/typescript/cdk/bin/app.ts b/appconfig-ai-model-lambda-bedrock/typescript/cdk/bin/app.ts
new file mode 100644
index 000000000..d93e95822
--- /dev/null
+++ b/appconfig-ai-model-lambda-bedrock/typescript/cdk/bin/app.ts
@@ -0,0 +1,8 @@
+#!/usr/bin/env node
+import * as cdk from 'aws-cdk-lib';
+import { AppconfigAiModelLambdaBedrockStack } from '../lib/appconfig-ai-model-lambda-bedrock-stack';
+
+const app = new cdk.App();
+new AppconfigAiModelLambdaBedrockStack(app, 'AppconfigAiModelLambdaBedrockStack', {
+ env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },
+});
diff --git a/appconfig-ai-model-lambda-bedrock/typescript/cdk/cdk.json b/appconfig-ai-model-lambda-bedrock/typescript/cdk/cdk.json
new file mode 100644
index 000000000..a6700a2ff
--- /dev/null
+++ b/appconfig-ai-model-lambda-bedrock/typescript/cdk/cdk.json
@@ -0,0 +1,3 @@
+{
+ "app": "npx ts-node --prefer-ts-exts bin/app.ts"
+}
diff --git a/appconfig-ai-model-lambda-bedrock/typescript/cdk/example-pattern.json b/appconfig-ai-model-lambda-bedrock/typescript/cdk/example-pattern.json
new file mode 100644
index 000000000..29052c2ce
--- /dev/null
+++ b/appconfig-ai-model-lambda-bedrock/typescript/cdk/example-pattern.json
@@ -0,0 +1,67 @@
+{
+ "title": "Roll out Amazon Bedrock model settings with AWS AppConfig and AWS Lambda",
+ "description": "AWS AppConfig rolls out Amazon Bedrock model and prompt settings to an AWS Lambda function gradually and rolls back on an Amazon CloudWatch alarm.",
+ "language": "TypeScript",
+ "level": "300",
+ "framework": "AWS CDK",
+ "introBox": {
+ "headline": "How it works",
+ "text": [
+ "An AWS AppConfig AI model invocation configuration profile holds the Amazon Bedrock model ID, inference parameters and system prompt. AWS AppConfig validates every version against the AI model invocation schema.",
+ "An AWS Lambda function reads the deployed configuration through the AWS AppConfig Agent Lambda extension and maps it onto an Amazon Bedrock Converse request.",
+ "A new version is rolled out with a gradual deployment strategy. An Amazon CloudWatch alarm on the function's errors is an environment monitor, so AWS AppConfig rolls a bad version back automatically.",
+ "The function role may invoke only two Amazon Nova models, so calls with a version that names another model fail, and those errors during the rollout trigger the rollback."
+ ]
+ },
+ "gitHub": {
+ "template": {
+ "templateFile": "lib/appconfig-ai-model-lambda-bedrock-stack.ts"
+ }
+ },
+ "resources": {
+ "bullets": [
+ {
+ "text": "Creating an AI model invocation configuration profile in AWS AppConfig",
+ "link": "https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-ai-model-configuration.html"
+ },
+ {
+ "text": "Monitoring deployments for automatic rollback",
+ "link": "https://docs.aws.amazon.com/appconfig/latest/userguide/monitoring-deployments.html"
+ },
+ {
+ "text": "Using AWS AppConfig Agent with AWS Lambda",
+ "link": "https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-integration-lambda-extensions.html"
+ },
+ {
+ "text": "Amazon Bedrock Converse API",
+ "link": "https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html"
+ }
+ ]
+ },
+ "deploy": {
+ "text": [
+ "npm install",
+ "npx cdk bootstrap (once per account and Region)",
+ "npx cdk deploy"
+ ]
+ },
+ "testing": {
+ "text": [
+ "See the GitHub repo for detailed testing instructions."
+ ]
+ },
+ "cleanup": {
+ "text": [
+ "Delete the hosted configuration versions created during testing (see the README).",
+ "npx cdk destroy"
+ ]
+ },
+ "authors": [
+ {
+ "name": "Nithin Chandran R",
+ "image": "https://github.com/NithinChandranR-AWS.png",
+ "bio": "Technical Account Manager at AWS",
+ "linkedin": "nithin-chandran-r"
+ }
+ ]
+}
diff --git a/appconfig-ai-model-lambda-bedrock/typescript/cdk/lambda/index.mjs b/appconfig-ai-model-lambda-bedrock/typescript/cdk/lambda/index.mjs
new file mode 100644
index 000000000..ef8f6df31
--- /dev/null
+++ b/appconfig-ai-model-lambda-bedrock/typescript/cdk/lambda/index.mjs
@@ -0,0 +1,51 @@
+// Reads the deployed AI model invocation configuration from the AWS AppConfig Agent Lambda extension
+// and maps it onto an Amazon Bedrock Converse request.
+import { BedrockRuntimeClient, ConverseCommand } from '@aws-sdk/client-bedrock-runtime';
+
+const CONFIG_PATH = process.env.CONFIG_PATH;
+if (!CONFIG_PATH) throw new Error('CONFIG_PATH is not set');
+const AGENT_URL = `http://localhost:${process.env.AWS_APPCONFIG_EXTENSION_HTTP_PORT ?? '2772'}${CONFIG_PATH}`;
+const MAX_PROMPT_CHARS = 2000;
+
+const bedrock = new BedrockRuntimeClient({ maxAttempts: 2 });
+
+async function loadConfig() {
+ try {
+ const res = await fetch(AGENT_URL, { signal: AbortSignal.timeout(3000) });
+ if (!res.ok) throw new Error(`AppConfig Agent returned HTTP ${res.status}: ${await res.text()}`);
+ return await res.json();
+ } catch (err) {
+ console.error(JSON.stringify({ message: 'Could not read the model configuration', error: err.name, detail: err.message }));
+ throw err;
+ }
+}
+
+export const handler = async (event) => {
+ // Bad input is the caller's problem, not the configuration's: return it without throwing, so it does not
+ // count as a function error and cannot trigger a configuration rollback.
+ const prompt = typeof event?.prompt === 'string' ? event.prompt.trim() : '';
+ if (!prompt || prompt.length > MAX_PROMPT_CHARS) {
+ return { error: `prompt must be a non-empty string of at most ${MAX_PROMPT_CHARS} characters` };
+ }
+
+ const cfg = await loadConfig();
+ const configured = cfg.messages ?? [];
+ const system = configured.filter((m) => m.role === 'system').map((m) => ({ text: m.content }));
+ const turns = configured.filter((m) => m.role !== 'system').map((m) => ({ role: m.role, content: [{ text: m.content }] }));
+
+ try {
+ const out = await bedrock.send(new ConverseCommand({
+ modelId: cfg.model,
+ ...(system.length ? { system } : {}),
+ messages: [...turns, { role: 'user', content: [{ text: prompt }] }],
+ ...(cfg.inferenceParameters ? { inferenceConfig: cfg.inferenceParameters } : {}),
+ ...(cfg.customParameters ? { additionalModelRequestFields: cfg.customParameters } : {}),
+ }));
+ const answer = (out.output?.message?.content ?? []).map((c) => c.text ?? '').join('');
+ return { model: cfg.model, inferenceParameters: cfg.inferenceParameters ?? {}, answer, usage: out.usage };
+ } catch (err) {
+ // Rethrow: the function error is the signal the CloudWatch alarm and the AppConfig rollback rely on.
+ console.error(JSON.stringify({ message: 'Converse failed', model: cfg.model, error: err.name, detail: err.message }));
+ throw err;
+ }
+};
diff --git a/appconfig-ai-model-lambda-bedrock/typescript/cdk/lib/appconfig-ai-model-lambda-bedrock-stack.ts b/appconfig-ai-model-lambda-bedrock/typescript/cdk/lib/appconfig-ai-model-lambda-bedrock-stack.ts
new file mode 100644
index 000000000..874b4589c
--- /dev/null
+++ b/appconfig-ai-model-lambda-bedrock/typescript/cdk/lib/appconfig-ai-model-lambda-bedrock-stack.ts
@@ -0,0 +1,171 @@
+import * as path from 'path';
+import * as cdk from 'aws-cdk-lib';
+import { Construct } from 'constructs';
+import * as appconfig from 'aws-cdk-lib/aws-appconfig';
+import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';
+import * as iam from 'aws-cdk-lib/aws-iam';
+import * as lambda from 'aws-cdk-lib/aws-lambda';
+import * as logs from 'aws-cdk-lib/aws-logs';
+
+// Amazon Bedrock models the function may call. AWS AppConfig stores only the model id, so this IAM list is the
+// allowlist: a configuration that names any other model fails with AccessDeniedException and fires the alarm.
+const ALLOWED_MODELS = ['amazon.nova-2-lite-v1:0', 'amazon.nova-micro-v1:0'];
+const INITIAL_MODEL = ALLOWED_MODELS[0];
+
+// Destination Regions of the us. and eu. geo inference profiles of both models (Nova 2 Lite and Nova Micro model cards).
+const GEO_DESTINATIONS: Record = {
+ us: ['us-east-1', 'us-east-2', 'us-west-2'],
+ eu: ['eu-central-1', 'eu-north-1', 'eu-south-1', 'eu-south-2', 'eu-west-1', 'eu-west-3'],
+};
+
+// Supported Regions: geo prefix plus the AWS-published arm64 layer of the AWS AppConfig Agent Lambda extension
+// (owner account and layer version for extension 2.0.27899, from the "available versions" page of the AppConfig guide).
+const REGIONS: Record = {
+ 'us-east-1': { geo: 'us', layer: '027255383542:289' },
+ 'us-east-2': { geo: 'us', layer: '728743619870:262' },
+ 'us-west-2': { geo: 'us', layer: '359756378197:307' },
+ 'eu-central-1': { geo: 'eu', layer: '066940009817:264' },
+ 'eu-north-1': { geo: 'eu', layer: '646970417810:253' },
+ 'eu-west-1': { geo: 'eu', layer: '434848589818:269' },
+ 'eu-west-3': { geo: 'eu', layer: '493207061005:225' },
+};
+
+export class AppconfigAiModelLambdaBedrockStack extends cdk.Stack {
+ constructor(scope: Construct, id: string, props?: cdk.StackProps) {
+ super(scope, id, props);
+
+ if (cdk.Token.isUnresolved(this.region) || !REGIONS[this.region]) {
+ throw new Error(`Deploy to one of: ${Object.keys(REGIONS).join(', ')} (set AWS_REGION or a default Region). See the README.`);
+ }
+ const { geo, layer } = REGIONS[this.region];
+ const [layerOwner, layerVersion] = layer.split(':');
+
+ // AWS AppConfig names are scoped to this stack, so two stacks can deploy side by side.
+ const application = new appconfig.Application(this, 'Application', { applicationName: this.stackName });
+ const environmentName = `${this.stackName}-live`;
+ const profileName = `${this.stackName}-model`;
+
+ // The function reads its configuration through the agent by name. Names (not ids) keep the function
+ // independent of the environment, which depends on the alarm, which depends on the function.
+ const logGroup = new logs.LogGroup(this, 'AssistantLogGroup', {
+ retention: logs.RetentionDays.TWO_WEEKS,
+ removalPolicy: cdk.RemovalPolicy.DESTROY,
+ });
+ const fn = new lambda.Function(this, 'AssistantFunction', {
+ runtime: lambda.Runtime.NODEJS_24_X,
+ architecture: lambda.Architecture.ARM_64,
+ handler: 'index.handler',
+ code: lambda.Code.fromAsset(path.join(__dirname, '..', 'lambda')),
+ timeout: cdk.Duration.seconds(30),
+ memorySize: 256,
+ logGroup,
+ loggingFormat: lambda.LoggingFormat.JSON,
+ layers: [lambda.LayerVersion.fromLayerVersionArn(this, 'AppConfigAgentLayer',
+ `arn:${this.partition}:lambda:${this.region}:${layerOwner}:layer:AWS-AppConfig-Extension-Arm64:${layerVersion}`)],
+ environment: {
+ CONFIG_PATH: `/applications/${this.stackName}/environments/${environmentName}/configurations/${profileName}`,
+ AWS_APPCONFIG_EXTENSION_POLL_INTERVAL_SECONDS: '15', // default 45; shorter so a test sees changes quickly
+ },
+ });
+
+ // Converse needs bedrock:InvokeModel on the geo inference profile and on the model in every destination Region.
+ fn.addToRolePolicy(new iam.PolicyStatement({
+ actions: ['bedrock:InvokeModel'],
+ resources: ALLOWED_MODELS.flatMap((model) => [
+ `arn:${this.partition}:bedrock:${this.region}:${this.account}:inference-profile/${geo}.${model}`,
+ ...GEO_DESTINATIONS[geo].map((r) => `arn:${this.partition}:bedrock:${r}::foundation-model/${model}`),
+ ]),
+ }));
+
+ // Any function error during a deployment or its bake time makes AWS AppConfig roll the configuration back.
+ const errorsAlarm = fn.metricErrors({ period: cdk.Duration.minutes(1), statistic: 'Sum' }).createAlarm(this, 'ErrorsAlarm', {
+ threshold: 1,
+ evaluationPeriods: 1,
+ comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
+ treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
+ alarmDescription: 'AWS AppConfig rolls back a model configuration deployment when this alarm fires',
+ });
+
+ // Role AWS AppConfig assumes to read the alarm, trusted only for calls from this account (confused deputy).
+ // DescribeAlarms needs Resource "*" (AWS AppConfig user guide, "Configure permissions for automatic rollback").
+ // An inline policy, so the role can read the alarm as soon as the environment that references it exists.
+ const monitorRole = new iam.Role(this, 'MonitorRole', {
+ assumedBy: new iam.ServicePrincipal('appconfig.amazonaws.com', {
+ conditions: { StringEquals: { 'aws:SourceAccount': this.account } },
+ }),
+ inlinePolicies: {
+ ReadAlarm: new iam.PolicyDocument({
+ statements: [new iam.PolicyStatement({ actions: ['cloudwatch:DescribeAlarms'], resources: ['*'] })],
+ }),
+ },
+ });
+ const environment = new appconfig.Environment(this, 'Environment', {
+ application,
+ environmentName,
+ monitors: [appconfig.Monitor.fromCloudWatchAlarm(errorsAlarm, monitorRole)],
+ deletionProtectionCheck: appconfig.DeletionProtectionCheck.BYPASS, // demo: cdk destroy works right after a test
+ });
+
+ // L1 resource: the L2 ConfigurationType enum in aws-cdk-lib has no value for AI model invocation profiles yet.
+ const profile = new appconfig.CfnConfigurationProfile(this, 'ModelProfile', {
+ applicationId: application.applicationId,
+ name: profileName,
+ locationUri: 'hosted',
+ type: 'AWS.AppConfig.AIModelInvocation',
+ deletionProtectionCheck: 'BYPASS',
+ });
+ const profileId = profile.attrConfigurationProfileId;
+
+ // Version 1. AWS AppConfig validates it against the AI model invocation schema. CloudFormation rejects plain
+ // application/json for this profile type and asks for the typed content type below.
+ const version1 = new appconfig.CfnHostedConfigurationVersion(this, 'ModelConfigV1', {
+ applicationId: application.applicationId,
+ configurationProfileId: profileId,
+ contentType: 'application/json; type=AWS.AppConfig.AIModelInvocation',
+ content: JSON.stringify({
+ schemaVersion: '1',
+ model: `${geo}.${INITIAL_MODEL}`,
+ inferenceParameters: { temperature: 0.2, maxTokens: 300 },
+ messages: [{ role: 'system', content: 'You are a concise assistant. Answer in at most two sentences.' }],
+ }),
+ });
+
+ // Stack creation deploys version 1 at once; later changes use the gradual strategy below.
+ const initialStrategy = new appconfig.DeploymentStrategy(this, 'InitialStrategy', {
+ rolloutStrategy: appconfig.RolloutStrategy.linear({
+ growthFactor: 100, deploymentDuration: cdk.Duration.minutes(0), finalBakeTime: cdk.Duration.minutes(0),
+ }),
+ });
+ // 50 percent of the agents, then 100 percent, over 4 minutes, then 5 minutes of bake time with the alarm watched.
+ const rolloutStrategy = new appconfig.DeploymentStrategy(this, 'RolloutStrategy', {
+ rolloutStrategy: appconfig.RolloutStrategy.linear({
+ growthFactor: 50, deploymentDuration: cdk.Duration.minutes(4), finalBakeTime: cdk.Duration.minutes(5),
+ }),
+ });
+ new appconfig.CfnDeployment(this, 'InitialDeployment', {
+ applicationId: application.applicationId,
+ environmentId: environment.environmentId,
+ configurationProfileId: profileId,
+ configurationVersion: version1.attrVersionNumber,
+ deploymentStrategyId: initialStrategy.deploymentStrategyId,
+ });
+
+ // A separate policy (not the role's default policy) keeps the function out of the environment's dependency chain.
+ new iam.Policy(this, 'ReadModelConfig', {
+ roles: [fn.role as iam.IRole],
+ statements: [new iam.PolicyStatement({
+ actions: ['appconfig:StartConfigurationSession', 'appconfig:GetLatestConfiguration'],
+ resources: [`${environment.environmentArn}/configuration/${profileId}`],
+ })],
+ });
+
+ new cdk.CfnOutput(this, 'FunctionName', { value: fn.functionName });
+ new cdk.CfnOutput(this, 'LogGroupName', { value: logGroup.logGroupName });
+ new cdk.CfnOutput(this, 'ApplicationId', { value: application.applicationId });
+ new cdk.CfnOutput(this, 'EnvironmentId', { value: environment.environmentId });
+ new cdk.CfnOutput(this, 'ConfigurationProfileId', { value: profileId });
+ new cdk.CfnOutput(this, 'RolloutStrategyId', { value: rolloutStrategy.deploymentStrategyId });
+ new cdk.CfnOutput(this, 'AlarmName', { value: errorsAlarm.alarmName });
+ new cdk.CfnOutput(this, 'GeoPrefix', { value: geo });
+ }
+}
diff --git a/appconfig-ai-model-lambda-bedrock/typescript/cdk/package.json b/appconfig-ai-model-lambda-bedrock/typescript/cdk/package.json
new file mode 100644
index 000000000..964dc92ff
--- /dev/null
+++ b/appconfig-ai-model-lambda-bedrock/typescript/cdk/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "appconfig-ai-model-lambda-bedrock-cdk",
+ "version": "1.0.0",
+ "private": true,
+ "scripts": {
+ "build": "tsc --noEmit",
+ "synth": "cdk synth"
+ },
+ "dependencies": {
+ "aws-cdk-lib": "^2.278.0",
+ "constructs": "^10.8.1"
+ },
+ "devDependencies": {
+ "@types/node": "^24.0.0",
+ "aws-cdk": "^2.1149.0",
+ "ts-node": "^10.9.2",
+ "typescript": "~5.9.3"
+ }
+}
diff --git a/appconfig-ai-model-lambda-bedrock/typescript/cdk/tsconfig.json b/appconfig-ai-model-lambda-bedrock/typescript/cdk/tsconfig.json
new file mode 100644
index 000000000..3be9624ee
--- /dev/null
+++ b/appconfig-ai-model-lambda-bedrock/typescript/cdk/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "commonjs",
+ "lib": ["es2022"],
+ "strict": true,
+ "noImplicitAny": true,
+ "noImplicitReturns": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "skipLibCheck": true,
+ "types": ["node"]
+ },
+ "include": ["bin/**/*.ts", "lib/**/*.ts"],
+ "exclude": ["node_modules", "cdk.out"]
+}