All Products
Search
Document Center

Alibaba Cloud Model Studio:Application API reference

Last Updated:Nov 28, 2024

This topic describes the request and response parameters for application API calling.

The endpoint for HTTP calls: POST https://dashscope-intl.aliyuncs.com/api/v1/apps/{YOUR_APP_ID}/completion

You must first obtain an API key and set the API key as an environment variable. If you need to use SDK, you must install the SDK.

Request parameters

app_id string Required

The application ID. You can obtain the application ID on the My Applications page.

In the Java SDK, this parameter is appid. For HTTP calls, include the application ID in the URL.

Single-round conversation

Python

Sample request

from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
response = Application.call(app_id='YOUR_APP_ID', prompt='Who are you?')

if response.status_code != HTTPStatus.OK:
    print(f'request_id={response.request_id}\ncode={response.status_code}\nmessage={response.message}\n')
else:
    print(f'request_id={response.request_id}\noutput={response.output}\nusage={response.usage}\n')

Sample response

request_id=e3bba3a5-5784-9592-aa18-03170770de1e
output={"text": "I am a large language model from Alibaba Cloud, named Qwen.
I can answer various questions, provide information, and engage in conversation with you. How can I assist you?", 
"finish_reason": "stop", "session_id": "a0606349b3c34c6fad7cf1d6454e0072", 
"thoughts": null, "doc_references": null}
usage={"models": [{"model_id": "qwen-max", "input_tokens": 121, "output_tokens": 37}]}

Java

Sample request

// Recommended version of dashscope SDK >= 2.12.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.List;
import com.alibaba.dashscope.utils.Constants;

public class Main{
      static {
          Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
      }
      public static void appCall()
            throws ApiException, NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                .appId("YOUR_APP_ID")
                .prompt("Who are you?")
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);

        System.out.printf("requestId: %s, text: %s, finishReason: %s\n",
                result.getRequestId(), result.getOutput().getText(), result.getOutput().getFinishReason());

        if (result.getUsage() != null && result.getUsage().getModels() != null) {
            for (ApplicationUsage.ModelUsage usage : result.getUsage().getModels()) {
                System.out.printf("modelId: %s, inputTokens: %d, outputTokens: %d\n",
                        usage.getModelId(), usage.getInputTokens(), usage.getOutputTokens());
            }
        }
    }

    public static void main(String[] args) {
        try {
            appCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            throw new RuntimeException(e);
        }
        System.exit(0);
    }  
}

Sample response

requestId: 1458c2c0-05aa-9df3-9f99-e36d6a11cfbe, 
text: I am a language model from Alibaba Cloud, named Qwen. I am designed to help users obtain information, answer questions, and engage in conversation. How can I assist you?, 
finishReason: stop
modelId: qwen-max, inputTokens: 121, outputTokens: 34

cURL

Sample Request

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Who are you?"
    },
    "parameters":  {},
    "debug": {}
}' 

Sample Response

