Skip to content

阿里云 DashScope 使用指南

阿里云 DashScope(通义千问)系列模型是国产旗舰 LLM,具有出色的中文理解能力、互联网搜索能力和极具竞争力的价格(2025 年降价 88%)。

模型概览

推荐模型

模型 上下文 特色 适用场景
qwen-turbo 8K 快速、低成本 简单对话、快速响应
qwen-plus 32K 平衡性能和成本 通用对话、代码生成
qwen-max 131K 综合性能最强 复杂推理、长文档分析
qwen-max-2025-01-25 131K 最新旗舰模型 最强性能、多模态
qwen-vl-plus 131K 多模态能力 图文理解、视觉问答
qwen3-math-plus 131K 数学能力增强 数学推理、科学计算

模型选择建议

from tfrobot.brain.chain.llms import DashScope

# 通用场景(推荐)
llm = DashScope(name="qwen-max")

# 成本敏感
llm = DashScope(name="qwen-turbo")

# 多模态任务
llm = DashScope(name="qwen-vl-plus")

# 数学推理
llm = DashScope(name="qwen3-math-plus")

配置参数

核心参数

from tfrobot.brain.chain.llms import DashScope

llm = DashScope(
    name="qwen-max",
    temperature=0.7,        # 0.0-2.0,控制随机性
    top_p=0.8,             # 0.0-1.0,核采样
    top_k=50,              # 1-∞,top-k 采样
    max_tokens=4096,        # 最大输出 tokens
    stream=False,           # 是否流式输出
)

API 配置

llm = DashScope(
    name="qwen-max",
    dashscope_api_key="sk-...",  # API 密钥(推荐使用环境变量)
    timeout=60.0,                 # 请求超时时间
    max_retries=3,                # 最大重试次数
)

互联网搜索

DashScope 支持联网搜索功能:

llm = DashScope(
    name="qwen-max",
    enable_search=True,      # 启用互联网搜索
    search_result_size=5,    # 返回搜索结果数量
)

# 模型会自动搜索最新信息
result = llm.complete(
    current_input=TextMessage(content="今天北京的天气怎么样?")
)

增量输出

llm = DashScope(
    name="qwen-max",
    incremental_output=True,  # 启用增量输出
)

工具调用

原生模式(推荐)

from tfrobot.brain.chain.llms import DashScopeWithTools
from tfrobot.brain.chain.prompt.tool_prompt import ToolPrompt
from tfrobot.drive.tool.tool import tool

@tool
def get_weather(city: str) -> str:
    """获取指定城市的天气"""
    return f"{city} 今天晴天,温度 25°C"

llm = DashScopeWithTools(name="qwen-max")
llm.system_msg_prompt = [ToolPrompt()]

result = llm.complete(
    current_input=TextMessage(content="北京今天的天气怎么样?"),
    tools=[get_weather]
)

DashScope vs DashScopeWithTools

  • DashScope:基础模型,需要手动配置 ToolPrompt
  • DashScopeWithTools:预配置 ToolPrompt,更方便
# 方式一:使用 DashScope
llm = DashScope(name="qwen-max")
llm.system_msg_prompt.append(ToolPrompt())

# 方式二:使用 DashScopeWithTools(推荐)
llm = DashScopeWithTools(name="qwen-max")

多模态支持

图片理解

from tfrobot.schema.message.conversation.message_dto import MultiPartMessage
from tfrobot.schema.message.msg_part import TextPart, ImagePart

msg = MultiPartMessage(content=[
    TextPart(text="这张图片里有什么?"),
    ImagePart(
        image_url=ImgUrl(url="path/to/image.jpg"),
    ),
])

result = llm.complete(current_input=msg)

图片 Token 计算

DashScope 图片 Token 计算公式:

# Token 计算:(width ÷ 28) × (height ÷ 28) + 2
# 例如:1000×1000 像素的图片
# (1000 ÷ 28) × (1000 ÷ 28) + 2 ≈ 1277 tokens

def calculate_image_tokens(width: int, height: int) -> int:
    """计算 DashScope 图片 Token 消耗"""
    return int((width / 28) * (height / 28)) + 2

