返回 VideoClaw
vlm_dashscope.py
根目录 / video-claw / video-claw / backend / models / vlm_dashscope.py
1 # -*- coding: utf-8 -*-
2 """
3 Qwen3.5-VL 多模态大模型 API 客户端(DashScope 多模态接口专用)
4 只支持 Qwen3.5-VL 及兼容 DashScope 多模态对话接口
5 参考官方文档:https://help.aliyun.com/zh/model-studio/qwen-api-reference
6 """
7
8 import os
9 import sys
10
11 models_dir = os.path.dirname(os.path.abspath(__file__))
12 backend_dir = os.path.dirname(models_dir)
13 if backend_dir not in sys.path:
14 sys.path.insert(0, backend_dir)
15
16
17 import dashscope
18 from dashscope import MultiModalConversation
19 import logging
20
21 logger = logging.getLogger(__name__)
22 from typing import Any, Dict, List, Optional
23 from config import Config
24
25 class QwenVLClient:
26 def __init__(self,
27 api_key: Optional[str] = None,
28 base_url: Optional[str] = None):
29 """
30 Qwen3.5-VL 多模态客户端
31 :param api_key: DashScope/Qwen3.5 API Key
32 :param model: 模型名(如 qwen3.5-plus/qwen3.5-max 等)
33 """
34 self.api_key = api_key or Config.DASHSCOPE_API_KEY
35
36 def chat(self, text: str, images: List[str], model: str, stream: bool = False, parameters: Optional[Dict] = None, **kwargs) -> Any:
37 """
38 使用阿里云 dashscope SDK 进行多模态对话(文本+图片),风格与 image_dashscope.py 一致。
39 :param text: 文本内容
40 :param images: 图片路径列表(支持本地路径或URL,内部会转换为file://绝对路径)
41 :param model: 模型名(支持qwen3.5-plus, qwen3-vl-plus)
42 :param stream: 是否流式输出(暂不支持流式)
43 :param parameters: 其他API参数
44 :return: API响应内容 dict
45 """
46 dashscope.api_key = self.api_key
47 # 只支持非流式
48 try:
49 messages = [{"role": "user", "content": [
50 {"text": text},
51 *({"image": p} for p in images)
52 ]}]
53 response = MultiModalConversation.call(
54 model=model,
55 messages=messages,
56 api_key=self.api_key,
57 enable_thinking=False,
58 **(parameters or {})
59 )
60 if hasattr(response, 'status_code') and response.status_code == 200:
61 # qwen3.5-plus 的返回格式为 { choices: [ { message: { content: [...] } } ] }
62 resp = response.output.choices[0].message.content[0]
63 if resp.get('text'):
64 return resp['text']
65 return resp
66 else:
67 raise RuntimeError(f"DashScope QwenVLClient failed: {getattr(response, 'message', response)}")
68 except Exception as e:
69 raise RuntimeError(f"DashScope QwenVLClient error: {e}")
70
71
72 if __name__ == "__main__":
73 import sys
74 import time
75 import json
76 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
77 from config import Config
78
79 # 支持的 VLM 模型列表
80 MODELS = ["qwen3.7-plus", "qwen3.6-plus", "qwen3.6-flash", "qwen3.5-plus", "kimi-k2.6"]
81
82 print("=== Qwen VL (DashScope) 多模态可用性测试 ===")
83 api_key = Config.DASHSCOPE_API_KEY
84 if not api_key:
85 print("✗ DASHSCOPE_API_KEY 未设置,跳过")
86 sys.exit(1)
87 print(f" API Key: {api_key[:6]}***{api_key[-4:]}")
88 client = QwenVLClient(api_key=api_key)
89
90 # 测试图片
91 img_path = ''
92 abs_img_path = os.path.abspath(img_path)
93 if not os.path.exists(img_path):
94 img_path = "code/result/image/test_avail/test_input.png"
95 abs_img_path = os.path.abspath(img_path)
96 if not os.path.exists(img_path):
97 print("✗ 测试图片不存在,跳过")
98 sys.exit(0)
99
100 text = "请描述这张图片的内容"
101 print(f"\n[多模态] Prompt: {text}")
102 print(f" 图片: {img_path}")
103
104 for model in MODELS:
105 print(f"\n--- 测试模型: {model} ---")
106 t0 = time.time()
107 try:
108 result = client.chat(text=text, images=[img_path], model=model, stream=False)
109 elapsed = time.time() - t0
110 if result:
111 print(f"✓ 返回结果 ({elapsed:.1f}s): {str(result)[:200]}")
112 else:
113 print(f"✗ 返回空结果 ({elapsed:.1f}s)")
114 except Exception as e:
115 print(f"✗ 失败: {e}")
116
116 lines PYTHON