qwen-adpter.py 21.9 KB
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 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
"""
阿里云百炼(DashScope)模型调用示例库
=========================================
本文件演示通过 DashScope SDK 和 OpenAI 兼容接口调用阿里云百炼模型的各种方式。

使用方法:
  1. 安装依赖
     pip install dashscope openai

  2. 设置环境变量(推荐,不要硬编码 API Key)
     set DASHSCOPE_API_KEY=sk-xxx

  3. 运行某个示例
     python qwen-adpter.py

注意事项:
  - 所有示例均从环境变量 DASHSCOPE_API_KEY 读取 API Key
  - 不同地域的 API Key 不同,base_url 也需对应修改
  - 中国内地使用 dashscope.aliyuncs.com,新加坡使用 dashscope-intl.aliyuncs.com
  - 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
"""

import os
import json
from http import HTTPStatus

import dashscope
from dashscope import Generation, MultiModalConversation, ImageSynthesis

# ============================================================
# 全局配置
# ============================================================
DASHSCOPE_API_KEY = os.environ.get("DASHSCOPE_API_KEY", "")
# 中国内地地域,如使用新加坡地域请改为:
# dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
dashscope.base_http_api_url = "https://dashscope.aliyuncs.com/api/v1"


def _print_response(title: str, response):
    """辅助函数:打印响应结果"""
    print(f"\n{'='*60}")
    print(f"  {title}")
    print(f"{'='*60}")
    if response.status_code == HTTPStatus.OK:
        content = response.output.choices[0].message.content
        print(f"  响应内容:{content}")
        print(f"  用量:{dict(response.usage)}" if hasattr(response, 'usage') else "")
    else:
        print(f"  错误:code={response.code}, message={response.message}")
    print(f"{'='*60}\n")


# ============================================================
# 1. 非流式文本生成(最常用方式)
# ============================================================
def example_non_streaming():
    """DashScope SDK 非流式调用

    适用于大多数对话、问答、翻译等场景。
    请求发送后阻塞等待完整响应返回。
    """
    messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "你是谁?"},
    ]
    response = Generation.call(
        api_key=DASHSCOPE_API_KEY,
        model="qwen-plus",  # 可选:qwen-turbo, qwen-plus, qwen-max, qwen3-max
        messages=messages,
        result_format="message",  # message 格式返回结构化结果
        temperature=0.7,          # 控制随机性 [0, 2),默认 0.7
        max_tokens=2048,          # 最大输出 token 数
        top_p=0.8,                # 核采样阈值,默认 0.8
    )
    _print_response("1. 非流式文本生成", response)


# ============================================================
# 2. 流式文本生成(逐 token 输出)
# ============================================================
def example_streaming():
    """DashScope SDK 流式调用

    模型每生成一个 token 就立即返回,适合实时聊天、长文本生成。
    流式模式下 response 是一个迭代器,每次 yield 一个 chunk。
    """
    messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "请用 100 字介绍一下自己"},
    ]
    print(f"\n{'='*60}")
    print("  2. 流式文本生成")
    print(f"{'='*60}")
    responses = Generation.call(
        api_key=DASHSCOPE_API_KEY,
        model="qwen-plus",
        messages=messages,
        result_format="message",
        stream=True,              # 开启流式
        incremental_output=True,  # 增量输出模式(仅返回新 token)
    )
    print("  响应:", end="", flush=True)
    for resp in responses:
        if resp.status_code == HTTPStatus.OK:
            content = resp.output.choices[0].message.content
            if content:
                print(content, end="", flush=True)
    print("\n" + "="*60 + "\n")


# ============================================================
# 3. 异步非流式生成(asyncio 支持)
# ============================================================
async def example_async_non_streaming():
    """DashScope SDK 异步非流式调用

    使用 AioGeneration 实现异步非阻塞调用,适用于并发场景。
    """
    from dashscope import AioGeneration

    messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "介绍一下量子计算的基本原理"},
    ]
    response = await AioGeneration.call(
        api_key=DASHSCOPE_API_KEY,
        model="qwen-plus",
        messages=messages,
        result_format="message",
    )
    _print_response("3. 异步非流式文本生成", response)


# ============================================================
# 4. 图片理解(多模态)
# ============================================================
def example_multimodal_image():
    """DashScope SDK 多模态调用 - 图片理解

    支持传入图片 URL 或本地文件路径,模型理解并描述图片内容。
    适用于图像描述、视觉问答、物体识别等场景。
    """
    messages = [
        {
            "role": "user",
            "content": [
                {
                    "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg",
                },
                {"text": "图中描绘的是什么景象?"},
            ],
        }
    ]
    response = MultiModalConversation.call(
        api_key=DASHSCOPE_API_KEY,
        model="qwen-vl-plus",  # 多模态模型:qwen-vl-plus, qwen-vl-max
        messages=messages,
    )
    _print_response("4. 图片理解(多模态)", response)


