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?

【langchain】ChatPromptTemplateで画像を受け取る

Posted at

コード

langchain v0.3で検証。
ChatPromptTemplate.from_messagesに渡すlistのtuple要素の2つめをリストにすれば良い。

from langchain.prompts import ChatPromptTemplate

messages = [
    (
        "user",
        [
            {"type": "text", "text": "{question}"},
            {
                "type": "image_url",
                "image_url": {"url": "data:image/jpeg;base64,{base64_image}"},
            },
        ],
    ),
]

# チェインの作成
prompt = ChatPromptTemplate.from_messages(messages)

print(prompt.format_messages(question="質問", base64_image="test"))
[HumanMessage(content=[{'type': 'text', 'text': '質問'}, {'type': 'image_url', 'image_url': {'url': 'data:image/jpeg;base64,test'}}], additional_kwargs={}, response_metadata={})]

以下のようにチェインにも渡せる。

import base64

import dotenv
import httpx
from langchain.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

dotenv.load_dotenv()

messages = [
    (
        "user",
        [
            {"type": "text", "text": "{question}"},
            {
                "type": "image_url",
                "image_url": {"url": "data:image/jpeg;base64,{base64_image}"},
            },
        ],
    ),
]

prompt = ChatPromptTemplate.from_messages(messages)


print(prompt.format_messages(question="質問", base64_image="test"))


model = ChatOpenAI(model="gpt-4o-mini")

chain = prompt | model

image_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
image_data = base64.b64encode(httpx.get(image_url).content).decode("utf-8")

print(chain.invoke({"question": "画像の天気は?", "base64_image": image_data}))
画像の天気は、青空に白い雲が浮かんでいるように見えます。全体的に明るく、穏やかな気候の印象を受けます。湿地や草原が広がっているため、自然の美しさを感じられそうです。
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?