调用通义千问(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代码

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

相关推荐
2501_9403910820 小时前
GEO优化服务商选择的四维标尺:避开AI搜索时代的合作陷阱
ai
Electrolux21 小时前
[wllama]纯前端实现大语言模型调用:在浏览器里跑 AI 是什么体验。以调用腾讯 HY-MT1.5 混元翻译模型为例
前端·aigc·ai编程
薛晓刚21 小时前
AI编程:爽感背后的成本与隐忧
人工智能·ai编程
俊哥V21 小时前
[深度分析]英伟达发布新一代 AI 芯片架构 Vera Rubin:AI 算力进入“成本—规模曲线重构”的关键时刻
人工智能·ai
wdfk_prog21 小时前
[Linux]学习笔记系列 -- [fs]super
linux·笔记·学习
GHL28427109021 小时前
Temperature、Top P 学习
学习·ai
webkubor1 天前
🧠 2025:AI 写代码越来越强,但我的项目返工却更多了
前端·机器学习·ai编程
NanBox1 天前
2025 年 AI 大事件纪要
ai编程
Yyuanyuxin1 天前
保姆级学习开发安卓手机软件(三)--安装模拟机并开始简单的进入开发
android·学习