用Amazon Bedrock上最新模型Claude3 Opus制作网页小游戏

2024年4月16日,亚马逊云科技官方发布Anthropic Claude系列最强模型 Claude 3 Opus现已在Amazon Bedrock平台上正式可用,这一更新对于亚马逊云科技的用户和开发者们来说是个重大的好消息。因为企业云端应用可以更便捷、安全地集成Claude 3 Opus的API,将这款大模型的超强能力赋能到企业业务之中。Claude 3 Opus在处理困难的开放式问题上相对于Claude 2.1有约两倍的准确度提升,更加适用于医疗、金融和法律等对于数据安全性和信息准确性有着极高要求的企业级用户。

在Anthropic的官方报告中显示,Claude 3 Opus在人工智能领域热门的大模型基准测试中表现均优于目前市场上的同类模型(如 GPT-4),基准测试包括undergraduate-level expert knowledge (MMLU), graduate-level expert reasoning (GPQA), basic mathematics (GSM8K)等。在响应速度上,Opus 的实际速度与 Claude 2 和 2.1 相同,这表示Claude 3 Opus有着强的性能。

Claude 3 Opus在性能上具有深度推理、高级数学和编码能力,在高度复杂的任务上具有顶级性能,展现了几乎与人类相媲美的理解和表达能。同时Opus拥有行业领先的多模态的视觉能力,能够极其准确地分析和处理照片、图表、图形和技术绘图。它可以非常流畅地导航开放式提示和新颖场景,包括任务自动化、假设生成以及图表、图形和预测的分析。

看到这里想必大家已经迫不及待的想尝试这款超强大模型了,今天小李哥就带着大家按照Amazon Bedrock官方提供的Claude 3 Opus模型云端开发应用场景案例,实操试用这款最强大模型,通过API调用Claude 3 Opus大模型制作一款网页小游戏。

1. 通过API调用Claude 3 Opus大模型制作一款网页小游戏。

事先准备:

跟着小李哥访问Claude 3 Opus API需要大家已具备以下条件:

  • 拥有亚马逊云科技海外区账号。
  • 账号开通了Amazon Bedrock上的Claude 3模型访问。
  • 创建过用于访问云端API的IAM用户并生成了对应的Access Key。
  • 为IAM用户配置了访问Amazon Bedrock上的Claude 3 Opus模型的最小化权限。
  • 本地下载了aws cli命令行工具,并通过”aws configure”配置了访问云端API的access key(Access Key ID、Secret Access Key)和Default Region: “us-west-2”。

如果大家还不满足上述条件,想了解如何注册亚马逊云科技海外账号、开启模型访问、配置本地API 访问授权等操作细节,请参考小李哥之前在云师兄账户上的文章:“Amazon Bedrock 模型“上新”!技领云博主带你上手体验“  Amazon Bedrock 模型“上新”!技领云博主带你上手体验

下面就跟着小李哥一起通过API调用Claude 3 Opus模型制作一款网页小游戏吧!

1) 在亚马逊云科技控制台中选择区域”us-west-2 (Oregon)”,目前只有这个区域支持。

2)在控制台中搜索“Amazon Bedrock”进入服务主页,再点击左侧的“Model Access”

3) 进入后点击右上角“Manage Model Access”。

4) 进入界面后找到Anthropic类别下的”Claude 3 Opus”,勾选前面的方框,并点击页面右下角的Save(未显示)。因为Amazon Bedrock新发布的模型,是默认在账户中没有开启的,需要用户自己开启。

5) 在此点击左侧侧边栏,点击”Examples”。

6) 在Amazon Bedrock上为大家提供了适用于Amazon Titan、Anthropic Claude、AI21、Cohere、Meta Llama、Mistral AI、Stability AI等不同厂商模型的云端开发应用场景案例,共有48个。大家可以直接点击右上角“Open in Playground”开始使用,每个场景也为大家提供了Prompt提示词、参考响应内容、模型推理参数和API调用方法,帮助大家用于云端应用集成。