{"output":{"finish_reason":"stop",
"session_id":"232ea2e9e6ef448db6b14465c06a9a56",
"text":"I am a large language model from Alibaba Cloud, named Qwen.
I am an AI assistant capable of answering questions, creating text, expressing opinions, and writing code.
If you have any questions or need assistance, please feel free to let me know, and I will do my best to help you."},
"usage":{"models":[{"output_tokens":51,"model_id":"qwen-max","input_tokens":121}]},
"request_id":"661c9cad-e59c-9f78-a262-78eff243f151"}% 

Multi-round conversation

Python

Sample request

from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

def call_with_session():
    response = Application.call(app_id='YOUR_APP_ID',
                                prompt='I want to visit Singapore')

    if response.status_code != HTTPStatus.OK:
        print('request_id=%s, code=%s, message=%s\n' % (response.request_id, response.status_code, response.message))
        return response

    response1 = Application.call(app_id='YOUR_APP_ID',
                                 prompt='What are the attractions and foods there?',
                                 session_id=response.output.session_id)
    if response1.status_code != HTTPStatus.OK:
        print('request_id=%s, code=%s, message=%s\n' % (response1.request_id, response1.status_code, response1.message))
    else:
        print('request_id=%s\n output=%s\n usage=%s\n' % (response1.request_id, response1.output, response1.usage))


if __name__ == '__main__':
    call_with_session()

Sample response

request_id=a9d3f1b1-6745-981a-af82-9ec58522d78f
 output={"text": "Singapore is famous for its diverse attractions and a vibrant food scene that reflects its multicultural heritage. 
 Here are some popular attractions and must-try foods:\n\n
 **Attractions:**\n\n
 1. **Merlion Park**: Home to the iconic Merlion statue, a half-lion, half-fish symbol of Singapore.\n\n
 2. **Botanic Gardens**: A lush green space featuring a variety of plants, including the National Orchid Garden.\n\n
 3. **Marina Bay Sands**: An integrated resort with luxury shopping, dining, a casino, and a breathtaking infinity pool.\n\n
 4. **Gardens by the Bay**: A futuristic garden with massive Supertrees, two cooled conservatories (Flower Dome and Cloud Forest), and nightly light shows.\n\n
 5. **Sentosa Island**: An entertainment hub with beaches, theme parks (Universal Studios Singapore), Madame Tussauds, and the S.E.A. Aquarium.\n\n
 6. **Orchard Road**: Singapore's premier shopping district lined with malls, boutiques, restaurants, and entertainment venues.\n\n
 7. **Chinatown, Little India, and Kampong Glam**: Cultural enclaves offering a glimpse into Singapore's ethnic diversity through architecture, markets, and food.\n\n
 8. **National Museum of Singapore**: A museum showcasing Singapore's history and cultural heritage.\n\n
 **Foods:**\n\n
 1. **Hainanese Chicken Rice**: A national dish consisting of poached chicken served with fragrant rice cooked in chicken broth, accompanied by chili sauce and ginger paste.\n\n
 2. **Laksa**: A spicy noodle soup typically made with coconut milk, shrimp or fish, and a blend of spices.\n\n
 3. **Chilli Crab**: Fresh crabs cooked in a sweet and savory tomato and chili-based sauce, often eaten with mantou (deep-fried buns).\n\n
 4. **Char Kway Teow**: Stir-fried rice noodles with egg, Chinese sausage, bean sprouts, and cockles, seasoned with dark soy sauce and chili.\n\n
 5. **Satay**: Grilled skewered meat (usually chicken, beef, or mutton) served with peanut sauce and cucumber slices.\n\n
 6. **Nasi Lemak**: A Malay dish of fragrant coconut rice served with fried anchovies, peanuts, egg, and sambal chili paste, often accompanied by a side of chicken or fish.\n\n
 7. **Roti Prata**: A flaky Indian-style flatbread usually served with curry or sugar for dipping.\n\n
 8. **Kaya Toast**: Traditional breakfast item featuring toast filled with a spread made from coconut jam and butter, typically paired with soft-boiled eggs and coffee or tea.\n\n
 These are just a few highlights; Singapore's food scene is incredibly diverse, and exploring hawker centers like Maxwell Food Centre, Lau Pa Sat, or Tiong Bahru Market is a must for any food enthusiast.", 
 "finish_reason": "stop", 
 "session_id": "443f935a8d80496f94dcfa4a04b7edfa", 
 "thoughts": null, "doc_references": null}
 usage={"models": [{"model_id": "qwen-max", 
 "input_tokens": 688, 
 "output_tokens": 423}]}request_id=a9d3f1b1-6745-981a-af82-9ec58522d78f
 output={"text": "Singapore is famous for its diverse attractions and a vibrant food scene that reflects its multicultural heritage. 
 Here are some popular attractions and must-try foods:\n\n
 **Attractions:**\n\n
 1. **Merlion Park**: Home to the iconic Merlion statue, a half-lion, half-fish symbol of Singapore.\n\n
 2. **Botanic Gardens**: A lush green space featuring a variety of plants, including the National Orchid Garden.\n\n
 3. **Marina Bay Sands**: An integrated resort with luxury shopping, dining, a casino, and a breathtaking infinity pool.\n\n
 4. **Gardens by the Bay**: A futuristic garden with massive Supertrees, two cooled conservatories (Flower Dome and Cloud Forest), and nightly light shows.\n\n
 5. **Sentosa Island**: An entertainment hub with beaches, theme parks (Universal Studios Singapore), Madame Tussauds, and the S.E.A. Aquarium.\n\n
 6. **Orchard Road**: Singapore's premier shopping district lined with malls, boutiques, restaurants, and entertainment venues.\n\n
 7. **Chinatown, Little India, and Kampong Glam**: Cultural enclaves offering a glimpse into Singapore's ethnic diversity through architecture, markets, and food.\n\n
 8. **National Museum of Singapore**: A museum showcasing Singapore's history and cultural heritage.\n\n
 **Foods:**\n\n
 1. **Hainanese Chicken Rice**: A national dish consisting of poached chicken served with fragrant rice cooked in chicken broth, accompanied by chili sauce and ginger paste.\n\n
 2. **Laksa**: A spicy noodle soup typically made with coconut milk, shrimp or fish, and a blend of spices.\n\n
 3. **Chilli Crab**: Fresh crabs cooked in a sweet and savory tomato and chili-based sauce, often eaten with mantou (deep-fried buns).\n\n
 4. **Char Kway Teow**: Stir-fried rice noodles with egg, Chinese sausage, bean sprouts, and cockles, seasoned with dark soy sauce and chili.\n\n
 5. **Satay**: Grilled skewered meat (usually chicken, beef, or mutton) served with peanut sauce and cucumber slices.\n\n
 6. **Nasi Lemak**: A Malay dish of fragrant coconut rice served with fried anchovies, peanuts, egg, and sambal chili paste, often accompanied by a side of chicken or fish.\n\n
 7. **Roti Prata**: A flaky Indian-style flatbread usually served with curry or sugar for dipping.\n\n
 8. **Kaya Toast**: Traditional breakfast item featuring toast filled with a spread made from coconut jam and butter, typically paired with soft-boiled eggs and coffee or tea.\n\n
 These are just a few highlights; Singapore's food scene is incredibly diverse, and exploring hawker centers like Maxwell Food Centre, Lau Pa Sat, or Tiong Bahru Market is a must for any food enthusiast.", 
 "finish_reason": "stop", 
 "session_id": "443f935a8d80496f94dcfa4a04b7edfa", 
 "thoughts": null, "doc_references": null}
 usage={"models": [{"model_id": "qwen-max", 
 "input_tokens": 688, 
 "output_tokens": 423}]}

Java

Sample request

import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;

import java.util.Arrays;
import java.util.List;
import com.alibaba.dashscope.utils.Constants;

public class Main {
      static {
          Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
      }
      public static void callWithSession()
            throws ApiException, NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                .appId("YOUR_APP_ID")
                .prompt("I want to visit Singapore")
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);

        param.setSessionId(result.getOutput().getSessionId());
        param.setPrompt("What are the attractions and foods there?");
        result = application.call(param);

        System.out.printf("requestId: %s, text: %s, finishReason: %s\n",
                result.getRequestId(), result.getOutput().getText(), result.getOutput().getFinishReason());
    }
  
   public static void main(String[] args) {
        try {
            callWithSession();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
        }
        System.exit(0);
    }  
}

Sample response

requestId: 440a0772-3c67-922e-8acb-d90840b96217, text: Singapore is a vibrant city-state brimming with exciting attractions and a rich culinary scene. Here are some must-visit attractions and must-try foods:

### Tourist Attractions

1. **Merlion Park**: Home to the iconic Merlion statue, a half-lion, half-fish symbol of Singapore.
2. **Botanic Gardens**: A UNESCO World Heritage Site featuring lush gardens, including the National Orchid Garden.
3. **Universal Studios Singapore**: Located on Sentosa Island, it offers thrilling rides and entertainment based on popular movies.\n\n4. **National Museum of Singapore**: A fascinating insight into the country's history and culture.
4. **Clarke Quay**: A lively riverside area filled with restaurants, bars, and entertainment venues.
5. **National Museum of Singapore**: A fascinating insight into the country's history and culture.
6. **Singapore Flyer**: A giant observation wheel offering panoramic views of the city skyline.
7. **ArtScience Museum**: Unique exhibitions that blend art, science, and technology.

