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?

LangChain1.0の気になるトピックをDatabricks Free Editionで検証: マルチモーダル対応エージェント

Posted at

はじめに

LangChain 1.0がリリースされました。
詳細は以下の公式Blogを確認ください。

主な変化点は以下のドキュメントにも掲載されています。

ドキュメント含めて大きく変更されており、またαリリースの際よりも組み込みMiddlewareも増えてましたので、個人的に気になる内容をピックアップしてDatabricks Free Edition上で検証していきます。


この記事では、あまり新機能とは関係ないのですが「マルチモーダルエージェント」を扱います。

画像や音声などを入出力として扱うエージェントのことですが、今回はテキスト+画像を入力に使うエージェントのサンプルを作成して実行します。

マルチモーダルエージェントの作成と実行

Databricksでは、先日いくつかの基盤モデルで画像入力が可能になりました。

そのうち、databricks-gemma-3-12bを使って画像入力が可能なエージェントを作成します。

まずはノートブックを作成して必要なパッケージをインストール。
TracingのためにMLflowもインストールします。

%pip install -U langchain>=1.0.0 langchain_openai>=1.0.0 mlflow

%restart_python

次に利用するモデルをセットアップします。

from langchain.chat_models import init_chat_model
import mlflow

mlflow.langchain.autolog()

creds = mlflow.utils.databricks_utils.get_databricks_host_creds()
model = init_chat_model(
    "openai:databricks-gemma-3-12b",
    api_key=creds.token,
    base_url=creds.host + "/serving-endpoints",
)

入力する画像データをロードします。
サンプルとしてGemini 2.5 Flash Imageで生成した以下の猫イラストを利用します。(かわいい)

image.png

import base64

with open("sample.png", "rb") as image_file:
    image_data = base64.b64encode(image_file.read()).decode("utf-8")

今回の重点。
単純なエージェントを作成し、画像およびテキストでのクエリを実行します。

LangChain1.0で画像をエージェントに渡すには、コード内のようにメッセージのコンテンツに含める形で渡します。

from langchain.agents import create_agent
from langchain_core.messages import AIMessageChunk, HumanMessage
from pprint import pprint

agent = create_agent(
    model=model,
    tools=[], # ツールの指定は今回無し
    system_prompt="You are a helpful assistant",
)

# メッセージのコンテンツに画像データを加える
human_message = HumanMessage(
    content=[
        {"type": "text", "text": "この画像を説明して"},
        {
            "type": "image",
            "base64": image_data,
            "mime_type": "image/png",
        },
    ],
)
input = {"messages": [human_message]}
result = agent.invoke(input)

print(result["messages"][-1].content)

実行結果は以下の通り。

出力
こちらが画像の記述です。

この画像は、カワイイアニメスタイルのイラストです。

**主要な要素:**

*   **猫:** 茶色と白の縞模様の小さな猫が、楽しそうな表情をしています。
*   **カップ:** 猫は、ピンクと白の模様が描かれた大きなカップの中に座っています。カップは縁に金色の装飾があります。
*   **背景:** カップの周りには、ピンクと黄色の雲、星、泡、魚、ハート型の木々などの要素が描かれた、カワイイ雰囲気の背景があります。

**全体的な雰囲気:**

画像の全体的な雰囲気は、夢のように愉快で、子供らしいものです。鮮やかな色とデフォルメされた形が、このイメージをより魅力的で魅力的にしています。

ちゃんと認識していますね。

まとめ

LangChainエージェントの入力に画像を用いる、マルチモーダルなエージェントを試しました。
エージェントの作り方は通常と同じであり、メッセージ内に画像データを含めるだけで(利用するモデルがマルチモーダル対応していれば)利用できます。

主要なLLM APIは概ねマルチモーダル対応が当たり前になってきていますので、エージェント統合が容易なのはありがたいですね。

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?