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

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

相关推荐
Flynt4 小时前
AI 写的 Three.js 大屏,为什么越跑越卡?我在 Node 里复现了它的内存曲线
前端·ai编程·three.js
J船长5 小时前
AI 知识库的主流做法是 RAG,RAG怎么做
ai编程
小虎AI生活5 小时前
哇塞~24小时开机的WorkBuddy免费领,速来
aigc·ai编程
最强小杰5 小时前
某 OpenAI 兼容网关上的 `kimi-k3.1-pro`:Cline、Zed 接入与 SSE 排错示例
java·服务器·网络·ai
Maynor9966 小时前
Trymodel 使用介绍:一个平台同时用 Claude、GPT、Gemini 和 Grok
人工智能·gpt·ai·程序员·教程·claude·语音
七夜zippoe6 小时前
多 Agent 通信灾难:状态不一致导致雪崩故障的排查与防护
ai·agent·通信灾难·雪崩故障·排查与防护
郑世录8 小时前
codex 接本地模型,单次输出卡在 3208 token:一份照着做就能改的完整教程
ai编程
Forget the Dream8 小时前
Spring AI 2.0 系列(二):第一个 ChatClient——从注入到一次完整调用
java·人工智能·spring boot·ai·springai
JavaGuide9 小时前
Gemini 真的变强了,写代码做视频的能力接近 Claude Opus5.5 了!
前端·ai编程
qinglongcn9 小时前
四面统一:记忆/Session/观测/Cron
agent·ai编程