### Food Recommendations

1. **Hainanese Chicken Rice** - Poached chicken, fragrant rice in chicken broth, chili sauce, ginger paste.
2. **Laksa** - Spicy coconut noodle soup with shrimp, cockles, fish cakes.
3. **Chilli Crab** - Fresh crab in sweet, tangy, spicy tomato sauce; mantou.
4. **Satay** - Grilled marinated meat skewers, peanut sauce, cucumber relish.
5. **Char Kway Teow** - Stir-fried flat rice noodles, prawns, cockles, veggies, soy-chili.
6. **Roti Prata** - Crispy flatbread, curry/sugar, plain/egg/cheese-filled options.
7. **Fish Head Curry** - Spicy, aromatic fish head curry with veggies, tamarind twist.
8. **Kaya Toast** - Toast with kaya (coconut jam), soft-boiled eggs, coffee/tea.
9. **Nasi Lemak** - Coconut rice, fried chicken, anchovies, peanuts, cucumber, sambal.
10. **Durian Desserts** - Durian ice cream, pastries, fresh fruit for the adventurous., finishReason: stop

cURL

Sample request (Previous Round)

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "I want to visit Singapore"
    },
    "parameters":  {},
    "debug": {}
}' 

Sample response (Previous Round)

{"output":{"finish_reason":"stop",
"session_id":"d380aeb21d4b4b018f1d7ae9f98de404",
"text":"Visiting Singapore is a great choice! It's a vibrant city-state known for its multiculturalism, modern architecture, delicious food, and lush green spaces. Here’s a guide to help you plan your trip:\nWhen to Go\nBest Time: November to January (cooler and less humid)\nAvoid: June to August (hot and humid, plus it's peak tourist season)\nGetting There\nBy Air: Changi Airport is one of the world's best airports. Many international airlines fly to Singapore.\nBy Sea: You can also arrive by cruise ship or ferry from neighboring countries like Malaysia and Indonesia.\nWhere to Stay\nLuxury: Marina Bay Sands, Raffles Hotel\nMid-Range: Hotel Indigo, Park Hotel"},
"usage":{"models":[{"output_tokens":389,"model_id":"qwen-max","input_tokens":51}]},
"request_id":"a1e8cbb2-51dc-9733-a97c-e7ca5a7f0438"}%   

Sample request (Next Round)

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "What are the foods there?",
        "session_id":"d380aeb21d4b4b018f1d7ae9f98de404"
    },
    "parameters":  {},
    "debug": {}
}' 

Sample response (Previous Round)

{"output":{"finish_reason":"stop",
"session_id":"d380aeb21d4b4b018f1d7ae9f98de404",
"text":"Here are some authentic foods you must try when you visit Singapore:\n\n
**Hainanese Chicken Rice** - Poached chicken, fragrant rice in chicken broth, chili sauce, ginger paste.
2. **Laksa** - Spicy coconut noodle soup with shrimp, cockles, fish cakes.
3. **Chilli Crab** - Fresh crab in sweet, tangy, spicy tomato sauce; mantou.
4. **Satay** - Grilled marinated meat skewers, peanut sauce, cucumber relish.
5. **Char Kway Teow** - Stir-fried flat rice noodles, prawns, cockles, veggies, soy-chili.
6. **Roti Prata** - Crispy flatbread, curry/sugar, plain/egg/cheese-filled options.
7. **Fish Head Curry** - Spicy, aromatic fish head curry with veggies, tamarind twist.
8. **Kaya Toast** - Toast with kaya (coconut jam), soft-boiled eggs, coffee/tea.
9. **Nasi Lemak** - Coconut rice, fried chicken, anchovies, peanuts, cucumber, sambal.
10. **Durian Desserts** - Durian ice cream, pastries, fresh fruit for the adventurous.
"usage":{"models":[{"output_tokens":411,"model_id":"qwen-max","input_tokens":454}]},
"request_id":"366d21f5-1a4a-9fe5-8ba2-e7955ff8cd23"}% 
Only agent applications and dialog workflow applications support multi-round conversations.

Streaming output

Python

Sample request

from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
def call_with_stream():
    responses = Application.call(app_id='YOUR_APP_ID',
                                 prompt='Who are you?',
                                 stream=True,
                                 incremental_output=True)
    for response in responses:
        if response.status_code != HTTPStatus.OK:
            print('request_id=%s, code=%s, message=%s\n' % (response.request_id, response.status_code,
                  response.message))
        else:
            print('request_id=%s\n output=%s\n usage=%s\n' % (response.request_id, response.output, response.usage))

if __name__ == '__main__':
    call_with_stream()

Sample response

request_id=b63c8c47-f4bd-9fa0-9cfc-f06da91588fe
 output={"text": "I am", "finish_reason": "null", "session_id": "42ece8924aa842a3b55405b6ddf97429", "thoughts": null, "doc_references": null}
 usage={"models": [{"model_id": "qwen-max", "input_tokens": 142, "output_tokens": 1}]}

request_id=b63c8c47-f4bd-9fa0-9cfc-f06da91588fe
 output={"text": "from", "finish_reason": "null", "session_id": "42ece8924aa842a3b55405b6ddf97429", "thoughts": null, "doc_references": null}
 usage={"models": [{"model_id": "qwen-max", "input_tokens": 142, "output_tokens": 2}]}

request_id=b63c8c47-f4bd-9fa0-9cfc-f06da91588fe
 output={"text": "Alibaba", "finish_reason": "null", "session_id": "42ece8924aa842a3b55405b6ddf97429", "thoughts": null, "doc_references": null}
 usage={"models": [{"model_id": "qwen-max", "input_tokens": 142, "output_tokens": 3}]}

request_id=b63c8c47-f4bd-9fa0-9cfc-f06da91588fe
 output={"text": "Cloud's language model assistant,", "finish_reason": "null", "session_id": "42ece8924aa842a3b55405b6ddf97429", "thoughts": null, "doc_references": null}
 usage={"models": [{"model_id": "qwen-max", "input_tokens": 142, "output_tokens": 8}]}

request_id=b63c8c47-f4bd-9fa0-9cfc-f06da91588fe
 output={"text": "I am called Qwen. I can", "finish_reason": "null", "session_id": "42ece8924aa842a3b55405b6ddf97429", "thoughts": null, "doc_references": null}
 usage={"models": [{"model_id": "qwen-max", "input_tokens": 142, "output_tokens": 16}]}

request_id=b63c8c47-f4bd-9fa0-9cfc-f06da91588fe
 output={"text": "answer various questions, provide information, and", "finish_reason": "null", "session_id": "42ece8924aa842a3b55405b6ddf97429", "thoughts": null, "doc_references": null}
 usage={"models": [{"model_id": "qwen-max", "input_tokens": 142, "output_tokens": 24}]}

request_id=b63c8c47-f4bd-9fa0-9cfc-f06da91588fe
 output={"text": "engage in conversation and other tasks. I am happy to serve you!", "finish_reason": "null", "session_id": "42ece8924aa842a3b55405b6ddf97429", "thoughts": null, "doc_references": null}
 usage={"models": [{"model_id": "qwen-max", "input_tokens": 142, "output_tokens": 32}]}

request_id=b63c8c47-f4bd-9fa0-9cfc-f06da91588fe
 output={"text": "How can I assist you?", "finish_reason": "null", "session_id": "42ece8924aa842a3b55405b6ddf97429", "thoughts": null, "doc_references": null}
 usage={"models": [{"model_id": "qwen-max", "input_tokens": 142, "output_tokens": 37}]}

request_id=b63c8c47-f4bd-9fa0-9cfc-f06da91588fe
 output={"text": "", "finish_reason": "stop", "session_id": "42ece8924aa842a3b55405b6ddf97429", "thoughts": null, "doc_references": null}
 usage={"models": [{"model_id": "qwen-max", "input_tokens": 142, "output_tokens": 37}]}
The examples provided illustrate streaming output for intelligent applications. Results from workflow and intelligent orchestration applications are delivered in real-time.

Java

Sample request

import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;
import java.util.Arrays;
import java.util.List;
import com.alibaba.dashscope.utils.Constants;

public class Main {
      static {
          Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
      }
      public static void streamCall() throws NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                .appId("YOUR_APP_ID")
                .prompt("Who are you?")
                .incrementalOutput(true)
                .build();

        Application application = new Application();
        Flowable<ApplicationResult> result = application.streamCall(param);
        result.blockingForEach(data -> {
            System.out.printf("requestId: %s, text: %s, finishReason: %s\n",
                    data.getRequestId(), data.getOutput().getText(), data.getOutput().getFinishReason());

        });
    }

    public static void main(String[] args) {
        try {
		        streamCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
        }
        System.exit(0);
    }
}

