Qwen 3 系列

Qwen3 系列是阿里推出的新一代開源大模型,能力大幅躍升:在代碼理解、數學推理、多語言表達、複雜推斷任務上,比肩甚至超越了目前市面上的頂級模型(如 o1、DeepSeek-R1)。它的核心突破在于引入了「思考模式」與「非思考模式」切換機制,讓模型在面對不同難度任務時,自主調節推理深度,實現了速度與精度的雙優平衡。 旗艦版 Qwen3-235B 採用稀疏激活,僅用 22B 參數推理,兼顧成本和卓越能力。全系模型全面開源,涵蓋從輕量到超大規模需求。

1. 基礎用法: 用 OpenAI 兼容格式轉發。
2. 工具調用: 常規 Tools 調用支持 OpenAI 兼容格式(適用於 V2.5、V3),而 MCP Tools 依賴 qwen-agent,需要先運行指令安裝依賴:pip install -U qwen-agent mcp。 更多細節可以參考阿里官方文件

from openai import OpenAI

client = OpenAI(
    api_key="sk-***", # 🔑 換成你在 AiHubMix 生成的密鑰
    base_url="https://aihubmix.com/v1",
)

completion = client.chat.completions.create(
    model="Qwen/Qwen3-30B-A3B",
    messages=[
        {
            "role": "user",
            "content": "Explain the Occam's Razor concept and provide everyday examples of it"
        }
    ],
    stream=True
)

# 某些 chunk 物件可能沒有 choices 屬性或 choices 是一個空列表,處理方法:
for chunk in completion:
    if hasattr(chunk.choices, '__len__') and len(chunk.choices) > 0:
        if hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content is not None:
            print(chunk.choices[0].delta.content, end="")

QvQ、Qwen 2.5 和 QwQ 系列

用 OpenAI 的兼容格式轉發即可,區別在於流式調用的提取,需要剔除為空的 chunk.choices[0].delta.content,參考如下。

1. QvQ、Qwen 2.5 VL: 圖片認識
2. QwQ: 文本任務

Qwen/QVQ-72B-Preview 是基于 Qwen2-VL-72B 構建的开源多模態推理模型,专注于视觉推理和跨模態任务。

from openai import OpenAI
import base64
import os

client = OpenAI(
    api_key="sk-***", # 🔑 換成你在 AiHubMix 生成的密鑰
    base_url="https://aihubmix.com/v1",
)

image_path = "yourpath/file.png"

# 讀取並編碼圖片
def encode_image(image_path):
    if not os.path.exists(image_path):
        raise FileNotFoundError(f"圖片文件不存在:{image_path}")
    
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')

# 獲取圖片的 base64 編碼
base64_image = encode_image(image_path)

# 創建包含文本和圖像的消息
completion = client.chat.completions.create(
    model="qwen2.5-vl-72b-instruct", #qwen2.5-vl-72b-instruct 或 Qwen/QVQ-72B-Preview
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "請詳細描述這張圖片,包括圖片中的內容、風格和可能的含義。"},
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/png;base64,{base64_image}"
                    }
                }
            ]
        }
    ],
    stream=True
)

for chunk in completion:
    # 安全地檢查是否有內容
    if hasattr(chunk.choices, '__len__') and len(chunk.choices) > 0:
        if hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content is not None:
            print(chunk.choices[0].delta.content, end="")