即刻起飞 —— 基于 Amazon Bedrock 快速构建生成式 AI 应用

1. 前言

在百模大战中,AI行业的发展正在经历前所未有的变革。这场竞争不仅推动了AI技术的快速发展,也揭示了AI行业的新趋势。这些趋势不仅影响着我们如何看待和使用AI,也预示着AI未来的发展方向。在这个快速发展的领域,了解这些新趋势对于理解AI行业的未来走向至关重要。

亚马逊云科技的Amazon Bedrock 是一项完全托管的服务,通过单个 API 提供来自 AI21 Labs、Anthropic、Cohere、Meta、Mistral AI、Stability AI 和 Amazon 等领先人工智能公司的高性能基础模型(FM),以及通过安全性、隐私性和负责任的人工智能构建生成式人工智能应用程序所需的一系列广泛功能。

使用 Amazon Bedrock,可以轻松试验和评估适合您的使用案例的热门 FM,通过微调和检索增强生成(RAG)等技术利用数据对其进行私人定制,并构建使用企业系统和数据来源执行任务的代理。由于 Amazon Bedrock 是无服务器的,因此无需管理任何基础设施,并且可以使用已经熟悉的 AWS 服务将生成式人工智能功能安全地集成和部署到我们的应用程序中。

今天炒香菇的书呆子通过亚马逊云科技提供的免费在线实验环境带大家体验和学习掌握如何基于Amazon Bedrock 快速构建生成式AI应用。

在构建AIGC方面,无论是小白还是大佬,Amazon Bedrock都是一个不错的选择

2. 实验前准备

点击进入实验网站

亚马逊云科技官网为大家准备了24h的实验环境,可以免费使用

若在实验完成后想要继续体验,可以购买相关服务

进入网址后,点击开始实验

image-20240526234838310

可以选择用微信或者账号密码登录

登录成功后可以看到临时实验账号的控制台

image-20240526235028186

在控制台左侧可以浏览操作界面

image-20240526235158879

3. 快速上手Stability AI SDXL 1.0构建艺术图像

3.1 Stability AI SDXL 1.0介绍

Stable Diffusion XL是在Stability AI 在2023年4 月份推出的新模型,训练参数是之前 Stable Diffusion v2.1 的 2.5 倍,其生成的图像在美学程度和质量上有了很大的改进。

据官方介绍,SDXL 1.0 相比之前的模型,优势主要体现在以下几个方面:

  • 可以直接根据文本生成生成任何艺术风格的高质量图像,无需其他训练模型辅助,写实类的表现是目前所有开源文生图模型里最好的。
  • 依据简单的提示词就能生成复杂、精致且美观的图像,不再需要调用“masterpiece”“best quality”等词语。
  • 可直接生成 1024x1024 的图像,色彩也更鲜艳、准确,在对比度、光照和阴影的处理上也比之前要好很多。
  • 在文本、物体空间排列、手部等内容的处理上表现很好。
  • 可以理解“The Red Square”(著名地点)与“red square”(形状)等概念之间的差异。

下面我们将通过Amazon Bedrock 快速上手Stability AI SDXL 1.0构建艺术图像

3.2 试用SDXL 1.0

在左侧控制台选择操作–>图像,右侧点击选择模型

image-20240526235759355

然后依次选择Stability AI --> SDXL 1.0–>按需,然后选择应用

image-20240526235846648

在右侧,我们可以下方设定关键词,在右侧调整模式,生成图像的基本信息等来控制如何生成图像

image-20240527000302644

image-20240527001418804

例如,我的测试demo如下

a student sit on his book desk and reading a book

image-20240527000547642

我们还可以进一步对细节进行修改

点击图像,进行编辑

image-20240527000813623

选中图中的student继续使用提示词

image-20240527000903132

可以看到生成的图片中student的头发为绿色

image-20240527000926870

3.3 基于Amazon Cloud9部署Stability AI SDXL 1.0

3.3.1 Amazon Cloud9 创建

打开亚马逊云科技控制台,搜索Cloud9,点击进入

image-20240527002326956

选择创建环境

image-20240527002405817

设置环境详细信息

  1. 设置名称为 bedrock
  2. 设置实例类型 t3.small
  3. 平台 Ubuntu Server 22.04 LTS
  4. 超时 30 分钟

