Skip to main content

Call an agent application

You can integrate Alibaba Cloud Model Studio agent applications into your business systems using the DashScope SDK (a unified API for Alibaba Cloud model services) or HTTP requests.

Prerequisites

Before you begin, complete the following three steps to set up your development environment.
  1. Obtain credentials
  2. Install the DashScope SDK
    Skip this step if you use HTTP APIs.
    Select and run the installation command for your programming language.
    • Python
    • Java
    Run the following command to install or upgrade the DashScope Python SDK:
    # 使用此命令,将SDK安装到您的Python 3环境中
    python3 -m pip install -U dashscope
    
  3. Configure environment variables (recommended) To protect your credentials and avoid hard-coding them in your code, we recommend that you configure the API key as an environment variable. The SDK reads the API key from this variable automatically.

Quick start

  • Python
  • Java
  • HTTP
Sample request
import os
import dashscope
from dashscope import DashScopeError

client = dashscope.Client(
    # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    response = client.apps.completions.create(
        app_id='APP_ID',# 替换为实际的应用 ID
        prompt='你是谁?')
    print(response.text)
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
Sample response
我是阿里云开发的一款超大规模语言模型,我叫千问。我被设计用来帮助用户生成各种类型的文本,如文章、故事、诗歌、故事等,并能根据不同的场景和需求进行调整和优化。此外,我还能够回答各种问题,提供信息和解释,辅助学习和研究。如果您有任何需要,欢迎随时向我提问!

Core features

Multi-turn conversation

Unlike single-turn conversations, multi-turn conversations enable large language models to reference historical information, resulting in more natural and realistic interactions.
Cloud storageSelf-managed
When you pass the session_id, the system automatically loads stored conversation history from the cloud and combines it with new instructions to generate context.You must maintain a messages array to manually record and pass conversation history and new instructions for each turn.
Required parameters:
  • session_id: The session ID.
  • prompt: The prompt.
Required parameter: messages arrayOptional parameter: prompt
  • If you pass a prompt, the prompt is converted to a {"role": "user", "content": "prompt"} object and automatically appended to the end of the messages array to form the final context.
  • Example:
// 原始传入
{
  "messages": [{"role": "user", "content": "你好"}],
  "prompt": "推荐一部电影"
}
// 实际生效的messages
[
  {"role": "user", "content": "你好"},
  {"role": "user", "content": "推荐一部电影"}
]
Priority rule: If both session_id and messages are passed, messages takes precedence. The session_id is ignored.
  • Cloud storage
  • Self-managed
  • Python
  • Java
  • HTTP
Sample request
import os
import dashscope
from dashscope import DashScopeError

