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:
    # Install the SDK in your Python 3 environment
    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
from http import HTTPStatus
from dashscope import Application
response = Application.call(
    # If environment variables are not configured, you can replace the following line with api_key="sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    app_id='YOUR_APP_ID',# Replace with the actual application ID
    prompt='Who are you?')

if response.status_code != HTTPStatus.OK:
    print(f'request_id={response.request_id}')
    print(f'code={response.status_code}')
    print(f'message={response.message}')
    print(f'Refer to: https://help.aliyun.com/en/model-studio/developer-reference/error-code')
else:
    print(response.output.text)
Sample response
I am a large language model developed by Alibaba Cloud, named Qwen. I am designed to help users generate various types of text, such as articles, stories, poems, stories, etc., and can be adjusted and optimized according to different scenarios and needs. In addition, I can also answer various questions, provide information and explanations, and assist in learning and research. If you have any needs, please feel free to ask me questions at any time!

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:
// Original input
{
  "messages": [{"role": "user", "content": "Hello"}],
  "prompt": "Recommend a movie"
}
// Actual effective messages
[
  {"role": "user", "content": "Hello"},
  {"role": "user", "content": "Recommend a movie"}
]
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
Request example
import os
from http import HTTPStatus
from dashscope import Application
def call_with_session():
    response = Application.call(
        # If you do not configure environment variables, replace the following line with api_key="sk-xxx". However, we do not recommend hard-coding the API key in production code to reduce the risk of exposure.
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='YOUR_APP_ID',  # Replace with your actual application ID
        prompt='Who are you?')

    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code')
        return response

    responseNext = Application.call(
                # If you do not configure environment variables, replace the following line with api_key="sk-xxx". However, we do not recommend hard-coding the API key in production code to reduce the risk of exposure.
                api_key=os.getenv("DASHSCOPE_API_KEY"),
                app_id='YOUR_APP_ID',  # Replace with your actual application ID
                prompt='What skills do you have?',
                session_id=response.output.session_id)  # Use the session_id from the previous response

    if responseNext.status_code != HTTPStatus.OK:
        print(f'request_id={responseNext.request_id}')
        print(f'code={responseNext.status_code}')
        print(f'message={responseNext.message}')
        print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code')
    else:
        print('%s\n session_id=%s\n' % (responseNext.output.text, responseNext.output.session_id))
        # print('%s\n' % (response.usage))

if __name__ == '__main__':
    call_with_session()
Response example
I have many skills to help you complete various tasks. Here are some of my main skills:

1. **Information retrieval**: Provide weather, news, historical facts, scientific knowledge, and more.
2. **Language processing**: Translate text, correct grammar errors, and generate articles and stories.
3. **Technical problem solving**: Answer programming, software usage, and technical troubleshooting questions.
4. **Learning support**: Help with math, physics, chemistry, and other subjects.
5. **Life advice**: Offer suggestions on health, diet, travel, shopping, and more.
6. **Entertainment interaction**: Tell jokes, play word games, and engage in casual chats.
7. **Schedule management**: Remind you of important dates, schedule events, and set reminders.
8. **Data analysis**: Explain charts and provide data analysis suggestions.
9. **Emotional support**: Listen to your feelings and provide comfort and support.

If you have specific needs or questions, just tell me, and I will do my best to help you!
 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
Request example
import os
from http import HTTPStatus
from dashscope import Application
responses = Application.call(
            # If you have not configured an environment variable, replace the next line with your DashScope API key: api_key="sk-xxx". Do not hard-code your API key in production code to reduce the risk of exposure.
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            app_id='YOUR_APP_ID',
            prompt='Who are you?',
            stream=True,  # Enable streaming output
            incremental_output=True)  # Enable incremental output

for response in responses:
    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code')
    else:
        print(f'{response.output.text}\n')  # Process only the text field