Sample response

requestId: a36ae034-bc33-91d0-a50f-3f4051211303, text: I am, finishReason: null
requestId: a36ae034-bc33-91d0-a50f-3f4051211303, text: from, finishReason: null
requestId: a36ae034-bc33-91d0-a50f-3f4051211303, text: Alibaba, finishReason: null
requestId: a36ae034-bc33-91d0-a50f-3f4051211303, text: Cloud's large language, finishReason: null
requestId: a36ae034-bc33-91d0-a50f-3f4051211303, text: model, I am called Qwen, finishReason: null
requestId: a36ae034-bc33-91d0-a50f-3f4051211303, text: . I can generate various types of text, such as, finishReason: null
requestId: a36ae034-bc33-91d0-a50f-3f4051211303, text: articles, stories, poems, and stories, finishReason: null
requestId: a36ae034-bc33-91d0-a50f-3f4051211303, text: , and can transform and expand according to different scenarios and needs. Additionally, I can, finishReason: null
requestId: a36ae034-bc33-91d0-a50f-3f4051211303, text: answer various questions, provide assistance and solutions, finishReason: null
requestId: a36ae034-bc33-91d0-a50f-3f4051211303, text: . If you have any questions or need help, please, finishReason: null
requestId: a36ae034-bc33-91d0-a50f-3f4051211303, text: feel free to let me know!, finishReason: null
requestId: a36ae034-bc33-91d0-a50f-3f4051211303, text: , finishReason: stop

cURL

Sample request

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--header 'X-DashScope-SSE: enable' \
--data '{
    "input": {
        "prompt": "Who are you?"
    },
    "parameters":  {},
    "debug": {}
}' 

Sample response

id:1
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"909ece989f1e4c59b416743abefc8a45","finish_reason":"null","text":"I am"},"usage":{"models":[{"input_tokens":184,"output_tokens":1,"model_id":"qwen-max"}]},"request_id":"e7dde240-6f52-9cf0-a70f-d2a4b94374c5"}

id:2
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"909ece989f1e4c59b416743abefc8a45","finish_reason":"null","text":"I am from"},"usage":{"models":[{"input_tokens":184,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"e7dde240-6f52-9cf0-a70f-d2a4b94374c5"}

id:3
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"909ece989f1e4c59b416743abefc8a45","finish_reason":"null","text":"I am from Alibaba"},"usage":{"models":[{"input_tokens":184,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"e7dde240-6f52-9cf0-a70f-d2a4b94374c5"}

id:4
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"909ece989f1e4c59b416743abefc8a45","finish_reason":"null","text":"I am from Alibaba Cloud's large language"},"usage":{"models":[{"input_tokens":184,"output_tokens":8,"model_id":"qwen-max"}]},"request_id":"e7dde240-6f52-9cf0-a70f-d2a4b94374c5"}

id:5
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"909ece989f1e4c59b416743abefc8a45","finish_reason":"null","text":"I am from Alibaba Cloud's large language model, I am called Qwen"},"usage":{"models":[{"input_tokens":184,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"e7dde240-6f52-9cf0-a70f-d2a4b94374c5"}

id:6
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"909ece989f1e4c59b416743abefc8a45","finish_reason":"null","text":"I am from Alibaba Cloud's large language model, I am called Qwen. I can generate text, answer questions,"},"usage":{"models":[{"input_tokens":184,"output_tokens":24,"model_id":"qwen-max"}]},"request_id":"e7dde240-6f52-9cf0-a70f-d2a4b94374c5"}