# ============================================================
# 5. 流式多模态(图片理解 + 逐 token 输出)
# ============================================================
def example_multimodal_streaming():
    """DashScope SDK 多模态流式调用

    图片理解 + 流式输出,适用于图片对话场景。
    """
    messages = [
        {
            "role": "user",
            "content": [
                {
                    "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg",
                },
                {"text": "这张照片里有什么?请详细描述"},
            ],
        }
    ]
    print(f"\n{'='*60}")
    print("  5. 流式多模态(图片理解)")
    print(f"{'='*60}")
    responses = MultiModalConversation.call(
        api_key=DASHSCOPE_API_KEY,
        model="qwen-vl-plus",
        messages=messages,
        stream=True,
    )
    print("  响应:", end="", flush=True)
    for resp in responses:
        if resp.status_code == HTTPStatus.OK:
            content = resp.output.choices[0].message.content
            if content and isinstance(content, list):
                for item in content:
                    if item.get("text"):
                        print(item["text"], end="", flush=True)
    print("\n" + "="*60 + "\n")


# ============================================================
# 6. OpenAI 兼容接口 - 非流式
# ============================================================
def example_openai_compat():
    """OpenAI 兼容接口 - 非流式

    如果你熟悉 OpenAI SDK,可以直接用 openai 库调用阿里云百炼模型。
    只需修改 base_url 和 api_key 即可。
    """
    from openai import OpenAI

    client = OpenAI(
        api_key=DASHSCOPE_API_KEY,
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )
    completion = client.chat.completions.create(
        model="qwen-plus",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "请用英文说一句关于 AI 的名言"},
        ],
    )
    print(f"\n{'='*60}")
    print("  6. OpenAI 兼容接口 - 非流式")
    print(f"{'='*60}")
    print(f"  响应:{completion.choices[0].message.content}")
    print(f"  用量:{dict(completion.usage)}")
    print(f"{'='*60}\n")


# ============================================================
# 7. OpenAI 兼容接口 - 流式
# ============================================================
def example_openai_compat_streaming():
    """OpenAI 兼容接口 - 流式

    使用 OpenAI SDK 的 stream=True 实现流式输出。
    """
    from openai import OpenAI

    client = OpenAI(
        api_key=DASHSCOPE_API_KEY,
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )
    print(f"\n{'='*60}")
    print("  7. OpenAI 兼容接口 - 流式")
    print(f"{'='*60}")
    print("  响应:", end="", flush=True)
    completion = client.chat.completions.create(
        model="qwen-plus",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "请用 100 字介绍量子计算"},
        ],
        stream=True,
        stream_options={"include_usage": True},  # 最后一个 chunk 返回 token 用量
    )
    for chunk in completion:
        if chunk.choices and chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="", flush=True)
        elif chunk.usage:
            print(f"\n  用量:prompt_tokens={chunk.usage.prompt_tokens}, "
                  f"completion_tokens={chunk.usage.completion_tokens}, "
                  f"total_tokens={chunk.usage.total_tokens}")
    print("\n" + "="*60 + "\n")


# ============================================================
# 8. OpenAI 兼容接口 - 多模态(图片理解)
# ============================================================
def example_openai_compat_multimodal():
    """OpenAI 兼容接口 - 多模态

    使用 OpenAI 协议的多模态格式传入图片。
    """
    from openai import OpenAI

    client = OpenAI(
        api_key=DASHSCOPE_API_KEY,
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )
    completion = client.chat.completions.create(
        model="qwen-vl-plus",
        messages=[
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
                        },
                    },
                    {"type": "text", "text": "这张图片中有什么?"},
                ],
            }
        ],
    )
    print(f"\n{'='*60}")
    print("  8. OpenAI 兼容接口 - 多模态(图片理解)")
    print(f"{'='*60}")
    print(f"  响应:{completion.choices[0].message.content}")
    print(f"{'='*60}\n")


# ============================================================
# 9. 文生图(万相)
# ============================================================
def example_text_to_image():
    """DashScope SDK 文生图 - 万相模型

    使用 wanx 系列模型根据文字描述生成图片。
    注意:图片生成是异步任务模式,需要轮询结果。
    """
    from dashscope import ImageSynthesis

    print(f"\n{'='*60}")
    print("  9. 文生图(万相)")
    print(f"{'='*60}")

    # 方式 A:同步调用(内部自动轮询,阻塞等待)
    rsp = ImageSynthesis.call(
        api_key=DASHSCOPE_API_KEY,
        model=ImageSynthesis.Models.wanx_v1,
        prompt="一只坐在窗台上的橘猫,夕阳,温暖的光线,写实风格",
        n=1,       # 生成图片数量
        size="1024*1024",
    )
    if rsp.status_code == HTTPStatus.OK:
        for result in rsp.output.results:
            print(f"  生成图片 URL:{result.url}")
    else:
        print(f"  错误:{rsp.message}")

    print(f"{'='*60}\n")


