Header menu logo FsCDK

Amazon Bedrock: Generative AI with FsCDK

Amazon Bedrock is a fully managed service that makes foundation models (FMs) from leading AI companies available through a unified API. FsCDK provides type-safe builders for Bedrock Agents, Knowledge Bases, Data Sources, and Guardrails.

What is Amazon Bedrock?

Amazon Bedrock lets you build and scale generative AI applications using foundation models from Anthropic (Claude), Amazon (Titan), Meta (Llama), and others. Key components include:

Quick Start

#r "../src/bin/Release/net8.0/publish/Amazon.JSII.Runtime.dll"
#r "../src/bin/Release/net8.0/publish/Constructs.dll"
#r "../src/bin/Release/net8.0/publish/Amazon.CDK.Lib.dll"
#r "../src/bin/Release/net8.0/publish/System.Text.Json.dll"
#r "../src/bin/Release/net8.0/publish/FsCDK.dll"

open Amazon.CDK
open Amazon.CDK.AwsBedrock
open FsCDK

Use Cases

AI Agent with Custom Instructions

stack "AgentStack" {
    description "Bedrock Agent with full configuration"

    let supportAgent =
        bedrockAgent "CustomerSupportAgent" {
            foundationModel "anthropic.claude-3-sonnet-20240229-v1:0"

            instruction
                "You are a customer support agent. Help users with order tracking, returns, and product questions."

            description "Handles customer inquiries"
            agentResourceRoleArn "arn:aws:iam::123456789012:role/BedrockAgentRole"
            idleSessionTtlInSeconds 1800
            autoPrepare true
            tags [ "Team", "AI"; "Environment", "Production" ]
        }

    ()
}

Knowledge Base with RAG

stack "KnowledgeBaseStack" {
    description "Bedrock Knowledge Base for document retrieval"

    let kbConfig =
        CfnKnowledgeBase.KnowledgeBaseConfigurationProperty(
            Type = "VECTOR",
            VectorKnowledgeBaseConfiguration =
                CfnKnowledgeBase.VectorKnowledgeBaseConfigurationProperty(
                    EmbeddingModelArn = "arn:aws:bedrock:us-east-1::foundation-model/amazon.titan-embed-text-v2:0"
                )
        )

    let storageConfig =
        CfnKnowledgeBase.StorageConfigurationProperty(
            Type = "OPENSEARCH_SERVERLESS",
            OpensearchServerlessConfiguration =
                CfnKnowledgeBase.OpenSearchServerlessConfigurationProperty(
                    CollectionArn = "arn:aws:aoss:us-east-1:123456789012:collection/my-collection",
                    FieldMapping =
                        CfnKnowledgeBase.OpenSearchServerlessFieldMappingProperty(
                            MetadataField = "metadata",
                            TextField = "text",
                            VectorField = "vector"
                        ),
                    VectorIndexName = "my-index"
                )
        )

    let productKB =
        bedrockKnowledgeBase "ProductDocsKB" {
            description "Knowledge base for product documentation"
            roleArn "arn:aws:iam::123456789012:role/BedrockKBRole"
            knowledgeBaseConfiguration kbConfig
            storageConfiguration storageConfig
            tags [ "Team", "AI" ]
        }

    ()
}

Data Source from S3

stack "DataSourceStack" {
    description "Bedrock Data Source connected to S3"

    let s3Config =
        CfnDataSource.DataSourceConfigurationProperty(
            Type = "S3",
            S3Configuration = CfnDataSource.S3DataSourceConfigurationProperty(BucketArn = "arn:aws:s3:::my-docs-bucket")
        )

    let docsSource =
        bedrockDataSource "ProductDocsSource" {
            knowledgeBaseId "KBXXXXXXXX"
            description "S3 bucket containing product documentation"
            dataSourceConfiguration s3Config
            dataDeletionPolicy "RETAIN"
        }

    ()
}

Content Safety Guardrail