image-20240527002534179

image-20240527002528442

点击创建

image-20240527002554529

待主机创建完成后,进入IDE终端

image-20240527002639767

image-20240527002749761

3.3.2 安装实验环境

复制以下内容到终端,执行命令,以下载和解压缩代码

cd ~/environment/
curl 'https://dev-media.amazoncloud.cn/doc/workshop.zip' --output workshop.zip
unzip workshop.zip

解压完成:

image-20240527002901860

image-20240527002924689

观察左侧主机目录

image-20240527002954428

继续使用 终端,安装实验所需的环境依赖项

pip3 install -r ~/environment/workshop/setup/requirements.txt -U

image-20240527003226489

3.3.3 开始编写 Amazon Bedrock 中 Stability AI SDXL 1.0 API

打开 Amazon Bedrock 示例,输入关键字 sdxl,选择 SDXL 1.0,查看 API 请求代码

image-20240527003518990

API为

{
  "modelId": "stability.stable-diffusion-xl-v1",
  "contentType": "application/json",
  "accept": "application/json",
  "body": "{\"text_prompts\":[{\"text\":\"Sri lanka tea plantation.\",\"weight\":1}],\"cfg_scale\":10,\"seed\":0,\"steps\":50,\"width\":1024,\"height\":1024}"
}

使用 Amazon Cloud9 IDE,选择 workshop/labs/api/bedrock_api.py 编写代码

添加 import 语句,这些语句允许我们使用 Amazon Web Services boto3 库来调用 Amazon Bedrock,使用 base64 进行编码和解码操作,使用 Image 模块处理图像,以及使用 io、os 模块进行文件输入/输出

import json
import boto3
import base64
import os
from PIL import Image
import io

初始化 Amazon Bedrock 客户端库

session = boto3.Session()

bedrock = session.client(service_name='bedrock-runtime') #creates a Bedrock client

在这里,我们将确定要使用的模型、提示和指定模型的推理参数。

bedrock_model_id = "stability.stable-diffusion-xl-v1"  # set the foundation model
prompt =  "a beautiful mountain landscape"  # the prompt to send to the model
seed = 10

body = json.dumps({
    "text_prompts": [{"text": prompt}],
    "seed": seed,
    "cfg_scale": 10,
    "steps": 30,
})  # build the request payload

调用 Bedrock API,我们使用 Bedrock 的 invoke_model 函数进行调用。

# send the payload to Bedrock
response = bedrock.invoke_model(
    body=body, modelId=bedrock_model_id, accept='application/json', contentType='application/json')

从响应中获取图像数据,并将其保存为文件

# read the response
response_body = json.loads(response.get('body').read())
base64_image_data = response_body.get("artifacts")[0]["base64"]
print(f"{base64_image_data[0:80]}...")
# Convert base64 image data to an image and save it to a file
image_data = base64.b64decode(base64_image_data)
os.makedirs("data", exist_ok=True)
image = Image.open(io.BytesIO(image_data))
image.save('data/sd_generated_image.jpg')

保存文件,并在命令行处执行代码:

image-20240527003915701

cd ~/environment/workshop/labs/api
python3 bedrock_api.py

image-20240527004139855

image-20240527004327536

同时,我们还可以通过进行文生图,图生图,图像修复等功能

欢迎在线体验实验:https://dev.amazoncloud.cn/experience/cloudlab?id=65fd7f888f852201f9704488

4. 快速构建Meta Llama 3生成式AI

4.1 Meta Llama 3介绍

Meta Llama 3是Meta公司于2024年4月18日发布的新一代开源大语言模型(LLM)。这一系列模型旨在推动人工智能领域的边界,提供卓越的性能和广泛的应用潜力。Meta Llama 3主要包括两个版本的模型:一个是拥有80亿参数的模型,另一个是更为强大的700亿参数模型。

