0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AWS初心者の勉強メモ:Bedrock(Llama3) を使って最小構成のAIチャットを作ってみた

0
Posted at

はじめに

AWS の勉強の一環で AI チャットを作ったのでメモ。
構成はAPI Gateway(WebSocket)+ Lambda + Bedrock。

全体構成

  • API Gateway(WebSocket)
    • WebSocket通信 でメッセージを受信した時Lambdaを呼び出す
  • Lambda(Python)
    1. メッセージを受信
    2. メッセージ内容でBedrock を呼び出す
    3. AI の返答を WebSocket 経由でブラウザに返す
  • Bedrock(Llama 3 8B)
    • AI が返答を生成
  • ブラウザの開発者ツール(クライアント側)
    • API GatewayとWebSocketで通信するために利用
[ブラウザ]
   │  ↑↓ WebSocket(リアルタイム)
   ▼
[API Gateway (WebSocket)]
   │  イベント
   ▼
[Lambda]
   │  AIに質問
   ▼
[Bedrock]

Lambda のコード(メッセージ受信時に呼び出し)

import json
import boto3
import os

bedrock = boto3.client("bedrock-runtime", region_name="us-west-2")

apigw = boto3.client(
    "apigatewaymanagementapi",
    endpoint_url=os.environ["WS_ENDPOINT"]
)

def lambda_handler(event, context):
    connection_id = event['requestContext']['connectionId']
    body = json.loads(event.get("body", "{}"))
    user_message = body.get("message", "")

    response = bedrock.converse(
        modelId="meta.llama3-8b-instruct-v1:0",
        messages=[
            {
                "role": "user",
                "content": [
                    {"text": user_message}
                ]
            }
        ],
        inferenceConfig={
            "maxTokens": 300
        }
    )

    reply = response["output"]["message"]["content"][0]["text"]
    apigw.post_to_connection(
        ConnectionId=connection_id,
        Data=json.dumps({"reply": reply}).encode("utf-8")
    )

    return {'statusCode': 200}

WebSocket のテスト(ブラウザで実施)

  1. WebSocket接続開始
const ws = new WebSocket("wss://hogehoge/hogehoge/");
ws.onopen = () => console.log("connected");
ws.onmessage = (e) => console.log("AI:", JSON.parse(e.data).reply);
  1. 接続成功
connected

3.メッセージ送信

ws.send(JSON.stringify({ message: "こんにちは" }));

4.レスポンス受信

AI:こんにちは!お元気ですか?

まとめ

以下で 最小構成の AI チャットが作れる。

  • WebSocket(API Gateway)
  • Lambda(Python)
  • Bedrock(Llama3)
  • ブラウザ(Console)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?