# ============================================================
# 10. 函数调用(Tool Calling)
# ============================================================
def example_tool_calling():
    """DashScope SDK 函数调用(Tool Calling)

    让模型根据用户意图选择调用外部函数,并返回结构化参数。
    适用于需要调用外部 API 或数据库的场景。
    """
    tools = [
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "获取指定城市的天气信息",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "city": {
                            "type": "string",
                            "description": "城市名称",
                        },
                        "date": {
                            "type": "string",
                            "description": "日期,格式 YYYY-MM-DD",
                        },
                    },
                    "required": ["city"],
                },
            },
        }
    ]
    messages = [
        {"role": "user", "content": "北京今天天气怎么样?"},
    ]
    response = Generation.call(
        api_key=DASHSCOPE_API_KEY,
        model="qwen-plus",
        messages=messages,
        tools=tools,
        result_format="message",
    )
    _print_response("10. 函数调用(Tool Calling)", response)

    # 解析函数调用参数
    if response.status_code == HTTPStatus.OK:
        msg = response.output.choices[0].message
        if hasattr(msg, 'tool_calls') and msg.tool_calls:
            print("  模型请求调用函数:")
            for tc in msg.tool_calls:
                print(f"    函数名:{tc['function']['name']}")
                print(f"    参数:{tc['function']['arguments']}")


# ============================================================
# 11. 思考模式(Thinking)
# ============================================================
def example_thinking():
    """DashScope SDK 思考模式

    开启 enable_thinking 后,模型会先输出推理过程(reasoning_content),
    再输出最终答案。适用于复杂推理、数学、逻辑等场景。
    QwQ 模型默认开启思考模式。
    注意:思考模式必须使用流式输出。
    """
    messages = [
        {"role": "user", "content": "计算 23 × 47 的值,并解释计算步骤"},
    ]
    print(f"\n{'='*60}")
    print("  11. 思考模式(Thinking)- 仅流式")
    print(f"{'='*60}")
    responses = Generation.call(
        api_key=DASHSCOPE_API_KEY,
        model="qwen-plus",
        messages=messages,
        result_format="message",
        stream=True,
        incremental_output=True,
        enable_thinking=True,     # 开启思考模式
    )
    print("  思考过程:", end="", flush=True)
    for resp in responses:
        if resp.status_code == HTTPStatus.OK:
            msg = resp.output.choices[0].message
            if msg.reasoning_content:
                print(msg.reasoning_content, end="", flush=True)
            elif msg.content:
                pass  # 最终答案会在后续输出
    print("\n" + "-"*40)
    print("  最终答案会在内容输出中展示")
    print(f"{'='*60}\n")


# ============================================================
# 12. 联网搜索
# ============================================================
def example_web_search():
    """DashScope SDK 联网搜索

    开启 enable_search 后,模型会自动联网搜索获取最新信息。
    适用于需要实时信息的问答场景。
    """
    messages = [
        {"role": "user", "content": "今天阿里巴巴股价是多少?"},
    ]
    response = Generation.call(
        api_key=DASHSCOPE_API_KEY,
        model="qwen-plus",
        messages=messages,
        result_format="message",
        enable_search=True,  # 开启联网搜索
    )
    _print_response("12. 联网搜索", response)

    # 搜索来源信息
    if hasattr(response.output, 'search_info') and response.output.search_info:
        print("  搜索来源:")
        for src in response.output.search_info.get('search_results', []):
            print(f"    - {src.get('title')}: {src.get('url')}")


# ============================================================
# 13. 语音合成(TTS)
# ============================================================
def example_text_to_speech():
    """DashScope SDK 语音合成(TTS)

    将文本合成为语音,支持多种音色。
    注意:需要安装 dashscope 库版本 >= 1.20.0
    """
    from dashscope.audio.tts_v2 import SpeechSynthesizer

    print(f"\n{'='*60}")
    print("  13. 语音合成(TTS)")
    print(f"{'='*60}")
    try:
        synthesizer = SpeechSynthesizer(
            model="cosyvoice-v2",
            voice="longxiaoxia",  # 音色:longxiaoxia(龙小夏)
            api_key=DASHSCOPE_API_KEY,
        )
        audio = synthesizer.call("你好,欢迎使用阿里云百炼语音合成服务。")
        # audio 为 bytes 类型,可保存为文件
        output_path = os.path.join(os.path.dirname(__file__), "output_tts.wav")
        with open(output_path, "wb") as f:
            f.write(audio)
        print(f"  语音已保存至:{output_path}")
    except Exception as e:
        print(f"  语音合成失败(可能缺少依赖或版本不匹配):{e}")
    print(f"{'='*60}\n")