stack "GuardrailStack" {
    description "Bedrock Guardrail for content safety"

    let safetyGuardrail =
        bedrockGuardrail "ContentSafety" {
            description "Filters harmful and inappropriate content"
            blockedInputMessaging "Your input contains content that is not allowed."
            blockedOutputsMessaging "The response was filtered for safety."

            contentPolicyConfig (
                CfnGuardrail.ContentPolicyConfigProperty(
                    FiltersConfig =
                        [| CfnGuardrail.ContentFilterConfigProperty(
                               Type = "SEXUAL",
                               InputStrength = "HIGH",
                               OutputStrength = "HIGH"
                           )
                           CfnGuardrail.ContentFilterConfigProperty(
                               Type = "VIOLENCE",
                               InputStrength = "HIGH",
                               OutputStrength = "HIGH"
                           )
                           CfnGuardrail.ContentFilterConfigProperty(
                               Type = "HATE",
                               InputStrength = "HIGH",
                               OutputStrength = "HIGH"
                           ) |]
                )
            )

            tags [ "Environment", "Production" ]
        }

    ()
}

Complete Production Example

stack "ProductionBedrockStack" {
    env (
        environment {
            account config.Account
            region config.Region
        }
    )

    description "Production Bedrock AI platform"
    tags [ "Environment", "Production"; "ManagedBy", "FsCDK" ]

    // Content safety guardrail
    let guardrail =
        bedrockGuardrail "ProductionSafety" {
            description "Production content safety filters"
            blockedInputMessaging "This input is not permitted."
            blockedOutputsMessaging "This response has been filtered."

            contentPolicyConfig (
                CfnGuardrail.ContentPolicyConfigProperty(
                    FiltersConfig =
                        [| CfnGuardrail.ContentFilterConfigProperty(
                               Type = "SEXUAL",
                               InputStrength = "HIGH",
                               OutputStrength = "HIGH"
                           )
                           CfnGuardrail.ContentFilterConfigProperty(
                               Type = "VIOLENCE",
                               InputStrength = "HIGH",
                               OutputStrength = "HIGH"
                           ) |]
                )
            )

            topicPolicyConfig (
                CfnGuardrail.TopicPolicyConfigProperty(
                    TopicsConfig =
                        [| CfnGuardrail.TopicConfigProperty(
                               Name = "Financial Advice",
                               Definition = "Providing specific investment or financial planning advice",
                               Type = "DENY"
                           ) |]
                )
            )

            kmsKeyArn "arn:aws:kms:us-east-1:123456789012:key/my-key"
            tags [ "Environment", "Production" ]
        }

    // AI Agent
    let agent =
        bedrockAgent "ProductionAgent" {
            foundationModel "anthropic.claude-3-sonnet-20240229-v1:0"
            instruction "You are a helpful product assistant. Answer questions accurately based on the knowledge base."
            description "Production customer-facing AI agent"
            agentResourceRoleArn "arn:aws:iam::123456789012:role/BedrockAgentRole"
            idleSessionTtlInSeconds 3600
            autoPrepare true
            tags [ "Environment", "Production" ]
        }

    ()
}

Best Practices

Security

Cost

Reliability

Operational Excellence

Default Settings

Setting

Default

Rationale

autoPrepare

true

Agent is immediately available after deployment

Escape Hatch

Access the underlying CDK resources via the mutable Agent, KnowledgeBase, DataSource, or Guardrail properties on the spec records after stack synthesis for advanced scenarios not covered by these builders.

Learning Resources