Response example
I am a large language model from Alibaba Cloud. My name is Qwen.

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": "Beijing"}}
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": "Beijing"}},
    "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
    from http import HTTPStatus
    import os
    # We recommend using DashScope SDK version 1.14.0 or later.
    from dashscope import Application
    biz_params = {
        # Custom variable parameters for the agent application. Replace them with your actual parameters. You can pass multiple key-value pairs separated by commas.
        "user_prompt_params":{
            "city": "Beijing"}}
    response = Application.call(
                # If you have not configured an environment variable, you can replace the next line with api_key="sk-xxx" and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks.
                api_key=os.getenv("DASHSCOPE_API_KEY"),
                app_id='YOUR_APP_ID', # Replace this with your actual application ID, which you can find on the application card.
                prompt='food recommendations',
                biz_params=biz_params)
    
    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # Process the text-only output
        # print('%s\n' % (response.usage))
    
    Sample response
    Peking Duck, Zhajiangmian, Douzhi
    

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
    Request example
    import os
    from http import HTTPStatus
    # We recommend DashScope SDK version >= 1.20.11
    from dashscope import Application
    response = Application.call(
        # If you have not set an environment variable, replace the next line with: api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure.
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='YOUR_APP_ID',  # Replace YOUR_APP_ID with your actual application ID
        prompt='Please recommend a smartphone under ¥3,000',
        rag_options={
            "pipeline_ids": ["YOUR_PIPELINE_ID1","YOUR_PIPELINE_ID2"],  # Replace with actual knowledge base IDs, separated by commas
        }
    )
    
    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # Process text-only output
        # print('%s\n' % (response.usage))
    
    Response example
    Based on your budget, I recommend the **Bailian Zephyr Z9**. Its reference price ranges from ¥2,499 to ¥2,799—well within your budget. It features a lightweight 6.4-inch 1080 × 2340 pixel display, 128 GB storage, and 6 GB RAM—ideal for everyday use. It also includes a 4,000 mAh battery and a 30× digital zoom lens, delivering strong performance for both photography and battery life. If you value portability and all-around functionality, the Bailian Zephyr Z9 is an excellent choice.
    
  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 ID (file_ids): You can find the ID in the document list on the Application Data page. You can also obtain it from the ID returned by the AddFile API after you import a document.
      • Document tags: You can view the tags on the Application Data page for unstructured documents. You can also obtain them using the DescribeFile API.
      • Document metadata: On the Knowledge Base page, open a knowledge base and view the metadata (Meta info) for unstructured documents.
    • You can pass multiple document IDs. However, only documents with built indexes are supported.
    • To use a document ID, you must also pass the ID of the knowledge base to which it belongs. Otherwise, the retrieval fails.
    • Retrieval is performed only on the specified documents. For example, if your web-based agent application references Knowledge Base A, but your API call specifies a document ID and its knowledge base ID (Knowledge Base B), then only the documents from Knowledge Base B are retrieved, not the documents from Knowledge Base A. For example, you can use Bailian Series Mobile Product Introduction.docx as an unstructured data knowledge base file.
      • Python
      • Java
      • HTTP
      Request example
      import os
      from http import HTTPStatus
      # We recommend DashScope SDK version >= 1.20.11
      from dashscope import Application
      response = Application.call(
          # If you have not set an environment variable, replace the next line with: api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure.
          api_key=os.getenv("DASHSCOPE_API_KEY"),
          app_id='YOUR_APP_ID',  # Replace YOUR_APP_ID with your actual application ID
          prompt='Please recommend a smartphone under ¥3,000',
          rag_options={
              "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"],  # Replace with actual knowledge base IDs, separated by commas
              "file_ids": ["YOUR_FILE_ID1", "YOUR_FILE_ID2"],  # Replace with actual unstructured document IDs, separated by commas
              "metadata_filter": {  # Document metadata key-value pairs, separated by commas
                  "key1": "value1",
                  "key2": "value2"
              },
              "tags": ["tag1", "tag2"]  # Document tags, separated by commas
          }
      )
      
      if response.status_code != HTTPStatus.OK:
          print(f'request_id={response.request_id}')
          print(f'code={response.status_code}')
          print(f'message={response.message}')
          print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code')
      else:
          print('%s\n' % (response.output))
      
      Response example
      {
          "text": "Within a ¥3,000 budget, I recommend the **Bailian Zephyr Z9**. Key features include the following:\n\n- **Screen**: 6.4-inch, 1080 × 2340 pixels—ideal for daily use and entertainment.\n- **Memory & storage**: 6 GB RAM + 128 GB storage—enough for most users’ smoothness and storage needs.\n- **Battery**: 4,000 mAh—lasts all day.\n- **Camera**: 30× digital zoom lens—captures distant details.\n- **Other features**: Lightweight and portable—easy to carry.\n\nIts reference price is ¥2,499–¥2,799—perfect for your budget and great value. Hope this helps!",
          "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
    Request example
    import os
    from http import HTTPStatus
    # We recommend DashScope SDK version >= 1.20.11
    from dashscope import Application
    
    response = Application.call(
        # If you have not set an environment variable, replace the next line with: api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure.
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='YOUR_APP_ID',  # Replace YOUR_APP_ID with your actual application ID
        prompt='Please recommend a smartphone under ¥3,000',
        rag_options={
            "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"],  # Replace with actual knowledge base IDs, separated by commas
             "structured_filter": {  # Structured data key-value pairs, corresponding to structured data, separated by commas
                "key1": "value1",
                "key2": "value2"
             }
        }
    )
    
    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output))
    
    Response example
    {
        "text": "I recommend the \"Bailian\" smartphone—it costs ¥2,999, fitting your budget. If you need more details—like performance or design—let me know.",
        "finish_reason": "stop",
        "session_id": "80a3b868b5ce42c8a12f01dccf8651e2",
        "thoughts": null,
        "doc_references": null
    }
    

