mcpField
V
VLM

VLM

github.com/answerzhao開発26343 回インストール41 週間前に更新
リポジトリ

VLM について

VLM は、z-ai-web-dev-sdk を使って画像とテキストのチャット機能を開発するためのガイドです。SDK はバックエンドでのみ使用し、z-ai CLI による簡易分析や、複数ターンの対話とバッチ処理にも対応します。

主な機能

  1. 01画像とテキストの同時分析
  2. 02複数画像の入力
  3. 03画像・動画・ドキュメントの入力
  4. 04複数ターンのビジョンチャット
  5. 05CLI のストリーミングと結果保存
  6. 06OCR、分類、画像タグ付け

活用シーン

  1. 01商品画像からの情報抽出
  2. 02領収書やフォームの文字読み取り
  3. 03画像の代替テキスト生成
  4. 04画像の一括分析や比較

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/answerzhao/agent-skills --skill vlm

インストール後、Claude Code で/vlmを入力して読み込まれたか確認します。

同梱ファイルLICENSE.txtscripts/vlm.ts

詳細

VLM(Vision Chat)スキル

このスキルは、z-ai-web-dev-sdk パッケージを使用したビジョンチャット機能の実装をガイドし、AI モデルが画像とテキストプロンプトを組み合わせて理解し応答できるようにします。

スキルのパス

スキルの場所: {project_path}/skills/VLM

このスキルは、プロジェクト内の上記のパスに配置されています。

参照スクリプト: 迅速なテストと参照用のサンプルテストスクリプトが {Skill Location}/scripts/ ディレクトリに用意されています。動作する例については {Skill Location}/scripts/vlm.ts を参照してください。

概要

Vision Chat を使用すると、画像を分析し、視覚的なコンテンツから情報を抽出し、自然言語の会話を通じて画像に関する質問に回答できるアプリケーションを構築できます。

重要: z-ai-web-dev-sdk はバックエンドコードでのみ使用する必要があります。クライアントサイドのコードでは決して使用しないでください。

前提条件

z-ai-web-dev-sdk パッケージはすでにインストールされています。以下の例に示すようにインポートしてください。

CLI の使用方法(簡単なタスク向け)

簡単な画像分析タスクでは、コードを書く代わりに z-ai CLI を使用できます。これは、迅速な画像の説明、ビジョン機能のテスト、または簡単な自動化に最適です。

基本的な画像分析
# Describe an image from URL
z-ai vision --prompt "What's in this image?" --image "https://example.com/photo.jpg"

# Using short options
z-ai vision -p "Describe this image" -i "https://example.com/image.png"
ローカル画像の分析
# Analyze a local image file
z-ai vision -p "What objects are in this photo?" -i "./photo.jpg"

# Save response to file
z-ai vision -p "Describe the scene" -i "./landscape.png" -o description.json
複数の画像
# Analyze multiple images at once
z-ai vision \
  -p "Compare these two images" \
  -i "./photo1.jpg" \
  -i "./photo2.jpg" \
  -o comparison.json

# Multiple images with detailed analysis
z-ai vision \
  --prompt "What are the differences between these images?" \
  --image "https://example.com/before.jpg" \
  --image "https://example.com/after.jpg"
思考あり(Chain of Thought)
# Enable thinking for complex visual reasoning
z-ai vision \
  -p "Count the number of people in this image and describe their activities" \
  -i "./crowd.jpg" \
  --thinking \
  -o analysis.json
ストリーミング出力
# Stream the vision analysis
z-ai vision -p "Describe this image in detail" -i "./photo.jpg" --stream
CLI パラメータ
  • --prompt, -p <text>: 必須 - 画像に関する質問または指示
  • --image, -i <URL or path>: オプション - 画像の URL またはローカルファイルパス(複数回使用できます)
  • --thinking, -t: オプション - 思考の連鎖(chain-of-thought)推論を有効にします(デフォルト: 無効)
  • --output, -o <path>: オプション - 出力ファイルパス(JSON 形式)
  • --stream: オプション - レスポンスをリアルタイムでストリーミングします
対応画像形式
  • PNG (.png)
  • JPEG (.jpg, .jpeg)
  • GIF (.gif)
  • WebP (.webp)
  • BMP (.bmp)
CLI と SDK の使い分け

CLI を使用する場合:

  • 迅速な画像分析
  • ビジョンモデルの機能のテスト
  • 単発の画像の説明
  • 簡単な自動化スクリプト

SDK を使用する場合:

  • 画像を用いたマルチターンの会話
  • アプリケーション内での動的な画像分析
  • カスタムロジックによるバッチ処理
  • 複雑なワークフローを伴う本番アプリケーション

推奨されるアプローチ

より良いパフォーマンスと信頼性のために、画像 URL ではなく base64 エンコーディングを使用して画像をモデルに渡してください。

対応コンテンツタイプ

Vision Chat API は 3 種類のメディアコンテンツをサポートしています:

1. image_url - 画像ファイル用

静的画像(PNG、JPEG、GIF、WebP など)にはこのタイプを使用します。

