Skip to main content

dashscope client sdk library

Project description

English

DashScope Python Library

Installation

To install the DashScope Python SDK, simply run:

pip install dashscope

If you clone the code from github, you can install from source by running:

pip install -e .

QuickStart

You can use Generation api to call model qwen-turbo(通义千问).

from http import HTTPStatus
import dashscope
from dashscope import Generation

dashscope.api_key = 'YOUR-DASHSCOPE-API-KEY'
responses = Generation.call(model=Generation.Models.qwen_turbo,
                            prompt='今天天气好吗?')

if responses.status_code == HTTPStatus.OK:
    print('Result is: %s' % responses.output)
else:
    print('Failed request_id: %s, status_code: %s, code: %s, message:%s' %
            (responses.request_id, responses.status_code, responses.code,
            responses.message))

API Key Authentication

The SDK uses API key for authentication. Please refer to official documentation regarding how to obtain your api-key.

Using the API Key

  1. Set the API key via code
import dashscope

dashscope.api_key = 'YOUR-DASHSCOPE-API-KEY'
# Or specify the API key file path via code
# dashscope.api_key_file_path='~/.dashscope/api_key'
  1. Set the API key via environment variables

a. Set the API key directly using the environment variable below

export DASHSCOPE_API_KEY='YOUR-DASHSCOPE-API-KEY'

b. Specify the API key file path via an environment variable

export DASHSCOPE_API_KEY_FILE_PATH='~/.dashscope/api_key'
  1. Save the API key to a file
from dashscope import save_api_key

save_api_key(api_key='YOUR-DASHSCOPE-API-KEY',
             api_key_file_path='api_key_file_location or (None, will save to default location "~/.dashscope/api_key"')

Sample Code

call function provides synchronous call, the function call will return when computation is done on the server side.

from http import HTTPStatus
from dashscope import Generation
# export DASHSCOPE_API_KEY='YOUR-DASHSCOPE-API-KEY' in environment
def sync_dashscope_sample():
    responses = Generation.call(
        model=Generation.Models.qwen_turbo,
        prompt='Is the weather good today?')

    if responses.status_code == HTTPStatus.OK:
        print('Result is: %s'%responses.output)
    else:
        print('Code: %s, status_code: %s, code: %s, message: %s'%(responses.status_code,
                                                   responses.code,
                                                   responses.message))

if __name__ == '__main__':
    sync_dashscope_sample()

For requests with longer processing times, you can obtain partial results before the full output is generated. Set the stream parameter to True. In this case, the results will be returned in batches, and the current output mode is incremental (output will overwrite the previous content). When the output is in stream mode, the interface returns a generator, and you need to iterate through the generator to get the results. Each output contains partial data for streaming, and the last output contains the final generated result.

Example with simple streaming:

from http import HTTPStatus
from dashscope import Generation

def sample_sync_call_stream():
    prompt_text = 'Give me a recipe using carrots, potatoes, and eggplants'
    response_generator = Generation.call(
        model=Generation.Models.qwen_turbo,
        prompt=prompt_text,
        stream=True,
        max_length=512,
        top_p=0.8)
    for resp in response_generator:  # Iterate through the streaming output results
        if resp.status_code == HTTPStatus.OK:
            print(resp.output)
        else:
            print('Request failed, message: %s'%resp.message)

if __name__ == '__main__':
    sample_sync_call_stream()

Streaming with History

from http import HTTPStatus

from dashscope import Conversation, History, HistoryItem
def conversation_stream_example():
    history = History()
    item = HistoryItem('user', text='Is the weather good today?')
    history.append(item)
    item = HistoryItem('bot', text='The weather is nice today, do you want to go out and play?')
    history.append(item)

    item = HistoryItem('user', text='Do you have any places to recommend?')
    history.append(item)
    item = HistoryItem('bot', text='I suggest you go to the park. Spring is here, and the flowers are blooming. It is beautiful.')
    history.append(item)
    chat = Conversation(history)
    response = chat.call(Conversation.Models.qwen_turbo,
                         prompt='Recommend a nearby park',
                         stream=True)
    for part in response:
        if part.status_code == HTTPStatus.OK:
            print(part.output)
        else:
            print('Failed request_id: %s, status_code: %s code: %s, message:%s' %
                  (part.id, part.status_code, part.code, part.message))
    response = chat.call(
        Conversation.Models.qwen_turbo,
        prompt='I have been to that park many times, how about a more distant one?',
        auto_history=True,
        stream=True,
    )
    for part in response:
        if part.status_code == HTTPStatus.OK:
            print(part.output.text)
            print(part.usage)
        else:
            print('Failed request_id: %s, status_code: %s, code: %s, message:%s' %
                  (part.id, part.status_code, part.code, part.message))


if __name__ == '__main__':
    conversation_stream_example()

Logging

To output Dashscope logs, you need to configure the logger.

export DASHSCOPE_LOGGING_LEVEL='info'

Output

The output contains the following fields:

     request_id (str): The request id.
     status_code (int): HTTP status code, 200 indicates that the
         request was successful, others indicate an error。
     code (str): Error code if error occurs, otherwise empty str.
     message (str): Set to error message on error.
     output (Any): The request output.
     usage (Any): The request usage information.

Error Handling

Currently, errors are thrown as exceptions.

Contributing

Coming soon.

License

This project is licensed under the Apache License (Version 2.0).

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

dashscope-1.13.2-py3-none-any.whl (78.7 kB view details)

Uploaded Python 3

File details

Details for the file dashscope-1.13.2-py3-none-any.whl.

File metadata

  • Download URL: dashscope-1.13.2-py3-none-any.whl
  • Upload date:
  • Size: 78.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.10.8

File hashes

Hashes for dashscope-1.13.2-py3-none-any.whl
Algorithm Hash digest
SHA256 9b7dc993e128bece0880063bd14d81424299e4e8581aeb3e7736cf809c25a6ff
MD5 bdf5f6ecd5bc5ff7a0fb1c37ea51f88a
BLAKE2b-256 34288feea32be6d1de52c50b82cee249b6cd93469a5b55e365de3423d2f5dd26

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page