View information

View retrieval process information: When you make an API call, add the has_thoughts parameter to your code and set its value to True. The retrieval process information is then returned in the thoughts field of the output object.

View source references: Click Knowledge base, and then click Configure. Turn on the Show source references switch, and then publish the application. The source references will then appear in the response.

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
Request example
import os
from http import HTTPStatus
from dashscope import Application

try:
    response = Application.call(
        # If you have not set an environment variable, replace the next line with: api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure.
        api_key=os.getenv('DASHSCOPE_API_KEY'),
        app_id='YOUR_APP_ID',# Replace with your actual application ID
        prompt='Who are you?',# Replace with your actual input
        stream=True,  # Stream output: True enables streaming; False (default) disables it
        incremental_output=True,  # Incremental output: True enables it; False (default) disables it
        has_thoughts=True  # Return thinking process: True returns it; False (default) does not
    )

except Exception as e:
    print(f"API request failed: {str(e)}")
    exit(1)

# Store full thinking process
reasoning_content = []
# Store full reply
answer_content = ""
# Track whether we've started replying
is_answering = False

def print_section(title):
    """Print a section header with decoration"""
    print(f"\n{'=' * 20} {title} {'=' * 20}\n", flush=True)

print_section("Thinking process")

for chunk in response:
    if chunk.status_code != HTTPStatus.OK:
        print(f'request_id={chunk.request_id}')
        print(f'code={chunk.status_code}')
        print(f'message={chunk.message}')
        print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code')
        continue

    # Skip empty chunks
    if not chunk.output or (not chunk.output.thoughts and not chunk.output.text):
        continue

    # Process thinking steps
    if chunk.output.thoughts:
        for it in chunk.output.thoughts:
            if it.action_type == 'reasoning':# Reasoning models use 'reasoning' for action_type; output appears in 'thought'
                content = str(it.thought) if not isinstance(it.thought, str) else it.thought
                reasoning_content.append(content)
                print(content, end="", flush=True)

    # Process reply
    if chunk.output.text:
        if not is_answering:
            print_section("Full reply")
            is_answering = True

        answer_content += str(chunk.output.text)
        print(chunk.output.text, end="", flush=True)

# Final results
final_reasoning = "".join(reasoning_content)
final_answer = "".join(answer_content)

# Uncomment the following lines to print full thinking and reply
#print_section("Full thinking process")
#print(final_reasoning)

#print_section("Full reply")
#print(final_answer)
Response example
==================== Thinking process ====================

Hmm, the user asked “Who are you?” I need to answer in Chinese. First, I’ll introduce myself as an AI assistant developed by DeepSeek. Then I’ll explain my functions—answering questions, providing information, helping with learning, etc. Keep it conversational, not too formal. Mention that I’m based on a large language model, but keep technical terms simple. Also note that the user might be testing my ability, so keep answers concise, friendly, and natural. Check for any missing key points—like the correct company name and emphasis on helpfulness. Finally, ensure formatting is clean, without markdown, and paragraphs are well spaced.
==================== Full reply ====================