7) 下面我们找到适用于Claude 3 Opus云端开发场景的案例,在搜索框中搜索“Claude 3 Opus”,并点击第三个”Create a Side-Scrolling Game”

8) 该应用开发场景主要是利用Claude 3 Opus模型制作一款卷轴动作网页小游戏,卷轴动作游戏就是玩家在屏幕上通过键盘直线移动,完成相应的任务最终通关,类似于马里奥、魂斗罗等。

我们这次的小游戏是让玩家通过键盘控制一个蓝色小方块,让小方块触碰到屏幕上滚动的英文单词,最后在屏幕上敲击输入小方块触碰的单词,及时输入正确的单词后就可以获取积分,赢得游戏。

我们将通过提示词,让Claude 3 Opus模型帮我们生成一个网页游戏的HTML代码文件,生成的代码会使用到JavaScript和TailwindCSS框架。

9) 大家可以通过控制台界面和API调用两种方式获取该场景下的回复。首先通过控制台,大家直接在案例主页点击右上角”Play in Playground”进入到和大模型的聊天交互窗口。

10) 提示词会自动填充,我们在交互窗口中点击红框中的”Run”

11) 大家在控制台中就可以看到输出的样例代码,Amazon Bedrock上的Claude模型最长输出有4096个token,可以完美满足大家生成长代码的需求。

12)下面就是最激动人心的时刻了,本篇文章会展示如何使用亚马逊云科技Python Boto3 SDK访问Amazon Bedrock上的Claude 3 Opus模型。并通过API调用的方式,生成网页游戏。

13)首先大家要在本地安装Boto3 SDK,在命令行输入“pip install boto3”进行安装。

pip install boto3

14) 接下来我们进入自己常用的IDE中,创建一个空的Python文件,复制下列代码并运行,这个脚本可以查看目前Amazon Bedrock上支持的Anthropic Claude系列的模型。因为每一个不同的Claude 3模型都有自己单独的模型ID,ID很长经常记不住,这个脚本可以帮助我们快速地找到想调用的模型ID。

import boto3

bedrock = boto3.client(service_name="bedrock",region_name="us-west-2")
response = bedrock.list_foundation_models(byProvider="anthropic")

for summary in response["modelSummaries"]:
    print(summary["modelId"])

15) 运行Python程序后,大家就可以找到我们这次要调用的Claude 3 Opus模型ID: “anthropic.claude-3-opus-20240229-v1:0”。其他ID是在Amazon Bedrock上可用的其他Claude系列模型,大家也可以记录下来,后续使用。

16) 接下来我们开始展示如何调用API访问Amazon Bedrock上的Claude 3模型。

我们需要使用Claude 3模型提供的标准Message API定义请求的输入内容,再利用Boto3的指定语法调用Amazon Bedrock上托管的Claude 3模型生成内容。关于Message API部分的参数解释为:

-“max_tokens”表示大模型可输出的最大长度

-“anthropic_version”表示API版本,我们填写"bedrock-2023-05-31"

-“messages”是对话消息组成的一个数组,每句对话由一个JSON对象表示,如果是用户发送的消息,role则为”user”,如果是大模型的回复,role则为”assistant”,content的键值则表示对话的内容。

   17) 首先我们通过之前样例提供的API方法,点击红框内的按键复制内容,分别取出modelId,contentType,body三个key的值。

18) 将三个key的值取出,分别放到Message API以及Bedrock invoke_model API的参数中。生成下面所示的与Claude 3 Ops交互的代码样例。每一行都写了代码备注,帮助大家理解。

import boto3
import json
import re

