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

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

相关推荐
带刺的坐椅21 小时前
从 Claude Code 隐私争议,看 SolonCode 的设计选择
ai·llm·agent·claudecode·soloncode·codingplan
Warson_L1 天前
独立开发推荐安装的skills
ai编程
threerocks1 天前
一用一个不吱声的视频解析 Skill,你值得拥有
aigc·ai编程
吴佳浩1 天前
AI 工程师知识地图:模型格式、框架、部署工具一次讲明白
人工智能·aigc·ai编程
lincats1 天前
Claude Code项目越写越乱?这套清理流程能救你
ai·ai agent·claude code
青木_JS1 天前
Headroom 是怎么给 Codex 省 Token 的:策略、效果与一次历史恢复记录
ai编程
MomentYY1 天前
Temperature:AI 的“脑洞旋钮”
前端·llm·ai编程
小九九的爸爸1 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
AlbertZein1 天前
别只盯着最强模型了,Agent 场景更该看这类 Flash 档模型
aigc·openai·ai编程
ZzT1 天前
公司用 AI 筛简历,他写了个 AI 帮你挑公司
面试·aigc·ai编程