Hello! I’m DeepSeek-R1, an intelligent assistant developed by DeepSeek. I’m here to help you with questions, information lookup, and learning support.

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 the long-term memory featurelong-term memory 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
  • Python
  • Java
  • HTTP
Request example (create memory content)
# DashScope SDK version ≥ 1.22.1
from http import HTTPStatus
import os
from dashscope import Application
response = Application.call(
           # If you have not set an environment variable, replace the next line with: api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure.
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            app_id='YOUR_APP_ID',  # Enter your actual application ID
            prompt='User food preference: noodles',
            memory_id='YOUR_MEMORY_ID')  # Enter your actual memory ID

if response.status_code != HTTPStatus.OK:
    print(f'request_id={response.request_id}')
    print(f'code={response.status_code}')
    print(f'message={response.message}')
    print(f'For more information, see https://help.aliyun.com/en/model-studio/error-code')
else:
    print('%s\n' % (response.output.text))  # Process text-only output
    # print('%s\n' % (response.usage))
Response example
Got it—you love noodles! If you’d like recommendations or info about noodle recipes or restaurants, tell me more. For example: What kind of noodles do you prefer—ramen, spaghetti, or something regional? Or do you have special taste preferences? That way, I can help better.
Request example (call again)
# DashScope SDK version ≥ 1.22.1
from http import HTTPStatus
import os
from dashscope import Application
response = Application.call(
           # If you have not set an environment variable, replace the next line with: api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure.
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            app_id='YOUR_APP_ID',  # Enter your actual application ID
            prompt='Food recommendation',
            memory_id='YOUR_MEMORY_ID')  # Enter your actual memory ID

if response.status_code != HTTPStatus.OK:
    print(f'request_id={response.request_id}')
    print(f'code={response.status_code}')
    print(f'message={response.message}')
    print(f'For more information, see https://help.aliyun.com/en/model-studio/error-code')
else:
    print('%s\n' % (response.output.text))  # Process text-only output
    # print('%s\n' % (response.usage))
Response example
Since you love noodles, here are some dishes to try:

1. **Zhajiangmian**: A classic Beijing dish—noodles topped with savory yellow bean sauce and minced pork. Rich and flavorful.
2. **Dandan noodles**: A Sichuan favorite—spicy, numbing, and refreshing. Perfect if you enjoy bold flavors.
3. **Daoxiao noodles**: A Shanxi specialty—hand-cut noodles cooked right into boiling water. Chewy and satisfying.
4. **Spaghetti**: For variety, try Western-style pasta—like tomato meat sauce or creamy mushroom pasta.