关键特性与成就:

  • 性能表现:在多项基准测试中,Meta Llama 3展示了出色的性能,比如在TriviaQA-Wiki测试中达到89.7%的准确率,这表明它在理解复杂文本和回答问题方面具有很高的能力。
  • 开源性:作为开源模型,Meta Llama 3强调开放合作,鼓励开发者和研究人员使用这些模型进行创新和改进,进一步推动AI社区的发展。
  • 硬件优化与兼容性:该模型得到了包括英特尔、高通在内的多家科技巨头的支持。英特尔已经优化并验证了Llama 3模型能在其多种AI产品上运行,而高通则宣布未来的骁龙旗舰平台将支持该模型,允许在终端侧高效执行。
  • 云平台部署:Meta Llama 3模型计划在多个主流云平台上上线,如AWS、Google Cloud、Microsoft Azure等,以及获得AMD、Dell、NVIDIA等硬件平台的支持,这将极大地方便用户和开发者接入和使用。
  • 应用范围:由于其高性能和广泛的平台支持,Llama 3模型预计将在多个领域找到应用,包括但不限于自然语言处理、内容生成、机器翻译、对话系统、智能助手等。

4.2 在线体验Meta Llama 3

在左侧控制台选择操作–>聊天,右侧点击选择模型

image-20240527005154769

选择 Meta Llama 3 8B Instruct,点击应用

image-20240527005248764

image-20240527005344664

下面我写一个调用示例

写一个冒泡排序算法,并给出详细注释

image-20240527005505916

image-20240527005805634

查看API请求参数

image-20240527005838427

image-20240527005847155

aws bedrock-runtime invoke-model \
--model-id meta.llama2-70b-chat-v1 \
--body "{\"prompt\":\"[INST]You are a Data scientist trying to explain to a 5 year old[/INST]\\nCan you explain what is a transformer in a machine learning context ?\\n \\n\\nSure, I'd be happy to explain! So, you know how we can teach machines to learn things, like how to recognize pictures or understand what people say?\\n\\nYes, I do!\\n\\nGreat! Well, there are different ways we can teach machines to learn, and one of the ways is called \\\"transformers.\\\"\\n\\nImagine you have a big box full of toys, and you want to give all the toys to your friend who loves toys. But, there are so many toys that it would take forever to give them all to your friend one by one.\\n\\nThat's kind of like how machines learn from data. They can look at lots and lots of data, like pictures or words, and learn things from it. But, just like it would take forever to give all the toys to your friend one by one, it would take forever for the machine to look at all the data one piece at a time.\\n\\nThat's where transformers come in! A transformer is like a special machine that can look at all the toys in the box at the same time. It can take all the toys, and give them to your friend all at once!\\n\\nIn the same way, a transformer in machine learning can look at lots and lots of data all at once, and learn things from it much faster than if it had to look at each piece of data one by one.\\n\\nDoes that make sense?\\n\\nI think so! So, it's like a machine that helps other machines learn faster?\\n\\nExactly! It's like a special tool that helps machines learn faster and more efficiently. And, just like how your friend would be really happy to get all the toys at once, machines are really happy to have transformers help them learn faster!\",\"max_gen_len\":512,\"temperature\":0.5,\"top_p\":0.9}" \
--cli-binary-format raw-in-base64-out \
--region us-west-2 \
invoke-model-output.txt

4.3 基于Amazon Cloud9快速构建 Meta Llama 3

4.3.1 Amazon Cloud9 创建

打开亚马逊云科技控制台,搜索Cloud9,点击进入

image-20240527002326956

选择创建环境

image-20240527002405817

设置环境详细信息

  1. 设置名称为 bedrock
  2. 设置实例类型 t3.small
  3. 平台 Ubuntu Server 22.04 LTS
  4. 超时 30 分钟

image-20240527002534179

image-20240527002528442

点击创建

image-20240527002554529

待主机创建完成后,进入IDE终端

image-20240527002639767

image-20240527002749761

4.3.2 体验调用 Meta Llama 3 API 应用

以下为请求参数内容:

image-20240527010421045

以下为返回参数内容:

{
    "generation": "\n\n<response>",
    "prompt_token_count": int,
    "generation_token_count": int,
    "stop_reason" : string
}

image-20240527010440460

打开 workshop/labs/api 文件夹,打开文件 bedrock_api.py

image-20240527010505582

  1. 添加导入依赖语句允许我们使用 Amazon boto3 库来调用 Amazon Bedrock
import json
import boto3
  1. 初始化 Bedrock 客户端库,创建一个 Bedrock 客户端