# 设定prompt内容
prompt = "[{\"type\":\"text\",\"text\":\"Write me a fully complete web app as a single HTML file. The app should contain a simple side-scrolling game where I use WASD to move around.  When moving around the world, occasionally the character/sprite will encounter words. When a word is encountered, the player must correctly type the word as fast as possible.The faster the word is successfully typed, the more point the player gets. We should have a counter in the top-right to keep track of points. Words should be random and highly variable to keep the game interesting. \\n\\nYou should make the website very aesthetic and use Tailwind.\"}]"

# 初始化Boto3客户端并设置模型所在区域
bedrock = boto3.client(service_name="bedrock-runtime",region_name="us-west-2")

#定义Claude 3模型的标准Message API
body = json.dumps({
  "max_tokens": 4096,
  "messages": [{"role": "user", "content": prompt}],
  "anthropic_version": "bedrock-2023-05-31"
})

#调用Amazon Bendrcok上的Claude 3模型生成内容
response = bedrock.invoke_model(contentType="application/json", body=body, modelId="anthropic.claude-3-opus-20240229-v1:0")

#提取API响应中的大模型回复部分
response_body = json.loads(response.get("body").read())
content = response_body.get("content")[0].get('text', '')

#提取大模型输出中的代码部分
pattern = r'```html(.*?)```'
match = re.search(pattern, content, re.DOTALL)
content_html = match.group(1).strip()

# 将内容写入game.html文件
with open('game.html', 'w') as file:
    file.write(content_html)

19) 大家复制上述代码,粘贴到一个空的Python文件中再运行,就可以在当前路径看到Claude 3的生成的网页游戏代码文件game.html了。

备注:大模型输出的预期参考代码如下,大模型每次生成的内容可能略有差别。

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
  <title>Side-Scrolling Typing Game</title>
