hit-cxf
2026-04-04 8c486e7efa254bc11f7727ae2aa581b366b9ffa8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# -*- coding: utf-8 -*-
"""
Qwen LLM API 客户端(DashScope Generation API)
支持 qwen3.5-plus, qwen3.5-max 等模型
"""
 
import os
import time
import logging
from typing import Optional
 
logger = logging.getLogger(__name__)
 
try:
    import dashscope
    from dashscope import Generation
except ImportError:
    dashscope = None
    Generation = None
 
 
class QwenLLM:
    """
    Qwen LLM 客户端,使用 DashScope Generation API
    支持纯文本生成(可作为 LLM 使用)
    """
    def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None):
        """
        :param api_key: DashScope API Key
        :param base_url: DashScope API Base URL (可选)
        """
        self.api_key = api_key or os.getenv("DASHSCOPE_API_KEY")
        self.base_url = base_url or os.getenv("DASHSCOPE_BASE_URL", "https://dashscope.aliyuncs.com/api/v1")
 
        if not self.api_key:
            print("Warning: DASHSCOPE_API_KEY is not set.")
 
        if dashscope:
            dashscope.api_key = self.api_key
 
        self.max_attempts = 3
 
    def query(self, prompt: str, image_urls: list = None, model: str = "qwen3.5-vl", web_search: bool = False):
        """
        Query Qwen model for text generation.
        Note: This is for text-only LLM use. For image+text, use VLM client.
 
        :param prompt: Text prompt
        :param image_urls: Ignored in this LLM implementation (use VLM for multimodal)
        :param model: Model name (e.g., qwen3.5-vl, qwen3.5-plus, qwen3.5-max)
        :param web_search: If True, adds enable_search: True to API call
        """
        if dashscope is None:
            raise RuntimeError("dashscope package not installed. Run: pip install dashscope")
 
        if not model:
            model = "qwen3.5-vl"
 
        # Map common model names to DashScope API names
        model_mapping = {
            "qwen3.5-plus": "qwen-plus",
            "qwen3.5-max": "qwen-max",
            "qwen2.5-plus": "qwen-plus",
            "qwen2.5-max": "qwen-max",
        }
        api_model = model_mapping.get(model.lower(), model)
 
        messages = [{"role": "system", "content": "You are a helpful assistant."}]
        messages.append({"role": "user", "content": prompt})
 
        attempts = 0
        while attempts < self.max_attempts:
            try:
                # Build request parameters
                request_params = {
                    "model": api_model,
                    "messages": messages,
                    "result_format": "message",
                    "stream": False
                }
                # Add web search if enabled
                if web_search:
                    request_params["enable_search"] = True
 
                response = Generation.call(**request_params)
 
                if response.status_code == 200:
                    if response.output.choices and response.output.choices[0].message.content:
                        return response.output.choices[0].message.content
                    else:
                        print("Received an empty response from Qwen. Retrying.")
                        time.sleep(2)
                else:
                    error_msg = f"Qwen API error: {response.code} - {response.message}"
                    logger.error(error_msg)
                    raise RuntimeError(error_msg)
 
            except Exception as e:
                logger.error(f"Error occurred with Qwen: {e}. Retrying.")
                time.sleep(5)
 
            attempts += 1
 
        raise Exception("Max attempts reached, failed to get a response from Qwen.")
 
 
if __name__ == "__main__":
    import sys
    sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    from config import Config
 
    # 支持的模型列表
    MODELS = ["qwen3.5-plus", "qwen3.5-max"]
 
    print("=== Qwen LLM (DashScope) 可用性测试 ===")
    api_key = os.getenv("DASHSCOPE_API_KEY", "")
    if not api_key:
        print("✗ DASHSCOPE_API_KEY 未设置,跳过")
        sys.exit(1)
    print(f"  API Key: {api_key[:6]}***{api_key[-4:]}")
 
    client = QwenLLM(api_key=api_key)
    prompt = "用一句话介绍你自己。"
    print(f"  Prompt: {prompt}")
 
    for model in MODELS:
        print(f"\n--- 测试模型: {model} ---")
        t0 = time.time()
        try:
            resp = client.query(prompt, model=model)
            elapsed = time.time() - t0
            print(f"✓ 响应 ({elapsed:.1f}s): {resp.strip()[:200]}")
        except Exception as e:
            print(f"✗ 失败: {e}")