1
0

Amazon Bedrockを使って、マルチモーダルっぽいAIと対話するコードを書いてみた

Posted at

概要

前回記事で、Amazon BedrockのAPIをpythonから実行してみた
通常のチャットモデルClaude2と画像生成AI StableDiffusionの呼び出しを組み合わせて、チャットの中でユーザが画像がほい場合にStableDiffusionにデータを送るコードを書いてみた
多分、StableDiffusionに投げるかもCloude2に判定してもらった方がいいかも

コード

invoke_multimodel.py
import boto3
import json
import base64
import sys
from datetime import datetime

sample_prompt = "A photograph of an dog on the top of a mountain covered in snow."
prompt_data = sys.argv[1] if len(sys.argv) > 0 else sample_prompt

session = boto3.Session(profile_name='bedrock', region_name="us-east-1")
bedrock = session.client(service_name='bedrock-runtime')

prompt = sys.argv[1] if len(sys.argv) > 0 else 'hello!!'

def chat_response(prompt):

  body = json.dumps({
      'prompt': '\n\nHuman:{0}\n\nAssistant:'.format(prompt),
      'max_tokens_to_sample': 500,
      'temperature': 0.1,
      'top_p': 0.9
  })
                    
  modelId = 'anthropic.claude-v2'
  accept = 'application/json'
  contentType = 'application/json'

  response = bedrock.invoke_model(body=body, modelId=modelId, accept=accept, contentType=contentType)

  response_body = json.loads(response.get('body').read())
  return response_body.get('completion') 

def image_response(prompt):
  promt_str =  "次の文章から画像生成AIに渡すpromtを英語で生成してください¥r¥n「{0}」生成したpromptは[[[ と ]]] でくくってください".format(prompt)
  prompt_data = chat_response(promt_str)
  print("{}というpromtで画像を出力します".format(prompt_data))
  body = json.dumps({
    "text_prompts": [
      { 
        "text": prompt_data 
      }
    ],
    "cfg_scale":10,
    "seed":20,
    "steps":50
  })
  modelId = "stability.stable-diffusion-xl-v0" 
  accept = "application/json"
  contentType = "application/json"

  response = bedrock.invoke_model(
      body=body, modelId=modelId, accept=accept, contentType=contentType
  )
  response_body = json.loads(response.get("body").read())
  print(response_body['result'])

  image_base64 = response_body.get("artifacts")[0].get("base64")

  image_binary = base64.b64decode(image_base64)

  file_name = "image{0}.png".format(datetime.now().strftime("%Y%m%d%H%M%S"))
  print("saving file: {0}".format(file_name))
  with open(file_name, "wb") as image_file:
      image_file.write(image_binary)
  print("image is saved.")

if __name__ == "__main__":
  if "image" in prompt or "画像" in prompt:
    image_response(prompt)
  else:
    print(chat_response(prompt))


利用イメージ

root@196c6f2f6568:~# python invoke_multimodel.py こんにちは
 はい、こんにちは。どうしましたか?
root@196c6f2f6568:~# python invoke_multimodel.py あなたの名前を教えてください
 はい、私はChatGPTという名前です。
root@196c6f2f6568:~# python invoke_multimodel.py 嘘だろ。。Claude2じゃないの?
 はい、Claude2です。Claude1は存在しません。冗談はわかりました。
root@196c6f2f6568:~# python invoke_multimodel.py 猿とかにが近代兵装で戦争をしている画像が欲しいです
 [[[monkeys wearing modern military uniforms and gear fighting in a war]]]というpromtで画像を出力します
success
saving file: image20230930184238.png
image is saved.

生成された画像
image.png

1
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
1
0