namespace Amazon
namespace Amazon.CDK
namespace Amazon.CDK.AwsBedrock
namespace FsCDK
val get: unit -> {| Account: string; Region: string |}
namespace System
type Environment = static member Exit: exitCode: int -> unit static member ExpandEnvironmentVariables: name: string -> string static member FailFast: message: string -> unit + 1 overload static member GetCommandLineArgs: unit -> string array static member GetEnvironmentVariable: variable: string -> string + 1 overload static member GetEnvironmentVariables: unit -> IDictionary + 1 overload static member GetFolderPath: folder: SpecialFolder -> string + 1 overload static member GetLogicalDrives: unit -> string array static member SetEnvironmentVariable: variable: string * value: string -> unit + 1 overload static member CommandLine: string ...
<summary>Provides information about, and means to manipulate, the current environment and platform. This class cannot be inherited.</summary>
System.Environment.GetEnvironmentVariable(variable: string) : string
System.Environment.GetEnvironmentVariable(variable: string, target: System.EnvironmentVariableTarget) : string
val config: {| Account: string; Region: string |}
module Config from Bedrock
val stack: name: string -> StackBuilder
<summary>Creates an AWS CDK Stack construct.</summary>
<param name="name">The name of the stack.</param>
<code lang="fsharp"> stack "MyStack" { lambda myFunction bucket myBucket } </code>
custom operation: description (string) Calls StackBuilder.Description
<summary>Sets the stack description.</summary>
<param name="config">The current stack configuration.</param>
<param name="desc">A description of the stack.</param>
<code lang="fsharp"> stack "MyStack" { description "My application stack" } </code>
val myAgent: BedrockAgentSpec
val bedrockAgent: name: string -> BedrockAgentBuilder
<summary> Creates a new Bedrock Agent builder. Example: bedrockAgent "MyAgent" { foundationModel "anthropic.claude-3-sonnet-20240229-v1:0" } </summary>
custom operation: foundationModel (string) Calls BedrockAgentBuilder.FoundationModel
<summary>Sets the foundation model for the agent (e.g., "anthropic.claude-3-sonnet-20240229-v1:0").</summary>
<param name="config">The agent configuration.</param>
<param name="model">The foundation model identifier string.</param>
<code lang="fsharp"> bedrockAgent "MyAgent" { foundationModel "anthropic.claude-3-sonnet-20240229-v1:0" } </code>
custom operation: instruction (string) Calls BedrockAgentBuilder.Instruction
<summary>Sets the instruction/system prompt for the agent.</summary>
<param name="config">The agent configuration.</param>
<param name="instruction">The instruction text.</param>
<code lang="fsharp"> bedrockAgent "MyAgent" { instruction "You are a helpful assistant that answers questions about AWS." } </code>
custom operation: description (string) Calls BedrockAgentBuilder.Description
<summary>Sets the description for the agent.</summary>
<param name="config">The agent configuration.</param>
<param name="description">The agent description.</param>
<code lang="fsharp"> bedrockAgent "MyAgent" { description "An agent for customer support" } </code>
custom operation: agentResourceRoleArn (string) Calls BedrockAgentBuilder.AgentResourceRoleArn
<summary>Sets the IAM role ARN for the agent.</summary>
<param name="config">The agent configuration.</param>
<param name="roleArn">The IAM role ARN.</param>
<code lang="fsharp"> bedrockAgent "MyAgent" { agentResourceRoleArn "arn:aws:iam::123456789012:role/BedrockAgentRole" } </code>
val supportAgent: BedrockAgentSpec
custom operation: idleSessionTtlInSeconds (int) Calls BedrockAgentBuilder.IdleSessionTtlInSeconds
<summary>Sets the idle session TTL in seconds.</summary>
<param name="config">The agent configuration.</param>
<param name="seconds">Idle session timeout in seconds.</param>
<code lang="fsharp"> bedrockAgent "MyAgent" { idleSessionTtlInSeconds 600 } </code>
custom operation: autoPrepare (bool) Calls BedrockAgentBuilder.AutoPrepare
<summary>Sets whether the agent should be auto-prepared after creation (default: true).</summary>
<param name="config">The agent configuration.</param>
<param name="value">True to auto-prepare.</param>
<code lang="fsharp"> bedrockAgent "MyAgent" { autoPrepare true } </code>
custom operation: tags ((string * string) list) Calls BedrockAgentBuilder.Tags
<summary>Adds tags to the agent.</summary>
<param name="config">The agent configuration.</param>
<param name="tags">List of key-value tag pairs.</param>
<code lang="fsharp"> bedrockAgent "MyAgent" { tags [ "Environment", "Production"; "Team", "AI" ] } </code>
val kbConfig: CfnKnowledgeBase.KnowledgeBaseConfigurationProperty
Multiple items
type CfnKnowledgeBase = inherit CfnResource interface IInspectable interface ITaggableV2 new: scope: Construct * id: string * props: ICfnKnowledgeBaseProps -> unit member Inspect: inspector: TreeInspector -> unit member AttrCreatedAt: string member AttrFailureReasons: string array member AttrKnowledgeBaseArn: string member AttrKnowledgeBaseId: string member AttrStatus: string ...

