通过api-key使用通义千问

一、申请API-KEY值

打开API-KEY申请指导官网:https://help.aliyun.com/zh/dashscope/developer-reference/activate-dashscope-and-create-an-api-key
跟随官网创建API-KEY

二、安装DashScope SDK

前提条件:
  已安装Python3.8及以上版本。请确保安装正确的Python版本,可能需要pip3 install dashscope。

# 安装dashscope,可在虚拟环境中安装
pip install dashscope

三、通过代码使用通义千问

激活虚拟环境,运行

import requests
import os

api_key = os.getenv("DASHSCOPE_API_KEY")
url = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation'
headers = {'Content-Type': 'application/json',
           'Authorization':f'Bearer {"YOUR_KEY"}'}
body = {
    'model': 'qwen-turbo',
    "input": {
        "messages": [
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": input("请输入:")
            }
        ]
    },
    "parameters": {
        "result_format": "message"
    }
}

response = requests.post(url, headers=headers, json=body)

# response.json()['output']['choices'][0]['message']['content']为回复的内容
print(response.json())

通过api-key使用通义千问_第1张图片

你可能感兴趣的:(语言模型,阿里云,python)