使用Amazon Bedrock上的Claude 3将图表转化为CDK/Terraform

- 使用人工智能从架构图和图像生成基础设施代码

简介

在当前的云原生环境中,将基础设施视为代码(IaC)已经成为开发人员和DevOps团队的重要实践。

随着Claude 3 Sonnet模型在Amazon Bedrock上发布以及其图像到文本的能力,架构图与基础设施代码(IaC)工具(如AWS Cloud Development Kit(CDK)或Terraform)之间的无缝集成开启了新时代。

本文将探讨如何利用这种集成的优势来简化您的基础设施配置和管理过程。

架构图

架构图是系统组件及其关系的可视化表示,展示了应用程序或基础设施的整体结构。它们充当团队成员间沟通、协作和决策制定的蓝图。然而,在复杂的环境中,将这些示意图手动转换为代码可能需要花费大量时间,并且容易出错。

使用Amazon Bedrock上的Claude 3 Sonnet模型

人工智能公司Anthropic推出了一系列名为Claude 3的先进AI模型,包括Claude 3 Opus、Claude 3 Sonnet和Claude 3 Haiku。这些模型拥有强大的功能,将为用户带来全新的体验。

这些模型具备解析图像中文字的能力,这一特性将被应用于公司的解决方案中。更多详细信息,请访问:Introducing the next generation of Claude \ Anthropic

在性能方面,Sonnet模型表现尤为出色,堪称MVP。它不仅在输入和输出速度上超越了Anthropic之前推出的Claude 2和2.1模型,而且智能程度更高。此外,Sonnet模型更加易于控制,这意味着用户可以获得更稳定且高质量的结果。这无疑是一个双赢的局面。

并且更棒的是

Amazon Bedrock近日宣布支持Anthropic Claude 3系列。详情请见:Amazon Bedrock adds Claude 3 Anthropic AI models

Amazon Bedrock是一款全面管理的服务,作为一站式商店,提供所有生成性AI方面的服务。通过使用基石,用户可以从诸如Anthropic等顶级AI公司提供的各种高性能基础模型中进行选择,同时基石还具备大量功能,使得构建和扩展生成性AI应用程序变得更加轻松愉快。

解决方案

好的,让我们直接进入解决方案。请按照以下步骤为您自己获取架构提取器。

1. 在亚马逊 Bedrock 中启用 Anthropic Claude 3,并复制以下脚本。

2. 创建一个名为 claude_vision.py 的文件

import base64
import json
import os

import boto3
import click
from botocore.exceptions import ClientError

def call_claude_multi_model(bedrock_runtime, model_id, input_text, image, max_tokens):
    """
    Streams the response from a multimodal prompt.
    Args:
        bedrock_runtime: The Amazon Bedrock boto3 client.
        model_id (str): The model ID to use.
        input_text (str) : The prompt text
        image (str) : The path to  an image that you want in the prompt.
        max_tokens (int) : The maximum  number of tokens to generate.
    Returns:
        None.
    """

    with open(image, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read())

    body = json.dumps(
        {
            "anthropic_version": "bedrock-2023-05-31",
            "max_tokens": max_tokens,
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": input_text},
                        {
                            "type": "image",
                            "source": {
                                "type": "base64",
                                "media_type": "image/jpeg",
                                "data": encoded_string.decode("utf-8"),
                            },
                        },
                    ],
                }
            ],
        }
    )

    response = bedrock_runtime.invoke_model_with_response_stream(
        body=body, modelId=model_id
    )

    for event in response.get("body"):
        chunk = json.loads(event["chunk"]["bytes"])

        if chunk["type"] == "content_block_delta":
            if chunk["delta"]["type"] == "text_delta":
                print(chunk["delta"]["text"], end="")

@click.command()
@click.option("--image_path", prompt="path to image", help="Image you want to parse")
def main(image_path):
    """
    Entrypoint for Anthropic Claude Sonnet multimodal prompt example.
    """

    model_id = "anthropic.claude-3-sonnet-20240229-v1:0"
    input_text = """
You are a AWS solution architect, 
The image provided is an architecture diagram. Use two heading to explain below.
1. Explain the technical data flow in detail.
2. Provide cdk typescript code to implement using aws-cdk-lib

Do not:
1. use preambles.
2. make assumptions.
"""
    max_tokens = 4000

    try:

        bedrock_runtime = boto3.client("bedrock-runtime")

        call_claude_multi_model(
            bedrock_runtime,
            model_id,
            input_text,
            os.path.abspath(image_path),
            max_tokens,
        )

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " + format(message))

if __name__ == "__main__":
    main()

3. 为了创建并保存以下图像,请注意路径。

4. 运行脚本

python src/utils/claude_vision.py --image_path ~/Desktop/s3_extractor.png

运行脚本后的响应

$ python src/utils/claude_vision.py --image_path ~/Desktop/s3_extractor.png

Technical Data Flow Explanation

The architecture diagram depicts a serverless data pipeline using AWS services. The data flow can be described as follows:

1. An Amazon S3 bucket is the source of data, which likely contains files or objects that need to be processed.
2. When a new object is uploaded or modified in the S3 bucket, it triggers an AWS Lambda function named "LambdaExtractor."
3. The LambdaExtractor function is responsible for extracting relevant data or events from the input files or objects in the S3 bucket.
4. After processing, the extracted data or events are stored in an Amazon DynamoDB table named "StoreEventsDB."

CDK Typescript Code Implementation

To implement this architecture using the AWS Cloud Development Kit (CDK) and TypeScript, you can use the following code:

```typescript
import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import * as lambdaEventSources from 'aws-cdk-lib/aws-lambda-event-sources';

const app = new cdk.App();
const stack = new cdk.Stack(app, 'DataPipelineStack');

// Create the S3 bucket
const sourceBucket = new s3.Bucket(stack, 'SourceBucket');

// Create the DynamoDB table
const eventsTable = new dynamodb.Table(stack, 'StoreEventsDB', {
partitionKey: { name: 'id', type: dynamodb.AttributeType.STRING },
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
});

// Create the Lambda function
const lambdaExtractor = new lambda.Function(stack, 'LambdaExtractor', {
runtime: lambda.Runtime.NODEJS_14_X,
code: lambda.Code.fromAsset('path/to/lambda/code'),
handler: 'index.handler',
environment: {
EVENTS_TABLE_NAME: eventsTable.tableName,
},
});

// Grant permissions for the Lambda function to access the DynamoDB table
eventsTable.grantWriteData(lambdaExtractor);

// Create the S3 event source and associate it with the Lambda function
lambdaExtractor.addEventSource(
new lambdaEventSources.S3EventSource(sourceBucket, {
events: [s3.EventType.OBJECT_CREATED, s3.EventType.OBJECT_REMOVED],
recursive: true,
})
);
```

In this code:

1. An S3 bucket named "SourceBucket" is created to serve as the source of data.
2. A DynamoDB table named "StoreEventsDB" is created with a partition key "id" of type string.
3. A Lambda function named "LambdaExtractor" is created with the provided source code and environment variables.
4. The Lambda function is granted write permissions to the DynamoDB table.
5. An S3 event source is created and associated with the Lambda function, triggering the function when objects are created or removed from the "SourceBucket."

Note: You need to replace 'path/to/lambda/code' with the actual path to your Lambda function code, and provide the necessary logic in the Lambda function to extract data from the S3 objects and store it in the DynamoDB table.%

将架构图转换为基础设施代码(IaC)的好处

  1. 一致性及准确性:通过自动化的转换过程,避免了人为错误的发生,确保了基础设施代码精确地反映了架构设计。
  2. 更快速的迭代和部署:借助快速将图表转化为代码的能力,可以迅速对基础设施进行迭代、测试变更,并自信地进行更新部署。
  3. 团队协作与标准化:架构图作为团队间有效沟通和协作的通用语言,将其转化为IaC后,整个组织内形成了一种统一且标准的基础设施管理方法。
  4. 版本控制和审计能力:由于CDK和Terraform代码储存在版本控制系统中,因此能够追踪基础设施更改的全貌,实现了更优秀的管理和合规性。

总结

将Claude 3的sonnet与AWS Bedrock和能够将架构图转换为CDK或Terraform代码的能力相集成,代表了开发人员和DevOps团队向前迈出了重大一步。


通过采用这种方式,您可以释放基础设施即代码的强大功能,简化您的工作流程,并加速可靠和可扩展的云基础设施的交付。踏上这一旅程,体验视觉设计和自动化代码生成的无缝融合,使您能够前所未有地高效和自信地构建和管理云环境。

接下来,基于Streamlit Web UI的方法将提供一个友好的交互式UI,让那些讨厌命令行界面的人也能使用这种解决方案。

限时免费体验Claude 3!

点击此处,扫码体验!

即刻注册亚马逊云科技账户,开启云端之旅!

【免费】亚马逊云科技“100 余种核心云服务产品免费试用”

【免费】亚马逊云科技中国区“40 余种核心云服务产品免费试用”

亚马逊云科技是谁?
亚马逊云科技(Amazon Web Services)是全球云计算的开创者和引领者,自 2006 年以来一直以不断创新、技术领先、服务丰富、应用广泛而享誉业界。亚马逊云科技可以支持几乎云上任意工作负载。亚马逊云科技目前提供超过 200 项全功能的服务,涵盖计算、存储、网络、数据库、数据分析、机器人、机器学习与人工智能、物联网、移动、安全、混合云、虚拟现实与增强现实、媒体,以及应用开发、部署与管理等方面;基础设施遍及 31 个地理区域的 99 个可用区,并计划新建 4 个区域和 12 个可用区。全球数百万客户,从初创公司、中小企业,到大型企业和政府机构都信赖亚马逊云科技,通过亚马逊云科技的服务强化其基础设施,提高敏捷性,降低成本,加快创新,提升竞争力,实现业务成长和成功。
 

  • 33
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值