id:7
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"909ece989f1e4c59b416743abefc8a45","finish_reason":"null","text":"I am from Alibaba Cloud's large language model, I am called Qwen. I can generate text, answer questions, create stories, write code, translate, and perform various"},"usage":{"models":[{"input_tokens":184,"output_tokens":32,"model_id":"qwen-max"}]},"request_id":"e7dde240-6f52-9cf0-a70f-d2a4b94374c5"}

id:8
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"909ece989f1e4c59b416743abefc8a45","finish_reason":"null","text":"I am from Alibaba Cloud's large language model, I am called Qwen. I can generate text, answer questions, create stories, write code, translate, and perform various language tasks. If you have any questions or need"},"usage":{"models":[{"input_tokens":184,"output_tokens":40,"model_id":"qwen-max"}]},"request_id":"e7dde240-6f52-9cf0-a70f-d2a4b94374c5"}

id:9
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"909ece989f1e4c59b416743abefc8a45","finish_reason":"null","text":"I am from Alibaba Cloud's large language model, I am called Qwen. I can generate text, answer questions, create stories, write code, translate, and perform various language tasks. If you have any questions or need assistance, please feel free to let me know, I will do my best to provide"},"usage":{"models":[{"input_tokens":184,"output_tokens":48,"model_id":"qwen-max"}]},"request_id":"e7dde240-6f52-9cf0-a70f-d2a4b94374c5"}

id:10
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"909ece989f1e4c59b416743abefc8a45","finish_reason":"null","text":"I am from Alibaba Cloud's large language model, I am called Qwen. I can generate text, answer questions, create stories, write code, translate, and perform various language tasks. If you have any questions or need assistance, please feel free to let me know, I will do my best to provide support."},"usage":{"models":[{"input_tokens":184,"output_tokens":50,"model_id":"qwen-max"}]},"request_id":"e7dde240-6f52-9cf0-a70f-d2a4b94374c5"}

id:11
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"909ece989f1e4c59b416743abefc8a45","finish_reason":"stop","text":"I am from Alibaba Cloud's large language model, I am called Qwen. I can generate text, answer questions, create stories, write code, translate, and perform various language tasks. If you have any questions or need assistance, please feel free to let me know, I will do my best to provide support."},"usage":{"models":[{"input_tokens":184,"output_tokens":50,"model_id":"qwen-max"}]},"request_id":"e7dde240-6f52-9cf0-a70f-d2a4b94374c5"}

Custom parameter pass-through

Python

Workflow and agent orchestration application

Sample request:

from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# Custom input parameter pass-through for workflow and agent orchestration applications
biz_params = {"city": "Singapore"}

response = Application.call(
    app_id='YOUR_APP_ID',
    prompt='Query the administrative divisions of this city',
    biz_params=biz_params  # Pass business parameters
)

if response.status_code != HTTPStatus.OK:
    print(f'request_id={response.request_id}, code={response.status_code}, message={response.message}')
else:
    print(f'output={response.output}, usage={response.usage}')

Sample response:

output={"text": "Singapore is a city-state, which means it is both a city and an independent sovereign state. It does not have the typical administrative divisions like provinces or states that larger countries might have. Instead, for administrative purposes, Singapore is divided into five regions, and further subdivided into planning areas. Here are the five regions:
Central Region, East Region, North Region, North-East Region, West Region", 
"finish_reason": "stop", "session_id": "6a3bf88eacda43128f57d87e29323166", 
"thoughts": null, "doc_references": null}, usage={"models": null}

Custom plug-in parameter

Sample request:

from http import HTTPStatus
# Recommended version of dashscope SDK >= 1.14.0
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

biz_params = {
    # Custom plugin input parameter pass-through for agent applications, replace {your_plugin_code} with your custom plugin ID
    "user_defined_params": {
        "{your_plugin_code}": {
            "article_index": 2}}}
response = Application.call(app_id='YOUR_APP_ID',
                            prompt='Dormitory convention content',
                            biz_params=biz_params)

if response.status_code != HTTPStatus.OK:
    print('request_id=%s, code=%s, message=%s\n' % (response.request_id, response.status_code, response.message))
else:
    print('request_id=%s\n output=%s\n usage=%s\n' % (response.request_id, response.output, response.usage))

Sample response:

request_id=d97e3c58-7a75-9ea1-9ecf-d5be869b748e
 output={"text": "The second article of the dormitory convention states: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This reminds us to maintain good interpersonal relationships in dormitory life and create a harmonious and positive living and learning environment together. If you need to know more about the convention, please tell me the specific number or continue to ask questions.", "finish_reason": "stop", "session_id": "8ec3fa6c59794ed3ab803b921aa38d7a", "thoughts": null, "doc_references": null}
 usage={"models": [{"model_id": "qwen-max", "input_tokens": 453, "output_tokens": 107}]}

Custom plug-in authentication

Sample request:

from http import HTTPStatus
# Recommended version of dashscope SDK >= 1.14.0
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
biz_params = {
    # Custom plugin authentication pass-through for agent applications, replace {your_plugin_code} with your custom plugin ID, and token with YOUR_TOKEN
    "user_defined_params": {
        "{your_plugin_code}": {
            "article_index": 2}},
    "user_defined_tokens": {
        "{your_plugin_code}": {
            "user_token": "YOUR_TOKEN"}}}
response = Application.call(app_id='YOUR_APP_ID',
                            prompt='Dormitory convention content',
                            biz_params=biz_params)

if response.status_code != HTTPStatus.OK:
    print('request_id=%s, code=%s, message=%s\n' % (response.request_id, response.status_code, response.message))