Hope this helps! Let me know if you have specific tastes or other needs.

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, .pdfImage (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, .wmvAudio (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.
image
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, this parameter is named sessionFileIds. When you make an HTTP call, include session_file_ids
    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
    Request example
    import os
    from http import HTTPStatus
    # We recommend DashScope SDK version >= 1.20.14
    from dashscope import Application
    response = Application.call(
        # If you have not set an environment variable, replace the next line with: api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure.
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='YOUR_APP_ID',  # Replace YOUR_APP_ID with your actual application ID
        prompt='Please recommend a smartphone under ¥3,000 based on the following file',
        rag_options={
            "session_file_ids": ["FILE_ID1"],  # Replace FILE_ID1 with your actual temporary file ID, separated by commas
        }
    )
    
    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'For more information, see https://help.aliyun.com/en/model-studio/error-code')
    else:
        print('%s\n' % (response.output.text))  # Process text-only output
        # print('%s\n' % (response.usage))
    
    Response example
    Based on your budget, I recommend the **Tongyi Vivid 7**. Key features include the following:
    
    - **Screen**: 6.5 inches, 1080 × 2400 pixels
    - **Storage & memory**: 128 GB storage, 8 GB RAM
    - **Battery**: 4,500 mAh
    - **Special features**: AI-powered smart photography, side-mounted fingerprint unlock
    - **Reference price**: ¥2,999–¥3,299
    
    The Tongyi Vivid 7 offers great value, solid performance, and practical features—ideal for users who love photography. Hope this helps!
    
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
    # Sample code for reference only—do not use in production
    import hashlib
    def calculate_md5(file_path):
        """Calculate the MD5 hash of a file.
    
        Args:
            file_path (str): Path to the file.
    
        Returns:
            str: MD5 hash of the file.
        """
        md5_hash = hashlib.md5()
    
        # Read file in binary mode
        with open(file_path, "rb") as f:
            # Read file in chunks to avoid high memory usage for large files
            for chunk in iter(lambda: f.read(4096), b""):
                md5_hash.update(chunk)
    
        return md5_hash.hexdigest()
    
    # Usage example
    file_path = "Replace with your actual local file path—for example, /Users/<username>/Desktop/Alibaba Cloud Bailian Series Mobile Product Introduction.docx"
    md5_value = calculate_md5(file_path)
    print(f"MD5 hash of the file: {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"
            }
        }
    }
    
    Description
    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
    # Sample code for reference only—do not use in production
    import requests
    from urllib.parse import urlparse
    
    def upload_file(pre_signed_url, file_path):
        try:
            # Set request headers
            headers = {
                "X-bailian-extra": "Replace with the X-bailian-extra value from Step 1's ApplyFileUploadLease response",
                "Content-Type": "Replace with the Content-Type value from Step 1's ApplyFileUploadLease response"
            }
    
            # Read and upload file
            with open(file_path, 'rb') as file:
                # Set request method for upload—must match the Method value from Step 1's ApplyFileUploadLease response
                response = requests.put(pre_signed_url, data=file, headers=headers)
    
            # Check response status
            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:
            # Set request headers
            headers = {
                "X-bailian-extra": "Replace with the X-bailian-extra value from Step 1's ApplyFileUploadLease response",
                "Content-Type": "Replace with the Content-Type value from Step 1's ApplyFileUploadLease response"
            }
    
            # Set GET method to access OSS
            source_response = requests.get(source_url_string)
            if source_response.status_code != 200:
                raise RuntimeError("Failed to get source file.")
    
            # Set request method for upload—must match the Method value from Step 1's ApplyFileUploadLease response
            response = requests.put(pre_signed_url, data=source_response.content, headers=headers)
    
            # Check response status
            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 = "Replace with the Url value from Step 1's ApplyFileUploadLease response"
    
        # Source can be local—upload local file to Model Studio temporary storage
        file_path = "Replace with your actual local file path"
        upload_file(pre_signed_url_or_http_url, file_path)
    
        # Source can also be Alibaba Cloud Object Storage Service (OSS)
        # file_path = "Replace with your actual OSS public URL"
        # 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.

    Configuration diagram

    Key parameters

    image

    LeaseId: Value of Data.FileUploadLeaseId from Step 1’s response.

    CategoryId: Must be default.

    CategoryType: Must be SESSION_FILE.

    Success response diagramA 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
    }
    
    Description
    • 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

    Description

    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
    from http import HTTPStatus
    from dashscope import Application
    # Configure the private domain name.
    os.environ['DASHSCOPE_HTTP_BASE_URL'] = 'https://{WorkspaceId}-{VpcId}.cn-beijing.maas.aliyuncs.com/api/v1/'
    response = Application.call(
        # If the environment variable is not set, use your API key directly (e.g., api_key="sk-xxx"). Avoid hard-coding the key in production to prevent leakage.
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='APP_ID',# Replace with your actual application ID.
        prompt='Who are you?')
    
    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-codes')
    else:
        print(response.output.text)
    

API Reference

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

Error codes

If the call fails and returns 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>Replace this with the latest version number, such as 2.16.4</version>
</dependency>
// https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: 'Replace this with the latest version number, such as 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>Update this version number to the latest version</version>
</dependency>
// https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: 'Update this version number to the latest version'
  1. Reload your project to apply the changes.
  2. Run the code example again.
  • session_id: Used for cloud-hosted multi-turn conversations. The system automatically maintains the conversation context. A session lasts for one hour and supports up to 50 turns. You do not need to manage the context manually. However, you must pass the session_id from the previous turn to the next turn.
  • memory_id: Used to create a long-term memory store for specific information. You can call the CreateMemory API to create a memory store and obtain a memoryId. To reference that information later, pass the memoryId in subsequent requests.
These two features serve different purposes: short-term conversation context and long-term information storage.
Agent Development
Agent Context
Agent Governance & Evolution
Store
Application Marketplace