python 呼叫通義千問SDK API

二月雪發表於2024-08-21

前言

  • 通義千問線上AI助手:https://tongyi.aliyun.com/qianwen/

  • 通義千問官網文件地址:https://help.aliyun.com/zh/dashscope/developer-reference/
    (通義千問2024.4.26 更新 模型的API-KEY收費,非限時免費開放模型,有使用Token數量的限制)

  • 支援python 3.8或以上版本

配置流程

1、通義千問API-KEY申請,
官方流程網址指導:https://help.aliyun.com/zh/dashscope/developer-reference/activate-dashscope-and-create-an-api-key

2、安裝DashScope SDK
官網教程網址:https://help.aliyun.com/zh/dashscope/developer-reference/install-dashscope-sdk

安裝和更新dashscope依賴庫

pip install dashscope
pip install dashscope --upgrade

3、API-KEY環境設定
參考官方文件網址:https://help.aliyun.com/zh/dashscope/developer-reference/api-key-settings

  • Linux/maxOS
export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
  • windows 環境變數,新建系統變數(變數:DASHSCOPE_API_KEY,值:你申請到的API_KEY字串)
    windows

  • 或者可以直接在程式碼呼叫中全域性設定(程式碼暴露風險)

import dashscope
dashscope.api_key="YOUR_DASHSCOPE_API_KEY"

4、程式碼例項

示例1:

# 官網示例
from http import HTTPStatus
from dashscope import Generation


def call_with_stream():
    user_input = input("請輸入:")
    messages = list()
    msg_dict = [
        {'role': 'system', 'content': 'you are a helpful assistant'},
        {'role': 'user', 'content': user_input}]
    messages.append(msg_dict)
    responses = Generation.call(
        model="qwen-turbo",
        messages=messages,  
        result_format='message',  # 設定輸出為'message'格式
        stream=True,  # 設定輸出方式為流式輸出
        incremental_output=True)  # 增量式流式輸出
    full_content = ""
    for response in responses:
        if response.status_code == HTTPStatus.OK:
            print(response)
            full_content += response.output.choices[0].message.content
        else:
            # 網路請求異常
            print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
                response.request_id, response.status_code, response.code, response.message))
    print(f"Full content:{full_content}")


if __name__ == '__main__':
    call_with_stream()

示:2:

from dashscope import Generation
from dashscope.api_entities.dashscope_response import Role

messages = list()

while True:
    message = input('user:')
    messages.append({'role': Role.USER, 'content': message})
    whole_message = ''
    responses = Generation.call(Generation.Models.qwen_max, messages=messages, result_format='message', stream=True,
                                incremental_output=True)
    print('system:', end='')
    for response in responses:
        whole_message += response.output.choices[0]['message']['content']
        print(response.output.choices[0]['message']['content'], end='')
    print()
    messages.append({'role': 'assistant', 'content': whole_message})    

參考文件:
呼叫阿里通義千問大語言模型API-小白新手教程-python

相關文章