else:
    print('request_id=%s\n output=%s\n usage=%s\n' % (response.request_id, response.output, response.usage))

Sample response:

request_id=e928fe3b-3df3-9a3f-9ea4-884aed3aea3c
 output={"text": "The second article of the dormitory convention is: 'Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely.' This emphasizes the importance of establishing harmonious, supportive, and respectful relationships among dormitory members.", "finish_reason": "stop", "session_id": "c3b909e48a0b4867a57b482dece9cbb7", "thoughts": null, "doc_references": null}
 usage={"models": [{"model_id": "qwen-max", "input_tokens": 432, "output_tokens": 82}]}

Java

Workflow and agent orchestration application

Sample request:

package org.example;

import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

import io.reactivex.Flowable;
import com.alibaba.dashscope.utils.Constants;

class Main {
    static {
        Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    public static void streamCall() throws NoApiKeyException, InputRequiredException {

        String bizParams =
                "{\"city\":\"Singapore\"}";
        ApplicationParam param = ApplicationParam.builder()
                .appId("YOUR_APP_ID")
                .prompt("Query the administrative divisions of this city")
                .bizParams(JsonUtils.parse(bizParams))
                .build();

        Application application = new Application();
        Flowable<ApplicationResult> result = application.streamCall(param);
        result.blockingForEach(data -> {
            System.out.printf("requestId: %s, text: %s, finishReason: %s\n",
                    data.getRequestId(), data.getOutput().getText(), data.getOutput().getFinishReason());

        });
    }

    public static void main(String[] args) {
        try {
            streamCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
        }
        System.exit(0);
    }
}

Sample response:

requestId: 713ebb6e-8840-9f31-bd58-e7e931ef345d, 
text: conventione is a city-state, which means it is both a city and an independent sovereign state. It does not have the typical administrative divisions like provinces or states that larger countries might have. Instead, for administrative purposes, Singapore is divided into five regions, and further subdivided into planning areas. Here are the five regions: Central Region, East Region, North Region, North-East Region, West Region, 
finishReason: stop

Custom plugin parameter

Sample request:

package org.example;

import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

import io.reactivex.Flowable;
import com.alibaba.dashscope.utils.Constants;

class Main {
    static {
        Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    public static void streamCall() throws NoApiKeyException, InputRequiredException {

        String bizParams =
                "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}}";
        ApplicationParam param = ApplicationParam.builder()
                .appId("YOUR_APP_ID")
                .prompt("Dormitory convention content")
                .bizParams(JsonUtils.parse(bizParams))
                .build();

        Application application = new Application();
        Flowable<ApplicationResult> result = application.streamCall(param);
        result.blockingForEach(data -> {
            System.out.printf("requestId: %s, text: %s, finishReason: %s\n",
                    data.getRequestId(), data.getOutput().getText(), data.getOutput().getFinishReason());

        });
    }

    public static void main(String[] args) {
        try {
            streamCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
        }
        System.exit(0);
    }
}

Sample response:

requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: Dorm, finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention, finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention states: Dormitory members should help, finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention states: Dormitory members should help each other, care for each other, learn from each other, finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention states: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention states: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely., finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention states: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This emphasizes the importance of harmonious coexistence and mutual progress among dormitory members. If you need, finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention states: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This emphasizes the importance of harmonious coexistence and mutual progress among dormitory members. If you need to know other articles, please tell me the number, finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention states: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This emphasizes the importance of harmonious coexistence and mutual progress among dormitory members. If you need to know other articles, please tell me the number., finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention states: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This emphasizes the importance of harmonious coexistence and mutual progress among dormitory members. If you need to know other articles, please tell me the number., finishReason: stop

Custom plugin authentication

Sample request:

package org.example;

import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

import io.reactivex.Flowable;
import com.alibaba.dashscope.utils.Constants;

class Main {
    static {
        Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    public static void streamCall() throws NoApiKeyException, InputRequiredException {

        String bizParams =
                "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}," +
                        "\"user_defined_tokens\":{\"{your_plugin_code}\":{\"user_token\":\"YOUR_TOKEN\"}}}";
        ApplicationParam param = ApplicationParam.builder()
                .appId("YOUR_APP_ID")
                .prompt("Dormitory convention content")
                .bizParams(JsonUtils.parse(bizParams))
                .build();

        Application application = new Application();
        Flowable<ApplicationResult> result = application.streamCall(param);
        result.blockingForEach(data -> {
            System.out.printf("requestId: %s, text: %s, finishReason: %s\n",
                    data.getRequestId(), data.getOutput().getText(), data.getOutput().getFinishReason());

        });
    }

    public static void main(String[] args) {
        try {
            streamCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
        }
        System.exit(0);
    }
}

Sample response:

requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: Dorm, finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention, finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention states: Dormitory members should help, finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention states: Dormitory members should help each other, care for each other, learn from each other, finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention states: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention states: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely., finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention states: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This emphasizes the importance of harmonious coexistence and mutual progress among dormitory members. If you need, finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention states: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This emphasizes the importance of harmonious coexistence and mutual progress among dormitory members. If you need to know other articles, please tell me the number, finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention states: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This emphasizes the importance of harmonious coexistence and mutual progress among dormitory members. If you need to know other articles, please tell me the number., finishReason: null
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second article of the dormitory convention states: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This emphasizes the importance of harmonious coexistence and mutual progress among dormitory members. If you need to know other articles, please tell me the number., finishReason: stop

cURL

Workflow and agent orchestration application

Sample request:

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Query the administrative divisions of this city",
        "biz_params": {
        "city": "convention"}
    },
    "parameters":  {}
}'

Sample response:

{"output":{"finish_reason":"stop","session_id":"c211219896004b50a1f6f66f2ec5413e",
"text":"Singapore is a city-state, which means it is both a city and an independent sovereign state. It does not have the typical administrative divisions like provinces or states that larger countries might have. Instead, for administrative purposes, Singapore is divided into five regions, and further subdivided into planning areas. Here are the five regions: Central Region, East Region, North Region, North-East Region, West Region"},"usage":{},
"request_id":"02c3c9e1-7912-9505-91aa-248d04fb1f5d"}

Custom plugin parameter

Sample request:

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Dormitory convention content",
        "biz_params": 
        {
            "user_defined_params":
            {
                "{your_plugin_code}":
                    {
                    "article_index": 2
                    }
            }
        } 
    },
    "parameters":  {},
    "debug":{}
}'