# 示例
tokens = calculate_image_tokens(1000, 1000)
print(f"1000×1000 图片约消耗 {tokens} tokens")

音频处理

from tfrobot.schema.message.conversation.message_dto import AudioMessage

msg = AudioMessage(
    content=Path("path/to/audio.mp3"),
    creator=BaseUser(name="User", uid="1")
)

result = llm.complete(current_input=msg)

成本优化

Token 计费

from tfrobot.brain.chain.llms import DashScope

# 设置价格(用于计费统计)
llm = DashScope(
    name="qwen-max",
    input_price=0.00024,   # ¥2.4/百万tokens(示例)
    output_price=0.00096   # ¥9.6/百万tokens(示例)
)

节省 Token 的技巧

  1. 使用 Turbo 模型qwen-turbo 价格最低,适合简单任务
  2. 优化图片尺寸:使用合适的图片分辨率减少 Token 消耗
  3. 启用缓存:DashScope 支持 Prompt 缓存,减少重复计算
  4. 使用摘要模式:历史消息自动摘要

上下文管理

设置上下文窗口

llm = DashScope(
    name="qwen-max",
    context_window=131072  # 131K tokens
)

上下文压缩

当上下文超出限制时,Chain 会自动触发压缩:

# Chain 自动处理
from tfrobot.brain.chain import SingleChain

chain = SingleChain(llm=llm)
result = chain.run(input_message=user_input)

错误处理

常见错误

错误类型 原因 解决方案
InvalidParameter 参数错误 检查请求参数
RequestTimeout 请求超时 自动重试(已配置)
QuotaExceeded 配额不足 检查账户余额
Unauthorized API 密钥错误 检查环境变量

手动错误处理

try:
    result = llm.complete(current_input=user_input)
except Exception as e:
    error_msg = str(e)
    if "InvalidParameter" in error_msg:
        # 参数错误
        print(f"参数错误: {e}")
    elif "QuotaExceeded" in error_msg:
        # 配额不足
        print("请检查账户余额")
    else:
        raise

高级用法

流式输出

llm = DashScope(name="qwen-max", stream=True)

result = llm.complete(current_input=user_input)
# result.generations[0].text 会逐步生成

互联网搜索应用

# 需要最新信息的任务
llm = DashScope(
    name="qwen-max",
    enable_search=True
)

result = llm.complete(
    current_input=TextMessage(content="最新的 AI 技术进展是什么?")
)

# 模型会自动搜索并引用最新信息

并行处理

import asyncio

async def batch_process(llm, inputs):
    tasks = [llm.async_complete(current_input=inp) for inp in inputs]
    results = await asyncio.gather(*tasks)
    return results

最佳实践

1. Temperature 设置

# 需要创造性(如写作)
llm = DashScope(name="qwen-max", temperature=1.0)

# 需要稳定性(如代码生成)
llm = DashScope(name="qwen-max", temperature=0.0)

2. Prompt 工程

llm.system_msg_prompt = [
    MemoPrompt(template="你是一个专业的 Python 开发者。"),
    ToolPrompt(),
]

llm.after_input_msg_prompt = [
    MemoPrompt(template="请使用 Markdown 格式回复,代码块标明语言。"),
]

3. 中文场景优化

# 通义千问对中文有天然优势
llm = DashScope(name="qwen-max")

# 中文任务
result = llm.complete(
    current_input=TextMessage(content="解释什么是量子纠缠")
)

4. 图片优化

# 压缩图片以减少 Token 消耗
from PIL import Image

def optimize_image(image_path: str, max_size: int = 512):
    """优化图片尺寸"""
    img = Image.open(image_path)
    img.thumbnail((max_size, max_size))

    optimized_path = image_path.replace(".", "_optimized.")
    img.save(optimized_path, quality=85)
    return optimized_path

# 使用优化后的图片
optimized = optimize_image("image.jpg")
# 512×512 图片仅消耗约 333 tokens

5. 联网搜索优化

# 需要实时信息的场景
llm = DashScope(
    name="qwen-max",
    enable_search=True,
    search_result_size=3  # 控制搜索结果数量
)

result = llm.complete(
    current_input=TextMessage(content="查询 2025 年春节的日期")
)

相关文档