LoginSignup
1
0

LangChainでOpenAIのGPT-4oモデルを使って画像を読み込ませる

Posted at

概要

OpenAIの最新モデルであるGPT-4oはすごいですね、速くて頭が良くなってます。
画像を読み込ませてLLMに評価させるアレ、LangChainでどうするの?が分からなかったので試してみました。

コード

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.prompts.chat import HumanMessagePromptTemplate
import base64
import os

os.environ["OPENAI_API_KEY"] = "<ここにAPIキーを入れる>"

#プロキシを使う場合
#os.environ['http_proxy'] = 'http://127.0.0.1:8080'
#os.environ['https_proxy'] = 'http://127.0.0.1:8080'

#画像ファイルをbase64エンコードする
def encode_image(image_path):
  with open(image_path, "rb") as image_file:
    return base64.b64encode(image_file.read()).decode('utf-8')


image_path = "<読み込ませるファイルをここで指定する>"
base64_image = encode_image(image_path)

#本当はImagePromptTemplateを使いたいが
image_template = {"image_url": {"url": f"data:image/png;base64,{base64_image}"}}

chat = ChatOpenAI(temperature=0, model_name="gpt-4o-2024-05-13")

system = (
    "あなたは有能なアシスタントです。ユーザーの問いに回答してください"
)

human_prompt = "{question}"
human_message_template = HumanMessagePromptTemplate.from_template([human_prompt, image_template])

prompt = ChatPromptTemplate.from_messages([("system", system), human_message_template])

chain = prompt | chat
result = chain.invoke({"question": "この画像は何の絵ですか?"})
print(result)

結果

画像を読み込んで、質問に回答してくれました。画像の解析は数秒かかります。

content='この画像は、かわいらしいキャラクターのイラストです。キャラクターは犬のように見え、白いシャツに青いサスペンダー 付きのズボンを着ており、ピンクの蝶ネクタイをしています。耳にはハートのマークが描かれています。' response_metadata={'token_usage': {'completion_tokens': 73, 'prompt_tokens': 294, 'total_tokens': 367}, 'model_name': 'gpt-4o-2024-05-13', 'system_fingerprint': 'fp_c45f7d0b45', 'finish_reason': 'stop', 'logprobs': None} id='run-187bd6c9-cdfc-4c02-a1ed-71fb82b8b3a1-0'
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