Sample response:

{"output":
{"finish_reason":"stop",
"session_id":"e151267ffded4fbdb13d91439011d31e",
"text":"The second article of the dormitory convention is: 'Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely.' This means that in dormitory life, everyone should support each other and create a harmonious and positive living environment together."},
"usage":{"models":[{"output_tokens":94,"model_id":"qwen-max","input_tokens":453}]},
"request_id":"a39fd2b5-7e2c-983e-84a1-1039f726f18a"}%

Custom plugin authentication

Sample request:

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Dormitory convention content",
        "biz_params": 
        {
            "user_defined_params":
            {
                "{your_plugin_code}":
                    {
                    "article_index": 2
                    }
            },
            "user_defined_tokens":
            {
                "{your_plugin_code}":
                    {
                    "user_token": "YOUR_TOKEN"
                    }
            }
        } 
    },
    "parameters":  {},
    "debug":{}
}'


Sample response:

{"output":{"finish_reason":"stop",
"session_id":"d3b5c3e269dc40479255a7a02df5c630",
"text":"The second article of the dormitory convention states: 'Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely.' This emphasizes the importance of harmonious coexistence and mutual progress among dormitory members."},
"usage":{"models":[{"output_tokens":80,"model_id":"qwen-max","input_tokens":432}]},
"request_id":"1f77154c-edc3-9003-b622-816fa2f849cf"}%

Knowledge base filtering

Sample request

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/{YOUR_APP_ID}/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Please recommend a phone under 3000 yuan"
    },
    "parameters":  {
                    "rag_options" : {
                    "pipeline_ids":["your_pipeline_id1"],
                    "file_ids":["your_file_id1"]
                    }
    },
    "debug": {}
}'

Sample response

