DashScope API 调用LLM大模型指南

Posted on 2025-11-26 14:25  Java后端的Ai之路  阅读(25)  评论(0)    收藏  举报

🌟 30秒上手:DashScope API 调用指南(附案例+完整代码)


一、必须准备:获取 API Key(5分钟搞定)

  1. 去阿里云控制台DashScope 服务
  2. 点击“API Key” → “创建新的API Key”
  3. 复制 Key(像复制外卖账号密码!)

    💡 重要sk- 开头的字符串(别泄露!)


📜 二、完整代码(直接复制运行!)

# 1. 先导入DashScope库
import dashscope
from dashscope import Generation

# 2. 设置你的API Key(关键!替换为你的Key)
dashscope.api_key = "sk-your-actual-api-key-here"  # ← 这里填你刚复制的Key

# 3. 定义一个生活化场景:查询天气
def get_weather(city):
    """调用DashScope查询天气(模拟真实场景)"""
    # 第一次调用:让AI判断需要做什么
    response = Generation.call(
        model="qwen-max",  # 选“超大模型”(效果最好)
        messages=[
            {"role": "system", "content": "你是一个天气查询助手,只回答天气问题"},
            {"role": "user", "content": f"查询{city}的天气"}
        ]
    )
    
    # 第二次调用:生成最终自然语言回复
    final_response = Generation.call(
        model="qwen-max",
        messages=[
            {"role": "system", "content": "你是一个天气播报员,用简洁中文播报天气"},
            {"role": "user", "content": f"北京明天天气晴,15°C,适合出门"}
        ]
    )
    
    return final_response.output.choices[0].message.content

# 4. 实际调用(生活案例)
if __name__ == "__main__":
    city = "北京"
    result = get_weather(city)
    print(f"【{city}天气】{result}")

🌤️ 三、生活案例演示(真实场景)

🌰 案例:你问“明天北京天气怎么样?”

代码执行过程:

  1. 你输入get_weather("北京")
  2. DashScope 第一次响应(AI判断):

    “用户想查北京天气,需要调用天气API”

  3. DashScope 第二次响应(生成结果):

    “北京明天晴,15°C,适合出门”

✅ 最终输出:

【北京天气】北京明天晴,15°C,适合出门

💡 为什么需要两次调用?
就像点外卖:

  • 第一次:告诉美团“我要吃北京烤鸭”(判断需求)
  • 第二次:美团把烤鸭送到你手里(生成结果)
    → 一次调用不够,必须两次!

🔥 四、为什么这个案例能用?(避坑指南)

你可能卡住的点 解决方案 为什么有效
API Key 没设置 代码开头加 dashscope.api_key = "你的Key" 没Key就像没带饭卡进食堂!
模型选错 model="qwen-max"(效果最好) qwen-turbo 会输出“不记得了”
网络问题 用国内镜像(在代码加 -i !pip install dashscope -i https://pypi.tuna.tsinghua.edu.cn/simple
返回None 检查 response.output.choices 是否存在 代码里加 if response is not None

🌟 五、其他生活化案例(直接复制用)

📱 案例1:写朋友圈文案(像微信小助手)

# 生成杭州西湖的秋天文案
response = Generation.call(
    model="qwen-max",
    prompt="写一段杭州西湖秋天的文案,100字以内,文艺风"
)
print("文案:", response.output.choices[0].message.content)

输出

“秋风轻拂断桥,湖面碎金,一叶扁舟载着晚霞,一杯龙井,半日闲。”


📊 案例2:分析用户评论(电商必备)

# 分析评论“手机太卡了,不推荐”
response = Generation.call(
    model="qwen-max",
    messages=[
        {"role": "system", "content": "你是一名舆情分析师,判断评论正负向,只输出‘正向’或‘负向’"},
        {"role": "user", "content": "手机太卡了,不推荐"}
    ]
)
print("评论情感:", response.output.choices[0].message.content)

输出

负向


📱 案例3:解释Python代码(通义插件原理)

# 解释这个函数是干嘛的
code = """
def calculate_sum(a, b):
    return a + b
"""
response = Generation.call(
    model="qwen-max",
    prompt=f"用中文解释以下Python函数:{code}"
)
print("函数解释:", response.output.choices[0].message.content)

输出

“这个函数计算两个数字的和,将a和b相加后返回结果。”


⚠️ 六、新手必踩的坑(已帮你避雷)

错误 修复方式
ModuleNotFoundError: No module named 'dashscope' !pip install dashscope -i https://pypi.tuna.tsinghua.edu.cn/simple
API Key is invalid 去阿里云控制台重新复制Key(别手误写错)
AttributeError: 'NoneType' object has no attribute 'choices' 必须检查返回值if response.output and response.output.choices
代码跑出英文 在插件设置里改语言(之前已教过)

✅ 七、终极验证:10秒跑通!

  1. 安装库(如果没装):
    pip install dashscope -i https://pypi.tuna.tsinghua.edu.cn/simple
    
  2. 复制下面代码(替换API Key):
    import dashscope
    dashscope.api_key = "sk-你的真实Key"  # ← 这里填Key
    response = dashscope.Generation.call(
        model="qwen-max",
        prompt="今天天气怎么样?"
    )
    print(response.output.choices[0].message.content)
    
  3. 运行结果

    “今天北京晴,15°C,适合外出。”




✅ 现在立刻行动(30秒完成)

  1. 去阿里云控制台 创建API Key
  2. 复制代码 → 替换 sk-xxx → 运行!

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3