调用通义千问(qwen-plus)模型demo-学习

1、准备工作

1、注册key(注意:key有免费100万token额度,超出会产生费用)

https://bailian.console.aliyun.com/?tab=model#/api-key

2、安装dashscope SDK

python 复制代码
pip install dashscope

3、将key放到环境变量中

2、代码

python 复制代码
#!/usr/bin/env python
# coding: utf-8

import os
import dashscope

# dashscope:阿里云通义千问的python sdk
# from dashscope import Generation:从 dashscope 模块中导入 Generation 类,用于调用大模型的文本生成接口,
# dashscope sdk内部包含多个功能模块:例如:
# Generation:文本生成(Qwen 等语言模型)
# ImageSynthesis:文生图(如通义万相)
# Speech:语音识别与合成
# TextEmbedding:获取文本向量
# 通过 from dashscope import Generation,只引入了文本生成相关的功能。
from dashscope import Generation

# 配置API密钥
api_key = os.environ.get('DASHSCOPE_API_KEY')
dashscope.api_key = api_key

# 封装模型响应函数(带异常处理)
def get_response(messages):
    try:
        # 发送请求到阿里云的模型服务
        response = Generation.call(
            model='qwen-plus',        # 使用qwen-plus模型
            messages=messages,        # 传入对话历史(系统提示 + 用户输入)
            result_format='message',  # 要求返回格式为标准的聊天消息结果
            temperature=0.0  # 固定温度,保证结果稳定,设置随机性为 0,让模型输出完全确定、可重复(相同输入永远得到相同输出),适合分类任务
        )

        if response.status_code == 200:
            return response.output.choices[0].message.content
        else:
            print(f"模型调用失败:{response.code} - {response.message}")
            return None
    except Exception as e:
        print(f"调用出错:{str(e)}")
        return None

# ========== 更换后的系统提示词和用户问题 ==========
# 待分析的文本
review = '这个手机续航太差了,用1小时就没电,太失望了!'
# 系统提示词:细分情绪(开心/生气/失望/中性)
messages=[
    {"role": "system", "content": "你是一名情感分析师,帮我判断用户文本的情绪类型,回复请用一个词语:开心、生气、失望、中性"},
    {"role": "user", "content": review}
]

# 获取并打印结果
result = get_response(messages)
if result:
    print(f"文本 '{review}' 的情绪类型:{result}")  # 预期输出:失望

3、了解模型有哪些参数

https://bailian.console.aliyun.com/?tab=model#/model-market

其实官网已经给出一些注意事项,和实现demo代码

官网:调用相关模型返回结果示例

相关推荐
牛奶1 天前
2026年大模型怎么选?前端人实用对比
前端·人工智能·ai编程
牛奶1 天前
前端人为什么要学AI?
前端·人工智能·ai编程
KEEN的创享空间1 天前
AI编程从0到1之10X提效(Vibe Coding 氛围式编码 )09篇
openai·ai编程
GPUStack1 天前
Token 不再焦虑:用 GPUStack + OpenClaw 搭一个“无限用”的本地 AI 助手
ai·模型推理·gpustack·openclaw
AlienZHOU1 天前
为 AI Agent 编写高质量 Skill:Claude 官方指南
agent·ai编程·claude
恋猫de小郭1 天前
移动端开发稳了?AI 目前还无法取代客户端开发,小红书的论文告诉你数据
前端·flutter·ai编程
KaneLogger1 天前
【翻译】打造 Agent Skills 的最佳实践
agent·ai编程·claude
王小酱1 天前
Everything Claude Code 文档
openai·ai编程·aiops
雮尘1 天前
如何在非 Claude IDE (TARE、 Cursor、Antigravity 等)下使用 Agent Skills
前端·agent·ai编程
刘贺同学1 天前
Day12-龙虾哥打工日记:OpenClaw 子 Agent 到底看到了什么?
aigc·ai编程