--------------------
CfnKnowledgeBase(scope: Constructs.Construct, id: string, props: ICfnKnowledgeBaseProps) : CfnKnowledgeBase
type KnowledgeBaseConfigurationProperty = interface IKnowledgeBaseConfigurationProperty new: unit -> unit member KendraKnowledgeBaseConfiguration: obj member SqlKnowledgeBaseConfiguration: obj member Type: string member VectorKnowledgeBaseConfiguration: obj
type VectorKnowledgeBaseConfigurationProperty = interface IVectorKnowledgeBaseConfigurationProperty new: unit -> unit member EmbeddingModelArn: string member EmbeddingModelConfiguration: obj member SupplementalDataStorageConfiguration: obj
val storageConfig: CfnKnowledgeBase.StorageConfigurationProperty
type StorageConfigurationProperty = interface IStorageConfigurationProperty new: unit -> unit member MongoDbAtlasConfiguration: obj member NeptuneAnalyticsConfiguration: obj member OpensearchManagedClusterConfiguration: obj member OpensearchServerlessConfiguration: obj member PineconeConfiguration: obj member RdsConfiguration: obj member Type: string
type OpenSearchServerlessConfigurationProperty = interface IOpenSearchServerlessConfigurationProperty new: unit -> unit member CollectionArn: string member FieldMapping: obj member VectorIndexName: string
type OpenSearchServerlessFieldMappingProperty = interface IOpenSearchServerlessFieldMappingProperty new: unit -> unit member MetadataField: string member TextField: string member VectorField: string
val productKB: BedrockKnowledgeBaseSpec
val bedrockKnowledgeBase: name: string -> BedrockKnowledgeBaseBuilder
<summary> Creates a new Bedrock Knowledge Base builder. Example: bedrockKnowledgeBase "MyKB" { roleArn "..." } </summary>
custom operation: description (string) Calls BedrockKnowledgeBaseBuilder.Description
<summary>Sets the description for the knowledge base.</summary>
<param name="config">The knowledge base configuration.</param>
<param name="description">The description.</param>
<code lang="fsharp"> bedrockKnowledgeBase "MyKB" { description "Knowledge base for product documentation" } </code>
custom operation: roleArn (string) Calls BedrockKnowledgeBaseBuilder.RoleArn
<summary>Sets the IAM role ARN for the knowledge base.</summary>
<param name="config">The knowledge base configuration.</param>
<param name="roleArn">The IAM role ARN.</param>
<code lang="fsharp"> bedrockKnowledgeBase "MyKB" { roleArn "arn:aws:iam::123456789012:role/BedrockKBRole" } </code>
custom operation: knowledgeBaseConfiguration (CfnKnowledgeBase.IKnowledgeBaseConfigurationProperty) Calls BedrockKnowledgeBaseBuilder.KnowledgeBaseConfiguration
<summary>Sets the knowledge base configuration (embedding model, type, etc.).</summary>
<param name="config">The knowledge base configuration.</param>
<param name="kbConfig">The CfnKnowledgeBase.IKnowledgeBaseConfigurationProperty.</param>
<code lang="fsharp"> bedrockKnowledgeBase "MyKB" { knowledgeBaseConfiguration myKBConfig } </code>
custom operation: storageConfiguration (CfnKnowledgeBase.IStorageConfigurationProperty) Calls BedrockKnowledgeBaseBuilder.StorageConfiguration
<summary>Sets the storage configuration (vector store backend).</summary>
<param name="config">The knowledge base configuration.</param>
<param name="storageConfig">The CfnKnowledgeBase.IStorageConfigurationProperty.</param>
<code lang="fsharp"> bedrockKnowledgeBase "MyKB" { storageConfiguration myStorageConfig } </code>
custom operation: tags ((string * string) list) Calls BedrockKnowledgeBaseBuilder.Tags
<summary>Adds tags to the knowledge base.</summary>
<param name="config">The knowledge base configuration.</param>
<param name="tags">List of key-value tag pairs.</param>
<code lang="fsharp"> bedrockKnowledgeBase "MyKB" { tags [ "Environment", "Production" ] } </code>
val s3Config: CfnDataSource.DataSourceConfigurationProperty
Multiple items
type CfnDataSource = inherit CfnResource interface IInspectable new: scope: Construct * id: string * props: ICfnDataSourceProps -> unit member Inspect: inspector: TreeInspector -> unit member AttrCreatedAt: string member AttrDataSourceConfigurationWebConfigurationCrawlerConfigurationUserAgentHeader: string member AttrDataSourceId: string member AttrDataSourceStatus: string member AttrFailureReasons: string array member AttrUpdatedAt: string ...