{
    role: 'user',
    content: [
        { type: 'text', text: prompt },
        { type: 'image_url', image_url: { url: imageUrl } }
    ]
}
2. video_url - 動画ファイル用

動画コンテンツ(MP4、AVI、MOV など)にはこのタイプを使用します。

{
    role: 'user',
    content: [
        { type: 'text', text: prompt },
        { type: 'video_url', video_url: { url: videoUrl } }
    ]
}
3. file_url - ドキュメントファイル用

ドキュメントファイル(PDF、DOCX、TXT など)にはこのタイプを使用します。

{
    role: 'user',
    content: [
        { type: 'text', text: prompt },
        { type: 'file_url', file_url: { url: fileUrl } }
    ]
}

注意: 1 つのメッセージ内で複数のコンテンツタイプを組み合わせることができます。たとえば、テキストと複数の画像を含めたり、テキストと画像およびドキュメントの両方を含めたりできます。

基本的な Vision Chat の実装

単一画像の分析
import ZAI from 'z-ai-web-dev-sdk';

async function analyzeImage(imageUrl, question) {
  const zai = await ZAI.create();

  const response = await zai.chat.completions.createVision({
    messages: [
      {
        role: 'user',
        content: [
          {
            type: 'text',
            text: question
          },
          {
            type: 'image_url',
            image_url: {
              url: imageUrl
            }
          }
        ]
      }
    ],
    thinking: { type: 'disabled' }
  });

  return response.choices[0]?.message?.content;
}

// Usage
const result = await analyzeImage(
  'https://example.com/product.jpg',
  'Describe this product in detail'
);
console.log('Analysis:', result);
複数画像の分析
import ZAI from 'z-ai-web-dev-sdk';

async function compareImages(imageUrls, question) {
  const zai = await ZAI.create();

  const content = [
    {
      type: 'text',
      text: question
    },
    ...imageUrls.map(url => ({
      type: 'image_url',
      image_url: { url }
    }))
  ];

  const response = await zai.chat.completions.createVision({
    messages: [
      {
        role: 'user',
        content: content
      }
    ],
    thinking: { type: 'disabled' }
  });

  return response.choices[0]?.message?.content;
}

// Usage
const comparison = await compareImages(
  [
    'https://example.com/before.jpg',
    'https://example.com/after.jpg'
  ],
  'Compare these two images and describe the differences'
);
Base64 画像のサポート
import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';

async function analyzeLocalImage(imagePath, question) {
  const zai = await ZAI.create();

  // Read image file and convert to base64
  const imageBuffer = fs.readFileSync(imagePath);
  const base64Image = imageBuffer.toString('base64');
  const mimeType = imagePath.endsWith('.png') ? 'image/png' : 'image/jpeg';

  const response = await zai.chat.completions.createVision({
    messages: [
      {
        role: 'user',
        content: [
          {
            type: 'text',
            text: question
          },
          {
            type: 'image_url',
            image_url: {
              url: `data:${mimeType};base64,${base64Image}`
            }
          }
        ]
      }
    ],
    thinking: { type: 'disabled' }
  });

  return response.choices[0]?.message?.content;
}

高度なユースケース

会話形式の Vision Chat
import ZAI from 'z-ai-web-dev-sdk';

class VisionChatSession {
  constructor() {
    this.messages = [];
  }

  async initialize() {
    this.zai = await ZAI.create();
  }

  async addImage(imageUrl, initialQuestion) {
    this.messages.push({
      role: 'user',
      content: [
        {
          type: 'text',
          text: initialQuestion
        },
        {
          type: 'image_url',
          image_url: { url: imageUrl }
        }
      ]
    });

    return this.getResponse();
  }

  async followUp(question) {
    this.messages.push({
      role: 'user',
      content: [
        {
          type: 'text',
          text: question
        }
      ]
    });

    return this.getResponse();
  }

  async getResponse() {
    const response = await this.zai.chat.completions.createVision({
      messages: this.messages,
      thinking: { type: 'disabled' }
    });

    const assistantMessage = response.choices[0]?.message?.content;
    
    this.messages.push({
      role: 'assistant',
      content: assistantMessage
    });

    return assistantMessage;
  }
}

// Usage
const session = new VisionChatSession();
await session.initialize();

const initial = await session.addImage(
  'https://example.com/chart.jpg',
  'What does this chart show?'
);
console.log('Initial analysis:', initial);

const followup = await session.followUp('What are the key trends?');
console.log('Follow-up:', followup);
画像の分類とタグ付け
import ZAI from 'z-ai-web-dev-sdk';

async function classifyImage(imageUrl) {
  const zai = await ZAI.create();

  const prompt = `Analyze this image and provide:
1. Main subject/category
2. Key objects detected
3. Scene description
4. Suggested tags (comma-separated)

Format your response as JSON.`;

  const response = await zai.chat.completions.createVision({
    messages: [
      {
        role: 'user',
        content: [
          {
            type: 'text',
            text: prompt
          },
          {
            type: 'image_url',
            image_url: { url: imageUrl }
          }
        ]
      }
    ],
    thinking: { type: 'disabled' }
  });

  const content = response.choices[0]?.message?.content;
  
  try {
    return JSON.parse(content);
  } catch (e) {
    return { rawResponse: content };
  }
}
OCR とテキスト抽出
import ZAI from 'z-ai-web-dev-sdk';