session = boto3.Session()
bedrock = session.client(service_name='bedrock-runtime') #初始化Bedrock客户端库
  1. 编写 API 调用代码
    我们将确定要使用的模型、提示和指定模型的推理参数
bedrock_model_id = "meta.llama3-8b-instruct-v1:0" #设置模型 

user_message = "用中文简述一下OSI七层网络模型" #提示词

prompt = f""" 
<|begin_of_text|> 
<|start_header_id|>user<|end_header_id|> 
{user_message} 
<|eot_id|> 
<|start_header_id|>assistant<|end_header_id|>
"""

body = json.dumps({
    "prompt": prompt, 
    "max_gen_len": 2048,
    "temperature":0.5,
    "top_p":0.9
}) 
  1. 使用 Amazon Bedrockinvoke_model 函数进行调用
response = bedrock.invoke_model(body=body, modelId=bedrock_model_id, accept='application/json', contentType='application/json') #发送调用请求
  1. 模型的响应 JSON 中提取并打印返回的文本
response_body = json.loads(response.get('body').read()) 
response_text=response_body['generation'] #从 JSON 中返回相应数据
print(response_text)
  1. 保存文件,并准备运行脚本
cd ~/environment/workshop/labs/api
python3 bedrock_api.py

image-20240527010716725

4.3.3 使用 Amazon Bedrock 中 Meta Llama 3、LangChain 和 Streamlit 构建一个简单的文本生成器

应用程序由两个文件组成:一个用于 Streamlit 前端另一个用于调用 Bedrock 的支持库

首先,创建支持库,将 Streamlit 前端连接到 Bedrock 后端

  1. 打开 workshop/labs/text 文件夹,然后打开文件 text_lib.py

添加导入语句,允许使用 LangChain 调用 Bedrock

from langchain_aws import BedrockLLM
复制
  1. 创建一个可以从 Streamlit 前端应用程序调用的函数,此函数使用 LangChain 创建 Bedrock 客户端,然后将输入内容传递给 Bedrock
def get_text_response(input_content): #文生文函数

    input_content = f"""
    <|begin_of_text|>
    <|start_header_id|>user<|end_header_id|>
    {input_content}
    <|eot_id|>
    <|start_header_id|>assistant<|end_header_id|>
    """

    llm = BedrockLLM( #创建Bedrock llm 客户端
        model_id="meta.llama3-8b-instruct-v1:0", #设置模型
        model_kwargs={
            "max_gen_len": 1024,
            "temperature":0.2,
            "top_p":0.5
        }
    )

    return llm.invoke(input_content) #返回数据
  1. 打开同一目录下的文件 text_app.py,并添加导入语句,使用 Streamlit 元素和调用函数
import streamlit as st #streamlit 命令使用别名 "st"
import text_lib as glib 
  1. 设置页面头部内容
st.set_page_config(page_title="Text to Text") #页面 title
st.title("Text to Text") #page title
  1. 添加输入元素,创建一个多行文本框和按钮,以获得用户的提示并将其发送到 Bedrock。
input_text = st.text_area("Input text", label_visibility="collapsed") #输入文本内容
go_button = st.button("Go", type="primary") #请求按钮
  1. 添加输出元素
if go_button: #运行按钮
    with st.spinner("Working..."): #当带有块的代码运行时显示一个微调器
      response_content = glib.get_text_response(input_content=input_text) #调用方法
      st.write(response_content) #显示响应内容
  1. 保存文件,运行代码
cd ~/environment/workshop/labs/text
streamlit run text_app.py --server.port 8080

执行结果如下

image-20240527011245049

预览方法:
打开 Cloud9 菜单栏->Preview->Preview Running Application

image-20240527011450856

image-20240527012606863

image-20240527012550884

如果大家想要深度体验基于Amazon Bedrock 构建属于自己的AI应用程序

可以继续体验:https://dev.amazoncloud.cn/experience/cloudlab?id=65fd7f888f852201f9704488

亚马逊云科技给广大开发者提供了大量主机资源和丰富的入门教程,开箱即用,可以快速上手~

也欢迎大家一起探索 Amazon Bedrock 更多的功能,为工作中赋能增效降本!

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

炒香菇的书呆子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值