--------------------
CfnDataSource(scope: Constructs.Construct, id: string, props: ICfnDataSourceProps) : CfnDataSource
type DataSourceConfigurationProperty = interface IDataSourceConfigurationProperty new: unit -> unit member ConfluenceConfiguration: obj member S3Configuration: obj member SalesforceConfiguration: obj member SharePointConfiguration: obj member Type: string member WebConfiguration: obj
type S3DataSourceConfigurationProperty = interface IS3DataSourceConfigurationProperty new: unit -> unit member BucketArn: string member BucketOwnerAccountId: string member InclusionPrefixes: string array
val docsSource: BedrockDataSourceSpec
val bedrockDataSource: name: string -> BedrockDataSourceBuilder
<summary> Creates a new Bedrock Data Source builder. Example: bedrockDataSource "MyDS" { knowledgeBaseId "..." } </summary>
custom operation: knowledgeBaseId (string) Calls BedrockDataSourceBuilder.KnowledgeBaseId
<summary>Sets the knowledge base ID this data source belongs to.</summary>
<param name="config">The data source configuration.</param>
<param name="id">The knowledge base ID.</param>
<code lang="fsharp"> bedrockDataSource "MyDS" { knowledgeBaseId "KB12345" } </code>
custom operation: description (string) Calls BedrockDataSourceBuilder.Description
<summary>Sets the description for the data source.</summary>
<param name="config">The data source configuration.</param>
<param name="description">The description.</param>
<code lang="fsharp"> bedrockDataSource "MyDS" { description "S3 data source for product docs" } </code>
custom operation: dataSourceConfiguration (CfnDataSource.IDataSourceConfigurationProperty) Calls BedrockDataSourceBuilder.DataSourceConfiguration
<summary>Sets the data source configuration (S3, web, etc.).</summary>
<param name="config">The data source configuration.</param>
<param name="dsConfig">The CfnDataSource.IDataSourceConfigurationProperty.</param>
<code lang="fsharp"> bedrockDataSource "MyDS" { dataSourceConfiguration myDSConfig } </code>
custom operation: dataDeletionPolicy (string) Calls BedrockDataSourceBuilder.DataDeletionPolicy
<summary>Sets the data deletion policy (RETAIN or DELETE).</summary>
<param name="config">The data source configuration.</param>
<param name="policy">The deletion policy string.</param>
<code lang="fsharp"> bedrockDataSource "MyDS" { dataDeletionPolicy "RETAIN" } </code>
val safetyGuardrail: BedrockGuardrailSpec
val bedrockGuardrail: name: string -> BedrockGuardrailBuilder
<summary> Creates a new Bedrock Guardrail builder. Example: bedrockGuardrail "MyGuardrail" { blockedInputMessaging "..." } </summary>
custom operation: description (string) Calls BedrockGuardrailBuilder.Description
<summary>Sets the description for the guardrail.</summary>
<param name="config">The guardrail configuration.</param>
<param name="description">The description.</param>
<code lang="fsharp"> bedrockGuardrail "MyGuardrail" { description "Content safety guardrail" } </code>
custom operation: blockedInputMessaging (string) Calls BedrockGuardrailBuilder.BlockedInputMessaging
<summary>Sets the message shown when input is blocked.</summary>
<param name="config">The guardrail configuration.</param>
<param name="message">The blocked input message.</param>
<code lang="fsharp"> bedrockGuardrail "MyGuardrail" { blockedInputMessaging "Your input was blocked by the guardrail." } </code>
custom operation: blockedOutputsMessaging (string) Calls BedrockGuardrailBuilder.BlockedOutputsMessaging
<summary>Sets the message shown when output is blocked.</summary>
<param name="config">The guardrail configuration.</param>
<param name="message">The blocked output message.</param>
<code lang="fsharp"> bedrockGuardrail "MyGuardrail" { blockedOutputsMessaging "The response was blocked by the guardrail." } </code>
custom operation: contentPolicyConfig (CfnGuardrail.IContentPolicyConfigProperty) Calls BedrockGuardrailBuilder.ContentPolicyConfig
<summary>Sets the content policy configuration (content filters).</summary>
<param name="config">The guardrail configuration.</param>
<param name="policyConfig">The CfnGuardrail.IContentPolicyConfigProperty.</param>
<code lang="fsharp"> bedrockGuardrail "MyGuardrail" { contentPolicyConfig myContentPolicy } </code>
Multiple items
type CfnGuardrail = inherit CfnResource interface IInspectable interface ITaggableV2 new: scope: Construct * id: string * props: ICfnGuardrailProps -> unit member Inspect: inspector: TreeInspector -> unit member AttrCreatedAt: string member AttrFailureRecommendations: string array member AttrGuardrailArn: string member AttrGuardrailId: string member AttrStatus: string ...

