dashscope


Namedashscope JSON
Version 1.20.13 PyPI version JSON
download
home_pagehttps://dashscope.aliyun.com/
Summarydashscope client sdk library
upload_time2024-11-18 07:16:09
maintainerNone
docs_urlNone
authorAlibaba Cloud
requires_python>=3.8.0
licenseApache 2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <h4 align="center">
    <p>
        <b>English</b>
    <p>
</h4>


</div>

# DashScope Python Library

## Installation
To install the DashScope Python SDK, simply run:
```shell
pip install dashscope
```

If you clone the code from github, you can install from  source by running:
```shell
pip install -e .
```

To use tokenizer in local mode without downloading any files, run:
```shell
pip install dashscope[tokenizer]
```


## QuickStart

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

```python
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](https://dashscope.aliyun.com) regarding how to obtain your api-key.

### Using the API Key

1. Set the API key via code
```python
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'

```

2. Set the API key via environment variables

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

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

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

```shell
export DASHSCOPE_API_KEY_FILE_PATH='~/.dashscope/api_key'
```

3. Save the API key to a file
```python
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.

```python
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:
```python
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()

```
#### Stream with Messages
```python
from http import HTTPStatus
from dashscope import Generation
from dashscope.api_entities.dashscope_response import Role


def stream_with_messages():
    messages = [{'role': Role.SYSTEM, 'content': 'You are a helpful assistant.'},
                {'role': Role.USER, 'content': '如何做西红柿炖牛腩?'}]
    responses = Generation.call(
        Generation.Models.qwen_turbo,
        messages=messages,
        result_format='message',  # set the result to be "message" format.
        stream=True,
    )
    for response in responses:
       if response.status_code == HTTPStatus.OK:
           print(response)
       else:
           print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
               response.request_id, response.status_code,
               response.code, response.message
           ))

if __name__ == '__main__':
    stream_with_messages()

```
## Logging
To output Dashscope logs, you need to configure the logger.
```shell
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).



            