# ============================================================
# 14. 异步任务模式(图像生成示例)
# ============================================================
def example_async_task():
    """DashScope 异步任务模式

    适用于耗时的任务(图像生成、视频生成等),
    先提交任务获取 task_id,再轮询结果。
    """
    from dashscope.aigc.image_generation import ImageGeneration

    print(f"\n{'='*60}")
    print("  14. 异步任务模式 - 提交任务 + 轮询结果")
    print(f"{'='*60}")
    try:
        # 步骤 1:创建异步任务
        task_rsp = ImageGeneration.async_call(
            model="wan2.1-t2i-turbo",
            api_key=DASHSCOPE_API_KEY,
            prompt="一只柴犬在海滩上奔跑,阳光明媚",
            n=1,
        )
        if task_rsp.status_code != HTTPStatus.OK:
            print(f"  创建任务失败:{task_rsp.message}")
            print(f"{'='*60}\n")
            return

        task_id = task_rsp.output.task_id
        print(f"  任务已创建,task_id={task_id}")

        # 步骤 2:轮询任务结果
        import time
        for i in range(30):  # 最多等待 30 次
            status_rsp = ImageGeneration.fetch(
                task=task_rsp,
                api_key=DASHSCOPE_API_KEY,
            )
            if status_rsp.status_code == HTTPStatus.OK:
                task_status = status_rsp.output.task_status
                print(f"  轮询[{i+1}] 状态={task_status}")
                if task_status == "SUCCEEDED":
                    # 处理结果(不同模型响应结构可能不同)
                    print("  任务成功!")
                    break
                elif task_status in ("FAILED", "CANCELED"):
                    print(f"  任务失败:{status_rsp.output.message}")
                    break
            time.sleep(2)
        else:
            print("  轮询超时")
    except Exception as e:
        print(f"  异步任务调用失败:{e}")
    print(f"{'='*60}\n")


# ============================================================
# 15. 多轮对话
# ============================================================
def example_multi_turn():
    """DashScope SDK 多轮对话

    通过持续传入对话历史,实现多轮对话交互。
    result_format='message' 返回结构化消息。
    """
    conversation = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "1+1 等于多少?"},
    ]
    # 第一轮
    r1 = Generation.call(
        api_key=DASHSCOPE_API_KEY,
        model="qwen-plus",
        messages=conversation,
        result_format="message",
    )
    if r1.status_code == HTTPStatus.OK:
        answer = r1.output.choices[0].message.content
        conversation.append({"role": "assistant", "content": answer})
        print(f"  第一轮:{answer}")

        # 第二轮 - 追问
        conversation.append({"role": "user", "content": "那 2+2 呢?"})
        r2 = Generation.call(
            api_key=DASHSCOPE_API_KEY,
            model="qwen-plus",
            messages=conversation,
            result_format="message",
        )
        if r2.status_code == HTTPStatus.OK:
            answer2 = r2.output.choices[0].message.content
            conversation.append({"role": "assistant", "content": answer2})
            print(f"  第二轮:{answer2}")
    print(f"{'='*60}\n")


# ============================================================
# 主程序 - 逐个执行示例
# ============================================================
if __name__ == "__main__":
    print(f"\n{'#'*60}")
    print(f"  #  阿里云百炼 DashScope API 调用示例库")
    print(f"{'#'*60}")
    print(f"\n  API Key 来源:环境变量 DASHSCOPE_API_KEY")
    print(f"  API Key 是否已设置:{'✓ 是' if DASHSCOPE_API_KEY else '✗ 否,请先设置环境变量'}")
    if not DASHSCOPE_API_KEY:
        print(f"\n  【提示】请先设置环境变量:")
        print(f"    set DASHSCOPE_API_KEY=sk-xxx")
        exit(1)

    # 同步示例(逐个执行)
    example_non_streaming()
    example_streaming()

    # 异步示例(需要 asyncio 事件循环)
    print("  [3. 异步生成 - 使用 asyncio 运行]")
    import asyncio
    asyncio.run(example_async_non_streaming())

    example_multimodal_image()
    example_multimodal_streaming()
    example_openai_compat()
    example_openai_compat_streaming()
    example_openai_compat_multimodal()
    example_text_to_image()
    example_tool_calling()
    example_thinking()
    example_web_search()
    example_text_to_speech()
    example_async_task()
    example_multi_turn()

    print(f"\n{'#'*60}")
    print(f"  #  所有示例执行完毕")
    print(f"{'#'*60}\n")