Skip to main content

Application Calling

You can integrate Model Studio applications (agents, workflows, or agent orchestration) into your business systems via the DashScope SDK or HTTP.

Prerequisites

You can call Model Studio applications using the DashScope SDK or HTTP API. Set up your computing environment according to your needs.
Regardless of the calling method, we recommend that you configure your API key in environment variables. If you call through the DashScope SDK, you also need to install the DashScope SDK.

How to use

QuickStart

  • Python
  • Java
  • HTTP
Request example
import os
import dashscope
from dashscope import DashScopeError

# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.
client = dashscope.Client(
    # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)
try:
    response = client.apps.completions.create(
        app_id='APP_ID',  # Replace with the actual application 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'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
Response example
我是阿里云开发的一款超大规模语言模型,我叫千问。我被设计用来帮助用户生成各种类型的文本,如文章、故事、诗歌、故事等,并能根据不同的场景和需求进行调整和优化。此外,我还能够回答各种问题,提供信息和解释,辅助学习和研究。如果您有任何需要,欢迎随时向我提问!

Multi-turn

Compared with single-turn conversations, multi-turn conversations allow the LLM to reference historical conversation information, better matching everyday communication scenarios.
  • Python
  • Java
  • HTTP
Request example
import os
import dashscope
from dashscope import DashScopeError

# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.
client = dashscope.Client(
    # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

def call_with_session():
    try:
        response = client.apps.completions.create(
            app_id='YOUR_APP_ID',  # Replace with the actual application ID
            prompt='你是谁?')

        responseNext = client.apps.completions.create(
                    app_id='YOUR_APP_ID',  # Replace with the actual application ID
                    prompt='你有什么技能?',
                    session_id=response.session_id)  # The session_id from the previous response

        print('%s\n session_id=%s\n' % (responseNext.text, responseNext.session_id))
        # 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'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')

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

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

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

Pass custom parameters

To adapt the same agent or workflow to different business scenarios, you can configure custom prompt variables, custom node parameters, plug-in parameters, and user-level authentication parameters. During application calling, pass the required parameters via biz_params for flexible adaptation.
  1. Custom variable parameters: Add custom variables in an agent application in the console and reference them in the prompt. After you publish the application, pass them via user_prompt_params during API calls;
    Make sure the custom variable names added in the application match the names passed during API calls.
  2. Parameters of custom plug-ins: passed via the associated agent application. You can pass the parameter information of custom plug-ins and user-level authentication information:
    • The parameter information of a custom plug-in is passed via user_defined_params.
    • The user-level authentication information of a custom plug-in is passed via user_defined_tokens, where the value passed by user_token is the authentication information required by the plug-in, such as the actual DASHSCOPE_API_KEY value.
    For how to configure plug-in parameters, see Parameter passing of applications. Plug-in tools can only be associated with agent applications in the same business space.
Refer to the following example of calling in an agent application.
  • Custom plug-in parameter passing
  • Custom plug-in user-level authentication
The following example passes the "index" parameter information of the associated plug-in and user-level authentication information to query dormitory convention content.
<YOUR_TOOL_ID>Replace it with the ID of the associated plug-in tool (which can be obtained from the plug-in card), and pass the input parameter key-value pairs configured in the plug-in. In this example, the parameter passed is article_index, and the value is 2.
  • Python
  • Java
  • HTTP
Request example
import os
# The Dashscope SDK version must be 2.0.1 or later.
import dashscope
from dashscope import DashScopeError

# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.
client = dashscope.Client(
        # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage.
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        workspace="{WorkspaceId}",
        region="ap-southeast-1",
)
biz_params = {
    # Pass the custom plugin input parameters of the agent application. Replace <YOUR_TOOL_ID> with your custom plugin ID
    "user_defined_params": {
        "<YOUR_TOOL_ID>": {
            "article_index": 2}}}
try:
    response = client.apps.completions.create(
        app_id='YOUR_APP_ID',
        prompt='寝室公约内容',
        biz_params=biz_params)
    print('%s\n' % (response.text))  # Process the text-only output
    # 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'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
Response example
寝室公约的第二条规定如下:

"寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。"

这表明在寝室内,成员之间应该培养一种积极正面的生活和学习氛围,彼此帮助和支持,同时也要学会理解和尊重他人。如果您需要了解公约的其他条款,请告诉我!
  1. Custom node parameters: add them in the start node of a workflow application or an agent orchestration application, and pass them through biz_params. Refer to the following example of passing a city name parameter in a workflow application: set a String-type variable named city in the start node, insert the variable city and the variable query into the Prompt, and then publish the application.
    image
    When calling the application, pass city through biz_params and pass query through prompt.
    • Python
    • Java
    • HTTP
    Request example
    import os
    import dashscope
    from dashscope import DashScopeError
    
    # The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.
    client = dashscope.Client(
        # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage.
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        workspace="{WorkspaceId}",
        region="ap-southeast-1",
    )
    # Pass custom parameters of the workflow or agent orchestration application
    biz_params = {"city": "杭州"}
    try:
        response = client.apps.completions.create(
            app_id='YOUR_APP_ID',  # Replace with the actual application ID
            prompt='查询这个城市的行政区域划分',
            biz_params=biz_params  # Pass business parameters
        )
        print(f'{response.text}')  # Process the text-only output
    except DashScopeError as e:
        print(f'request_id={e.request_id}')
        print(f'code={e.code}')
        print(f'message={e.message}')
        print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
    
    Response example
    杭州市,作为浙江省的省会城市,其行政区域划分包括10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。每个区都有其独特的特色和发展重点。
    
    - 上城区:位于杭州市中心地带,是杭州的政治、经济、文化中心之一。
    - 拱墅区:以运河文化为特色,拥有众多历史文化遗产。
    - 西湖区:著名的西湖风景区就位于此区,是旅游观光的重要目的地。
    - 滨江区:高新技术产业聚集地,阿里巴巴等知名企业坐落于此。
    - 萧山区:东南部的一个行政区,经济发展迅速,特别是制造业方面。
    - 余杭区:近年来发展快速,尤其是互联网经济领域,阿里巴巴总部也设在这里(注:阿里巴巴总部实际位于滨江区)。
    - 临平区:新成立的行政区,旨在促进该地区经济社会全面发展。
    - 钱塘区:同样是一个较新的行政区划调整结果,强调创新发展和生态保护相结合。
    - 富阳区:位于杭州西南方向,以其丰富的自然景观和悠久的历史文化著称。
    - 临安区:地处杭州西部,以生态优美闻名,并且有着深厚的文化底蕴。
    
    请注意,随着时间推移,具体的城市规划可能会有所变化,请参考最新的官方信息。
    

Streaming output

After an LLM receives the input, it generates intermediate results step by step, and the final result is assembled from these intermediate results. This approach of generating and outputting intermediate results as they are produced is called streaming output. With streaming output, you can read the content while the model is generating it, reducing the wait time for the model's response. Depending on the calling method, you can set the corresponding parameter to enable streaming output:
  • Python SDK: set the stream parameter to True to enable streaming output.
  • Java SDK: you need to call through the streamCall interface.
  • HTTP: you need to specify X-DashScope-SSE as enable in the Header.
By default, streaming output content is non-incremental (that is, each response contains all previously generated content). If you need incremental streaming output, set the incremental_output (the incrementalOutput interface in Java) parameter to true. When calling through HTTP, set incremental_output to true and put it into the parameters object.
Refer to the following examples:
  • The following is an example of a streaming output call for an agent application:
    • Python
    • Java
    • HTTP
    Request example
    import os
    import dashscope
    from dashscope import DashScopeError
    
    # The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.
    client = dashscope.Client(
                # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage.
                api_key=os.getenv("DASHSCOPE_API_KEY"),
                workspace="{WorkspaceId}",
                region="ap-southeast-1",
    )
    try:
        stream = client.apps.completions.create(
                    app_id='YOUR_APP_ID',
                    prompt='你是谁?',
                    stream=True,  # Enable streaming output
                    incremental_output=True)  # Enable incremental output
    
        for partial in stream:
            print(f'{partial.text}\n')  # Process the text-only output
    except DashScopeError as e:
        print(f'request_id={e.request_id}')
        print(f'code={e.code}')
        print(f'message={e.message}')
        print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
    
    Response example
    我是来自
    
    阿里
    
    云
    
    的大规模语言模型
    
    ,我叫通
    
    义千问。
    
The following is an example of a streaming output call for a workflow application: As shown in the figure, the published workflow application configuration streams output about food and attractions in Hangzhou.
image
Call it through the API.
  • Python
  • Java
  • HTTP
Request example
import os
import dashscope
from dashscope import DashScopeError

# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.
client = dashscope.Client(
    # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)
biz_params = {
    "city": "杭州"}
try:
    stream = client.apps.completions.create(
        # Replace with the actual application ID
        app_id='YOUR_APP_ID',
        prompt='你好',
        biz_params=biz_params,
        # Enable streaming output
        stream=True,
        # incremental_output set to true enables incremental output, false disables it, and the default value is false if not specified
        incremental_output=True,
        # has_thoughts must be set to True
        has_thoughts=True)

    for response in stream:
        print(f'{response.thoughts}\n')  # The output only returns thoughts; the process information is returned in the thoughts field
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
Response example
[ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_Ilo9","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_Ilo9"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]

[ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"西湖醋鱼,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_Ilo9"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]

[ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"东坡肉,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_Ilo9"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]

[ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"知味观小\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_Ilo9"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]

[ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"笼包,龙井虾仁,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_Ilo9"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]

[ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"叫化鸡\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]

[ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_vQDv","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_vQDv"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]

[ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_kBgf","nodeResult":"{\\"result\\":\\"西湖,灵隐\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_vQDv"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]

[ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_kBgf","nodeResult":"{\\"result\\":\\"寺,宋城\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_vQDv"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]

[ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_kBgf","nodeResult":"{\\"result\\":\\",西溪湿地\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_vQDv"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]

[ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_kBgf","nodeResult":"{\\"result\\":\\",千岛湖\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_vQDv"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]

[ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_kBgf","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_vQDv","nodeExecTime":"948ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"结束","nodeResult":"{\\"result\\":\\"西湖,灵隐寺,宋城,西溪湿地,千岛湖\\"}","nodeType":"End","nodeStatus":"success","nodeId":"End_DrQn7F","nodeExecTime":"1ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]

Retrieve knowledge base

As the RAG capability of Model Studio, the knowledge base feature can effectively supplement LLMs with private knowledge and provide up-to-date information. When calling an agent application, you can specify the retrieval scope to improve the accuracy of the LLM's answers. For more information about the knowledge base feature, see Create and use a knowledge base.

Prerequisites

In the agent application on the Model Studio console, turn on the knowledge base switch, and then publish the application.
Among them, RAG applications can skip this prerequisite.

Specify the retrieval scope

  1. To retrieve a specified knowledge base (see Create and use a knowledge base), there are three ways:
    1. In the application, click Configure to associate the specified knowledge base, and then publish the application;
    2. Do not associate a specified knowledge base in the application, and pass the knowledge base ID through rag_options when calling the API;
    3. Associate the specified knowledge base in the application, and also pass the knowledge base ID through rag_options when calling the API.
      In this case, only the knowledge bases passed in during the call are retrieved. For example, if an agent application on the web console is associated with knowledge base A, but only knowledge base B is specified during the API call, knowledge base A will not be retrieved; only knowledge base B will be retrieved.
    Obtain the knowledge base ID (pipeline_ids): You can obtain it on the Knowledge Base page, or use the Data.Id returned by the CreateIndex API (only unstructured knowledge bases are supported). Call example: Here, Model Studio series phone product introduction.docx is selected as a file of an unstructured data knowledge base.
    • Python
    • Java
    • HTTP
    Request example
    import os
    # The Dashscope SDK version must be 2.0.1 or later.
    import dashscope
    from dashscope import DashScopeError
    
    # The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.
    client = dashscope.Client(
        # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage.
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        workspace="{WorkspaceId}",
        region="ap-southeast-1",
    )
    
    try:
        response = client.apps.completions.create(
            app_id='YOUR_APP_ID',  # Replace YOUR_APP_ID with the actual application ID
            prompt='请帮我推荐一款3000元以下的手机',
            rag_options={
                "pipeline_ids": ["YOUR_PIPELINE_ID1,YOUR_PIPELINE_ID2"],  # Replace with the actual knowledge base IDs. Use commas to separate multiple IDs
            }
        )
        print('%s\n' % (response.text))  # Process the text-only output
        # 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'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
    
    Response example
    根据您的预算,我推荐您选择**百炼 Zephyr Z9**。这款手机的参考售价在2499-2799元之间,符合您的预算需求。它拥有轻巧的6.4英寸1080 x 2340像素屏幕设计,搭配128GB存储与6GB RAM,适合日常使用。此外,它还配备了4000mAh电池以及支持30倍数字变焦的镜头,能够很好地满足拍照及续航的需求。如果您追求的是轻薄便携且功能全面的手机,那么百炼 Zephyr Z9会是一个不错的选择。
    
  2. Retrieve the specified unstructured data documents: Pass the knowledge base ID, document ID, document tags, or document metadata (key-value pairs) in rag_options.
    Document IDs, document tags, and document metadata only take effect for unstructured data document retrieval.
    • How to obtain:
      • Document IDs (file_ids): You can obtain them from the document list on the Application Data page, or use the IDs returned by the AddFile API when importing documents.
      • Document tags (tags): You can view the tags of unstructured documents on the Application Data page, or obtain them through the DescribeFile API.
      • 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 multiple document IDs; only documents with knowledge indexes established are supported.
    • When passing document IDs, you must also pass the ID of the knowledge base to which the documents belong for the retrieval to take effect.
    • Retrieval is performed only in the specified documents. For example: if an agent application on the web console references knowledge base A, but the API call specifies document IDs and the ID of knowledge base B to which they belong, documents in knowledge base A will not be retrieved; only documents in knowledge base B will be retrieved. This example selects Model Studio series phone product introduction.docx as an unstructured data knowledge base file.
      • Python
      • Java
      • HTTP
      Request example
      import os
      # The Dashscope SDK version must be 2.0.1 or later.
      import dashscope
      from dashscope import DashScopeError
      
      # The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.
      client = dashscope.Client(
          # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage.
          api_key=os.getenv("DASHSCOPE_API_KEY"),
          workspace="{WorkspaceId}",
          region="ap-southeast-1",
      )
      
      try:
          response = client.apps.completions.create(
              app_id='YOUR_APP_ID',  # Replace YOUR_APP_ID with the actual application ID
              prompt='请帮我推荐一款3000元以下的手机',
              rag_options={
                  "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"],  # Replace with the actual knowledge base IDs. Use commas to separate multiple IDs
                  "file_ids": ["YOUR_FILE_ID1", "YOUR_FILE_ID2"],  # Replace with the actual unstructured document IDs. Use commas to separate multiple IDs
                  "metadata_filter": {  # Document metadata key-value pairs. Use commas to separate multiple pairs
                      "key1": "value1",
                      "key2": "value2"
                  },
                  "tags": ["tag1", "tag2"]  # Document tags. Use commas to separate multiple tags
              }
          )
          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'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
      
      Response example
      {
          "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 the specified data in structured data documents: Pass the knowledge base ID and the key-value pairs of the structured data document's "structured data header + value" in rag_options. Obtain the structured data key-value pairs (structured_filter): On the Knowledge Base page, after entering a knowledge base, you can click View Index to view the index information of structured documents.
    • Python
    • Java
    • HTTP
    Request example
    import os
    # The Dashscope SDK version must be 2.0.1 or later.
    import dashscope
    from dashscope import DashScopeError
    
    # The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.
    client = dashscope.Client(
        # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage.
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        workspace="{WorkspaceId}",
        region="ap-southeast-1",
    )
    
    try:
        response = client.apps.completions.create(
            app_id='YOUR_APP_ID',  # Replace YOUR_APP_ID with the actual application ID
            prompt='请帮我推荐一款3000元以下的手机',
            rag_options={
                "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"],  # Replace with the actual knowledge base IDs. Use commas to separate multiple IDs
                 "structured_filter": {  # Structured data key-value pairs, corresponding to the structured data. Use commas to separate multiple pairs
                    "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'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
    
    Response example
    {
        "text": "我为您推荐"百炼"这款手机,它的价格是2999元,符合您的预算要求。如果您需要了解更多信息,比如性能、外观等,请告诉我。",
        "finish_reason": "stop",
        "session_id": "80a3b868b5ce42c8a12f01dccf8651e2",
        "thoughts": null,
        "doc_references": null
    }
    
View Information

To 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 output.

To view answer source information: Turn on the Show Source switch in the Configure section of the agent application and publish the application; you can then view the answer sources in the response of the call.
image

API Reference

You can view the complete parameter list in Workflow and legacy agent application API application DashScope API Reference.

Error Codes

If the call fails and returns an error message, refer to Error Codes to resolve it.

FAQ

  1. Check whether the class names and package names in the import statements are correct.
  2. Add the dependency library: If you use Maven or Gradle for project management, make sure the DashScope Java SDK dependency library has been added to the pom.xml or build.gradle file and is the latest version. You can visit Maven to obtain the latest version number of the DashScope Java SDK.
<!-- 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: Earlier versions of the DashScope Java SDK may not contain the features or classes you are trying to use. If you have already added the DashScope Java SDK dependency library, make sure the DashScope Java SDK you are using is the latest version. If the current version is earlier, upgrade it to the latest version. You can change the DashScope Java SDK version to the latest version in the 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 the project for the changes to take effect.
  2. Run the code example again. If the problem persists, see the Model Studio FAQ or submit a ticket for further assistance.