--------------------
CfnGuardrail(scope: Constructs.Construct, id: string, props: ICfnGuardrailProps) : CfnGuardrail
type ContentPolicyConfigProperty = interface IContentPolicyConfigProperty new: unit -> unit member ContentFiltersTierConfig: obj member FiltersConfig: obj
type ContentFilterConfigProperty = interface IContentFilterConfigProperty new: unit -> unit member InputAction: string member InputEnabled: obj member InputModalities: string array member InputStrength: string member OutputAction: string member OutputEnabled: obj member OutputModalities: string array member OutputStrength: string ...
custom operation: tags ((string * string) list) Calls BedrockGuardrailBuilder.Tags
<summary>Adds tags to the guardrail.</summary>
<param name="config">The guardrail configuration.</param>
<param name="tags">List of key-value tag pairs.</param>
<code lang="fsharp"> bedrockGuardrail "MyGuardrail" { tags [ "Environment", "Production"; "Team", "AI" ] } </code>
custom operation: env (IEnvironment) Calls StackBuilder.Env
val environment: EnvironmentBuilder
<summary>Creates an AWS CDK Environment configuration.</summary>
<code lang="fsharp"> environment { account "123456789012" region "us-west-2" } </code>
custom operation: account (string) Calls EnvironmentBuilder.Account
<summary>Sets the AWS account ID for the environment.</summary>
<param name="config">The current configuration.</param>
<param name="accountId">The AWS account ID.</param>
<code lang="fsharp"> environment { account "123456789012" } </code>
anonymous record field Account: string
custom operation: region (string) Calls EnvironmentBuilder.Region
<summary>Sets the AWS region for the environment.</summary>
<param name="config">The current configuration.</param>
<param name="regionName">The AWS region name.</param>
<code lang="fsharp"> environment { region "us-west-2" } </code>
anonymous record field Region: string
custom operation: tags ((string * string) list) Calls StackBuilder.Tags
<summary>Adds tags to the stack.</summary>
<param name="config">The current stack configuration.</param>
<param name="tags">A list of key-value pairs for tagging.</param>
<code lang="fsharp"> stack "MyStack" { tags [ "Environment", "Production"; "Team", "DevOps" ] } </code>
val guardrail: BedrockGuardrailSpec
custom operation: topicPolicyConfig (CfnGuardrail.ITopicPolicyConfigProperty) Calls BedrockGuardrailBuilder.TopicPolicyConfig
<summary>Sets the topic policy configuration (denied topics).</summary>
<param name="config">The guardrail configuration.</param>
<param name="policyConfig">The CfnGuardrail.ITopicPolicyConfigProperty.</param>
<code lang="fsharp"> bedrockGuardrail "MyGuardrail" { topicPolicyConfig myTopicPolicy } </code>
type TopicPolicyConfigProperty = interface ITopicPolicyConfigProperty new: unit -> unit member TopicsConfig: obj member TopicsTierConfig: obj
type TopicConfigProperty = interface ITopicConfigProperty new: unit -> unit member Definition: string member Examples: string array member InputAction: string member InputEnabled: obj member Name: string member OutputAction: string member OutputEnabled: obj member Type: string
custom operation: kmsKeyArn (string) Calls BedrockGuardrailBuilder.KmsKeyArn
<summary>Sets the KMS key ARN for encrypting the guardrail.</summary>
<param name="config">The guardrail configuration.</param>
<param name="keyArn">The KMS key ARN.</param>
<code lang="fsharp"> bedrockGuardrail "MyGuardrail" { kmsKeyArn "arn:aws:kms:us-east-1:123456789012:key/my-key" } </code>
val agent: BedrockAgentSpec

Type something to start searching.