</head>
<body class="bg-gray-900 text-white">
  <div class="fixed top-4 right-4 text-2xl">Score: <span id="score">0</span></div>
  <div id="game" class="h-screen w-screen overflow-hidden relative">
    <div id="player" class="absolute bottom-10 left-10 w-8 h-8 bg-blue-500"></div>
  </div>
  <div id="word-input" class="fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white text-black p-4 rounded hidden">
    <input type="text" id="typed-word" class="border border-gray-300 rounded px-2 py-1 mb-2 w-full">
    <button id="submit-word" class="bg-blue-500 text-white px-4 py-2 rounded">Submit</button>
  </div>
  <script>
    const words = ['ability', 'able', 'about', 'above', 'accept', 'according', 'account', 'across', 'action', 'activity', 'actually', 'address', 'administration', 'admit', 'adult', 'affect', 'after', 'again', 'against', 'agency', 'agent', 'ago', 'agree', 'agreement', 'ahead', 'air', 'all', 'allow', 'almost', 'alone', 'along', 'already', 'also', 'although', 'always', 'American', 'among', 'amount', 'analysis', 'and', 'animal', 'another', 'answer', 'any', 'anyone', 'anything', 'appear', 'apply', 'approach', 'area', 'argue', 'arm', 'around', 'arrive', 'art', 'article', 'artist', 'as', 'ask', 'assume', 'at', 'attack', 'attention', 'attorney', 'audience', 'author', 'authority', 'available', 'avoid', 'away', 'baby', 'back', 'bad', 'bag', 'ball', 'bank', 'bar', 'base', 'be', 'beat', 'beautiful', 'because', 'become', 'bed', 'before', 'begin', 'behavior', 'behind', 'believe', 'benefit', 'best', 'better', 'between', 'beyond', 'big', 'bill', 'billion', 'bit', 'black', 'blood', 'blue', 'board', 'body', 'book', 'born', 'both', 'box', 'boy', 'break', 'bring', 'brother', 'budget', 'build', 'building', 'business', 'but', 'buy', 'by', 'call', 'camera', 'campaign'];

    let score = 0;
    let currentWord;
    let startTime;

    const game = document.getElementById('game');
    const player = document.getElementById('player');
    const wordInput = document.getElementById('word-input');
    const typedWord = document.getElementById('typed-word');
    const submitWord = document.getElementById('submit-word');
    const scoreDisplay = document.getElementById('score');

    let playerX = 10;
    let playerY = game.offsetHeight - 50;
    const speed = 5;

    function placeWord() {
      const word = document.createElement('div');
      word.textContent = words[Math.floor(Math.random() * words.length)];
      word.className = 'absolute text-2xl';
      word.style.left = `${game.offsetWidth + 10}px`;
      word.style.top = `${Math.random() * (game.offsetHeight - 50)}px`;
      game.appendChild(word);
      return word;
    }

    function checkCollision(word) {
      const playerRect = player.getBoundingClientRect();
      const wordRect = word.getBoundingClientRect();
      return !(
        playerRect.right < wordRect.left ||
        playerRect.left > wordRect.right ||
        playerRect.bottom < wordRect.top ||
        playerRect.top > wordRect.bottom
      );
    }

    function startInput(word) {
      currentWord = word.textContent;
      wordInput.style.display = 'block';
      typedWord.value = '';
      typedWord.focus();
      startTime = Date.now();
    }

    function endInput() {
      wordInput.style.display = 'none';
      const endTime = Date.now();
      const elapsedTime = endTime - startTime;
      const timeBonus = Math.max(2000 - elapsedTime, 0);
      score += Math.round(1000 + timeBonus);
      scoreDisplay.textContent = score;
    }

    function checkInput() {
      if (typedWord.value === currentWord) {
        endInput();
      }
    }

    function gameLoop() {
      playerY = Math.max(0, Math.min(playerY, game.offsetHeight - player.offsetHeight));
      playerX = Math.max(0, Math.min(playerX, game.offsetWidth - player.offsetWidth));
      player.style.top = `${playerY}px`;
      player.style.left = `${playerX}px`;

      const words = Array.from(document.querySelectorAll('#game > div:not(#player)'));
      words.forEach(word => {
        const currentLeft = parseInt(word.style.left);
        word.style.left = `${currentLeft - speed}px`;
        if (checkCollision(word)) {
          startInput(word);
        }
        if (currentLeft < -word.offsetWidth) {
          word.remove();
        }
      });

      if (Math.random() < 0.01) {
        placeWord();
      }

      requestAnimationFrame(gameLoop);
    }

    document.addEventListener('keydown', e => {
      if (e.key === 'w') playerY -= speed;
      if (e.key === 'a') playerX -= speed;
      if (e.key === 's') playerY += speed;
      if (e.key === 'd') playerX += speed;
    });

    typedWord.addEventListener('input', checkInput);
    submitWord.addEventListener('click', checkInput);

    gameLoop();
  </script>
</body>
</html>

21)在本地双击打开HTML文件后大家就可以愉快的玩游戏啦!

22)除了利用Claude 3 Opus生成网页小游戏之外,在Amazon Bedrock上大家还能找到利用Opus分析报表、制作企业官网等多个应用开发案例场景的代码,大家快去自己尝试吧!

2. 我该如何学习Amazon Bedrock?

说到学习Amazon Bedrock,快速上手AI大模型,学习目前最前沿的AI技术。小李哥想给大家推荐亚马逊云科技官方的免费课程平台Skill Builder, 该平台不仅包括超过600多门的在线课程帮助大家学习各类云服务,还包含了亚马逊云科技认证的备考课程、动手实验和练习题,帮助大家更容易地考取高含金量的云计算技能认证,为职场加速。

目前Skill Builder上已经上线了免费的中文版Amazon Bedrock学习课程,只需要1个小时,就能快速掌握Amazon Bedrock的理论知识、应用场景和实操步骤,中文课程更好的帮助小伙伴们掌握该服务,快速将AI技术应用于自己的工作中。该课程主要覆盖如下内容:

看过了课程的介绍,大家是不是很心动呢?扫描下方二维码就可以开启自己的AI之旅啦!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值