DashScope Python SDK

1.25.16 · active · verified Sat Apr 11

The DashScope Python SDK provides a client library for interacting with Alibaba Cloud's DashScope AI services, offering access to various models including Large Language Models (LLMs), text-to-image, and embedding models. The library is actively developed, with its current version at 1.25.16, and new releases occurring frequently to incorporate updates and new features.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `dashscope.Generation` API to interact with an LLM, such as `qwen-turbo`. It emphasizes setting the API key via an environment variable for security and includes basic error handling. It also highlights the importance of potentially setting the `base_http_api_url` for different regions.

import os
from http import HTTPStatus
from dashscope import Generation

# Set your DashScope API key via environment variable for security
# export DASHSCOPE_API_KEY='YOUR_API_KEY'
dashscope_api_key = os.environ.get('DASHSCOPE_API_KEY', '')

if not dashscope_api_key:
    print("Error: DASHSCOPE_API_KEY environment variable not set.")
    print("Please set it using: export DASHSCOPE_API_KEY='YOUR_API_KEY'")
else:
    # Set the API key programmatically if not using environment variable or for testing
    # dashscope.api_key = dashscope_api_key 
    
    # For models in specific regions, you might need to set the base URL.
    # For Singapore region (international users):
    # dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
    # For China (Beijing) region:
    # dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'

    print("Calling DashScope LLM...")
    responses = Generation.call(
        model=Generation.Models.qwen_turbo, # or 'qwen-plus', 'qwen-max', etc.
        prompt='Tell me a short story about a brave knight.',
        api_key=dashscope_api_key # It's good practice to explicitly pass the key or ensure it's set globally
    )

    if responses.status_code == HTTPStatus.OK:
        print('Story generated:')
        print(responses.output.text)
    else:
        print(f'Failed request_id: {responses.request_id}, status_code: {responses.status_code}, ')
        print(f'code: {responses.code}, message: {responses.message}')

view raw JSON →