Raw data

            {
    "_id": null,
    "home_page": "https://dashscope.aliyun.com/",
    "name": "dashscope",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8.0",
    "maintainer_email": null,
    "keywords": null,
    "author": "Alibaba Cloud",
    "author_email": "dashscope@alibabacloud.com",
    "download_url": null,
    "platform": "Posix; MacOS X; Windows",
    "description": "<h4 align=\"center\">\n    <p>\n        <b>English</b>\n    <p>\n</h4>\n\n\n</div>\n\n# DashScope Python Library\n\n## Installation\nTo install the DashScope Python SDK, simply run:\n```shell\npip install dashscope\n```\n\nIf you clone the code from github, you can install from  source by running:\n```shell\npip install -e .\n```\n\nTo use tokenizer in local mode without downloading any files, run:\n```shell\npip install dashscope[tokenizer]\n```\n\n\n## QuickStart\n\nYou can use `Generation` api to call model qwen-turbo(\u901a\u4e49\u5343\u95ee).\n\n```python\nfrom http import HTTPStatus\nimport dashscope\nfrom dashscope import Generation\n\ndashscope.api_key = 'YOUR-DASHSCOPE-API-KEY'\nresponses = Generation.call(model=Generation.Models.qwen_turbo,\n                            prompt='\u4eca\u5929\u5929\u6c14\u597d\u5417\uff1f')\n\nif responses.status_code == HTTPStatus.OK:\n    print('Result is: %s' % responses.output)\nelse:\n    print('Failed request_id: %s, status_code: %s, code: %s, message:%s' %\n            (responses.request_id, responses.status_code, responses.code,\n            responses.message))\n\n```\n\n## API Key Authentication\n\nThe SDK uses API key for authentication. Please refer to [official documentation](https://dashscope.aliyun.com) regarding how to obtain your api-key.\n\n### Using the API Key\n\n1. Set the API key via code\n```python\nimport dashscope\n\ndashscope.api_key = 'YOUR-DASHSCOPE-API-KEY'\n# Or specify the API key file path via code\n# dashscope.api_key_file_path='~/.dashscope/api_key'\n\n```\n\n2. Set the API key via environment variables\n\na. Set the API key directly using the environment variable below\n\n```shell\nexport DASHSCOPE_API_KEY='YOUR-DASHSCOPE-API-KEY'\n```\n\nb. Specify the API key file path via an environment variable\n\n```shell\nexport DASHSCOPE_API_KEY_FILE_PATH='~/.dashscope/api_key'\n```\n\n3. Save the API key to a file\n```python\nfrom dashscope import save_api_key\n\nsave_api_key(api_key='YOUR-DASHSCOPE-API-KEY',\n             api_key_file_path='api_key_file_location or (None, will save to default location \"~/.dashscope/api_key\"')\n\n```\n\n\n## Sample Code\n\n`call` function provides  synchronous call, the function call will return when computation is done on the server side.\n\n```python\nfrom http import HTTPStatus\nfrom dashscope import Generation\n# export DASHSCOPE_API_KEY='YOUR-DASHSCOPE-API-KEY' in environment\ndef sync_dashscope_sample():\n    responses = Generation.call(\n        model=Generation.Models.qwen_turbo,\n        prompt='Is the weather good today?')\n\n    if responses.status_code == HTTPStatus.OK:\n        print('Result is: %s'%responses.output)\n    else:\n        print('Code: %s, status_code: %s, code: %s, message: %s'%(responses.status_code,\n                                                   responses.code,\n                                                   responses.message))\n\nif __name__ == '__main__':\n    sync_dashscope_sample()\n```\n\nFor 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.\n\nExample with simple streaming:\n```python\nfrom http import HTTPStatus\nfrom dashscope import Generation\n\ndef sample_sync_call_stream():\n    prompt_text = 'Give me a recipe using carrots, potatoes, and eggplants'\n    response_generator = Generation.call(\n        model=Generation.Models.qwen_turbo,\n        prompt=prompt_text,\n        stream=True,\n        max_length=512,\n        top_p=0.8)\n    for resp in response_generator:  # Iterate through the streaming output results\n        if resp.status_code == HTTPStatus.OK:\n            print(resp.output)\n        else:\n            print('Request failed, message: %s'%resp.message)\n\nif __name__ == '__main__':\n    sample_sync_call_stream()\n\n```\n#### Stream with Messages\n```python\nfrom http import HTTPStatus\nfrom dashscope import Generation\nfrom dashscope.api_entities.dashscope_response import Role\n\n\ndef stream_with_messages():\n    messages = [{'role': Role.SYSTEM, 'content': 'You are a helpful assistant.'},\n                {'role': Role.USER, 'content': '\u5982\u4f55\u505a\u897f\u7ea2\u67ff\u7096\u725b\u8169\uff1f'}]\n    responses = Generation.call(\n        Generation.Models.qwen_turbo,\n        messages=messages,\n        result_format='message',  # set the result to be \"message\" format.\n        stream=True,\n    )\n    for response in responses:\n       if response.status_code == HTTPStatus.OK:\n           print(response)\n       else:\n           print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (\n               response.request_id, response.status_code,\n               response.code, response.message\n           ))\n\nif __name__ == '__main__':\n    stream_with_messages()\n\n```\n## Logging\nTo output Dashscope logs, you need to configure the logger.\n```shell\nexport DASHSCOPE_LOGGING_LEVEL='info'\n\n```\n\n## Output\nThe output contains the following fields:\n```\n     request_id (str): The request id.\n     status_code (int): HTTP status code, 200 indicates that the\n         request was successful, others indicate an error\u3002\n     code (str): Error code if error occurs, otherwise empty str.\n     message (str): Set to error message on error.\n     output (Any): The request output.\n     usage (Any): The request usage information.\n```\n\n## Error Handling\nCurrently, errors are thrown as exceptions.\n\n\n## Contributing\nComing soon.\n\n\n## License\nThis project is licensed under the Apache License (Version 2.0).\n\n\n",
    "bugtrack_url": null,
    "license": "Apache 2.0",
    "summary": "dashscope client sdk library",
    "version": "1.20.13",
    "project_urls": {
        "Homepage": "https://dashscope.aliyun.com/"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "edea6d0a41151dfe3a9e92c0d67182e923f2be25893ba6e92d2b3fdfb9dc4554",
                "md5": "6a176c48494fdb30ea4af48da128e732",
                "sha256": "68fb7e9ffa260ebba7188520ca3e462b651ead0d5ee470ccd510c84856be7465"
            },
            "downloads": -1,
            "filename": "dashscope-1.20.13-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "6a176c48494fdb30ea4af48da128e732",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8.0",
            "size": 1264298,
            "upload_time": "2024-11-18T07:16:09",
            "upload_time_iso_8601": "2024-11-18T07:16:09.472623Z",
            "url": "https://files.pythonhosted.org/packages/ed/ea/6d0a41151dfe3a9e92c0d67182e923f2be25893ba6e92d2b3fdfb9dc4554/dashscope-1.20.13-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-18 07:16:09",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "dashscope"
}
        
Elapsed time: 0.80752s