{"output":{"finish_reason":"stop","session_id":"949af3a78c6a4f08889189bc8b971fac",
"text":"Based on your budget, I recommend considering the 'DashScope Zephyr Z9'.
It has the following features:\n- A lightweight 6.4-inch 1080 x 2340 pixel design, suitable for daily carrying.
\n- Equipped with 128GB storage and 6GB RAM, meeting most daily usage needs.
\n- A 4000mAh battery ensures worry-free use throughout the day.
\n- A lens supporting 30x digital zoom, convenient for capturing distant scenes.\n
\nThe reference price is 3999-4299 yuan, slightly above 3000 yuan, but considering its performance and features, it is still a cost-effective phone.
If the budget is tight, you can also look for discounts or other promotions, which may offer the opportunity to purchase at a more favorable price."},
"usage":{"models":[{"output_tokens":172,"model_id":"qwen-plus","input_tokens":1024}]},
"request_id":"2ca66967-b692-9027-9d9b-609f4d9fec56"}%
Only HTTP calls support knowledge base filtering

prompt string Required

The instruction for the application to execute, which guides the application to generate a response.

For HTTP calls, include prompt in input.

session_id string Optional

The unique ID of the conversation session. For multi-round conversations, use the session_id from the previous round as a parameter for the next. When session_id is provided, the conversation history is stored in the cloud, and the application call automatically includes the stored history.

Only agent applications and dialog workflow applications support multi-round conversations.
In the Java SDK, use setSessionId.

workspace string Optional

The workspace ID. workspace is required when calling an application in a sub-workspace. workspace is optional when calling an application in the default workspace.

In a sub-workspace, go to My Applications and click Call on the desired application card. From the displayed API sample, you can obtain the workspace ID. For more information, see Obtain the workspace ID.

For HTTP calls, specify X-DashScope-WorkSpace in the Header.

stream boolean Optional

Specifies whether to use the streaming output mode. Valid values:

  • false (default): The model delivers the complete response at a time.

  • true: The model returns output in chunks as content is generated.

Only the Python SDK supports this parameter.
For streaming output with the Java SDK, use streamCall.
For HTTP calls, set X-DashScope-SSE to enable in the Header or set the Accept header to text/event-stream.

incremental_output boolean Optional

Specifies whether to enable incremental output in the streaming output mode. Valid values:

  • false (default): Each output includes the entire sequence generated so far.

    I
    I like
    I like apple
    I like apple.
  • true: Each output excludes previous content. You need to read the outputs in real-time to obtain the full result.

    I
    like
    apple
    .

biz_params object Optional

  • This parameter is used to pass through custom parameters for workflow applications and agent orchestration applications. For example:

    Python

    biz_params = {"city": "Singapore"}

    Java

    String bizParams ="{\"city\":\"Singapore\"}";

    cURL

    "biz_params": {
      "city": "Singapore"}
  • This parameter is also used to pass parameters for custom plug-ins and user-level authentication for agent applications. For example:

    Properties

    user_defined_params object Optional

    Specifies the information of the custom plug-in.

    Properties

    plugin_id string Optional

    The plug-in ID, your_plugin_code, which varies by plug-ins.

    ${plugin_params} string Optional

    Contains key-value pairs within the innermost object. Each pair represents a user-defined parameter name and its value, such as:

    "article_index": 2

    user_defined_tokens object Optional

    The user-level authentication information for custom plug-ins.

    Properties

    plugin_id string Optional

    Identifies the plug-in, your_plugin_code, which varies by plug-in.

    user_token string Optional

    The Token represents the user authentication credential required by the plug-in.

In the Java SDK, use bizParams.

has_thoughts boolean Optional

Specifies whether to include information about the plug-in calling and knowledge retrieval process in the response.

Default value: False.

image_list Array Optional

A list of input image URLs.

When an agent application is associated with a structured knowledge base, it can process image URLs through the image_list parameter. If the knowledge base includes image indexes, the system converts the input images into vectors and retrieve related records, then passes these records along with the query to the LLM.

"image_list" : ["https://example.com/images/example.jpg"]
#This is a fictional URL, please replace it with an actual image URL

rag_options Array Optional

Specifies the scope for knowledge base retrieval, which can limited to specific knowledge bases or documents.

Only HTTP calls support this parameter.

Properties

pipeline_ids Array Required

Specifies the knowledge base ID. Only the documents in the specified knowledge base are retrieved.

You can obtain the knowledge base ID on the Knowledge Base Index page, or by calling the CreateIndex operation, which returns Data.Id.

You can specify up to five knowledge base IDs in the following format. If more than five IDs are provided, only the first five IDs are effective.
["Knowledge Base ID1", "Knowledge Base ID2"]

file_ids Array Optional

Specifies the unstructured document ID. Only specified unstructured document are retrieved.

You can obtain the document ID in the document list on the Data Management page, or by calling the AddFile operation.

If you specify document IDs, you must also specify the ID of the knowledge base to which the documents belong.
["Document ID1", "Document ID2"]

metadata_filter Object Optional

Specifies the metadata for unstructured documents. Only unstructured documents with the specified metadata are retrieved.

To obtain the metadata, go to the Knowledge Base Index page, view the details of a knowledge base and click Metadata Information in the Actions column. Metadata can be set when creating an unstructured knowledge base. You can also call ListChunks to obtain the metadata of all chunks of a specified document.

If you specify metadata_filter, you must also specify the ID of the knowledge base to which the documents belong.

tags: Array (Optional)

The tags associated with unstructured documents. Only unstructured documents with the specified tags are retrieved.

To obtain the metadata, go to the Knowledge Base Index page, view the details of a knowledge base and click Tag in the Actions column. You can also call DescribeFile to obtain document tags.

Only tags set before the creation of the knowledge base are effective. You can specify multiple tags. Documents with at least one of the tags are retrieved.
["Tag1", "Tag2"]

Response parameters

status_code integer

The response code. The status code 200 indicates that the request is successful. Other status codes indicate that the request failed.

The Java SDK does not return this parameter. Instead, an exception is thrown with status_code and message.

Sample response

Single-round conversation

request_id=e3bba3a5-5784-9592-aa18-03170770de1e
output={"text": "I am a large language model from Alibaba Cloud, named Qwen.
I can answer various questions, provide information, and engage in conversation with you.
How can I assist you?", 
"finish_reason": "stop", 
"session_id": "a0606349b3c34c6fad7cf1d6454e0072", 
"thoughts": null, "doc_references": null}
usage={"models": [{"model_id": "qwen-max", 
"input_tokens": 121, 
"output_tokens": 37}]}

Show source

{"output":{"finish_reason":"stop",
"session_id":"6a2f38cd3170477eaa09cef8ccb1431f",
"text":"I recommend considering the Bailian Zephyr Z9 phone<ref>[3]</ref>.
It is lightweight and portable, with a 6.4-inch 1080 x 2340 pixel screen, equipped with 128GB of storage and 6GB of RAM, sufficient for daily use needs.
In addition, it is equipped with a 4000mAh battery, ensuring a worry-free day of power, and a 30x digital zoom lens, suitable for users who like to take photos.
Most importantly, its reference price is between 2499 and 2799 yuan, perfectly meeting your budget requirements.",
"doc_references":[{"images":[],"doc_name":"1",
"text":"[Document Name]:1\n[Title]:Bailian Phone Product Introduction\nPrice:[\"2999\"]\n
[Text]:Bailian Zephyr Z9 - The Art of Lightweight Portability: A lightweight 6.4-inch 1080 x 2340 pixel design, paired with 128GB storage and 6GB RAM, effortlessly handling daily use.
A 4000mAh battery ensures a worry-free day, and a 30x digital zoom lens captures distant details, lightweight yet powerful. Reference price: 2499-2799.\n",
"index_id":"3","title":"Bailian Phone Product Introduction","doc_id":"file_e20344bc014c48a4aa5111a12e8c243d_10269262"}]},
"usage":{"models":[{"output_tokens":125,
"model_id":"qwen-max","input_tokens":1496}]},
"request_id":"7ff5edca-a718-9402-9f73-d3385ce9691d"}%

Exception response

An error during a request returns the code and message parameters.

The following is an example of an exception response when an incorrect API-KEY is provided.

request_id=1d14958f-0498-91a3-9e15-be477971967b, code=401, message=Invalid API-key provided.

request_id string

The request ID.

In the Java SDK, this is returned as requestId.

code string

The error code, which is empty for successful calls. For a list of error codes, see Status codes

This parameter is returned only for the Python SDK.

message string

The error message returned in case of a failed request.

This parameter is returned only for the Python SDK.

output object

The result of the request.

Output Properties

text string

The response generated by the model.

finish_reason string

The finish reason. Valid values:

  • null: The model is generating the answer.

  • stop: The stop condition of the model is met.

session_id string

The ID for the conversation session, used to maintain the context in multi-round conversations.

thoughts array

The thought information of the model

thoughts properties

thought string

The thought process.

action_type string

The type of action taken by the model.

api: Executes an API plug-in;

response: Returns the final result.

action_name string

The name of the executed action, such as document retrieval or API plug-in call.

action string

The executed action.

action_input_stream string

The streaming result of the input parameters.

action_input string

The request parameters for the plug-in.

response string

The response returned by the model.

observation string

The result of document retrieval or plug-in execution.

doc_references array

Details of documents referenced by the model during RAG retrieval.

doc_references properties

index_id string

The index of the document referenced by the model, such as [1].

title string

The title of the text chunk referenced by the model.

doc_id string

The ID of the document referenced by the model.

doc_name string

The name of the document referenced by the model.

text string

The specific text content referenced by the model.

images array

A list of image URLs referenced by the model.

usage object

The token consumed by this request.

Usage Properties

models array

The models called for the request.

Models Properties

model_id string

The ID of the called model.

input_tokens integer

The number of tokens converted from the user input.

output_tokens integer

The number of tokens converted from the model response.