关于 VLM
VLM 技能指导开发者使用 z-ai-web-dev-sdk 构建图像与文本对话功能,并要求 SDK 仅在后端使用。指南也介绍 z-ai 命令行用于快速图像分析,以及多轮对话和批处理等 SDK 场景。
主要功能
- 01图像与文本联合分析
- 02支持多图输入
- 03图像、视频和文档内容输入
- 04多轮视觉对话
- 05命令行流式输出与保存结果
- 06OCR、分类和图像标注
适用场景
- 01为商品图片提取信息
- 02从收据和表单识别文本
- 03生成图片替代文本
- 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,其中提供了可运行的示例。
概述
视觉聊天支持你构建能够分析图像、从视觉内容中提取信息,并通过自然语言对话回答有关图像的问题的应用程序。
重要: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"
启用思考(思维链)
# 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:可选 - 启用思维链推理(默认:禁用)--output, -o <path>:可选 - 输出文件路径(JSON 格式)--stream:可选 - 实时流式传输响应
支持的图像格式
- PNG (.png)
- JPEG (.jpg, .jpeg)
- GIF (.gif)
- WebP (.webp)
- BMP (.bmp)
何时使用 CLI 或 SDK
适用于 CLI 的场景:
- 快速分析图像
- 测试视觉模型能力
- 一次性生成图像描述
- 简单的自动化脚本
适用于 SDK 的场景:
- 使用图像进行多轮对话
- 在应用程序中动态分析图像
- 使用自定义逻辑进行批量处理
- 具有复杂工作流的生产应用程序
推荐方法
为获得更好的性能和可靠性,请使用 base64 编码将图像传递给模型,而不是使用图像 URL。
支持的内容类型
视觉聊天 API 支持三种媒体内容类型:
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 } }
]
}
注意:你可以在一条消息中组合多种内容类型。例如,你可以同时包含文本和多张图像,或者包含文本、图像和文档。
基本视觉聊天实现
单张图像分析
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;
}
高级用例
对话式视觉聊天
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 凭据
常见用例
- 产品分析:分析电子商务应用中的产品图像
- 文档理解:从收据、发票和表单中提取信息
- 医学影像:协助进行初步分析(需提供适当免责声明)
- 质量控制:检测制造过程中的缺陷或异常
- 内容审核:分析图像是否符合政策要求
- 无障碍访问:自动为图像生成替代文本
- 视觉搜索:理解并分类图像,为搜索功能提供支持
集成示例
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 已安装,按示例所示导入即可
- 清晰地组织提示词,以获得最佳效果
- 在生产应用中妥善处理错误
- 处理图像时应考虑用户隐私