def call_with_session():
    client = dashscope.Client(
        # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        api_key=os.getenv("DASHSCOPE_API_KEY"))
    try:
        response = client.apps.completions.create(
            app_id='YOUR_APP_ID',  # 替换为实际的应用 ID
            prompt='你是谁?')

        responseNext = client.apps.completions.create(
                    app_id='YOUR_APP_ID',  # 替换为实际的应用 ID
                    prompt='你有什么技能?',
                    session_id=response.session_id)  # 上一轮response的session_id

        print('%s\n session_id=%s\n' % (responseNext.text, responseNext.session_id))
        # print('%s\n' % (responseNext.usage))
    except DashScopeError as e:
        print(f'request_id={e.request_id}')
        print(f'code={e.code}')
        print(f'message={e.message}')
        print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

if __name__ == '__main__':
    call_with_session()
Sample response
我具备多种技能,可以协助你完成各种任务。以下是一些主要的技能:

1. **信息查询**:提供天气、新闻、历史事实、科学知识等各种信息。
2. **语言处理**:翻译文本、纠正语法错误、生成文章和故事。
3. **技术问题解答**:解答编程、软件使用、技术故障排除等问题。
4. **学习辅导**:帮助解答数学、物理、化学等学科的问题。
5. **生活建议**:提供健康、饮食、旅行、购物等方面的建议。
6. **娱乐互动**:讲笑话、玩文字游戏、进行简单的聊天互动。
7. **日程管理**:提醒重要日期、安排日程、设置提醒。
8. **数据分析**:解释数据图表、提供数据分析建议。
9. **情感支持**:倾听你的感受、提供安慰和支持。

如果你有具体的需求或问题,可以直接告诉我,我会尽力帮助你!
 session_id=98ceb3ca0c4e4b05a20a00f913050b42

Streaming output

A large language model receives input and generates intermediate results step by step. It outputs these results in real time. This approach is called streaming output. It lets you view content as the model generates it, which reduces wait time. How to enable streaming output Set the appropriate parameter based on your calling method:
  • Python SDK: Set the stream parameter to True.
  • Java SDK: Use the streamCall method.
  • HTTP: In the Header, set X-DashScope-SSE to enable.
By default, streaming output returns non-incremental content. Each response includes all content generated up to that point. To return incremental content, set the corresponding parameter:
  • Python SDK: Set the incremental_output parameter to True.
  • Java SDK: Use the incrementalOutput method and set it to true.
  • HTTP: In the parameters object, use the incremental_output parameter and set it to true.
Example call If your agent application uses a deep thinking model such as Qwen3, the output order is “think first, then answer.” Set the has_thoughts parameter to True to return the thinking process in the thoughts field.
  • You can enable thinking mode for the Qwen3 model in two ways. First, turn on the Thinking mode toggle in your application and publish the application. Second, set enable_thinking to true in your API call. If both are set, the API parameter takes precedence.
  • Other thinking models enable thinking mode by default. You cannot disable it.
  • Python
  • Java
  • HTTP
Sample request
import os
import dashscope
from dashscope import DashScopeError

client = dashscope.Client(
            # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
            api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    stream = client.apps.completions.create(
                app_id='YOUR_APP_ID',
                prompt='你是谁?',
                stream=True,  # 流式输出
                incremental_output=True)  # 增量输出

    for partial in stream:
        print(f'{partial.text}\n')  # 处理只输出文本text
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
Sample response
我是来自

阿里

云

的大规模语言模型

,我叫通

义千问。

Pass custom parameters

Agents can adapt to various business scenarios using custom prompt variables to guide output, plugin parameters to extend capabilities, and user-level authentication parameters for access control. When you make a call, use the biz_params parameter to pass these custom parameters for flexible responses.
DescriptionInstructions
user_prompt_paramsType: objectPasses custom prompt variables.Use this to pass variables that are inserted into the prompt. You can define the variables in the console and pass their specific values during the API call.Example:Prompt: Please recommend three local dishes for {{city}}. Display only the dish names, separated by commas.Parameters:
biz_params = {
    "user_prompt_params":{
        "city": "北京"}}
Effective prompt: Please recommend three local dishes for Beijing. Display only the dish names, separated by commas.
In the console, perform the following steps:
  1. You can add a custom variable in the agent application.
  2. Reference the variable in the prompt.
  3. Publish the application.
Ensure that the custom variable name added in the application matches the name passed in the API call.
user_defined_paramsType: objectPasses custom plugin parameters.Use this to pass business data, such as a city or date, that the plugin needs to execute its task.In the console, perform the following steps:
  1. Configure the business pass-through parameters for the plugin in the console.
    For more information about how to configure custom plugin parameters, see Custom plugins.
  2. Test and publish the plugin.
  3. You can associate the plugin with an agent application, and then publish the application.
    A plugin can only be associated with an agent application in the same workspace.
user_defined_tokensType: objectPasses custom user-level authentication parameters for a plugin.This parameter is used for user identity verification when calling a plugin, such as a DASHSCOPE_API_KEY.
biz_params = {
    "user_defined_params": {
        "<YOUR_TOOL_ID>": {
            "city": "北京"}},
    "user_defined_tokens": {
        "<YOUR_TOOL_ID>": {
            "user_token": "sk-xxx"}}}
The following are API call examples:
  • Prompt variables
  • Plugin business parameters
  • Plugin user-level authentication parameters
Steps
  1. In the console, add a custom variable to the agent application, reference it in the prompt, and then publish the application. Example:
    1. Click + Custom Variable to add a variable.
    2. Configure the variable: set the name to city, description to city name, and default value to Hangzhou.
    3. In the prompt editing area, enter a prompt that references the variable, for example: Based on the city name ${city}, recommend three local delicacies. Display only the food names, separated by commas.
  2. Make an API call. The following are examples:
    • Python
    • Java
    • HTTP
    Sample request
    import os
    import dashscope
    # 需要 dashscope 2.0.1 及以上版本
    from dashscope import DashScopeError
    
    client = dashscope.Client(
                # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
                api_key=os.getenv("DASHSCOPE_API_KEY"))
    biz_params = {
        # 智能体应用的自定义变量参数,可替换为实际参数,支持传入多个变量键值对,英文逗号隔开
        "user_prompt_params":{
            "city": "北京"}}
    try:
        response = client.apps.completions.create(
                    app_id='YOUR_APP_ID', # 替换为实际的应用ID,应用卡片获取
                    prompt='美食推荐',
                    biz_params=biz_params)
    
        print('%s\n' % (response.text))  # 处理只输出文本text
        # print('%s\n' % (response.usage))
    except DashScopeError as e:
        print(f'request_id={e.request_id}')
        print(f'code={e.code}')
        print(f'message={e.message}')
        print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
    
    Sample response
    北京烤鸭,炸酱面,豆汁儿
    

Advanced features

Retrieve from a knowledge base

The knowledge base feature powers Model Studio’s retrieval-augmented generation (RAG) capability. It helps large language models (LLMs) access private knowledge and stay up to date with the latest information. You can specify a retrieval scope when calling an agent application to improve response accuracy. For more information, see Create and use a knowledge base.

Prerequisites

In the Model Studio console, enable your agent application and turn on the knowledge base switch. Then, publish the application.

Specify a retrieval scope

  1. You can retrieve from a specific knowledge base in three ways:
    1. In your application, click Configure knowledge base to associate a specific knowledge base, and then publish the application.
    2. Do not associate a knowledge base in your application. Instead, pass the knowledge base ID in the rag_options parameter during the API call.
    3. Associate a knowledge base in your application and pass the knowledge base ID in the rag_options parameter during the API call.
      In this case, only the knowledge base passed in the API call is used for retrieval. For example, if your web-based agent application is linked to Knowledge Base A, but your API call specifies only Knowledge Base B, then only Knowledge Base B is retrieved, not Knowledge Base A.
    Obtain the knowledge base ID (pipeline_ids): You can find it on the Knowledge Base page. You can also obtain it from the Data.Id field in the response from the CreateIndex API call (for unstructured knowledge bases only). The knowledge base can be one already associated with your agent application, or one that is not yet associated. For example, you can use Bailian Series Mobile Product Introduction.docx as an unstructured data knowledge base file.
    • Python
    • Java
    • HTTP
    Sample request
    import os
    import dashscope
    # 需要 dashscope 2.0.1 及以上版本
    from dashscope import DashScopeError
    
    client = dashscope.Client(
        # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        api_key=os.getenv("DASHSCOPE_API_KEY"))
    try:
        response = client.apps.completions.create(
            app_id='YOUR_APP_ID',  # 应用ID替换YOUR_APP_ID
            prompt='请帮我推荐一款3000元以下的手机',
            rag_options={
                "pipeline_ids": ["YOUR_PIPELINE_ID1","YOUR_PIPELINE_ID2"],  # 替换为实际的知识库ID,逗号隔开多个
            }
        )
    
        print('%s\n' % (response.text))  # 处理只输出文本text
        # print('%s\n' % (response.usage))
    except DashScopeError as e:
        print(f'request_id={e.request_id}')
        print(f'code={e.code}')
        print(f'message={e.message}')
        print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
    
    Sample response
    根据您的预算,我推荐您选择**百炼 Zephyr Z9**。这款手机的参考售价在2499-2799元之间,符合您的预算需求。它拥有轻巧的6.4英寸1080 x 2340像素屏幕设计,搭配128GB存储与6GB RAM,适合日常使用。此外,它还配备了4000mAh电池以及支持30倍数字变焦的镜头,能够很好地满足拍照及续航的需求。如果您追求的是轻薄便携且功能全面的手机,那么百炼 Zephyr Z9会是一个不错的选择。
    
  2. Retrieve from a specific unstructured data document: Pass the knowledge base ID, document ID, document tags, or document metadata (key-value pairs) in the rag_options parameter.
    Document IDs, tags, and metadata apply only to unstructured data documents.
    • How to obtain them:
      • Document IDs (file_ids): Use the ID returned by AddFile, or open Collections, click Details for the target file dataset, and get the ID from the document list.
      • Document tags (tags): In Collections, click Details for the target file dataset to view its document tags. You can also obtain tags through DescribeFile.
      • Document metadata (metadata): On the Knowledge Base page, after entering a knowledge base, you can view the metadata of unstructured documents (Meta information).
    • You can pass in multiple document IDs, but only documents with established knowledge indexes are supported.
    • When passing in document IDs, you must also pass in the ID of the knowledge base to which the documents belong; otherwise, retrieval will not take effect.
    • Retrieval is performed only in the specified documents. For example: if the agent application on the web page references knowledge base A, but the API call specifies document IDs and the ID of knowledge base B to which they belong, then documents in knowledge base A will not be retrieved, and only documents in knowledge base B will be retrieved. For example, you can use Bailian Series Mobile Product Introduction.docx as an unstructured data knowledge base file.
      • Python
      • Java
      • HTTP
      Sample request
      import os
      import dashscope
      # 需要 dashscope 2.0.1 及以上版本
      from dashscope import DashScopeError
      
      client = dashscope.Client(
          # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
          api_key=os.getenv("DASHSCOPE_API_KEY"))
      try:
          response = client.apps.completions.create(
              app_id='YOUR_APP_ID',  # 应用ID替换YOUR_APP_ID
              prompt='请帮我推荐一款3000元以下的手机',
              rag_options={
                  "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"],  # 替换为实际的知识库ID,逗号隔开多个
                  "file_ids": ["YOUR_FILE_ID1", "YOUR_FILE_ID2"],  # 替换为实际的非结构化文档 ID,逗号隔开多个
                  "metadata_filter": {  # 文档元数据键值对,逗号隔开多个
                      "key1": "value1",
                      "key2": "value2"
                  },
                  "tags": ["tag1", "tag2"]  # 文档标签,逗号隔开多个
              }
          )
      
          print('%s\n' % (response.text))
      except DashScopeError as e:
          print(f'request_id={e.request_id}')
          print(f'code={e.code}')
          print(f'message={e.message}')
          print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
      
      Sample response
      {
          "text": "在3000元以下的预算范围内,我推荐您考虑**百炼 Zephyr Z9**。这款手机的特点如下:
      
      - **屏幕**:6.4英寸 1080 x 2340像素,适合日常使用和娱乐。
      - **内存与存储**:6GB RAM + 128GB 存储空间,能够满足大部分用户对于流畅度以及存储的需求。
      - **电池容量**:4000mAh,提供了一整天的使用保障。
      - **摄像头功能**:配备了一个支持30倍数字变焦的镜头,可以捕捉到更远距离的细节。
      - **其他特性**:设计轻薄便携,易于携带。
      
      参考售价为2499至2799元之间,正好符合您的预算要求,并且提供了不错的性价比。希望这些建议对您有所帮助!",
          "finish_reason": "stop",
          "session_id": "10bdea3d1435406aad8750538b701bee",
          "thoughts": null,
          "doc_references": null
      }
      
  3. Retrieve specific data from a structured data document by passing the knowledge base ID and key-value pairs for structured data fields—such as table header and value—in the rag_options parameter. Retrieve structured data key-value pairs (structured_filter): On the Knowledge Base page, open a knowledge base and click View index to view index information for structured documents.
    • Python
    • Java
    • HTTP
    Sample request
    import os
    import dashscope
    # 需要 dashscope 2.0.1 及以上版本
    from dashscope import DashScopeError
    
    client = dashscope.Client(
        # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        api_key=os.getenv("DASHSCOPE_API_KEY"))
    try:
        response = client.apps.completions.create(
            app_id='YOUR_APP_ID',  # 应用ID替换YOUR_APP_ID
            prompt='请帮我推荐一款3000元以下的手机',
            rag_options={
                "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"],  # 替换为实际的知识库ID,逗号隔开多个
                 "structured_filter": {  # 结构化数据键值对,对应结构化数据,逗号隔开多个
                    "key1": "value1",
                    "key2": "value2"
                 }
            }
        )
    
        print('%s\n' % (response.text))
    except DashScopeError as e:
        print(f'request_id={e.request_id}')
        print(f'code={e.code}')
        print(f'message={e.message}')
        print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
    
    Sample response
    {
        "text": "我为您推荐"百炼"这款手机,它的价格是2999元,符合您的预算要求。如果您需要了解更多信息,比如性能、外观等,请告诉我。",
        "finish_reason": "stop",
        "session_id": "80a3b868b5ce42c8a12f01dccf8651e2",
        "thoughts": null,
        "doc_references": null
    }
    

View information

  • View retrieval process information: Add has_thoughts in the code and set it to True when calling. The retrieval process information will then be returned in the thoughts field of the response.
  • View answer source information: Click Configure next to the Knowledge Base switch, turn on the Show Source switch on the page, and then publish the application. You can then view the answer sources in the returned results of the call.

Deep thinking

If you select the deep thinking model in your agent application and successfully publish it, then: Enable thinking mode: To enable thinking mode and obtain its output, you can configure it in one of two ways.
  1. Console settings For Qwen3 models: In the console, make sure the thinking mode switch is turned on, then republish the application. For other models: Thinking mode is enabled by default. No action is required.
  2. API parameter settings For Qwen3 models: Set the enable_thinking parameter to true. For other models: The enable_thinking parameter has no effect.
Priority: If you use both methods, the API parameter setting takes precedence.
Retrieve the thinking process:
  • Set the has_thoughts parameter to true.
Processing the response:
  • Thinking process: Is returned in the thought field of the response.
  • Final reply: Is returned in the text field of the response.
Deep thinking models may produce long thinking processes. To reduce the risk of a timeout, use streaming output. See the following examples.
  • Python
  • Java
  • curl
Sample request
import os
import dashscope
from dashscope import DashScopeError

client = dashscope.Client(
    # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    api_key=os.getenv('DASHSCOPE_API_KEY'))

try:
    stream = client.apps.completions.create(
        app_id='YOUR_APP_ID',# 替换为实际的应用 ID
        prompt='你是谁?',# 替换为实际的应用输入
        stream=True,  # 是否流式输出,True:流式输出;False(默认值): 非流式输出
        incremental_output=True,  # 是否增量输出,True:增量输出;False(默认值): 非增量输出
        has_thoughts=True  # 是否返回思考过程,True:返回;False(默认值): 不返回
    )

except Exception as e:
    print(f"API请求异常: {str(e)}")
    exit(1)

# 定义完整思考过程
reasoning_content = []
# 定义完整回复
answer_content = ""
# 判断是否结束思考过程并开始回复
is_answering = False

def print_section(title):
    """打印带装饰的分段标题"""
    print(f"\n{'=' * 20} {title} {'=' * 20}\n", flush=True)

print_section("思考过程")

try:
    for chunk in stream:
        # 跳过空数据块
        if not chunk.thoughts and not chunk.text:
            continue

        # 处理思考过程
        if chunk.thoughts:
            for it in chunk.thoughts:
                if it.action_type == 'reasoning':# 推理类模型的思考过程action_type为reasoning,输出在thought
                    content = str(it.thought) if not isinstance(it.thought, str) else it.thought
                    reasoning_content.append(content)
                    print(content, end="", flush=True)

        # 处理回答内容
        if chunk.text:
            if not is_answering:
                print_section("完整回复")
                is_answering = True

            answer_content += str(chunk.text)
            print(chunk.text, end="", flush=True)
except DashScopeError as e:
    # 流式输出中的错误会直接抛出异常
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

# 最终结果整合
final_reasoning = "".join(reasoning_content)
final_answer = "".join(answer_content)

# 如果您需要打印完整思考过程与完整回复,请将以下代码解除注释后运行
#print_section("完整思考过程")
#print(final_reasoning)

#print_section("完整回复")
#print(final_answer)
Sample response
==================== 思考过程 ====================

嗯,用户问我“你是谁?”,我需要用中文回答。首先,我得介绍自己是一个AI助手,由DeepSeek公司开发。然后要说明我的功能,比如回答问题、提供信息、帮助学习等。要记得保持口语化,不用太正式。还要注意用户可能想了解我的背景,所以可以提到基于大语言模型,但不用太技术化。另外,用户可能在测试我的回答能力,所以需要简洁明了,同时友好自然。可能需要检查有没有遗漏的关键点,比如公司的正确名称,以及是否强调帮助性质。最后确保回答符合格式要求,不使用markdown,保持段落结构清晰。
==================== 完整回复 ====================

您好!我是DeepSeek-R1,一个由深度求索(DeepSeek)公司开发的智能助手,我会尽我所能为您提供帮助,包括回答问题、信息查询以及学习辅助等。

Retrieving from a knowledge base

  • The model's thinking process is returned in the thoughts object's thought field. Its action_type is reasoning.
  • The retrieval process is returned in the thoughts object's observation field. Its action_type is agentRag.
Use the action_type to distinguish between these processes and handle the output accordingly.

Long-term memory

Alibaba Cloud Model Studio’s agent applications retain some of your conversation history. However, due to large language model (LLM) attention limits, they may forget details. To address this, store important information in long-term memory. Your application will then reference that memory in future conversations. Steps Step 1: Enable thelong-term memoryfeature Go to the Application Management page. Find your agent application, turn on the long-term memory switch, and then publish the application. Step 2: Create a memory Call the CreateMemory API to create a memory. From the response, retrieve a unique memoryId. Step 3: Save conversation information Pass the memoryId you retrieved earlier. The system automatically analyzes your conversation and saves key information as memory linked to that memoryId. Step 4: Use long-term memory in conversations Each time you interact with the agent, provide the same memoryId. The system retrieves the corresponding memory content based on the provided memoryId and passes it along with the current question to the model to generate a response. Example call
  • Python
  • Java
  • HTTP
Request example (create memory content)
# 需要 dashscope 2.0.1 及以上版本
import os
import dashscope
from dashscope import DashScopeError

client = dashscope.Client(
           # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
            api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    response = client.apps.completions.create(
            app_id='YOUR_APP_ID',  # 请输入实际的应用 ID
            prompt='用户饮食偏好:面食',
            memory_id='YOUR_MEMORY_ID')  # 请输入实际的记忆体 ID

    print('%s\n' % (response.text))  # 处理只输出text
    # print('%s\n' % (response.usage))
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
Sample response
了解了,您对面食情有独钟。如果想要推荐或者寻找面食相关的食谱、餐厅等信息,请告诉我更多细节,比如是想吃哪种类型的面条(如拉面、意大利面等),还是有什么特别的口味偏好?这样我能更好地为您提供帮助。
Request example (call again)
# 需要 dashscope 2.0.1 及以上版本
import os
import dashscope
from dashscope import DashScopeError

client = dashscope.Client(
           # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
            api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    response = client.apps.completions.create(
            app_id='YOUR_APP_ID',  # 请输入实际的应用 ID
            prompt='美食推荐',
            memory_id='YOUR_MEMORY_ID')  # 请输入实际的记忆体 ID

    print('%s\n' % (response.text))  # 处理只输出text
    # print('%s\n' % (response.usage))
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
Sample response
既然您偏好面食,我推荐您可以尝试一下几种美食:

1. **炸酱面**:经典的北京风味,面条搭配特制的黄豆酱和肉末,口感丰富。
2. **担担面**:四川特色,辣中带麻,非常开胃。如果您喜欢尝试一些稍微刺激一点的味道,这会是个不错的选择。
3. **刀削面**:山西的传统名吃之一,以其独特的制作方法——用刀将面团直接削入锅中煮熟而得名,口感劲道。
4. **意大利面**:如果想要换换口味的话,不妨试试西式的意面,比如番茄肉酱意面或是奶油培根意面等,都是不错的选择。

希望这些建议对您有所帮助!如果有更具体的口味偏好或其他需求,请随时告诉我哦~

Upload files (documents, images, videos, or audio)

In your agent application, you can upload files such as documents, images, videos, or audio, and ask questions based on their content.

Scenarios

  • Text parsing: You can extract text content from documents, images, videos, or audio, and combine the extracted content with large language models to answer questions.
  • Visual understanding: You can use the Qwen-VL series models to analyze image content (objects, scenes, and actions) without requiring text input.
To upload files and interact with large language models via the console, see Upload files. For API usage, see below.
  • Text parsing
  • Visual understanding
Step 1: Prepare filesYour files must meet these requirements.You can upload up to 10 files, including local documents, images, videos, or audio files in the following formats:
  • Document (Up to 100 MB): .doc, .docx, .ppt, .pptx, .xls, .xlsx, .md, .txt, .pdf;
  • Image (Up to 20 MB): .png, .jpg, .jpeg, .bmp, .gif; Currently, only local images that contain text are supported.
  • Videos (Up to 512 MB): .mp4, .mkv, .avi, .mov, .wmv;
  • Audio (Up to 512 MB): .aac, .amr, .flac, .flv, .m4a, .mp3, .mpeg, .ogg, .opus, .wav, .webm, .wma.
Step 2: Get a session file ID
  1. You can obtain a session file ID starting with “file_session” using the API to obtain a session file ID.
  2. Ensure the file status is FILE_IS_READY.
Step 3: Call your application via API
  1. In the console agent application, you can select any model, turn on the dynamic file parsing switch, and then publish the application.
    Your agent application and the uploaded files must be in the same workspace.
  2. When calling the API, you must pass the session file ID obtained in Step 2 in the session_file_ids parameter. For example:
    In the Java SDK, it is sessionFileIds. When calling via HTTP, put session_file_ids into the parameters object.
    The session file ID must start with “file_session_”, and its file status must be FILE_IS_READY. Otherwise, the call will fail.
    • Python
    • Java
    • HTTP
    Sample request
    import os
    import dashscope
    # 需要 dashscope 2.0.1 及以上版本
    from dashscope import DashScopeError
    
    client = dashscope.Client(
        # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        api_key=os.getenv("DASHSCOPE_API_KEY"))
    try:
        response = client.apps.completions.create(
            app_id='YOUR_APP_ID',  # 应用ID替换YOUR_APP_ID
            prompt='请根据以下文件帮我推荐一款3000元以下的手机',
            rag_options={
                "session_file_ids": ["FILE_ID1"],  # FILE_ID1 替换为实际的临时文件ID,逗号隔开多个
            }
        )
    
        print('%s\n' % (response.text))  # 处理只输出文本text
        # print('%s\n' % (response.usage))
    except DashScopeError as e:
        print(f'request_id={e.request_id}')
        print(f'code={e.code}')
        print(f'message={e.message}')
        print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
    
    Sample response
    根据您的预算,我推荐您选择**通义 Vivid 7**这款手机。以下是它的主要特点:
    
    - **屏幕**:6.5英寸,1080 x 2400像素
    - **存储与内存**:128GB存储,8GB RAM
    - **电池**:4500mAh
    - **特色功能**:AI智能摄影,侧面指纹解锁
    - **参考售价**:2999-3299元
    
    通义Vivid 7不仅价格适中,而且具有良好的性能和实用的功能,特别适合喜欢拍照的用户。希望这个建议对您有所帮助!
    
Get a session file ID via API

Steps

  1. Request a file upload lease Try it online You can use the ApplyFileUploadLease API.
    Call diagramKey parameters
    Set CategoryType to SESSION_FILE, complete the parameter configuration, and then click Initiate Call.CategoryId: Must be default.
    FileName: File name with extension.
    Md5: You can run the sample code below to obtain the MD5 hash of your file.

    MD5 generation sample code

    Python
    # 示例代码仅供参考,请勿在生产环境中直接使用
    import hashlib
    def calculate_md5(file_path):
        """计算文档的 MD5 值。
    
        Args:
            file_path (str): 文档的路径。
    
        Returns:
            str: 文档的 MD5 值。
        """
        md5_hash = hashlib.md5()
    
        # 以二进制形式读取文件
        with open(file_path, "rb") as f:
            # 按块读取文件,避免大文件占用过多内存
            for chunk in iter(lambda: f.read(4096), b""):
                md5_hash.update(chunk)
    
        return md5_hash.hexdigest()
    
    # 使用示例
    file_path = "请替换为您需要上传文档的实际本地路径,例如/Users/<username>/Desktop/阿里云百炼系列手机产品介绍.docx"
    md5_value = calculate_md5(file_path)
    print(f"文档的MD5值为: {md5_value}")
    
    SizeInBytes: File size in bytes. For example: 6 KB equals 6 × 1024 bytes, which is 6144 bytes.
    CategoryType: Must be SESSION_FILE.
    Success responseA successful call returns the following JSON response (sensitive fields are masked):
    {
        "Status": "200",
        "Message": "",
        "RequestId": "519DD942-4701-xxx",
        "Data": {
            "FileUploadLeaseId": "ed76eb4xxx",
            "Type": "OSS.PreSignedUrl",
            "Param": {
                "Headers": {
                    "X-bailian-extra": "MTY3MzAyNxxx==",
                    "Content-Type": "application/msword"
                },
                "Method": "PUT",
                "Url": "https://dashscope-file-datacenter-xxx"
            }
        }
    }
    
    Instructions
    1. Make sure to save the values of the Data.FileUploadLeaseId, Data.Param.Method, Data.Param.Url, Data.Param.Headers.X-bailian-extra, and Data.Param.Headers.Content-Type fields from this API response. They are required for the subsequent upload steps.
    2. The Data.Param.Url value (the lease) expires in minutes—upload your file promptly to avoid expiration.
  2. Upload file to Alibaba Cloud Model Studio temporary storage You can run the sample code below. Replace placeholder values with the information obtained in Step 1. If the response indicates “File uploaded successfully.”, the upload was successful.
    You can write multilingual examples yourself.
    Python
    # 示例代码仅供参考,请勿在生产环境中直接使用
    import requests
    from urllib.parse import urlparse
    
    def upload_file(pre_signed_url, file_path):
        try:
            # 设置请求头
            headers = {
                "X-bailian-extra": "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中X-bailian-extra字段的值",
                "Content-Type": "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中Content-Type字段的值"
            }
    
            # 读取文档并上传
            with open(file_path, 'rb') as file:
                # 下方设置请求方法用于文档上传,需与您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Method字段的值一致
                response = requests.put(pre_signed_url, data=file, headers=headers)
    
            # 检查响应状态码
            if response.status_code == 200:
                print("File uploaded successfully.")
            else:
                print(f"Failed to upload the file. ResponseCode: {response.status_code}")
    
        except Exception as e:
            print(f"An error occurred: {str(e)}")
    
    def upload_file_link(pre_signed_url, source_url_string):
        try:
            # 设置请求头
            headers = {
                "X-bailian-extra": "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中X-bailian-extra字段的值",
                "Content-Type": "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中Content-Type字段的值"
            }
    
            # 设置访问OSS的请求方法为GET
            source_response = requests.get(source_url_string)
            if source_response.status_code != 200:
                raise RuntimeError("Failed to get source file.")
    
            # 下方设置请求方法用于文档上传,需与您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Method字段的值一致
            response = requests.put(pre_signed_url, data=source_response.content, headers=headers)
    
            # 检查响应状态码
            if response.status_code == 200:
                print("File uploaded successfully.")
            else:
                print(f"Failed to upload the file. ResponseCode: {response.status_code}")
    
        except Exception as e:
            print(f"An error occurred: {str(e)}")
    
    if __name__ == "__main__":
    
        pre_signed_url_or_http_url = "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Url字段的值"
    
        # 文档来源可以是本地,上传本地文档至百炼临时存储
        file_path = "请替换为您需要上传文档的实际本地路径"
        upload_file(pre_signed_url_or_http_url, file_path)
    
        # 文档来源还可以是阿里云对象存储OSS
        # file_path = "请替换为您需要上传文档的实际阿里云对象存储OSS可公网访问地址"
        # upload_file_link(pre_signed_url_or_http_url, file_path)
    
  3. Add file to Alibaba Cloud Model Studio Data Management After Step 2 is successful, your file remains in Model Studio’s temporary storage for 12 hours. Then, you can call the Try it online AddFile API to obtain the session file ID.
    • LeaseId: Value of Data.FileUploadLeaseId from Step 1’s response.
    • CategoryId: Must be default.
    • CategoryType: Must be SESSION_FILE.
    Success responseA successful call returns the following JSON response, where FileId is the session file ID that will be used in all subsequent API operations related to this document.
    {
      "Status": 200,
      "Message": "",
      "RequestId": "AD2FB14B-8A0E-5DCB-xxx",
      "Data": {
        "FileId": "file_session_6c6bb333395xxx",
        "Parser": "DASHSCOPE_DOCMIND"
      },
      "Code": "Success",
      "Success": true
    }
    
    Instructions
    • Get the session file ID. Example: "file_session_6c6bb33339524b7xxx".
      Only IDs starting with “file_session_” can be used in the next step. If not, verify that CategoryId and CategoryType were entered correctly in Step 1.
    • After AddFile succeeds, the LeaseId (lease ID) becomes invalid—do not reuse it.
  4. Check file parsing status You can call the Try it online DescribeFile API to check the parsing status.

    Status code

    Instructions

    INIT

    File uploaded—waiting for parsing.

    PARSING

    Parsing file content.

    PARSE_SUCCESS

    File parsed successfully.

    PARSE_FAILED

    File parsing failed—re-upload required.

    SAFE_CHECKING

    Running security scan.

    SAFE_CHECK_FAILED

    Security scan failed—re-upload or choose another file.

    INDEX_BUILDING

    Building index for file.

    INDEX_BUILD_SUCCESS

    Index built successfully.

    INDEX_BUILDING_FAILED

    Index build failed—re-upload required.

    INDEX_DELETED

    Index deleted.

    FILE_IS_READY

    File ready: Parsing, security scan, and indexing all complete.

    FILE_EXPIRED

    File expired. Files last only for the current session (max 7 days). They expire automatically after closing the session—re-upload required.

    You must wait until the Status field shows FILE_IS_READY before proceeding.
    On the DescribeFile API debugging page, fill in the WorkspaceId and FileId parameters, and then click Initiate Call. Verify that the Status field in the response is FILE_IS_READY and Parser is DASHSCOPE_DOCMIND.
  5. After obtaining a valid session file ID, proceed to Step 3 above: Call your application via API.
For more information about the parameters in these steps, see Upload files via API.

Private network calls

Call applications on Alibaba Cloud Model Studio over a private network to improve data transmission security and efficiency.
  1. Add a PrivateLink connection and associate your workspace: In the Model Studio console, add a PrivateLink connection for your VPC, and then associate the target workspace with the connection.
  2. Replace the domain name: Replace the public domain name in the API request URL, dashscope.aliyuncs.com, with the private domain name that is generated after the workspace is associated. For example: https://{WorkspaceId}-{VpcId}.cn-beijing.maas.aliyuncs.com/api/v1/
  3. Make the request.
    • Python
    • Java
    • HTTP
    import os
    import dashscope
    from dashscope import DashScopeError
    # 配置私网域名:显式指定base_url
    client = dashscope.Client(
        # 若没有配置环境变量,可用阿里云百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        base_url='https://{WorkspaceId}-{VpcId}.cn-beijing.maas.aliyuncs.com/api/v1/')
    try:
        response = client.apps.completions.create(
            app_id='APP_ID',# 替换为实际的应用 ID
            prompt='你是谁?')
    
        print(response.text)
    except DashScopeError as e:
        print(f'request_id={e.request_id}')
        print(f'code={e.code}')
        print(f'message={e.message}')
        print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
    

API Reference

For a complete list of parameters, refer to the Workflow and Legacy Agent Application API.

Error codes

If the call fails (the Python SDK throws a DashScopeError exception and HTTP calls return an error message), see error messages for troubleshooting steps.

References

FAQ

  1. Verify that the class name and package name in your import statement are correct.
  2. Add the dependency library: If you use Maven or Gradle to manage your project, make sure the DashScope Java SDK dependency is added to your pom.xml or build.gradle file and that it is the latest version. You can obtain the latest version number for the DashScope Java SDK from Maven.
<!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dashscope-sdk-java</artifactId>
    <version>在此处填写最新版本号,例如2.16.4</version>
</dependency>
// https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: '在此处填写最新版本号,例如2.16.4'
  1. Upgrade the SDK: Older versions of the DashScope Java SDK may not include the features or classes that you are trying to use. If your current version is outdated, upgrade it by updating the DashScope Java SDK version in your pom.xml or build.gradle file.
<!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dashscope-sdk-java</artifactId>
    <version>请将此处的版本号修改为最新版本</version>
</dependency>
// https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: '请将此处的版本号修改为最新版本'
  1. Reload your project to apply the changes.
  2. Run the code example again.
  • session_id: Used for cloud-hosted multi-turn conversations, automatically maintaining the conversation context. Valid for 1 hour, with a maximum of 50 history rounds. Callers do not need to maintain the context themselves, but must pass in the session_id of the previous round of conversation in the next round.
  • memory_id: Used to create a long-term memory that stores specific information. You need to call the CreateMemory API to create it and obtain memoryId. To reference specific information in subsequent conversations, pass in memoryId.
These two features serve different purposes: short-term conversation context and long-term information storage.