async function extractText(imageUrl) {
  const zai = await ZAI.create();

  const response = await zai.chat.completions.createVision({
    messages: [
      {
        role: 'user',
        content: [
          {
            type: 'text',
            text: 'Extract all text from this image. Preserve the layout and formatting as much as possible.'
          },
          {
            type: 'image_url',
            image_url: { url: imageUrl }
          }
        ]
      }
    ],
    thinking: { type: 'disabled' }
  });

  return response.choices[0]?.message?.content;
}

ベストプラクティス

1. 画像の品質とサイズ
  • より良い分析結果を得るために高品質の画像を使用してください
  • 品質と処理速度のバランスを取るために画像サイズを最適化してください
  • 対応形式: JPEG、PNG、WebP
2. プロンプトエンジニアリング
  • 画像から必要な情報について具体的に指定してください
  • 複雑なリクエストは番号付きリストや箇条書きで構造化してください
  • 画像の種類(写真、図、グラフなど)に関するコンテキストを提供してください
3. エラー処理
async function safeVisionChat(imageUrl, question) {
  try {
    const zai = await ZAI.create();
    
    const response = await zai.chat.completions.createVision({
      messages: [
        {
          role: 'user',
          content: [
            { type: 'text', text: question },
            { type: 'image_url', image_url: { url: imageUrl } }
          ]
        }
      ],
      thinking: { type: 'disabled' }
    });

    return {
      success: true,
      content: response.choices[0]?.message?.content
    };
  } catch (error) {
    console.error('Vision chat error:', error);
    return {
      success: false,
      error: error.message
    };
  }
}
4. パフォーマンスの最適化
  • 複数の画像を処理する際は SDK インスタンスの生成をキャッシュしてください
  • 適切な画像形式を使用してください(写真には JPEG、図には PNG)
  • 大量のバッチ処理では画像の前処理を検討してください
5. セキュリティに関する考慮事項
  • 処理前に画像 URL を検証する
  • ユーザーが提供した画像データをサニタイズする
  • 公開向け API にはレート制限を実装する
  • クライアント側のコードに SDK の認証情報を絶対に露出させない

一般的なユースケース

  1. 商品分析: E コマースアプリケーション向けに商品画像を分析する
  2. ドキュメント理解: レシート、請求書、フォームから情報を抽出する
  3. 医療画像: 予備的な分析を支援する(適切な免責事項を含める)
  4. 品質管理: 製造工程における欠陥や異常を検出する
  5. コンテンツモデレーション: ポリシー準拠のために画像を分析する
  6. アクセシビリティ: 画像の代替テキストを自動生成する
  7. ビジュアル検索: 検索機能のために画像を理解して分類する

統合の例

Express.js API エンドポイント
import express from 'express';
import ZAI from 'z-ai-web-dev-sdk';

const app = express();
app.use(express.json());

let zaiInstance;

// Initialize SDK once
async function initZAI() {
  zaiInstance = await ZAI.create();
}

app.post('/api/analyze-image', async (req, res) => {
  try {
    const { imageUrl, question } = req.body;

    if (!imageUrl || !question) {
      return res.status(400).json({ 
        error: 'imageUrl and question are required' 
      });
    }

    const response = await zaiInstance.chat.completions.createVision({
      messages: [
        {
          role: 'user',
          content: [
            { type: 'text', text: question },
            { type: 'image_url', image_url: { url: imageUrl } }
          ]
        }
      ],
      thinking: { type: 'disabled' }
    });

    res.json({
      success: true,
      analysis: response.choices[0]?.message?.content
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

initZAI().then(() => {
  app.listen(3000, () => {
    console.log('Vision chat API running on port 3000');
  });
});

トラブルシューティング

問題: 「SDK must be used in backend」

  • 解決策: z-ai-web-dev-sdk がサーバー側のコードでのみインポートされ使用されていることを確認してください

問題: 画像が読み込まれない、または分析されない

  • 解決策: 画像 URL にアクセス可能で、有効な画像形式を返すことを確認してください

問題: 分析品質が低い

  • 解決策: より具体的なプロンプトを提供し、画像品質が十分であることを確認してください

問題: 応答時間が遅い

  • 解決策: 画像サイズを最適化し、頻繁に分析される画像のキャッシュを検討してください

覚えておくこと

  • z-ai-web-dev-sdk は常にバックエンドコードでのみ使用してください
  • SDK はすでにインストールされています - 例に示すようにインポートしてください
  • 最良の結果を得るためにプロンプトを明確に構成してください
  • 本番アプリケーションではエラーを適切に処理してください
  • 画像を処理する際はユーザーのプライバシーを考慮してください

コメント