All Products
Search
Document Center

Alibaba Cloud Model Studio:Application calling

Last Updated:Apr 21, 2025

You can integrate agent, workflow, or agent orchestration applications from Model Studio into your business systems through DashScope SDK or HTTP.

Prerequisites

You can use DashScope SDK or HTTP interface to call Model Studio applications. Prepare your environment before you go.

Regardless of which calling method you use, we recommend that you configure the API key as an environment variable. If you use DashScope SDK, you must also install DashScope SDK.

How to use

Single-round conversation

Sample code for the DashScope SDK or HTTP method to implement single-round conversation.

Python

Sample request

import os
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(
    # 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://www.alibabacloud.com/help/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!

Java

Sample request

// Recommended dashscope SDK version >= 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 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()
                // If environment variables are not configured, you can replace the following line with .apiKey("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.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("YOUR_APP_ID")
                .prompt("Who are you?")
                .build();

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

        System.out.printf("text: %s\n",
                result.getOutput().getText());
    }

    public static void main(String[] args) {
        try {
            appCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("message: "+e.getMessage());
            System.out.println("Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

Sample response

text: I am a large language model developed by Alibaba Cloud, named Qwen.

HTTP

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": {}
}' 
Replace YOUR_APP_ID with the actual application ID.

Sample response

{"output":{"finish_reason":"stop",
"session_id":"232ea2e9e6ef448db6b14465c06a9a56",
"text":"I am a super-large-scale language model developed by Alibaba Cloud, and my name is Qwen. I am an AI assistant who can answer questions, create text, express opinions, and even write code. If you have any questions or need assistance, please don't hesitate to let me know, and I will do my best to provide you with the help you need."},
"usage":{"models":[{"output_tokens":51,"model_id":"qwen-max","input_tokens":121}]},
"request_id":"661c9cad-e59c-9f78-a262-78eff243f151"}% 
PHP

Sample request

<?php

# If the environment variable is not configured, you can replace the following line with your API Key: $api_key="sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with your actual application ID

$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";

// Construct request data
$data = [
    "input" => [
        'prompt' => 'Who are you?'
    ]
];

// Encode data as JSON
$dataString = json_encode($data);

// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// Initialize curl session
$ch = curl_init($url);

// Set curl options
curl_setopt($ch, curlOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, curlOPT_POSTFIELDS, $dataString);
curl_setopt($ch, curlOPT_RETURNTRANSFER, true);
curl_setopt($ch, curlOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
]);

// Execute the request
$response = curl_exec($ch);

// Check if curl execution was successful
if ($response === false) {
    die("curl Error: " . curl_error($ch));
}

// Get HTTP status code
$status_code = curl_getinfo($ch, curlINFO_HTTP_CODE);
// Close curl session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Handle response
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    }}
else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";} 
    else {
        echo "message=Unknown error\n";}
}
?>

Sample response

I am a super-large-scale language model developed by Alibaba Cloud, and my name is Qwen.
Node.js

Dependency:

npm install axios

Sample request

const axios = require('axios');

async function callDashScope() {
    // If environment variables are not configured, you can replace the following line with apiKey='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.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'YOUR_APP_ID';// Replace with the actual application ID

    const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "Who are you?"
        },
        parameters: {},
        debug: {}
    };

    try {
        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            console.log(`${response.data.output.text}`);
        } else {
            console.log(`request_id=${response.headers['request_id']}`);
            console.log(`code=${response.status}`);
            console.log(`message=${response.data.message}`);
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}

callDashScope();

Sample response

I am a large-scale language model developed by Alibaba Cloud, and my name is Qwen.
C#

Sample request

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        //If environment variables are not configured, you can replace the following line with apiKey="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. 
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "YOUR_APP_ID"; // Replace with the actual application ID

        string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

            string jsonContent = @"{
                ""input"": {
                    ""prompt"": ""Who are you?""
                },
                ""parameters"": {},
                ""debug"": {}
            }";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Request successful:");
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Sample response

{
    "output": {
        "finish_reason": "stop",
        "session_id": "c274e14a58d9492f9baeffdc003a97c5",
        "text": "I am a super-large-scale language model developed by Alibaba Cloud, and my name is Qwen. I am designed to assist users in generating various types of text, such as articles, stories, poems, etc., and can adapt and innovate according to different scenarios and needs. Additionally, I am capable of answering a wide range of questions, providing information and explanations, and helping users solve problems and acquire knowledge. If you have any questions or need assistance, please feel free to let me know anytime!"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 79,
                "model_id": "qwen-plus",
                "input_tokens": 74
            }
        ]
    },
    "request_id": "5c4b86b1-cd2d-9847-8d00-3fba8f187bc6"
}
Go

Sample request

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	// If environment variables are not configured, you can replace the following line with apiKey := "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.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "YOUR_APP_ID" // Replace with the actual application ID

	if apiKey == "" {
		fmt.Println("Please ensure DASHSCOPE_API_KEY is set.")
		return
	}

	url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)

	// Create request body
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt": "Who are you?",
		},
		"parameters": map[string]interface{}{},
		"debug":      map[string]interface{}{},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Printf("Failed to marshal JSON: %v\n", err)
		return
	}

	// Create HTTP POST request
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// Set request headers
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// Send request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// Read response
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// Process response
	if resp.StatusCode == http.StatusOK {
		fmt.Println("Request successful:")
		fmt.Println(string(body))
	} else {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		fmt.Println(string(body))
	}
}

Sample response

{
    "output": {
        "finish_reason": "stop",
        "session_id": "6105c965c31b40958a43dc93c28c7a59",
        "text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 36,
                "model_id": "qwen-plus",
                "input_tokens": 74
            }
        ]
    },
    "request_id": "f97ee37d-0f9c-9b93-b6bf-bd263a232bf9"
}

Multi-round conversation

In multi-round conversations, the LLM can reference the conversation history, making it more similar to everyday communication scenarios.

Currently, only agent applications and dialog workflow applications support multi-round conversation.
  • When you pass in session_id, the request automatically carries the conversation history stored in the cloud.

    When passing in session_id, prompt is required.
  • You can also choose to maintain a messages array. Add each round of conversation history and new instructions to the messages array. Then, pass the history through messages.

    When passing in messages, prompt is optional. If both are passed in, prompt will be appended to the end of messages as supplementary information.
If both session_id and messages are passed in, messages will be used preferentially.

Cloud storage (session_id)

Python

Sample request

import os
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(
        # 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://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
        return response

    responseNext = 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='What skills do you have?',
                session_id=response.output.session_id)  # 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'Refer to: https://www.alibabacloud.com/help/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()

Sample response

I have multiple skills and can assist you with various tasks. Here are some of my main skills:

1. **Information retrieval**: Providing weather, news, historical facts, scientific knowledge, and various other information.
2. **Language processing**: Translating text, correcting grammar errors, generating articles and stories.
3. **Technical problem solving**: Answering programming questions, software usage, technical troubleshooting, etc.
4. **Educational assistance**: Helping with questions in subjects like mathematics, physics, chemistry, etc.
5. **Life advice**: Providing advice on health, diet, travel, shopping, etc.
6. **Entertainment interaction**: Telling jokes, playing word games, engaging in simple chat interactions.
7. **Schedule management**: Reminding important dates, arranging schedules, setting reminders.
8. **Data analysis**: Explaining data charts, providing data analysis suggestions.
9. **Emotional support**: Listening to your feelings, providing comfort and support.

If you have specific needs or questions, you can tell me directly, and I'll do my best to help you!
 session_id=98ceb3ca0c4e4b05a20a00f913050b42
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()
                // If environment variables are not configured, you can replace the following line with .apiKey("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.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // Replace with the actual application ID
                .appId("YOUR_APP_ID")
                .prompt("Who are you?")
                .build();

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

        param.setSessionId(result.getOutput().getSessionId());
        param.setPrompt("What skills do you have?");
        result = application.call(param);

        System.out.printf("%s\n, session_id: %s\n",
                result.getOutput().getText(), result.getOutput().getSessionId());
    }

    public static void main(String[] args) {
        try {
            callWithSession();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

Sample response

I possess multiple skills and can provide various types of assistance. Here are some of my main skills:

1. **Multilingual understanding and generation**: I can understand and generate text in multiple languages including Chinese and English.
2. **Information retrieval and synthesis**: I can search for relevant information based on your questions and organize and summarize it.
3. **Writing assistance**: Whether it's writing articles, reports, or creative writing, I can provide support.
4. **Programming assistant**: For programmers, I can help answer programming-related questions, provide code examples, etc.
5. **Educational guidance**: When encountering difficulties in the learning process, I can serve as an assistant to provide help, covering multiple subject areas from mathematics to history.
6. **Life advice**: I can also give some advice on issues related to healthy eating, travel planning, etc.
7. **Emotional communication**: Although I am an AI, I strive to communicate with you in a warm and supportive way.

If you have any specific needs or want to learn more about a particular aspect, please feel free to tell me!
, session_id: f2e94a980a34424fa25be45a7048d77c
HTTP
curl

Sample request (round 1)

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": "4f8ef7233dc641aba496cb201fa59f8c",
        "text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 36,
                "model_id": "qwen-plus",
                "input_tokens": 75
            }
        ]
    },
    "request_id": "e571b14a-423f-9278-8d1e-d86c418801e0"
}

Sample request (round 2)

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 skills do you have?",
        "session_id":"4f8ef7233dc641aba496cb201fa59f8c"
    },
    "parameters":  {},
    "debug": {}
}' 

Sample response

{
    "output": {
        "finish_reason": "stop",
        "session_id": "4f8ef7233dc641aba496cb201fa59f8c",
        "text": "As an AI assistant, I have multiple skills that can help you complete various tasks, including but not limited to:

1. **Knowledge queries**: I can help you find information in various fields such as science, history, culture, technology, etc.
2. **Language translation**: I can help you translate text in different languages, supporting translation between multiple languages.
3. **Text generation**: I can generate articles, stories, poems, press releases, and various other types of text.
4. **Question answering**: Whether it's academic questions, common knowledge, or technical problems, I can try to provide answers for you.
5. **Conversational exchange**: I can have natural and smooth conversations with you, providing emotional support or entertainment.
6. **Code writing and debugging**: I can help you write code and solve problems in programming.
7. **Data analysis**: I can help you analyze data, provide statistical results and visualization suggestions.
8. **Creative inspiration**: If you need creative inspiration, such as design, advertising copy, marketing strategies, etc., I can also provide help.

If you have any specific needs or questions, feel free to tell me anytime!"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 208,
                "model_id": "qwen-plus",
                "input_tokens": 125
            }
        ]
    },
    "request_id": "9de2c3ed-e1f0-9963-85f4-8f289203418b"
}
PHP

Sample request (round 1)

<?php
# If the environment variable is not configured, you can replace the next line with your API key: $api_key="sk-xxx". However, it is not recommended to hardcode the API key directly into the code in a production environment to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with the actual application ID

$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";

// Construct request data
$data = [
    "input" => [
        'prompt' => 'Who are you?'
    ]
];

// Encode data as JSON
$dataString = json_encode($data);

// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// Initialize curl session
$ch = curl_init($url);

// Set curl options
curl_setopt($ch, curlOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, curlOPT_POSTFIELDS, $dataString);
curl_setopt($ch, curlOPT_RETURNTRANSFER, true);
curl_setopt($ch, curlOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
]);

// Execute the request
$response = curl_exec($ch);

// Check if curl execution was successful
if ($response === false) {
    die("curl Error: " . curl_error($ch));
}

// Get HTTP status code
$status_code = curl_getinfo($ch, curlINFO_HTTP_CODE);
// Close curl session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Handle response
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    };
    if (isset($response_data['output']['session_id'])) {
        echo "session_id={$response_data['output']['session_id']}\n";
    }
} else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";
    }
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";
    } else {
        echo "message=Unknown error\n";
    }
}
?>

Sample response

I am a large-scale language model from Alibaba Cloud, my name is Qwen.
session_id=2e658bcb514f4d30ab7500b4766a8d43

Sample request (round 2)

<?php
# If the environment variable is not configured, you can replace the next line with your API key: $api_key="sk-xxx". However, it is not recommended to hardcode the API key directly into the code in a production environment to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with the actual application ID

$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";

// Construct request data
$data = [
    "input" => [
        'prompt' => 'What skills do you have?',
        // Replace with the session_id returned from the previous round of conversation
        'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
    ]
];

// Encode data as JSON
$dataString = json_encode($data);

// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// Initialize curl session
$ch = curl_init($url);

// Set curl options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
]);

// Execute the request
$response = curl_exec($ch);

// Check if curl execution was successful
if ($response === false) {
    die("curl Error: " . curl_error($ch));
}

// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close curl session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Handle response
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    }
    if (isset($response_data['output']['session_id'])) {
        echo "session_id={$response_data['output']['session_id']}\n";
    }
} else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";
    }
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";
    } else {
        echo "message=Unknown error\n";
    }
}
?>

Sample response

I have multiple skills, including but not limited to:

1. **Multilingual capability**: I can understand and generate text content in multiple languages.
2. **Writing and creation**: Help with writing articles, stories, poems, and other creative content.
3. **Knowledge Q&A**: Answer common and professional questions from various fields.
4. **Code writing and understanding**: Able to write simple program code, and help explain or debug code.
5. **Logical reasoning**: Solve problems and puzzles that require logical thinking.
6. **Emotional support**: Provide positive psychological support and encouragement.
7. **Games and entertainment**: Participate in word games or other forms of interactive entertainment activities.

My goal is to be your capable assistant, providing help and support when you need it. If you have any specific needs or features you'd like to try, please feel free to tell me!
session_id=2e658bcb514f4d30ab7500b4766a8d43
Node.js

Dependency:

npm install axios

Sample request (round 1)

const axios = require('axios');

async function callDashScope() {
    // If environment variables are not configured, you can replace the following line with apiKey='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.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'YOUR_APP_ID';// Replace with the actual application ID

    const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "Who are you?"
        },
        parameters: {},
        debug: {}
    };

    try {
        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            console.log(`${response.data.output.text}`);
            console.log(`session_id=${response.data.output.session_id}`);
        } else {
            console.log(`request_id=${response.headers['request_id']}`);
            console.log(`code=${response.status}`);
            console.log(`message=${response.data.message}`);
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}
callDashScope();

Sample response

I am Qwen, an artificial intelligence assistant developed by Alibaba Cloud. I can answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?
session_id=fe4ce8b093bf46159ea9927a7b22f0d3

Sample request (round 2)

const axios = require('axios');

async function callDashScope() {
    // If environment variables are not configured, you can replace the following line with apiKey='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.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'YOUR_APP_ID';// Replace with the actual application ID

    const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    // Replace session_id with the actual session_id from the previous conversation
    const data = {
        input: {
            prompt: "What skills do you have?",
            session_id: 'fe4ce8b093bf46159ea9927a7b22f0d3',
        },
        parameters: {},
        debug: {}
    };

    try {
        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            console.log(`${response.data.output.text}`);
            console.log(`session_id=${response.data.output.session_id}`);
        } else {
            console.log(`request_id=${response.headers['request_id']}`);
            console.log(`code=${response.status}`);
            console.log(`message=${response.data.message}`);
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}
callDashScope();

Sample response

I have various skills that can help you handle different tasks and questions. Here are some of my main skill areas:

1. **Information query and retrieval**: I can help find specific information, data, or news.
2. **Writing and creation**: Including writing articles, stories, poems, reports, etc.
3. **Language translation**: Can provide translation services between different languages.
4. **Educational tutoring**: Answer academic questions, help understand complex concepts.
5. **Technical support**: Solve technical problems encountered in computer use.
6. **Life advice**: Provide advice on health, diet, travel, and other aspects.
7. **Entertainment interaction**: Tell jokes, play word games, and other relaxing activities.

If you have specific needs or want to learn more about a particular aspect, please let me know!
session_id=fe4ce8b093bf46159ea9927a7b22f0d3
C#

Sample request (round 1)

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        //If environment variables are not configured, you can replace the following line with apiKey="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. 
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "YOUR_APP_ID"; // Replace with the actual application ID

        string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

            string jsonContent = @"{
                ""input"": {
                    ""prompt"": ""Who are you?""
                },
                ""parameters"": {},
                ""debug"": {}
            }";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Request successful:");
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Sample response

{
    "output": {
        "finish_reason": "stop",
        "session_id": "7b830e4cc8fe44faad0e648f9b71435f",
        "text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 36,
                "model_id": "qwen-plus",
                "input_tokens": 75
            }
        ]
    },
    "request_id": "53691ae5-be17-96c6-a830-8f0f92329028"
}

Sample request (round 2)

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        //If environment variables are not configured, you can replace the following line with apiKey="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. 
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "YOUR_APP_ID"; // Replace with the actual application ID

        string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

            string jsonContent = @"{
                ""input"": {
                    ""prompt"": ""What skills do you have?"",
                    ""session_id"": ""7b830e4cc8fe44faad0e648f9b71435f""
                },
                ""parameters"": {},
                ""debug"": {}
            }";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Request successful:");
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Sample response

{
    "output": {
        "finish_reason": "stop",
        "session_id": "7b830e4cc8fe44faad0e648f9b71435f",
        "text": "I have multiple skills and can:

- Answer knowledge questions from a wide range of fields
- Provide learning resources and suggestions
- Assist with technical problems
- Communicate in multiple languages
- Help plan trips and activities
- Provide practical advice for daily life

If you have any specific needs or questions, feel free to let me know!"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 70,
                "model_id": "qwen-plus",
                "input_tokens": 123
            }
        ]
    },
    "request_id": "da5044ed-461e-9e91-8ca5-38a3c72a8306"
}
Go

Sample request (round 1)

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	// If environment variables are not configured, you can replace the following line with apiKey := "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.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "YOUR_APP_ID" // Replace with the actual application ID

	if apiKey == "" {
		fmt.Println("Please make sure DASHSCOPE_API_KEY is set.")
		return
	}

	url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)

	// Create request body
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt": "Who are you?",
		},
		"parameters": map[string]interface{}{},
		"debug":      map[string]interface{}{},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Printf("Failed to marshal JSON: %v\n", err)
		return
	}

	// Create HTTP POST request
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// Set request headers
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// Send request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// Read response
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// Process response
	if resp.StatusCode == http.StatusOK {
		fmt.Println("Request successful:")
		fmt.Println(string(body))
	} else {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		fmt.Println(string(body))
	}
}

Sample response

{
    "output": {
        "finish_reason": "stop",
        "session_id": "f7eea37f0c734c20998a021b688d6de2",
        "text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 36,
                "model_id": "qwen-plus",
                "input_tokens": 75
            }
        ]
    },
    "request_id": "fa65e14a-ab63-95b2-aa43-035bf5c51835"
}

Sample request (round 2)

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	// If environment variables are not configured, you can replace the following line with apiKey := "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.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "YOUR_APP_ID" // Replace with the actual application ID

	if apiKey == "" {
		fmt.Println("Please make sure DASHSCOPE_API_KEY is set.")
		return
	}

	url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)

	// Create request body
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt":     "What skills do you have?",
			"session_id": "f7eea37f0c734c20998a021b688d6de2", // Replace with the actual session_id from the previous conversation
		},
		"parameters": map[string]interface{}{},
		"debug":      map[string]interface{}{},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Printf("Failed to marshal JSON: %v\n", err)
		return
	}

	// Create HTTP POST request
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// Set request headers
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// Send request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}```
	defer resp.Body.Close()

	// Read response
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// Process response
	if resp.StatusCode == http.StatusOK {
		fmt.Println("Request successful:")
		fmt.Println(string(body))
	} else {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		fmt.Println(string(body))
	}
}

Sample response

{
    "output": {
        "finish_reason": "stop",
        "session_id": "f7eea37f0c734c20998a021b688d6de2",
        "text": "I have multiple skills and can:

- Answer various knowledge questions in fields such as science, history, culture, etc.
- Provide practical advice, such as travel tips, health tips, study methods, etc.
- Assist with text work, such as writing articles, editing documents, creating stories or poems.
- Perform multilingual translation, supporting translation between multiple languages.
- Have natural and smooth conversations with users, keeping them company, answering questions.

If you have any specific needs, feel free to let me know!"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 104,
                "model_id": "qwen-plus",
                "input_tokens": 125
            }
        ]
    },
    "request_id": "badccade-9f54-986b-8d8c-75ef15e9616c"
}
Replace YOUR_APP_ID with the actual application ID. For round 2, replace the session_id with the actual session_id returned from round 1.

Self-management (messages)

Python

Sample request

# dashscope SDK version needs to be >= 1.20.14
import os
from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

messages = [
    {'role': 'system', 'content': 'You are a helpful assistant.'},
    {'role': 'user', 'content': 'Who are you?'},
    {"role": "assistant","content": "I am a large-scale language model developed by Alibaba Cloud, my name is Qwen."},
    {"role": "user","content": "What can you do?"}
]
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
    messages=messages)

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://www.alibabacloud.com/help/en/model-studio/error-code')
else:
    print('%s\n' % (response.output.text))

Sample response

As Qwen, I can help you complete various tasks, including but not limited to:

1. Answering questions: Whether it's scientific knowledge, technical problems, or common sense, I can provide accurate information and answers.
2. Creating text: Such as writing stories, poems, articles, etc., generating creative content based on given conditions.
3. Programming assistant: Can assist with programming learning, explain code logic, help debug program errors, etc.
4. Language translation: Support translation services between multiple languages.
5. Providing suggestions: Offering advice or solutions when facing decisions.
6. Emotional communication: Engaging in conversations with users, listening and giving positive responses and support.

In short, my goal is to be your capable assistant in work and life. If you have any specific needs, please feel free to tell me!
Java

Sample request

// dashscope SDK version needs to be >= 2.17.0
import java.util.ArrayList;
import java.util.List;

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

public class Main {
      static {
        Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
      }
      public static void appCall()
            throws ApiException, NoApiKeyException, InputRequiredException {
        List messages = new ArrayList<>();
        messages.add(Message.builder().role("system").content("You are a helpful assistant.").build());
        messages.add(Message.builder().role("user").content("Who are you?").build());
        messages.add(Message.builder().role("assistant").content("I am a large-scale language model developed by Alibaba Cloud, my name is Qwen.").build());
        messages.add(Message.builder().role("user").content("What can you do?").build());

        ApplicationParam param = ApplicationParam.builder()
                // If environment variables are not configured, you can replace the following line with .apiKey("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.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("YOUR_APP_ID")
                .messages(messages)
                .build();

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

        System.out.printf("text: %s\n",
                result.getOutput().getText());
    }

    public static void main(String[] args) {
        try {
            appCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("message:"+e.getMessage());
            System.out.println("Refer to: https://www.alibabacloud.com/help/en/model-studio/error-code");
        }
        System.exit(0);
    }
}

Sample response

text: I can help you complete various tasks, including but not limited to:

1. Answering questions: Whether academic questions, common knowledge, or questions in professional fields, I will do my best to provide accurate answers.
2. Creating text: Such as writing stories, official documents, emails, scripts, etc., just give me some basic information and requirements.
3. Table processing: Can help you organize data, generate or modify tables.
4. Code writing: Support code writing and explanation in multiple programming languages.
5. Multilingual translation: Can translate between different languages.
6. Simulated dialogue: Can play different roles to engage in simulated conversations with users.

If you have any specific needs, please feel free to tell me!
HTTP
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": {
        "messages":[      
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "Who are you?"
            },
            {
                "role": "assistant",
                "content": "I am a large-scale language model developed by Alibaba Cloud, my name is Qwen."
            },
            {
                "role": "user",
                "content": "What can you do?"
            }
        ]
    },
    "parameters":  {},
    "debug": {}
}' 

Sample response

{"output":
{"finish_reason":"stop","session_id":"990ca89d89794826976d7499ad10cddb",
"text":"I can help you complete various tasks, including but not limited to:\n\n1. Answering questions: Whether academic knowledge, practical tips, or common sense questions, I will do my best to provide accurate answers.\n2. Creating text: Such as writing stories, official documents, emails, scripts, etc., as long as you tell me your specific needs, I can help you write them.\n3. Expressing opinions: For some subjective questions, I can also give my own views and discuss them with you.\n4. Games and entertainment: We can play word games together, or I can tell you a joke to help you relax.\n\nIn short, anything related to language, you can ask me for help!"},
"usage":{"models":[{"output_tokens":126,"model_id":"qwen-max","input_tokens":86}]},"request_id":"3908c4a3-8d7a-9e51-81a5-0fc366582990"}%  
PHP

Sample request

<?php
# If the environment variable is not configured, you can replace the next line with your API key: $api_key="sk-xxx". However, it is not recommended to hardcode the API key directly into the code in a production environment to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with the actual application ID

$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";

// Construct request data
$data = [
    "input" => [
        "messages" => [
            [
                "role" => "system",
                "content" => "You are a helpful assistant."
            ],
            [
                "role" => "user",
                "content" => "Who are you?"
            ],
            [
                "role" => "assistant",
                "content" => "I am a large-scale language model developed by Alibaba Cloud, and my name is Qwen."
            ],
            [
                "role" => "user",
                "content" => "What can you do?"
            ]
        ]
    ]
];

// Encode data as JSON
$dataString = json_encode($data);

// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// Initialize curl session
$ch = curl_init($url);

// Set curl options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
]);

// Execute the request
$response = curl_exec($ch);

// Check if curl execution was successful
if ($response === false) {
    die("curl Error: " . curl_error($ch));
}

// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close curl session
curl_close($ch);

// Decode response data
$response_data = json_decode($response, true);

// Handle response
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    }
} else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";
    }
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";
    } else {
        echo "message=Unknown error\n";
    }
}
?>

Sample response

I can help you complete various tasks, such as:

1. Answering questions: Whether academic questions, practical knowledge, or entertainment gossip, I will do my best to provide accurate answers.
2. Creating text: Including but not limited to writing stories, official documents, emails, etc.
3. Providing advice: Such as travel suggestions, learning methods, career planning, and other guidance and advice.
4. Engaging in conversation: We can chat, share feelings, and even have some interesting discussions.

If you need help with anything, just let me know!
Node.js

Dependency:

npm install axios

Sample request

const axios = require('axios');
async function callDashScope() {
    // If environment variables are not configured, you can replace the following line with apiKey='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.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'YOUR_APP_ID';//Replace with the actual application ID

    const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        "input": {
        "messages":[      
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "Who are you?"
            },
            {
                "role": "assistant",
                "content": "I am a large-scale language model developed by Alibaba Cloud, my name is Qwen."
            },
            {
                "role": "user",
                "content": "What can you do?"
            }
        ]
    },
        parameters: {},
        debug: {}
    };

    try {
        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            console.log(`${response.data.output.text}`);
        } else {
            console.log(`request_id=${response.headers['request_id']}`);
            console.log(`code=${response.status}`);
            console.log(`message=${response.data.message}`);
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}

callDashScope();

Sample response

I can help you complete various tasks, including but not limited to:

1. Answering questions: Whether academic knowledge, practical information, or common sense questions, I will do my best to provide accurate answers.
2. Creating text: Such as writing stories, official documents, emails, scripts, etc., as long as you provide enough background information and requirements, I can help you write them.
3. Providing suggestions: If you need advice on certain decisions, such as travel destination selection, gift selection, study methods, etc., I can also provide suggestions based on your description.
4. Language translation: Support text translation between multiple languages.
5. Code writing and explanation: For programming-related questions, I can help write simple programs or explain complex concepts.
6. Engaging in conversation: In addition to the above functions, I can also have daily communication with users, sharing ideas.

If you have any specific needs, please feel free to tell me!
C#

Sample request

using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        // If environment variables are not configured, you can replace the following line with apiKey="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.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
        string appId = "YOUR_APP_ID";// Replace with the actual application ID
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("Please make sure DASHSCOPE_API_KEY is set.");
            return;
        }

        string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
        
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            string jsonContent = $@"{{
                ""input"": {{
                    ""messages"": [
                        {{
                            ""role"": ""system"",
                            ""content"": ""You are a helpful assistant.""
                        }},
                        {{
                            ""role"": ""user"",
                            ""content"": ""Who are you?""
                        }},
                        {{
                            ""role"": ""assistant"",
                            ""content"": ""I am a large-scale language model developed by Alibaba Cloud, my name is Qwen.""
                        }},
                        {{
                            ""role"": ""user"",
                            ""content"": ""What can you do?""
                        }}
                    ]
                }},
                ""parameters"": {{}},
                ""debug"": {{}}
            }}";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Sample response

{
    "output": {
        "finish_reason": "stop",
        "session_id": "a6d041ca3d084a7ca9eff1c456afad70",
        "text": "As Qwen, I can help you complete various tasks, including but not limited to:\n\n1. Answering questions: Providing answers to various knowledge-based questions.\n2. Text generation: Writing articles, stories, poems, and other text content.\n3. Language translation: Performing translation work between different languages.\n4. Conversational exchange: Having natural and smooth conversations with users.\n5. Providing suggestions: Offering suggestions or solutions based on user needs.\n\nIf you have any specific needs, please tell me, and I will do my best to help you."
    },
    "usage": {
        "models": [
            {
                "output_tokens": 102,
                "model_id": "qwen-max",
                "input_tokens": 87
            }
        ]
    },
    "request_id": "27fb8a01-70d5-974f-bb0a-e9408a9c1772"
}
Go

Sample request

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	// If environment variables are not configured, you can replace the following line with apiKey := "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.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "YOUR_APP_ID" // Replace with the actual application ID

	if apiKey == "" {
		fmt.Println("Please make sure DASHSCOPE_API_KEY is set.")
		return
	}

	url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)

	// Create request body
	requestBody := map[string]interface{}{
		"input": map[string]interface{}{
			"messages": []interface{}{
				map[string]string{
					"role":    "system",
					"content": "You are a helpful assistant.",
				},
				map[string]string{
					"role":    "user",
					"content": "Who are you?",
				},
				map[string]string{
					"role":    "assistant",
					"content": "I am a large-scale language model developed by Alibaba Cloud, my name is Qwen.",
				},
				map[string]string{
					"role":    "user",
					"content": "What can you do?",
				},
			},
		},
		"parameters": map[string]interface{}{},
		"debug":      map[string]interface{}{},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Printf("Failed to marshal JSON: %v\n", err)
		return
	}

	// Create HTTP POST request
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// Set request headers
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// Send request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// Read response
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// Process response
	if resp.StatusCode == http.StatusOK {
		fmt.Println("Request successful:")
		fmt.Println(string(body))
	} else {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		fmt.Println(string(body))
	}
}

Sample response

{
    "output": {
        "finish_reason": "stop",
        "session_id": "2ae51a5eac3b4b269834cf0695330a05",
        "text": "I can help you complete various tasks, including but not limited to:\n\n1. Answering questions: Providing answers to knowledge-based questions in various fields.\n2. Text creation: Writing stories, articles, poems, etc.\n3. Programming assistant: Providing guidance and code examples for programming.\n4. Conversational chat: Engaging in daily conversations, keeping you company.\n5. Translation services: Providing translation support between multiple languages.\n6. Information queries: Finding news, weather forecasts, historical data, and other information.\n7. Learning guidance: Helping answer questions in learning, providing learning suggestions.\n\nIf you have any specific needs or questions, you can tell me, and I will do my best to help you!"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 132,
                "model_id": "qwen-max",
                "input_tokens": 87
            }
        ]
    },
    "request_id": "1289eb09-e4ed-9f9e-98ca-805c83b333a1"
}

Pass custom parameters

To adapt the same agent or workflow to different business scenarios, you can configure custom parameters for plug-ins or nodes, and pass parameters through biz_params when calling the application. For how to configure the parameters, see Parameter pass-through for applications. Sample code:

  1. Custom plug-in parameters: Pass through the associated Agent Application or through the Plug-in Node of the associated Workflow Application.

    You can pass parameter and user-level authentication information for custom plug-ins:

    • Parameters: user_defined_params.

    • User-level authentication: user_defined_tokens. user_token is the authentication information required by the plug-in, such as the DASHSCOPE_API_KEY.

    The following sample is an Agent Application that requires the index parameter and user-level authentication information of the associated plug-in.

    Plug-in tools can only be associated with Agent Applications in the same workspace.
    Replace your_plugin_code with the associated plug-in tool ID displayed on the plug-in card, and pass the key-value pairs of input parameters. In this example, article_index with a value of 2.

    Parameter passing

    Python

    Sample request

    import os
    from http import HTTPStatus
    # Recommended dashscope SDK version >= 1.14.0
    from dashscope import Application
    import dashscope
    dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
    biz_params = {
        # Custom plug-in input parameter passing for agent applications, replace your_plugin_code with your custom plug-in ID
        "user_defined_params": {
            "your_plugin_code": {
                "article_index": 2}}}
    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',
            prompt='Dormitory convention content',
            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'Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # Process text output only
        # print('%s\n' % (response.usage))

    Sample response

    The second rule of the Dormitory Convention states:
    
    "Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity."
    
    This indicates that within the dormitory, members should cultivate a positive atmosphere for living and studying, support and assist each other, and also learn to understand and respect one another. If you need to know about other clauses of the convention, please let me know!
    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 com.alibaba.dashscope.utils.JsonUtils;
    
    import com.alibaba.dashscope.utils.Constants;
    
    public class Main {
        static {
            Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
        }
        public static void appCall() throws NoApiKeyException, InputRequiredException {
            String bizParams =
                    // Custom plug-in input parameter passing for agent applications, replace {your_plugin_code} with your custom plug-in ID
                    "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}}";
            ApplicationParam param = ApplicationParam.builder()
                    // If environment variables are not configured, you can replace the following line with .apiKey("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.
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID")
                    .prompt("Dormitory convention content")
                    .bizParams(JsonUtils.parse(bizParams))
                    .build();
    
            Application application = new Application();
            ApplicationResult result = application.call(param);
            System.out.printf("%s\n",
                    result.getOutput().getText());
        }
    
        public static void main(String[] args) {
            try {
                appCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }      

    Sample response

    Article Two of the Dormitory Convention stipulates:
    
    Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity.
    
    This emphasizes that within a shared living environment, roommates should maintain positive relationships and foster a harmonious atmosphere for living and studying through mutual assistance and support. If you need to know more specific clauses, please let me know.
    HTTP
    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": "Dormitory convention content",
            "biz_params": 
            {
                "user_defined_params":
                {
                    "{your_plugin_code}":
                        {
                        "article_index": 2
                        }
                }
            } 
        },
        "parameters":  {},
        "debug":{}
    }'
    Replace YOUR_APP_ID with the actual application ID.

    Sample response

    {"output":
    {"finish_reason":"stop",
    "session_id":"e151267ffded4fbdb13d91439011d31e",
    "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, humble, respect each other, and treat each other with sincerity." This implies that in dormitory life, everyone should support each other and jointly create a harmonious and positive living environment."},
    "usage":{"models":[{"output_tokens":94,"model_id":"qwen-max","input_tokens":453}]},
    "request_id":"a39fd2b5-7e2c-983e-84a1-1039f726f18a"}%
    PHP

    Sample request

    <?php
    
    # If environment variables are not configured, replace with the Dashscope API Key: $api_key="sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in production environments to reduce the risk of API Key leakage.
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    // Replace {your_plugin_code} with the actual plugin ID
    // Construct request data
    $data = [
        "input" => [
            'prompt' => 'Dormitory convention content',
            'biz_params' => [
            'user_defined_params' => [
                '{your_plugin_code}' => [
                    'article_index' => 2            
                    ]
                ]
            ]
        ],
    ];
    // Encode the data as JSON
    $dataString = json_encode($data);
    
    // Check if json_encode succeeded
    if (json_last_error() !== JSON_ERROR_NONE) {
        die("JSON encoding failed with error: " . json_last_error_msg());
    }
    
    // Initialize curl session
    $ch = curl_init($url);
    
    // Set curl options
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key
    ]);
    
    // Execute request
    $response = curl_exec($ch);
    
    // Check if curl execution succeeded
    if ($response === false) {
        die("curl Error: " . curl_error($ch));
    }
    
    // Get HTTP status code
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    // Close curl session
    curl_close($ch);
    // Decode response data
    $response_data = json_decode($response, true);
    // Handle response
    if ($status_code == 200) {
        if (isset($response_data['output']['text'])) {
            echo "{$response_data['output']['text']}\n";
        } else {
            echo "No text in response.\n";
        }
    }else {
        if (isset($response_data['request_id'])) {
            echo "request_id={$response_data['request_id']}\n";}
        echo "code={$status_code}\n";
        if (isset($response_data['message'])) {
            echo "message={$response_data['message']}\n";} 
        else {
            echo "message=Unknown error\n";}
    }
    ?>
    

    Sample response

    Article Two of the Dormitory Convention stipulates: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity.This emphasizes that within a shared living environment, roommates should maintain positive relationships and foster a harmonious atmosphere for living and studying through mutual assistance and support. If you need to know more specific clauses, please let me know.
    Node.js

    Dependency:

    npm install axios

    Sample request

    const axios = require('axios');
    
    async function callDashScope() {
        // If environment variables are not configured, you can replace the following line with apiKey='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.
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID';// Replace with the actual application ID
        const pluginCode = 'YOUR_PLUGIN_CODE';// Replace with the actual plug-in ID
        const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    
        const data = {
            input: {
                prompt: "Dormitory convention content",
                biz_params: {
                    user_defined_params: {
                        [pluginCode]: {
                            // article_index is a variable for the custom plug-in, replace with the actual plug-in variable
                            'article_index': 3
                        }
                    }
                }
            },
            parameters: {},
            debug: {}
        };
    
        try {
            console.log("Sending request to DashScope API...");
    
            const response = await axios.post(url, data, {
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json'
                }
            });
    
            if (response.status === 200) {
                if (response.data.output && response.data.output.text) {
                    console.log(`${response.data.output.text}`);
                }
            } else {
                console.log("Request failed:");
                if (response.data.request_id) {
                    console.log(`request_id=${response.data.request_id}`);
                }
                console.log(`code=${response.status}`);
                if (response.data.message) {
                    console.log(`message=${response.data.message}`);
                } else {
                    console.log('message=Unknown error');
                }
            }
        } catch (error) {
            console.error(`Error calling DashScope: ${error.message}`);
            if (error.response) {
                console.error(`Response status: ${error.response.status}`);
                console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
            }
        }
    }
    callDashScope();
    

    Sample response

    The third rule of the Dormitory Convention is as follows:
    
    Pay attention to electrical safety, and eliminate fire hazards. The use of open flames, unauthorized electrical appliances, various stoves, and other prohibited items is strictly forbidden in the dormitory. It is also forbidden to store explosive or flammable materials and to privately connect to the power supply.
    
    If you need to know more regulations, please let me know.
    C#

    Sample request

    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // If environment variables are not configured, you can replace the following line with apiKey="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.
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
            string appId = "YOUR_APP_ID";// Replace with the actual application ID
    
            if (string.IsNullOrEmpty(apiKey))
            {
                Console.WriteLine("Make sure you have set DASHSCOPE_API_KEY.");
                return;
            }
    
            string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
    
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                string pluginCode = "{your_plugin_code}"; // Replace {your_plugin_code} with the actual plug-in ID
                string jsonContent = $@"{{
                    ""input"": {{
                        ""prompt"": ""Dormitory convention content"",
                        ""biz_params"": {{
                            ""user_defined_params"": {{
                                ""{pluginCode}"": {{
                                    ""article_index"": 2
                                }}
                            }}
                        }}
                    }},
                    ""parameters"": {{}},
                    ""debug"": {{}}
                }}";
    
                HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    
                try
                {
                    HttpResponseMessage response = await client.PostAsync(url, content);
    
                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine("Request successful:");
                        Console.WriteLine(responseBody);
                    }
                    else
                    {
                        Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error calling DashScope: {ex.Message}");
                }
            }
        }
    }

    Sample response

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "237ca6187c814f3b9e7461090a5f8b74",
            "text": "The second rule of the Dormitory Convention is as follows:
            
    "Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity.\"
    
    This indicates that within the dormitory, members need to establish positive relationships and create a harmonious living and learning environment through mutual assistance, caring, and support. It is also important to understand and accept differences among roommates and communicate sincerely. If there are other clauses or specific contents you want to know, please let me know!"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 133,
                    "model_id": "qwen-max",
                    "input_tokens": 829
                }
            ]
        },
        "request_id": "64e8c359-d071-9d2e-bb94-187e86cc3a79"
    }
    
    Go

    Sample request

    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"io"
    	"net/http"
    	"os"
    )
    
    func main() {
    	// If environment variables are not configured, you can replace the following line with apiKey := "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.
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID"           // Replace with the actual application ID
    	pluginCode := "YOUR_PLUGIN_CODE" // Replace with the actual plug-in ID
    
    	if apiKey == "" {
    		fmt.Println("Make sure you have set DASHSCOPE_API_KEY.")
    		return
    	}
    
    	url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
    
    	// Create request body
    	requestBody := map[string]interface{}{
    		"input": map[string]interface{}{
    			"prompt": "Dormitory convention content",
    			"biz_params": map[string]interface{}{
    				"user_defined_params": map[string]interface{}{
    					pluginCode: map[string]interface{}{
    						"article_index": 2,
    					},
    				},
    			},
    		},
    		"parameters": map[string]interface{}{},
    		"debug":      map[string]interface{}{},
    	}
    
    	jsonData, err := json.Marshal(requestBody)
    	if err != nil {
    		fmt.Printf("Failed to marshal JSON: %v\n", err)
    		return
    	}
    
    	// Create HTTP POST request
    	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    	if err != nil {
    		fmt.Printf("Failed to create request: %v\n", err)
    		return
    	}
    
    	// Set request headers
    	req.Header.Set("Authorization", "Bearer "+apiKey)
    	req.Header.Set("Content-Type", "application/json")
    
    	// Send request
    	client := &http.Client{}
    	resp, err := client.Do(req)
    	if err != nil {
    		fmt.Printf("Failed to send request: %v\n", err)
    		return
    	}
    	defer resp.Body.Close()
    
    	// Read response
    	body, err := io.ReadAll(resp.Body)
    	if err != nil {
    		fmt.Printf("Failed to read response: %v\n", err)
    		return
    	}
    
    	// Process response
    	if resp.StatusCode == http.StatusOK {
    		fmt.Println("Request successful:")
    		fmt.Println(string(body))
    	} else {
    		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
    		fmt.Println(string(body))
    	}
    }
    

    Sample response

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "860d2a4c1f3649ac880298537993cb51",
            "text": "The second rule of the Dormitory Convention is as follows:
    Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity.
    
    This emphasizes that in dormitory life, roommates should maintain good mutual assistance while also respecting each other. Would you like to know about other clauses?"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 84,
                    "model_id": "qwen-max",
                    "input_tokens": 876
                }
            ]
        },
        "request_id": "0a250055-90a4-992d-9276-e268ad35d1ab"
    }
    

    User-level authentication

    Python

    Sample request

    from http import HTTPStatus
    import os
    # Recommended dashscope SDK version >= 1.14.0
    from dashscope import Application
    import dashscope
    dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
    biz_params = {
        # Custom plug-in authentication passing for agent applications, replace your_plugin_code with your custom plug-in ID, and YOUR_TOKEN with authentication information, such as API key
        "user_defined_params": {
            "your_plugin_code": {
                "article_index": 2}},
        "user_defined_tokens": {
            "your_plugin_code": {
                "user_token": "YOUR_TOKEN"}}}
    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',
                prompt='Dormitory convention content',
                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'Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # Process text output only
        # print('%s\n' % (response.usage))

    Sample response

    The second rule of the Dormitory Convention is as follows:
    
    Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity.
    
    If you need further information on additional rules, please let me know.
    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 com.alibaba.dashscope.utils.JsonUtils;
    import com.alibaba.dashscope.utils.Constants;
    
    public class Main {
        static {
            Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
        }
        public static void appCall() throws NoApiKeyException, InputRequiredException {
            String bizParams =
                    // Replace {your_plugin_code} with the actual plug-in ID, YOUR_TOKEN with the actual Token, such as API key
                    "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}," +
                            "\"user_defined_tokens\":{\"{your_plugin_code}\":{\"user_token\":\"YOUR_TOKEN\"}}}";
            ApplicationParam param = ApplicationParam.builder()
                    // If environment variables are not configured, you can replace the following line with .apiKey("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.
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID")
                    .prompt("Dormitory convention content")
                    .bizParams(JsonUtils.parse(bizParams))
                    .build();
    
            Application application = new Application();
            ApplicationResult result = application.call(param);
            System.out.printf("%s\n",
                    result.getOutput().getText());
        }
        public static void main(String[] args) {
            try {
                appCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }

    Sample response

    The second rule of the Dormitory Convention says:
    
    Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity.
    
    If you need further information on additional rules, please let me know.
    HTTP
    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": "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":{}
    }'
    
    
    
    Replace YOUR_APP_ID with the actual application ID.

    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, humble, respect each other, and treat each other with sincerity." This implies that in dormitory life, everyone should support each other and jointly create a harmonious and positive living environment."},
    "usage":{"models":[{"output_tokens":80,"model_id":"qwen-max","input_tokens":432}]},
    "request_id":"1f77154c-edc3-9003-b622-816fa2f849cf"}%
    PHP

    Sample request

    <?php
    
    # If environment variables are not configured, replace with the Dashscope API Key: $api_key="sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in production environments to reduce the risk of API Key leakage.
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    
    // Construct the request data
    $data = [
        "input" => [
            'prompt' => 'Dormitory convention content',
            'biz_params' => [
            'user_defined_params' => [
                '{your_plugin_code}' => [// Replace {your_plugin_code} with the actual plugin ID
                    'article_index' => 2            
                    ]
                ],
            'user_defined_tokens' => [
                '{your_plugin_code}' => [// Replace {your_plugin_code} with the actual plugin ID
                    'user_token' => 'YOUR_TOKEN'// Replace with the actual Token, such as API key
                ]
            ]
            ]
        ],
    ];
    // Encode the data as JSON
    $dataString = json_encode($data);
    
    // Check if json_encode succeeded
    if (json_last_error() !== JSON_ERROR_NONE) {
        die("JSON encoding failed with error: " . json_last_error_msg());
    }
    
    // Initialize curl session
    $ch = curl_init($url);
    
    // Set curl options
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key
    ]);
    
    // Execute the request
    $response = curl_exec($ch);
    
    // Check if curl execution succeeded
    if ($response === false) {
        die("curl Error: " . curl_error($ch));
    }
    
    // Get HTTP status code
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    // Close curl session
    curl_close($ch);
    // Decode the response data
    $response_data = json_decode($response, true);
    // Handle the response
    if ($status_code == 200) {
        if (isset($response_data['output']['text'])) {
            echo "{$response_data['output']['text']}\n";
        } else {
            echo "No text in response.\n";
        }
    }else {
        if (isset($response_data['request_id'])) {
            echo "request_id={$response_data['request_id']}\n";}
        echo "code={$status_code}\n";
        if (isset($response_data['message'])) {
            echo "message={$response_data['message']}\n";} 
        else {
            echo "message=Unknown error\n";}
    }
    ?>
    

    Sample response

    The second rule of the Dormitory Convention is as follows:
    
    > Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity.
    
    If you need more information about the convention or other details, please feel free to let me know!
    Node.js

    Dependency:

    npm install axios

    Sample request

    const axios = require('axios');
    async function callDashScope() {
        // If environment variables are not configured, you can replace the following line with apiKey='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.
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID';// Replace with the actual application ID
        const pluginCode = 'YOUR_PLUGIN_CODE';// Replace with the actual plug-in ID
        const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    
        const data = {
            input: {
                prompt: "Dormitory convention content",
                biz_params: {
                    user_defined_params: {
                        [pluginCode]: {
                            // article_index is a variable for the custom plug-in, replace with the actual plug-in variable
                            'article_index': 6
                        }
                    },
                    user_defined_tokens: {
                        [pluginCode]: {
                            // Replace YOUR_TOKEN with the actual authentication information, such as API key
                            user_token: 'YOUR_TOKEN'
                        }
                    }
                }
            },
            parameters: {},
            debug: {}
        };
    
        try {
            console.log("Sending request to DashScope API...");
    
            const response = await axios.post(url, data, {
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json'
                }
            });
    
            if (response.status === 200) {
                if (response.data.output && response.data.output.text) {
                    console.log(`${response.data.output.text}`);
                }
            } else {
                console.log("Request failed:");
                if (response.data.request_id) {
                    console.log(`request_id=${response.data.request_id}`);
                }
                console.log(`code=${response.status}`);
                if (response.data.message) {
                    console.log(`message=${response.data.message}`);
                } else {
                    console.log('message=Unknown error');
                }
            }
        } catch (error) {
            console.error(`Error calling DashScope: ${error.message}`);
            if (error.response) {
                console.error(`Response status: ${error.response.status}`);
                console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
            }
        }
    }
    callDashScope();

    Sample response

    The sixth rule of the Dormitory Convention stipulates: Cultivate good habits regarding daily routines; every dormitory member has the right to rest and the responsibility to ensure others’ rights to rest. If you need more information on the regulations, please let me know.
    C#

    Sample request

    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // If environment variables are not configured, you can replace the following line with apiKey="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.
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
            string appId = "YOUR_APP_ID";// Replace with the actual application ID
    
            if (string.IsNullOrEmpty(apiKey))
            {
                Console.WriteLine("Make sure you have set DASHSCOPE_API_KEY.");
                return;
            }
    
            string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
    
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                string pluginCode = "your_plugin_code"; // Replace your_plugin_code with the actual plug-in ID
                // Replace YOUR_TOKEN with the actual Token, such as API key
                string jsonContent = $@"{{
                    ""input"": {{
                        ""prompt"": ""Dormitory convention content"",
                        ""biz_params"": {{
                            ""user_defined_params"": {{
                                ""{pluginCode}"": {{
                                    ""article_index"": 2
                                }}
                            }},
                            ""user_defined_tokens"": {{
                                ""{pluginCode}"": {{
                                    ""user_token"": ""YOUR_TOKEN"" 
                                }}
                            }}
                        }}
                    }},
                    ""parameters"": {{}},
                    ""debug"": {{}}
                }}";
    
                HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    
                try
                {
                    HttpResponseMessage response = await client.PostAsync(url, content);
    
                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine("Request successful:");
                        Console.WriteLine(responseBody);
                    }
                    else
                    {
                        Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error calling DashScope: {ex.Message}");
                }
            }
        }
    }

    Sample response

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "1a1913a9922a401f8eba36df8ea1a062",
            "text": "The second rule of the Dormitory Convention is as follows:
            
    Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity.
    
    If there are other clauses or specific contents you want to know, please let me know!"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 66,
                    "model_id": "qwen-max",
                    "input_tokens": 802
                }
            ]
        },
        "request_id": "04bac806-c5e6-9fab-a846-a66641862be9"
    }
    Go

    Sample request

    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"io"
    	"net/http"
    	"os"
    )
    
    func main() {
    	// If environment variables are not configured, you can replace the following line with apiKey := "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.
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID"           // Replace with the actual application ID
    	pluginCode := "YOUR_PLUGIN_CODE" // Replace with the actual plug-in ID
    
    	if apiKey == "" {
    		fmt.Println("Make sure you have set DASHSCOPE_API_KEY.")
    		return
    	}
    
    	url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
    
    	// Create request body
    	requestBody := map[string]interface{}{
    		"input": map[string]interface{}{
    			"prompt": "Dormitory convention content",
    			"biz_params": map[string]interface{}{
    				"user_defined_params": map[string]interface{}{
    					pluginCode: map[string]interface{}{
    						"article_index": 10,
    					},
    				},
    				"user_defined_tokens": map[string]interface{}{
    					pluginCode: map[string]interface{}{
    						"user_token": "YOUR_USER_TOKEN", // Replace with the actual authentication token, such as API key
    					},
    				},
    			},
    		},
    		"parameters": map[string]interface{}{},
    		"debug":      map[string]interface{}{},
    	}
    
    	jsonData, err := json.Marshal(requestBody)
    	if err != nil {
    		fmt.Printf("Failed to marshal JSON: %v\n", err)
    		return
    	}
    
    	// Create HTTP POST request
    	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    	if err != nil {
    		fmt.Printf("Failed to create request: %v\n", err)
    		return
    	}
    
    	// Set request headers
    	req.Header.Set("Authorization", "Bearer "+apiKey)
    	req.Header.Set("Content-Type", "application/json")
    
    	// Send request
    	client := &http.Client{}
    	resp, err := client.Do(req)
    	if err != nil {
    		fmt.Printf("Failed to send request: %v\n", err)
    		return
    	}
    	defer resp.Body.Close()
    
    	// Read response
    	body, err := io.ReadAll(resp.Body)
    	if err != nil {
    		fmt.Printf("Failed to read response: %v\n", err)
    		return
    	}
    
    	// Process response
    	if resp.StatusCode == http.StatusOK {
    		fmt.Println("Request successful:")
    		fmt.Println(string(body))
    	} else {
    		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
    		fmt.Println(string(body))
    	}
    }
    

    Sample response

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "b8e051ba7e954ff8919208e7b84430fa",
            "text": "The tenth rule of the Dormitory Convention states that dormitory members should work together to create and maintain a clean, tidy, aesthetically pleasing, and culturally rich dormitory environment. If you need to understand the complete Dormitory Convention content, you may need to check other clauses or directly consult the dormitory management department. Is there any more specific content you would like to know?"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 70,
                    "model_id": "qwen-max",
                    "input_tokens": 855
                }
            ]
        },
        "request_id": "0921ee34-2754-9616-a826-cea33a0e0a14"
    }
    
  2. Custom node parameters: Pass through the Workflow Application's Start Node, or through the Agent Orchestration Application's Application Node.

    In the following sample, the Workflow Application defines a parameter city in the Start Node. Insert the variables city and query in the Prompt, and then Publish the application.

    image

    When calling, pass city through biz_params and pass query through prompt.

    Python

    Sample request

    import os
    from http import HTTPStatus
    from dashscope import Application
    import dashscope
    dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
    # Custom parameter passing for workflow and agent orchestration applications
    biz_params = {"city": "Hangzhou"}
    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='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}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
    else:
        print(f'{response.output.text}')  # Process text output only

    Sample response

    The city of Hangzhou, as the capital of Zhejiang Province, has an administrative division consisting of 10 districts: Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, and Lin'an District. Each district has its own unique characteristics and development focus.
    
    - Shangcheng District: Located in the central area of Hangzhou, it is one of the political, economic, and cultural centers of the city.
    - Gongshu District: Known for its canal culture, it features numerous historical and cultural heritage sites.
    - Xihu District: Famous for the West Lake scenic area, it is an important destination for tourism.
    - Binjiang District: A hub for high-tech industries, with renowned companies like Alibaba situated here.
    - Xiaoshan District: An administrative district in the southeast, experiencing rapid economic growth, particularly in the manufacturing sector.
    - Yuhang District: Has developed rapidly in recent years, especially in the field of internet economy; Alibaba's headquarters is also located here (Note: Alibaba headquarters is actually in Binjiang District).
    - Linping District: A newly established district aimed at promoting comprehensive economic and social development in the area.
    - Qiantang District: Also a result of recent administrative adjustments, focusing on the integration of innovation and ecological protection.
    - Fuyang District: Located southwest of Hangzhou, known for its rich natural landscapes and long history and culture.
    - Lin'an District: Situated west of Hangzhou, famous for its beautiful ecological environment and profound cultural heritage.
    
    Please note that city planning may change over time, and it is recommended to refer to the latest official information.

    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 com.alibaba.dashscope.utils.JsonUtils;
    import io.reactivex.Flowable;
    import com.alibaba.dashscope.utils.Constants;
    
    public class Main {
        static {
            Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
        }
        public static void appCall() throws NoApiKeyException, InputRequiredException {
    
            String bizParams =
                    "{\"city\":\"Hangzhou\"}";
            ApplicationParam param = ApplicationParam.builder()
                    // If environment variables are not configured, you can replace the following line with .apiKey("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.
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID")
                    .prompt("Query the administrative divisions of this city")
                    .bizParams(JsonUtils.parse(bizParams))
                    .build();
    
            Application application = new Application();
            ApplicationResult result = application.call(param);
            System.out.printf("%s\n",
                    result.getOutput().getText());
        }
    
        public static void main(String[] args) {
            try {
                appCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }

    Sample response

    The city of Hangzhou is the capital of Zhejiang Province and its administrative division mainly includes 10 districts: Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, and Lin'an District. Each district has its own distinctive characteristics and development focuses.
    
    - Shangcheng District: Located in the city center of Hangzhou, it houses many historical and cultural heritage sites.
    - Gongshu District: Known for its Grand Canal culture, it is also an important commercial and residential area.
    - Xihu District: Famous for its beautiful natural scenery, including the renowned West Lake scenic area.
    - Binjiang District: A hub for high-tech industries, home to the Hangzhou National High-Tech Industry Development Zone.
    - Xiaoshan District: Experiences rapid economic growth, particularly outstanding in the manufacturing sector.
    - Yuhang District: Has rapidly risen in recent years following the development of high-tech companies like Alibaba.
    - Linping District: Formed in 2021 from parts of the original Yuhang District, it focuses on ecological construction and technological innovation.
    - Qiantang District: Also established as a new district in 2021, positioned as the eastern transportation hub and new industrial development area of Hangzhou.
    - Fuyang District: A cultural city with a long history and one of the important bases for the paper industry.
    - Lin'an District: Located in the western part of Hangzhou, known for its high forest coverage and good ecological environment.
    
    These districts together form the unique geographical layout and socio-economic structure of Hangzhou city. If you are interested in a particular district or need more detailed information, please let me know!

    HTTP

    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": "Query the administrative divisions of this city",
            "biz_params": {
            "city": "Hangzhou"}
        },
        "parameters":  {}
    }'
    
    Replace YOUR_APP_ID with the actual application ID.

    Sample response

    {
      "output": {
        "finish_reason": "stop",
        "session_id": "c211219896004b50a1f6f66f2ec5413e",
        "text": "The city of Hangzhou has jurisdiction over 10 districts, 1 county, and manages 2 county-level cities, which are as follows:
    Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, Lin'an District, Tonglu County, Chun'an County, Jiande City, Zhuji City.
    Note that Zhuji City is directly under the administration of Zhejiang Province and is jointly managed by both Hangzhou and Shaoxing cities."
      },
      "usage": {},
      "request_id": "02c3c9e1-7912-9505-91aa-248d04fb1f5d"
    }
    
    PHP

    Sample request

    <?php
    
    # 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 leaks.
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    
    // Construct request data
    $data = [
        "input" => [
            'prompt' => 'Query the administrative divisions of this city',
            'biz_params' => [
                'city' => 'Hangzhou'
            ]
        ],
    ];
    // Encode the data to JSON
    $dataString = json_encode($data);
    
    // Check if json_encode was successful
    if (json_last_error() !== JSON_ERROR_NONE) {
        die("JSON encoding failed with error: " . json_last_error_msg());
    }
    
    // Initialize curl session
    $ch = curl_init($url);
    
    // Set curl options
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key
    ]);
    
    // Execute the request
    $response = curl_exec($ch);
    
    // Check if curl execution was successful
    if ($response === false) {
        die("curl Error: " . curl_error($ch));
    }
    
    // Get the HTTP status code
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    // Close the curl session
    curl_close($ch);
    
    // Decode the response data
    $response_data = json_decode($response, true);
    
    // Handle the response
    if ($status_code == 200) {
        if (isset($response_data['output']['text'])) {
            echo "{$response_data['output']['text']}\n";
        } else {
            echo "No text in response.\n";
        }
    } else {
        if (isset($response_data['request_id'])) {
            echo "request_id={$response_data['request_id']}\n";
        }
        echo "code={$status_code}\n";
        if (isset($response_data['message'])) {
            echo "message={$response_data['message']}\n";
        } else {
            echo "message=Unknown error\n";
        }
    }
    

    Sample response

    Hangzhou is the capital city of Zhejiang Province and its administrative division mainly includes 10 districts: Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, and Lin'an District.
    
    Each district has its own unique characteristics and development focuses, such as:
    - **Shangcheng District** and **Gongshu District** are located in the center of Hangzhou, known for their bustling commerce and rich history.
    - **Xihu District** is famous for the beautiful West Lake and is also an important area for science, education, and culture.
    - **Binjiang District** is renowned for its high-tech industry development.
    - **Xiaoshan District** and **Yuhang District**, among others, have rapidly emerged as new urban districts or economic development zones due to recent city growth.
    - **Lin'an District** and **Fuyang District** have retained more of the natural scenery and rural charm.
    
    Please note that China's administrative divisions may change based on national policies, so please refer to official channels for the latest information.
    Node.js

    Dependency:

    npm install axios

    Sample request

    const axios = require('axios');
    
    async function callDashScope() {
        // If environment variables are not configured, you can replace the following line with apiKey='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.
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID'; // Replace with the actual application ID
    
        const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    
        const data = {
            input: {
                prompt: "Query the administrative divisions of this city",
                biz_params: {
                    'city': 'Hangzhou',
                },
            },
            parameters: {},
            debug: {},
        };
    
        try {
            console.log("Sending request to DashScope API...");
    
            const response = await axios.post(url, data, {
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json'
                }
            });
    
            if (response.status === 200) {
                if (response.data.output && response.data.output.text) {
                    console.log(`${response.data.output.text}`);
                }
            } else {
                console.log("Request failed:");
                if (response.data.request_id) {
                    console.log(`request_id=${response.data.request_id}`);
                }
                console.log(`code=${response.status}`);
                if (response.data.message) {
                    console.log(`message=${response.data.message}`);
                } else {
                    console.log('message=Unknown error');
                }
            }
        } catch (error) {
            console.error(`Error calling DashScope: ${error.message}`);
            if (error.response) {
                console.error(`Response status: ${error.response.status}`);
                console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
            }
        }
    }
    
    callDashScope();
    

    Sample response

    Hangzhou is the capital city of Zhejiang Province, and its administrative division includes 10 districts, specifically:
    
    1. **Shangcheng District (Shàngchéng Qū)**: Located in the southern part of central Hangzhou, it is one of the city's most historically rich and culturally significant areas.
    2. **Gongshu District (Gǒngshù Qū)**: Originally formed from the merger of Xiacheng District and Gongshu District, situated in the northern part of Hangzhou.
    3. **Xihu District (Xīhú Qū)**: Known for the World Heritage Site West Lake, featuring abundant natural and cultural landscapes.
    4. **Binjiang District (Bīnjiāng Qū)**: Located on the southern bank of the Qiantang River, it is a hub for high-tech industries.
    5. **Xiaoshan District (Xiāoshān Qū)**: Situated in the eastern part of Hangzhou, it is one of China's key manufacturing bases.
    6. **Yuhang District (Yúháng Qū)**: Once home to Linping, one of China's four famous ancient towns, it has now grown into an important economic development zone in Hangzhou.
    7. **Fuyang District (Fùyáng Qū)**: Located in the southwest of Hangzhou, named after the Fuchun River that flows through it.
    8. **Lin'an District (Lín'ān Qū)**: Positioned in the mountainous western area of Hangzhou, renowned for its beautiful natural scenery.
    9. **Qiantang District (Qiántáng Qū)**: Established in 2021, formed from the former Dajiangdong Industrial Cluster and parts of Xiaoshan District, aimed at fostering development in Hangzhou's eastern region.
    10. **Linping District (Lín Píng Qū)**: A new administrative division separated from Yuhang District, mainly covering areas like Linping Street that were originally part of Yuhang District.
    
    This information reflects the situation as of my last update. Please note that administrative divisions may change, so refer to the official latest announcements for current information.
    C#

    Sample request

    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            //If environment variables are not configured, you can replace the following line with apiKey="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. 
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
            string appId = "YOUR_APP_ID"; // Replace with the actual application ID
            string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
    
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                string jsonContent = @"{
                    ""input"": {
                        ""prompt"": ""Query the administrative divisions of this city"",
                        ""biz_params"":{
                            ""city"":""Hangzhou""
                        }
                    },
                    ""parameters"": {},
                    ""debug"": {}
                }";
    
                HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    
                try
                {
                    HttpResponseMessage response = await client.PostAsync(url, content);
    
                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine("Request successful:");
                        Console.WriteLine(responseBody);
                    }
                    else
                    {
                        Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error calling DashScope: {ex.Message}");
                }
            }
        }
    }

    Sample response

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "7a9ff57eec7d475fa5d487de5f5178d2",
            "text": "Hangzhou is the capital city of Zhejiang Province, and it has jurisdiction over 10 districts: Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, and Lin'an District. Each district has its unique geographical locations and development features. For example, Xihu District is renowned for its beautiful natural scenery, especially the famous West Lake located there; while Binjiang District is more well-known for its high-tech industry development. Additionally, with the city's growth, the administrative divisions may undergo adjustments. Please refer to the latest official announcements for the most current information."
        },
        "usage": {
    
        },
        "request_id": "d2c2fcc9-f821-98c9-9430-8704a2a41225"
    }
    Go

    Sample request

    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"io"
    	"net/http"
    	"os"
    )
    
    func main() {
    	// If environment variables are not configured, you can replace the following line with apiKey := "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.
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID" // Replace with the actual application ID
    
    	if apiKey == "" {
    		fmt.Println("Make sure you have set DASHSCOPE_API_KEY.")
    		return
    	}
    
    	url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
    
    	// Create request body
    	requestBody := map[string]interface{}{
    		"input": map[string]interface{}{
    			"prompt": "Query the administrative divisions of this city",
    			"biz_params": map[string]interface{}{
    				"city": "Hangzhou",
    			},
    		},
    		"parameters": map[string]interface{}{},
    		"debug":      map[string]interface{}{},
    	}
    
    	jsonData, err := json.Marshal(requestBody)
    	if err != nil {
    		fmt.Printf("Failed to marshal JSON: %v\n", err)
    		return
    	}
    
    	// Create HTTP POST request
    	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    	if err != nil {
    		fmt.Printf("Failed to create request: %v\n", err)
    		return
    	}
    
    	// Set request headers
    	req.Header.Set("Authorization", "Bearer "+apiKey)
    	req.Header.Set("Content-Type", "application/json")
    
    	// Send request
    	client := &http.Client{}
    	resp, err := client.Do(req)
    	if err != nil {
    		fmt.Printf("Failed to send request: %v\n", err)
    		return
    	}
    	defer resp.Body.Close()
    
    	// Read response
    	body, err := io.ReadAll(resp.Body)
    	if err != nil {
    		fmt.Printf("Failed to read response: %v\n", err)
    		return
    	}
    
    	// Process response
    	if resp.StatusCode == http.StatusOK {
    		fmt.Println("Request successful:")
    		fmt.Println(string(body))
    	} else {
    		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
    		fmt.Println(string(body))
    	}
    }
    

    Sample response

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "2dc3e1a9dcd248c6bb9ca92bffc3e745",
            "text": "Hangzhou, abbreviated as 'Hang,' is the capital city of Zhejiang Province. According to the latest administrative division adjustments, Hangzhou now oversees 10 districts, 2 county-level cities, and 1 county, specifically:
    
    - Districts (10): Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, Lin'an District.
    - County-level Cities (2): Jiande City, Tonglu County (Note that Tonglu is actually treated as a county-level city here, but more accurately, it is a county).
    - County (1): Chun'an County.
    
    Please be aware that administrative regions may change over time, so please refer to the latest official announcements for the most current information. The above information is compiled based on relatively recent data; for the latest changes, visiting government official websites for the most accurate information is advised."
        },
        "usage": {
    
        },
        "request_id": "d3c8f368-b645-9446-bfe4-20ca51821a02"
    }

Streaming output

In streaming output mode, the model generates intermediate results, and the final result is formed by concatenating these intermediate results. You can read as the model outputs, thereby shortening the wait for the model's response. Depending on the calling method, you can set parameters to implement streaming output:

  • Python SDK: Set stream to True.

  • Java SDK: Call through the streamCall interface.

  • HTTP: Specify X-DashScope-SSE as enable in the Header.

By default, streaming output is non-incremental, meaning each return includes all previously generated content. To use incremental streaming output, set the incremental_output (incrementalOutput for Java) parameter to true. For HTTP, set incremental_output to true and place it in the parameters object.

Examples:

  • For Agent Application:

    Python

    Sample request

    import os
    from http import HTTPStatus
    from dashscope import Application
    import dashscope
    dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
    responses = Application.call(
                # If environment variables are not configured, replace the following line with: api_key="sk-xxx". However, it is not recommended to hardcode 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',
                prompt='Who are you?',
                stream=True,  # Streaming output
                incremental_output=True)  # 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'Please refer to the documentation: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
        else:
            print(f'{response.output.text}\n')  # Process to output only the text

    Sample response

    I am
    
    Alibaba
    
    Cloud
    
    's large-scale language model
    
    , my name is
    
    Qwen.

    Java

    Sample request

    // Recommended dashscope SDK version >= 2.15.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 io.reactivex.Flowable;// Streaming output
    // Agent application implementation for streaming output results
    
    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()
                    // If environment variables are not configured, replace the following line with: .apiKey("sk-xxx"). However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    // Replace with the actual application ID
                    .appId("YOUR_APP_ID")
                    .prompt("Who are you?")
                    // Incremental output
                    .incrementalOutput(true)
                    .build();
            Application application = new Application();
            // .streamCall(): Streaming output content
            Flowable<ApplicationResult> result = application.streamCall(param);
            result.blockingForEach(data -> {
                System.out.printf("%s\n",
                        data.getOutput().getText());
            });
        }
        public static void main(String[] args) {
            try {
                streamCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("Please refer to the documentation: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }

    Sample response

    I am Alibaba
    Cloud
    's large-scale language
    model, my name is
    Qwen
    .

    HTTP

    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":  {
            "incremental_output":true
        },
        "debug": {}
    }'
    Replace YOUR_APP_ID with the actual application ID.

    Sample response

    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"I"},"usage":{"models":[{"input_tokens":203,"output_tokens":1,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"am"},"usage":{"models":[{"input_tokens":203,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":" Alibaba"},"usage":{"models":[{"input_tokens":203,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":" Cloud"},"usage":{"models":[{"input_tokens":203,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"'s large-scale language"},"usage":{"models":[{"input_tokens":203,"output_tokens":8,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    
    id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":" model, my name is"},"usage":{"models":[{"input_tokens":203,"output_tokens":12,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    
    id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":" Qwen"},"usage":{"models":[{"input_tokens":203,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    
    id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"."},"usage":{"models":[{"input_tokens":203,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    
    id:9
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":203,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    PHP

    Sample request

    <?php
    
    // If environment variables are not configured, replace the following line with: $api_key="sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
    
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    
    // Construct request data
    $data = [
        "input" => [
            'prompt' => 'Who are you?'],
        "parameters" => [
            'incremental_output' => true]];// Incremental output
    // Encode data as JSON
    $dataString = json_encode($data);
    
    // Check if json_encode was successful
    if (json_last_error() !== JSON_ERROR_NONE) {
        die("JSON encoding failed with error: " . json_last_error_msg());
    }
    
    // Initialize curl session
    $ch = curl_init($url);
    
    // Set curl options
    curl_setopt($ch, curlOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, curlOPT_POSTFIELDS, $dataString);
    curl_setopt($ch, curlOPT_RETURNTRANSFER, false); // Don't return the transferred data
    curl_setopt($ch, curlOPT_WRITEFUNCTION, function ($ch, $string) {
        echo $string; // Process streaming data
        return strlen($string);
    });
    curl_setopt($ch, curlOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key,
        'X-DashScope-SSE: enable' // Streaming output
    ]);
    
    // Execute request
    $response = curl_exec($ch);
    
    // Check if curl execution was successful
    if ($response === false) {
        die("curl Error: " . curl_error($ch));
    }
    
    // Get HTTP status code
    $status_code = curl_getinfo($ch, curlINFO_HTTP_CODE);
    // Close curl session
    curl_close($ch);
    
    if ($status_code != 200) {
        echo "HTTP Status Code: $status_code\n";
        echo "Request Failed.\n";
    }
    ?>

    Sample response

    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"I am Alibaba"},"usage":{"models":[{"input_tokens":58,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":" Cloud"},"usage":{"models":[{"input_tokens":58,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"'s"},"usage":{"models":[{"input_tokens":58,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":" a large-scale language"},"usage":{"models":[{"input_tokens":58,"output_tokens":8,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":" model, my name is"},"usage":{"models":[{"input_tokens":58,"output_tokens":12,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
    id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":" Qwen"},"usage":{"models":[{"input_tokens":58,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
    id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"."},"usage":{"models":[{"input_tokens":58,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
    id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":58,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
    
    Node.js

    Dependency:

    npm install axios

    Sample request

    1. Output complete response

    const axios = require('axios');
    
    async function callDashScope() {
        // If environment variables are not configured, replace the following line with: apiKey='sk-xxx'. However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID';// Replace with the actual application ID
    
        const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    
        const data = {
            input: {
                prompt: "Who are you?"
            },
            parameters: {
                'incremental_output' : 'true' // Incremental output
            },
            debug: {}
        };
    
        try {
            console.log("Sending request to DashScope API...");
    
            const response = await axios.post(url, data, {
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json',
                    'X-DashScope-SSE': 'enable' // Streaming output
                },
                responseType: 'stream' // For handling streaming responses
            });
    
            if (response.status === 200) {
                // Process streaming response
                response.data.on('data', (chunk) => {
                    console.log(`Received chunk: ${chunk.toString()}`);
                });
            } else {
                console.log("Request failed:");
                if (response.data.request_id) {
                    console.log(`request_id=${response.data.request_id}`);
                }
                console.log(`code=${response.status}`);
                if (response.data.message) {
                    console.log(`message=${response.data.message}`);
                } else {
                    console.log('message=Unknown error');
                }
            }
        } catch (error) {
            console.error(`Error calling DashScope: ${error.message}`);
            if (error.response) {
                console.error(`Response status: ${error.response.status}`);
                console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
            }
        }
    }
    
    callDashScope();

    Expand the panel to view the sample code:

    2. Output only text field

    const axios = require('axios');
    const { Transform } = require('stream');
    
    async function callDashScope() {
        // If environment variables are not configured, replace the following line with: apiKey='sk-xxx'. However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID'; // Replace with the actual application ID
    
        const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    
        const data = {
            input: { prompt: "Who are you?" },
            parameters: { incremental_output: true }, // Incremental output
            debug: {}
        };
    
        try {
            console.log("Sending request to DashScope API...");
    
            const response = await axios.post(url, data, {
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json',
                    'X-DashScope-SSE': 'enable' // Streaming output
                },
                responseType: 'stream' // For handling streaming responses
            });
    
            if (response.status === 200) {
                // // Process streaming response SSE protocol parsing transformer
                const sseTransformer = new Transform({
                    transform(chunk, encoding, callback) {
                        this.buffer += chunk.toString();
                        
                        // Split by SSE events (two line feeds)
                        const events = this.buffer.split(/\n\n/);
                        this.buffer = events.pop() || ''; // Keep incomplete part
                        
                        events.forEach(eventData => {
                            const lines = eventData.split('\n');
                            let textContent = '';
                            
                            // Parse event content
                            lines.forEach(line => {
                                if (line.startsWith('data:')) {
                                    try {
                                        const jsonData = JSON.parse(line.slice(5).trim());
                                        if (jsonData.output?.text) {
                                            textContent = jsonData.output.text;
                                        }
                                    } catch(e) {
                                        console.error('JSON parsing error:', e.message);
                                    }
                                }
                            });
    
                            if (textContent) {
                                // Add line feed and push
                                this.push(textContent + '\n');
                            }
                        });
                        
                        callback();
                    },
                    flush(callback) {
                        if (this.buffer) {
                            this.push(this.buffer + '\n');
                        }
                        callback();
                    }
                });
                sseTransformer.buffer = '';
    
                // Pipeline processing
                response.data
                    .pipe(sseTransformer)
                    .on('data', (textWithNewline) => {
                        process.stdout.write(textWithNewline); // Automatic line feed output
                    })
                    .on('end', () => console.log(""))
                    .on('error', err => console.error("Pipeline error:", err));
    
            } else {
                console.log("Request failed, status code:", response.status);
                response.data.on('data', chunk => console.log(chunk.toString()));
            }
        } catch (error) {
            console.error(`API call failed: ${error.message}`);
            if (error.response) {
                console.error(`Status code: ${error.response.status}`);
                error.response.data.on('data', chunk => console.log(chunk.toString()));
            }
        }
    }
    
    callDashScope();

    Sample response

    1. Output complete response
    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":"Hello!"},"usage":{"models":[{"input_tokens":56,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":" Is there"},"usage":{"models":[{"input_tokens":56,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":" anything I can"},"usage":{"models":[{"input_tokens":56,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":" help you with?"},"usage":{"models":[{"input_tokens":56,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":56,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}
    2. Output only text field
    I am
    Alibaba
    Cloud
    's large-scale
    language model, I
    am called 
    Qwen.
    C#

    Sample request

    using System.Net;
    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // If environment variables are not configured, replace the following line with: apiKey="sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
            string appId = "YOUR_APP_ID"; // Replace with the actual application ID
            string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
    
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");
    
                string jsonContent = @"{
                    ""input"": {
                        ""prompt"": ""Who are you""
                    },
                    ""parameters"": {""incremental_output"": true},
                    ""debug"": {}
                }";
    
                HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                try
                {
                    var request = new HttpRequestMessage(HttpMethod.Post, url);
                    request.Content = content;
    
                    HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
                    
    
                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("Request successful:");
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                        using (var stream = await response.Content.ReadAsStreamAsync())
                        using (var reader = new StreamReader(stream))
                        {
                            string? line; // Declare as nullable string
                            while ((line = await reader.ReadLineAsync()) != null)
                            {
                                if (line.StartsWith("data:"))
                                {
                                    string data = line.Substring(5).Trim();
                                    Console.WriteLine(data);
                                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error calling DashScope: {ex.Message}");
                }
            }
        }
    }

    Sample response

    2025-02-14 16:22:08:482
    Request successful:
    2025-02-14 16:22:09:098
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"I"},"usage":{"models":[{"input_tokens":51,"output_tokens":1,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:09:099
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" am"},"usage":{"models":[{"input_tokens":51,"output_tokens":2,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:09:172
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" Alibaba"},"usage":{"models":[{"input_tokens":51,"output_tokens":3,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:09:172
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" Cloud's large-scale language"},"usage":{"models":[{"input_tokens":51,"output_tokens":7,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:09:463
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" model, my name is"},"usage":{"models":[{"input_tokens":51,"output_tokens":11,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:09:618
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" Qwen"},"usage":{"models":[{"input_tokens":51,"output_tokens":15,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:09:777
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":". I am your AI"},"usage":{"models":[{"input_tokens":51,"output_tokens":19,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:09:932
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" assistant,"},"usage":{"models":[{"input_tokens":51,"output_tokens":23,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:10:091
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" I can answer questions,"},"usage":{"models":[{"input_tokens":51,"output_tokens":27,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:10:244
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" create text, such as"},"usage":{"models":[{"input_tokens":51,"output_tokens":31,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:10:389
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" writing stories, writing"},"usage":{"models":[{"input_tokens":51,"output_tokens":35,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:10:525
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" documents, writing"},"usage":{"models":[{"input_tokens":51,"output_tokens":39,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:10:662
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" emails, writing scripts"},"usage":{"models":[{"input_tokens":51,"output_tokens":43,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:10:902
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":", and I can also express"},"usage":{"models":[{"input_tokens":51,"output_tokens":47,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:11:062
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" opinions, play games, etc"},"usage":{"models":[{"input_tokens":51,"output_tokens":51,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:11:233
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"."},"usage":{"models":[{"input_tokens":51,"output_tokens":52,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:11:309
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":51,"output_tokens":52,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:11:388
    Go

    Sample request

    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"io"
    	"net/http"
    	"os"
    	"strings"
    	"time"
    )
    
    func main() {
    	// If environment variables are not configured, replace the following line with: apiKey := "sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID" // Replace with the actual application ID
    
    	if apiKey == "" {
    		fmt.Println("Please ensure DASHSCOPE_API_KEY is set.")
    		return
    	}
    
    	url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
    
    	// Create request body, where incremental_output indicates whether to enable streaming response
    	requestBody := map[string]interface{}{
    		"input": map[string]string{
    			"prompt": "Who are you?",
    		},
    		"parameters": map[string]interface{}{
    			"incremental_output": true,
    		},
    		"debug": map[string]interface{}{},
    	}
    
    	jsonData, err := json.Marshal(requestBody)
    	if err != nil {
    		fmt.Printf("Failed to marshal JSON: %v\n", err)
    		return
    	}
    
    	// Create HTTP POST request
    	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    	if err != nil {
    		fmt.Printf("Failed to create request: %v\n", err)
    		return
    	}
    
    	// Set request headers, where X-DashScope-SSE set to enable indicates enabling streaming response
    	req.Header.Set("Authorization", "Bearer "+apiKey)
    	req.Header.Set("Content-Type", "application/json")
    	req.Header.Set("X-DashScope-SSE", "enable")
    
    	// Send request
    	client := &http.Client{}
    	resp, err := client.Do(req)
    	if err != nil {
    		fmt.Printf("Failed to send request: %v\n", err)
    		return
    	}
    	defer resp.Body.Close()
    
    	if resp.StatusCode != http.StatusOK {
    		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
    		body, _ := io.ReadAll(resp.Body)
    		fmt.Println(string(body))
    		return
    	}
    
    	// Process streaming response
    	reader := io.Reader(resp.Body)
    	buf := make([]byte, 1024)
    	for {
    		n, err := reader.Read(buf)
    		if n > 0 {
    			data := string(buf[:n])
    			lines := strings.Split(data, "\n")
    			for _, line := range lines {
    				line = strings.TrimSpace(line)
    				if len(line) >= 5 && line[:5] == "data:" {
    					timestamp := time.Now().Format("2006-01-02 15:04:05.000")
    					fmt.Printf("%s: %s\n", timestamp, line[5:])
    				} else if len(line) > 0 {
    					fmt.Println(line)
    				}
    			}
    		}
    		if err != nil {
    			if err == io.EOF {
    				break
    			}
    			fmt.Printf("Error reading response: %v\n", err)
    			break
    		}
    	}
    }
    

    Sample response

    id:1
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:09.050: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"I am"},"usage":{"models":[{"input_tokens":262,"output_tokens":1,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:2
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" Tong"},"usage":{"models":[{"input_tokens":262,"output_tokens":2,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:3
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"yi"},"usage":{"models":[{"input_tokens":262,"output_tokens":3,"model_id":"qwen-plus"}]},"request_id:4
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" Qianwen, developed by"},"usage":{"models":[{"input_tokens":262,"output_tokens":7,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:5
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" Alibaba Cloud"},"usage":{"models":[{"input_tokens":262,"output_tokens":11,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:6
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":", an AI assistant. I"},"usage":{"models":[{"input_tokens":262,"output_tokens":15,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:7
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" am designed to answer"},"usage":{"models":[{"input_tokens":262,"output_tokens":19,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:8
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.018: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" various questions, provide"},"usage":{"models":[{"input_tokens":262,"output_tokens":23,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:9
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.102: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" information and engage"},"usage":{"models":[{"input_tokens":262,"output_tokens":27,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:10
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.257: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" in conversations. Need"},"usage":{"models":[{"input_tokens":262,"output_tokens":31,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:11
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.414: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" any help?"},"usage":{"models":[{"input_tokens":262,"output_tokens":34,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:12
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.481: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":262,"output_tokens":34,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
  • Workflow Application provides two streaming output modes, determined by the value of flow_stream_mode.

    Parameter values and usage methods:

    • full_thoughts (default value):

      • Description: Streaming results of all nodes will be output in the thoughts field.

      • Requirement: You must also set has_thoughts to True.

    • agent_format:

      • Description: The same output mode as agent applications.

      • Effect: In the console, you can turn on the Response switch for a specific node, and the streaming results of that node will be included in the text field of output.

      • Scenario: Suitable for scenarios where you only care about the output of specific intermediate nodes.

      The Response switch is available only in Text Conversion nodes, LLM nodes, and End nodes (The switch is on for End nodes by default). Nodes that do not support streaming output will output their content all at once.

    Example:

    full_thoughts

    This is a published Workflow Application with streaming output.

    image

    Python

    Sample request

    import os
    from http import HTTPStatus
    from dashscope import Application
    import dashscope
    dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
    biz_params = {
        "city": "Hangzhou"}
    responses = Application.call(
        # If environment variables are not configured, replace the following line with: api_key="sk-xxx". However, it is not recommended to hardcode 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"),
        # Replace with the actual application ID
        app_id='YOUR_APP_ID',
        prompt='Hello',
        biz_params=biz_params,
        # Enable streaming output
        stream=True,
        # incremental_output=true enables incremental output, false disables it, default is false if not specified
        incremental_output=True,
        # Need to set has_thoughts to True
        has_thoughts=True)
    
    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'Please refer to the documentation: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
        else:
            print(f'{response.output.thoughts}\n')  # Process output to return only thoughts; process information is returned in the thoughts field of output

    Sample response

    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_99FA","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_99FA"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"Dongpo\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_99FA"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\" Pork, West Lake Vinegar Fish,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_99FA"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\" Longjing Shrimp, Hangzhou Pa\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_99FA"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"stry, Beggar\'s Chicken\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_qkYJ","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\"West Lake,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\" Lingyin Temple, Xixi\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\" National Wetland Park, Hefang\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\" Street, Hangzhou Botanical Garden\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_qkYJ","nodeExecTime":"1048ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"End","nodeResult":"{\\"result\\":\\"What do you think about our recommendation?\\"}","nodeType":"End","nodeStatus":"success","nodeId":"End_DrQn7F","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    Java

    Sample request

    // Recommended dashscope SDK version >= 2.15.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 com.alibaba.dashscope.utils.JsonUtils;
    import io.reactivex.Flowable;
    
    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 {
            String bizParams =
                    "{\"city\":\"Hangzhou\"}";
            ApplicationParam param = ApplicationParam.builder()
                    // If environment variables are not configured, replace the following line with: .apiKey("sk-xxx"). However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID") //Replace with the actual application ID
                    .prompt("Hello")
                    .bizParams(JsonUtils.parse(bizParams))
                    .incrementalOutput(true) // Incremental output
                    .hasThoughts(true) // For workflow applications to implement streaming output, this parameter must be set to true, and output results can be viewed in the thoughts field
                    .build();
    
            Application application = new Application();
            Flowable<ApplicationResult> result = application.streamCall(param); // Implement streaming output
            result.blockingForEach(data -> {
                System.out.printf("%s\n",data.getOutput().getThoughts());// Process output to display only the thoughts field
            });
        }
    
        public static void main(String[] args) {
            try {
                streamCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("Please refer to the documentation: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }

    Sample response

    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_S78u","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"West Lake Fish in Vinegar Sauce,\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"Longjing Shrimp\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\",Dongpo Pork,Zhiwei Small\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"Steamed Buns,Beggar's\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"Chicken\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_5ZzA","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\"West Lake,\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\"Lingyin\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\" Temple,Songcheng\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\",Xixi Wetland,Thousand Island Lake\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_5ZzA","nodeExecTime":"938ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"End","nodeResult":"{\"result\":\"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Thousand Island Lake\"}","nodeType":"End","nodeStatus":"success","nodeId":"End_DrQn7F","nodeExecTime":"5ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    HTTP
    curl

    Sample request

    curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
    --header 'X-DashScope-SSE: enable' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header 'Content-Type: application/json' \
    --data '{
        "input": {
            "prompt": "Hello",
            "biz_params": {
            "city": "Hangzhou"}
        },
        "parameters":  {
            "has_thoughts": true,
            "incremental_output": true
        },
        "debug": {}
    }'
    Replace YOUR_APP_ID with the actual application ID.

    Sample response

    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_j45e\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Fish in Vinegar Sauce,Long\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":5,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"jing Shrimp,Dongpo Pork,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":13,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"Beggar's Chicken,Song\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":18,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"cheng Fish Soup\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2Km9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:9
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"Ling\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:10
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"yin Temple,Songcheng,Xixi\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:11
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\" National Wetland Park,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:12
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"Hangzhou Zoo\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_2Km9\",\"nodeExecTime\":\"1137ms\"}"},{"response":"{\"nodeName\":\"End\",\"nodeResult\":\"{\\\"result\\\":\\\"Dear, are you satisfied with my introduction\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"stop","text":"Dear, are you satisfied with my introduction"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    PHP

    Sample request

    <?php
    
    # If environment variables are not configured, replace the following line with: $api_key="sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
    
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    
    // Construct request data
    $data = [
        "input" => [
            'prompt' => 'Hello',
            'biz_params' => [
                'city' => 'Hangzhou'
            ]
        ],
        "parameters" => [
            'has_thoughts' => true, // For workflow applications and orchestration applications, this parameter must be set to true, and process information is returned in thoughts
            'incremental_output' => true // Incremental output
        ]
    ];
    // Encode data as JSON
    $dataString = json_encode($data);
    
    // Check if json_encode was successful
    if (json_last_error() !== JSON_ERROR_NONE) {
        die("JSON encoding failed with error: " . json_last_error_msg());
    }
    
    // Initialize curl session
    $ch = curl_init($url);
    
    // Set curl options
    curl_setopt($ch, curlOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, curlOPT_POSTFIELDS, $dataString);
    curl_setopt($ch, curlOPT_RETURNTRANSFER, false); // Don't return the transferred data
    curl_setopt($ch, curlOPT_WRITEFUNCTION, function ($ch, $string) {
        echo $string; // Process streaming data
        return strlen($string);
    });
    curl_setopt($ch, curlOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key,
        'X-DashScope-SSE: enable' // Fixed parameter for streaming output
    ]);
    
    // Execute request
    $response = curl_exec($ch);
    
    // Check if curl execution was successful
    if ($response === false) {
        die("curl Error: " . curl_error($ch));
    }
    
    // Get HTTP status code
    $status_code = curl_getinfo($ch, curlINFO_HTTP_CODE);
    // Close curl session
    curl_close($ch);
    
    if ($status_code != 200) {
        echo "HTTP Status Code: $status_code\n";
        echo "Request Failed.\n";
    }
    ?>

    Sample response

    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Ilo9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Fish in Vinegar Sauce\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\",\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"Dongpo Pork,Zhiwei Steamed\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\",Longjing Shrimp\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"requestid:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\",Beggar's Chicken\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_vQDv\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:9
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:10
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\" Temple,Songcheng\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:11
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\",Xixi Wetland\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:12
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\",Hangzhou Tower\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_vQDv\",\"nodeExecTime\":\"899ms\"}"},{"response":"{\"nodeName\":\"End\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Hangzhou Tower\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"stop","text":"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Hangzhou Tower"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    
    Node.js

    Dependency:

    npm install axios

    Sample request

    const axios = require('axios');
    
    async function callDashScope() {
        // If environment variables are not configured, you can replace the following line with: apiKey='sk-xxx' using the Model Studio API Key. 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.
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID';// Replace with the actual application ID
    
        const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    
        const data = {
            input: {
                prompt: "hello",
                biz_params:{
                    'city':'Hangzhou'
                }
            },
            parameters: {
                'incremental_output' : 'true',
                'has_thoughts':'true'//This parameter needs to be set for workflow applications and agent orchestration applications to implement streaming output
            },
            debug: {}
        };
    
        try {
            console.log("Sending request to DashScope API...");
    
            const response = await axios.post(url, data, {
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json',
                    'X-DashScope-SSE': 'enable'
                },
                responseType: 'stream' // Used to handle streaming response
            });
    
            if (response.status === 200) {
                console.log("Request successful:");
    
                // Handle streaming response
                response.data.on('data', (chunk) => {
                    console.log(`Received chunk: ${chunk.toString()}`);
                });
    
                response.data.on('end', () => {
                    console.log("Stream ended.");
                });
    
                response.data.on('error', (error) => {
                    console.error(`Stream error: ${error.message}`);
                });
            } else {
                console.log("Request failed:");
                if (response.data.request_id) {
                    console.log(`request_id=${response.data.request_id}`);
                }
                console.log(`code=${response.status}`);
                if (response.data.message) {
                    console.log(`message=${response.data.message}`);
                } else {
                    console.log('message=Unknown error');
                }
            }
        } catch (error) {
            console.error(`Error calling DashScope: ${error.message}`);
            if (error.response) {
                console.error(`Response status: ${error.response.status}`);
                console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
            }
        }
    }
    
    callDashScope();

    Sample response

    /opt/homebrew/bin/node ./index.js
    Sending request to DashScope API...
    Request successful:
    Received chunk: id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Fish\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\" in Vinegar Sauce,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Longjing Shrimp\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Dongpo Pork\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Zhiwei\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\" Steamed Buns,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:9
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Beggar's Chicken\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:10
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:11
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Lingyin\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:12
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\" Temple,Songcheng,Xixi Wetland\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:13
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Thousand Island Lake\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:14
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_5ZzA\",\"nodeExecTime\":\"855ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Thousand Island Lake\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"stop","text":"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Thousand Island Lake"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Stream ended.
    C#

    Sample request

    using System.Net;
    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // If environment variables are not configured, replace the following line with: apiKey="sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
            string appId = "YOUR_APP_ID"; // Replace with the actual application ID
            string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
    
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");
    
                string jsonContent = @"{
                    ""input"": {
                        ""prompt"": ""Hello"",
                        ""biz_params"":{
                            ""city"":""Hangzhou""
                        }
                    },
                    ""parameters"": {
                        ""incremental_output"": true,
                        ""has_thoughts"": true 
                        },
                    ""debug"": {}
                }";
    
                HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                try
                {
                    var request = new HttpRequestMessage(HttpMethod.Post, url);
                    request.Content = content;
    
                    HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
                    
    
                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("Request successful:");
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                        using (var stream = await response.Content.ReadAsStreamAsync())
                        using (var reader = new StreamReader(stream))
                        {
                            string? line; // Declare as nullable string
                            while ((line = await reader.ReadLineAsync()) != null)
                            {
                                if (line.StartsWith("data:"))
                                {
                                    string data = line.Substring(5).Trim();
                                    Console.WriteLine(data);
                                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error calling DashScope: {ex.Message}");
                }
            }
        }
    }

    Sample response

    2025-02-14 16:55:28:670
    Request successful:
    2025-02-14 16:55:28:980
    {"output":{"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:28:980
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:28:980
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_j45e\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:29:178
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Fish in Vinegar Sauce,Long\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":5,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:29:780
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"jing Shrimp,Dongpo Pork,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":13,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:29:979
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"Zhiwei Steamed Buns,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":18,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:30:179
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"Beggar's Chicken\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2Km9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:30:379
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:30:986
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"Lingyin Temple,Song\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:31:180
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"cheng,Xixi Wetland,Thousand Island Lake\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_2Km9\",\"nodeExecTime\":\"1008ms\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:31:382
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_2Km9\",\"nodeExecTime\":\"1008ms\"}"},{"response":"{\"nodeName\":\"End\",\"nodeResult\":\"{\\\"result\\\":\\\"Dear, are you satisfied with my introduction\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"stop","text":"Dear, are you satisfied with my introduction"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:31:751
    Go

    Sample request

    package main
    
    import (
    	"bufio"
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"net/http"
    	"os"
    )
    
    func main() {
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID" // Replace with the actual application ID
    
    	if apiKey == "" {
    		fmt.Println("Please ensure that DASHSCOPE_API_KEY is set.")
    		return
    	}
    
    	url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
    
    	requestBody := map[string]interface{}{
    		"input": map[string]interface{}{
    			"prompt": "hello",
    			"biz_params": map[string]interface{}{
    				"city": "Hangzhou",
    			},
    		},
    		"parameters": map[string]interface{}{
    			"incremental_output": true,
    			"has_thoughts":       true,
    		},
    		"debug": map[string]interface{}{},
    	}
    
    	jsonData, err := json.Marshal(requestBody)
    	if err != nil {
    		fmt.Printf("Failed to marshal JSON: %v\n", err)
    		return
    	}
    
    	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    	if err != nil {
    		fmt.Printf("Failed to create request: %v\n", err)
    		return
    	}
    
    	req.Header.Set("Authorization", "Bearer "+apiKey)
    	req.Header.Set("Content-Type", "application/json")
    	req.Header.Set("X-DashScope-SSE", "enable")
    
    	client := &http.Client{}
    	resp, err := client.Do(req)
    	if err != nil {
    		fmt.Printf("Failed to send request: %v\n", err)
    		return
    	}
    	defer resp.Body.Close()
    
    	scanner := bufio.NewScanner(resp.Body)
    	for scanner.Scan() {
    		line := scanner.Text()
    		fmt.Println(line)
    	}
    
    	if err := scanner.Err(); err != nil {
    		fmt.Printf("Error reading response: %v\n", err)
    	}
    
    	if resp.StatusCode != http.StatusOK {
    		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
    	}
    }
    

    Sample response

    Request successful:
    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Vinegar\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Fish,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Longjing Shrimp\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Dongpo Pork\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Zhiwei Small\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Basket,Beggar's\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:9
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Chicken\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:10
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:11
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Temple,Songcheng\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:12
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Xixi Wetland\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:13
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Qiandao Lake\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:14
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_5ZzA\",\"nodeExecTime\":\"1760ms\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:15
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_5ZzA\",\"nodeExecTime\":\"1760ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Qiandao Lake\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"stop","text":"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Qiandao Lake"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    • Each item in thoughts is the execution details of a node. Below is an example of an LLM node result.

      id:7
      event:result
      :HTTP_STATUS/200
      data:
      {
          "output": {
              "thoughts": [
                  {
                      "response": "{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"
                  },
                  {
                      "response": "{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"Songcheng Fish Soup\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"
                  },
                  {
                      "response": "{\"nodeName\":\"LLM_2Km9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"
                  }
              ],
              "session_id": "6035ee0814b64a9fb88346ecaf8b44bf",
              "finish_reason": "null"
          },
          "usage": {
              "models": [
                  {
                      "input_tokens": 25,
                      "output_tokens": 21,
                      "model_id": "qwen-max"
                  }
              ]
          },
          "request_id": "64825069-b3aa-93a7-bcf1-c66fe57111fd"
      }
      If you are interested in the streaming results of an LLM node (using LLM_j45e in the example above), you can focus on the output of the node with nodeId LLM_j45e in each push of thoughts.
    • If a node fails, the entire task will also fail.

    agent_format

    This is a published Workflow Application. The Response switch is on only for the first LLM Node, focusing only on the results of this node.

    image

    Python

    Sample request

    import os
    from http import HTTPStatus
    from dashscope import Application
    import dashscope
    dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
    biz_params = {
        "city": "Hangzhou"}
    responses = Application.call(
        # If environment variables are not configured, replace the following line with: api_key="sk-xxx". However, it is not recommended to hardcode 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"),
        # Replace with the actual application ID
        app_id='YOUR_APP_ID',
        prompt='Hello',
        biz_params=biz_params,
        # Enable streaming output
        stream=True,
        # Enable compatibility mode to output streaming results of specified nodes
        flow_stream_mode="agent_format",
        # incremental_output=true enables incremental output, false disables it, default is false if not specified
        incremental_output=True)
    
    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'Please refer to the documentation: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
        else:
            print(f'{response.output.text}\n')  # Process output text, results are returned in text

    Sample response

    West Lake
    
    Fish in Vinegar Sauce,
    
    Longjing Shrimp
    
    ,Dongpo Pork
    
    ,Zhiwei Small
    
    Steamed Buns,Beggar's Chicken
    HTTP
    curl

    Sample request

    curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
    --header 'X-DashScope-SSE: enable' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header 'Content-Type: application/json' \
    --data '{
        "input": {
            "prompt": "Hello",
            "biz_params": {
            "city": "Hangzhou"}
        },
        "parameters":  {
            "incremental_output": true,
            "flow_stream_mode": "agent_format"
        },
        "debug": {}
    }'

    Sample response

    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}
    
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Fish in Vinegar"},"usage":{"models":[{"input_tokens":25,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}
    
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Sauce"},"usage":{"models":[{"input_tokens":25,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}
    
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":",Longjing Shrimp,Dongpo"},"usage":{"models":[{"input_tokens":25,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}
    
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Pork,Zhiwei"},"usage":{"models":[{"input_tokens":25,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}
    
    id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Steamed Buns,Beggar's"},"usage":{"models":[{"input_tokens":25,"output_tokens":19,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}
    
    id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Chicken"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}
    
    id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"stop","text":"Dear, are you satisfied with my introduction"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}
    PHP

    Sample request

    <?php
    
    # If environment variables are not configured, replace the following line with: $api_key="sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
    
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    
    // Construct request data
    $data = [
        "input" => [
            'prompt' => 'Hello',
            'biz_params' => [
                'city' => 'Hangzhou'
            ]
        ],
        "parameters" => [
            'flow_stream_mode' => 'agent_format', // For workflow applications streaming output compatibility mode, set this parameter to agent_format
            'incremental_output' => true // Incremental output
        ]
    ];
    // Encode data as JSON
    $dataString = json_encode($data);
    
    // Check if json_encode was successful
    if (json_last_error() !== JSON_ERROR_NONE) {
        die("JSON encoding failed with error: " . json_last_error_msg());
    }
    
    // Initialize curl session
    $ch = curl_init($url);
    
    // Set curl options
    curl_setopt($ch, curlOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, curlOPT_POSTFIELDS, $dataString);
    curl_setopt($ch, curlOPT_RETURNTRANSFER, false); // Don't return the transferred data
    curl_setopt($ch, curlOPT_WRITEFUNCTION, function ($ch, $string) {
        echo $string; // Process streaming data
        return strlen($string);
    });
    curl_setopt($ch, curlOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key,
        'X-DashScope-SSE: enable' // Fixed parameter for streaming output
    ]);
    
    // Execute request
    $response = curl_exec($ch);
    
    // Check if curl execution was successful
    if ($response === false) {
        die("curl Error: " . curl_error($ch));
    }
    
    // Get HTTP status code
    $status_code = curl_getinfo($ch, curlINFO_HTTP_CODE);
    // Close curl session
    curl_close($ch);
    
    if ($status_code != 200) {
        echo "HTTP Status Code: $status_code\n";
        echo "Request Failed.\n";
    }
    ?>

    Sample response

    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":1,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"null","text":" Fish in Vinegar Sauce,Longjing Shrimp,Dongpo Pork,"},"usage":{"models":[{"input_tokens":25,"output_tokens":13,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32a0-960b-bdfb-1823545edb5f"}
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"null","text":"Zhiwei Steamed Buns,"},"usage":{"models":[{"input_tokens":25,"output_tokens":18,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32a0-960b-bdfb-1823545edb5f"}
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"null","text":"Beggar's Chicken"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32a0-960b-bdfb-1823545edb5f"}
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32a0-960b-bdfb-1823545edb5f"}
    
    Node.js

    Dependency:

    npm install axios

    Sample request

    const axios = require('axios');
    
    async function callDashScope() {
        // If environment variables are not configured, replace the following line with: apiKey='sk-xxx'. However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID';// Replace with the actual application ID
    
        const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    
        const data = {
            input: {
                prompt: "Hello",
                biz_params:{
                    'city':'Hangzhou'
                }
            },
            parameters: {
                'incremental_output' : 'true',
                "flow_stream_mode" : "agent_format"
            },
            debug: {}
        };
    
        try {
            console.log("Sending request to DashScope API...");
    
            const response = await axios.post(url, data, {
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json',
                    'X-DashScope-SSE': 'enable'
                },
                responseType: 'stream' // For handling streaming responses
            });
    
            if (response.status === 200) {
                console.log("Request successful:");
    
                // Process streaming response
                response.data.on('data', (chunk) => {
                    console.log(`Received chunk: ${chunk.toString()}`);
                });
    
                response.data.on('end', () => {
                    console.log("Stream ended.");
                });
    
                response.data.on('error', (error) => {
                    console.error(`Stream error: ${error.message}`);
                });
            } else {
                console.log("Request failed:");
                if (response.data.request_id) {
                    console.log(`request_id=${response.data.request_id}`);
                }
                console.log(`code=${response.status}`);
                if (response.data.message) {
                    console.log(`message=${response.data.message}`);
                } else {
                    console.log('message=Unknown error');
                }
            }
        } catch (error) {
            console.error(`Error calling DashScope: ${error.message}`);
            if (error.response) {
                console.error(`Response status: ${error.response.status}`);
                console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
            }
        }
    }
    
    callDashScope();

    Sample response

    Sending request to DashScope API...
    Request successful:
    Received chunk: id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"}
    
    
    Received chunk: id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":" Fish in Vinegar Sauce"},"usage":{"models":[{"input_tokens":25,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"}
    
    
    Received chunk: id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":",Longjing Shrimp"},"usage":{"models":[{"input_tokens":25,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"}
    
    
    Received chunk: id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":",Dongpo Pork"},"usage":{"models":[{"input_tokens":25,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"}
    
    
    Received chunk: id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":",Beggar's Chicken"},"usage":{"models":[{"input_tokens":25,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"}
    
    
    Received chunk: id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":",Zhiwei Steamed"},"usage":{"models":[{"input_tokens":25,"output_tokens":19,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"}
    
    
    Received chunk: id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":" Buns"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"}
    
    
    Received chunk: id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"}
    
    
    Stream ended.
    C#

    Sample request

    using System.Net;
    using System.Text;
    class Program
    {
        static async Task Main(string[] args)
        {
            // If environment variables are not configured, replace the following line with: apiKey="sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
            string appId = "YOUR_APP_ID"; // Replace with the actual application ID
            string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
    
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");
    
                string jsonContent = @"{
                    ""input"": {
                        ""prompt"": ""Hello"",
                        ""biz_params"":{
                            ""city"":""Hangzhou""
                        }
                    },
                    ""parameters"": {
                        ""incremental_output"": true,
                        ""flow_stream_mode"": ""agent_format"" 
                        },
                    ""debug"": {}
                }";
    
                HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                try
                {
                    var request = new HttpRequestMessage(HttpMethod.Post, url);
                    request.Content = content;
    
                    HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
                    
    
                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("Request successful:");
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                        using (var stream = await response.Content.ReadAsStreamAsync())
                        using (var reader = new StreamReader(stream))
                        {
                            string? line; // Declare as nullable string
                            while ((line = await reader.ReadLineAsync()) != null)
                            {
                                if (line.StartsWith("data:"))
                                {
                                    string data = line.Substring(5).Trim();
                                    Console.WriteLine(data);
                                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error calling DashScope: {ex.Message}");
                }
            }
        }
    }

    Sample response

    2025-02-14 17:17:09:408
    Request successful:
    2025-02-14 17:17:10:256
    {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":1,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"}
    2025-02-14 17:17:10:257
    {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"null","text":" Fish in Vinegar Sauce,Longjing Shrimp,"},"usage":{"models":[{"input_tokens":25,"output_tokens":9,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"}
    2025-02-14 17:17:10:449
    {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"null","text":"Beggar's Chicken,Dongpo"},"usage":{"models":[{"input_tokens":25,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"}
    2025-02-14 17:17:10:650
    {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"null","text":" Pork,Zhiwei Steamed Buns"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"}
    2025-02-14 17:17:10:850
    {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"stop","text":"Dear, are you satisfied with my introduction"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"}
    Go

    Sample request

    package main
    
    import (
    	"bufio"
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"net/http"
    	"os"
    )
    
    func main() {
    	// If environment variables are not configured, replace the following line with: apiKey := "sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID" // Replace with the actual application ID
    
    	if apiKey == "" {
    		fmt.Println("Please ensure DASHSCOPE_API_KEY is set.")
    		return
    	}
    
    	url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
    
    	// Create request body
    	requestBody := map[string]interface{}{
    		"input": map[string]interface{}{
    			"prompt": "Hello",
    			"biz_params": map[string]interface{}{
    				"city": "Hangzhou", // Parameter passing
    			},
    		},
    		"parameters": map[string]interface{}{
    			"incremental_output": true,           // Setting this parameter to true enables incremental output of results
    			"flow_stream_mode":   "agent_format", // For workflow applications to implement streaming output in compatibility mode, this parameter needs to be set to agent_format
    		},
    		"debug": map[string]interface{}{},
    	}
    
    	jsonData, err := json.Marshal(requestBody)
    	if err != nil {
    		fmt.Printf("Failed to marshal JSON: %v\n", err)
    		return
    	}
    
    	// Create HTTP POST request
    	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    	if err != nil {
    		fmt.Printf("Failed to create request: %v\n", err)
    		return
    	}
    
    	// Set request headers
    	req.Header.Set("Authorization", "Bearer "+apiKey)
    	req.Header.Set("Content-Type", "application/json")
    	req.Header.Set("X-DashScope-SSE", "enable") // Streaming output requests need to set this parameter to enable
    
    	// Send request
    	client := &http.Client{}
    	resp, err := client.Do(req)
    	if err != nil {
    		fmt.Printf("Failed to send request: %v\n", err)
    		return
    	}
    	defer resp.Body.Close()
    
    	// Read response
    	scanner := bufio.NewScanner(resp.Body)
    	for scanner.Scan() {
    		line := scanner.Text()
    		fmt.Println(line)
    	}
    
    	if err := scanner.Err(); err != nil {
    		fmt.Printf("Error reading response: %v\n", err)
    		return
    	}
    
    	// Process response
    	if resp.StatusCode == http.StatusOK {
    		fmt.Println("Request successful:")
    	} else {
    		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
    	}
    }
    

    Sample response

    Request successful:
    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}
    
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":" Fish in Vinegar Sauce"},"usage":{"models":[{"input_tokens":25,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}
    
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":",Longjing Shrimp"},"usage":{"models":[{"input_tokens":25,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}
    
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":",Dongpo Pork"},"usage":{"models":[{"input_tokens":25,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}
    
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":",Zhiwei"},"usage":{"models":[{"input_tokens":25,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}
    
    id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":" Steamed Buns,Beggar's"},"usage":{"models":[{"input_tokens":25,"output_tokens":19,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}
    
    id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":" Chicken"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}
    
    id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}

Retrieve knowledge base

Knowledge base is the RAG capability of Model Studio. It can effectively supplement private and latest knowledge for models. You can specify the retrieval scope when calling Agent Applications to improve the accuracy of answers.

Before you go

In the Model Studio console, turn on the Knowledge Base Retrieval Augmentation for your Agent Application. Then, Publish the application.

Skip this prerequisite for RAG Applications.

Specify retrieval scope

  1. To retrieve a specified knowledge base, choose one of the following methods:

    • In the console, click Configure Knowledge Base in the application and select the specified knowledge base. Then, Publish the application.

    • Do not associate the specified knowledge base in the console. Pass the knowledge base ID through rag_options when making an API call;

    • Associate the specified knowledge base in the console, and pass the knowledge base ID through rag_options when making an API call.

      In this case, only the knowledge base passed during the call will be retrieved. For example, an Agent Application is associated with knowledge base A. However, you specify knowledge base B when making the API call. Then, knowledge base A will not be retrieved, and only knowledge base B will be retrieved.

    To obtain the knowledge base ID (pipeline_ids): You can get it on the Knowledge Base Index page, or use the Data.Id returned by the CreateIndex API. CreateIndex only supports unstructured knowledge bases.

    Bailian Phones Specifications.docx is used in the following samples as an unstructured knowledge base.

    Python

    Sample request

    import os
    from http import HTTPStatus
    # Recommended dashscope SDK version >= 1.20.11
    from dashscope import Application
    import dashscope
    dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
    
    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 YOUR_APP_ID with the application ID
        prompt='Please recommend a mobile phone under 3000 yuan',
        rag_options={
            "pipeline_ids": ["YOUR_PIPELINE_ID1,YOUR_PIPELINE_ID2"],  # Replace with actual knowledge base IDs, separate multiple IDs with 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'Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # Process text output only
        # print('%s\n' % (response.usage))

    Sample response

    Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan, which fits your budget. It features a lightweight 6.4-inch 1080 x 2340 pixel screen design, paired with 128GB storage and 6GB RAM, suitable for daily use. Additionally, it has a 4000mAh battery and a lens that supports 30× digital zoom, which can meet your photography and battery life needs. If you're looking for a slim, portable phone with comprehensive features, the Bailian Zephyr Z9 would be a good choice.
    Java

    Sample request

    // Recommended dashscope SDK version >= 2.16.8;
    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.Collections;
    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()
                    // If environment variables are not configured, you can replace the following line with .apiKey("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.
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID") // Replace with the actual application ID
                    .prompt("Please recommend a mobile phone around 3000 yuan")
                    .ragOptions(RagOptions.builder()
                            // Replace with the actual specified knowledge base IDs, separate multiple with commas
                            .pipelineIds(List.of("PIPELINES_ID1", "PIPELINES_ID2"))
                            .build())
                    .build();
    
            Application application = new Application();
            ApplicationResult result = application.call(param);
            System.out.printf("%s\n",
                    result.getOutput().getText());// Process text output only
        }
    
        public static void main(String[] args) {
            try {
                streamCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }

    Sample response

    Within your 3000 yuan budget, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499 and 2799, which fits your budget perfectly. It has the following features:
    
    - **Lightweight design**: The 6.4-inch screen is moderately sized, convenient for one-handed operation.
    - **Balanced performance**: Equipped with 128GB storage and 6GB RAM, which is sufficient for daily use.
    - **Battery life**: Features a 4000mAh battery that can meet your normal usage needs throughout the day.
    - **Photography capabilities**: Has a lens with 30× digital zoom, suitable for capturing distant scenery.
    
    If you're more focused on gaming experience or have other specific requirements, please let me know so I can provide more personalized recommendations!
    HTTP
    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": "Please recommend a mobile phone under 3000 yuan"
        },
        "parameters":  {
                        "rag_options" : {
                        "pipeline_ids":["YOUR_PIPELINE_ID1"]}
        },
        "debug": {}
    }'
    Replace YOUR_APP_ID with the actual application ID, and YOUR_PIPELINE_ID1 with the specified knowledge base ID.

    Sample response

    {"output":{"finish_reason":"stop","session_id":"d1208af96f9a4d8390e9b29e86f0623c",
    "text":"For a budget under 3000 yuan, I recommend the Bailian Zephyr Z9.
    This phone is priced between 2499 and 2799 yuan, perfectly fitting your budget requirement.
    It features a lightweight 6.4-inch 1080 x 2340 pixel display, paired with 128GB storage and 6GB RAM, sufficient for handling various applications and multitasking in daily use.
    Additionally, it comes with a 4000mAh battery, ensuring your usage throughout the day, and is equipped with a 30× digital zoom lens, allowing you to capture details in your life.
    In summary, the Bailian Zephyr Z9 is a good choice in terms of cost-effectiveness, design, and functionality."},
    "usage":{"models":[{"output_tokens":158,"model_id":"qwen-max","input_tokens":1025}]},
    "request_id":"eb2d40f7-bede-9d48-88dc-08abdcdd0351"}% 
    PHP

    Sample request

    <?php
    # If the environment variable is not configured, you can replace the next line with your API key: $api_key="sk-xxx". However, it is not recommended to hardcode the API key directly into the code in a production environment to reduce the risk of API key leakage.
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
    
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    
    // Construct request data
    $data = [
        "input" => [
            'prompt' => 'Please recommend a smartphone under 3000 yuan.'
        ],
        "parameters" => [
            'rag_options' => [
                'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'] // Replace with the specified knowledge base IDs; use commas to separate multiple IDs
            ]
        ]
    ];
    
    // Encode data as JSON
    $dataString = json_encode($data);
    
    // Check if json_encode was successful
    if (json_last_error() !== JSON_ERROR_NONE) {
        die("JSON encoding failed with error: " . json_last_error_msg());
    }
    
    // Initialize curl session
    $ch = curl_init($url);
    
    // Set curl options
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key
    ]);
    
    // Execute the request
    $response = curl_exec($ch);
    
    // Check if curl execution was successful
    if ($response === false) {
        die("curl Error: " . curl_error($ch));
    }
    
    // Get HTTP status code
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    // Close curl session
    curl_close($ch);
    
    // Decode response data
    $response_data = json_decode($response, true);
    
    // Handle response
    if ($status_code == 200) {
        if (isset($response_data['output']['text'])) {
            echo "{$response_data['output']['text']}\n";
        } else {
            echo "No text in response.\n";
        }
    } else {
        if (isset($response_data['request_id'])) {
            echo "request_id={$response_data['request_id']}\n";
        }
        echo "code={$status_code}\n";
        if (isset($response_data['message'])) {
            echo "message={$response_data['message']}\n";
        } else {
            echo "message=Unknown error\n";
        }
    }
    ?>
    

    Sample response

    For a budget under 3000 yuan, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan, which is perfect for your budget. It features a lightweight design with a 6.4-inch 1080 x 2340 pixel screen, 128GB storage and 6GB RAM, which can meet your daily usage needs well. Additionally, its 4000mAh battery ensures a full day of normal use, and it's equipped with a 30× digital zoom lens to capture distant details, making it both slim and powerful.
    Node.js

    Dependency:

    npm install axios

    Sample request

    const axios = require('axios');
    async function callDashScope() {
        // If environment variables are not configured, you can replace the following line with apiKey='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.
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID';//Replace with the actual application ID
    
        const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    
        const data = {
            input: {
                prompt: "Please recommend a mobile phone under 3000 yuan"
            },
            parameters: {
                rag_options:{
                    pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2']  // Replace with specified knowledge base IDs, separate multiple with commas
                }
            },
            debug: {}
        };
    
        try {
            const response = await axios.post(url, data, {
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json'
                }
            });
    
            if (response.status === 200) {
                console.log(`${response.data.output.text}`);
            } else {
                console.log(`request_id=${response.headers['request_id']}`);
                console.log(`code=${response.status}`);
                console.log(`message=${response.data.message}`);
            }
        } catch (error) {
            console.error(`Error calling DashScope: ${error.message}`);
            if (error.response) {
                console.error(`Response status: ${error.response.status}`);
                console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
            }
        }
    }
    
    callDashScope();

    Sample response

    For a budget under 3000 yuan, I recommend you consider the **Bailian Zephyr Z9**. This phone has a reference price of 3999-4299 yuan, but if you can catch promotional activities or discounts, it might fall within your budget range.
    
    ### Bailian Zephyr Z9 — The Art of Lightweight Portability
    - **Screen**: 6.4-inch 1080 x 2340 pixels
    - **Storage and RAM**: 128GB storage / 6GB RAM
    - **Battery**: 4000mAh
    - **Camera**: 30× digital zoom lens
    
    This phone features a slim and portable design, very convenient for daily use, and has good battery life. If you're more concerned about value for money and daily user experience, the Bailian Zephyr Z9 is a good choice.
    
    If your budget is very strict, I suggest watching for promotional activities on e-commerce platforms, or considering other brands' phones in the same price range. Hope these suggestions are helpful!
    C#

    Sample request

    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // If environment variables are not configured, you can replace the following line with apiKey="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.
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
            string appId = "YOUR_APP_ID";// Replace with the actual application ID
            // YOUR_PIPELINE_ID1 replace with specified knowledge base ID
            if (string.IsNullOrEmpty(apiKey))
            {
                Console.WriteLine("Please make sure DASHSCOPE_API_KEY is set.");
                return;
            }
    
            string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
            
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                string jsonContent = $@"{{
                    ""input"": {{
                        ""prompt"": ""Please recommend a mobile phone under 3000 yuan""
                    }},
                    ""parameters"": {{
                        ""rag_options"" : {{
                            ""pipeline_ids"":[""YOUR_PIPELINE_ID1""]
                        }}
                    }},
                    ""debug"": {{}}
                }}";
    
                HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    
                try
                {
                    HttpResponseMessage response = await client.PostAsync(url, content);
    
                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                    else
                    {
                        Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error calling DashScope: {ex.Message}");
                }
            }
        }
    }

    Sample response

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "2344ddc540ec4c5fa110b92d813d3807",
            "text": "Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone has a reference price between 2499-2799 yuan, which fits your budget requirements. It features a 6.4-inch 1080 x 2340 pixel screen, 128GB storage and 6GB RAM, which is sufficient for daily use. Additionally, the 4000mAh battery ensures normal use throughout the day, while the 30× digital zoom lens can meet your needs for capturing distant scenery. This is a slim, portable, and feature-rich choice."
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 121,
                    "model_id": "qwen-max",
                    "input_tokens": 1841
                }
            ]
        },
        "request_id": "99fceedf-2034-9fb0-aaad-9c837136801f"
    }
    Go

    Sample request

    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"io"
    	"net/http"
    	"os"
    )
    
    func main() {
    	// If environment variables are not configured, you can replace the following line with apiKey := "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.
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID" // Replace with the actual application ID
    
    	if apiKey == "" {
    		fmt.Println("Please make sure DASHSCOPE_API_KEY is set.")
    		return
    	}
    
    	url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
    
    	// Create request body
    	requestBody := map[string]interface{}{
    		"input": map[string]string{
    			"prompt": "Please recommend a mobile phone under 3000 yuan",
    		},
    		"parameters": map[string]interface{}{
    			"rag_options": map[string]interface{}{
    				"pipeline_ids": []string{"YOUR_PIPELINE_ID1"}, // Replace with specified knowledge base ID
    			},
    		},
    		"debug": map[string]interface{}{},
    	}
    
    	jsonData, err := json.Marshal(requestBody)
    	if err != nil {
    		fmt.Printf("Failed to marshal JSON: %v\n", err)
    		return
    	}
    
    	// Create HTTP POST request
    	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    	if err != nil {
    		fmt.Printf("Failed to create request: %v\n", err)
    		return
    	}
    
    	// Set request headers
    	req.Header.Set("Authorization", "Bearer "+apiKey)
    	req.Header.Set("Content-Type", "application/json")
    
    	// Send request
    	client := &http.Client{}
    	resp, err := client.Do(req)
    	if err != nil {
    		fmt.Printf("Failed to send request: %v\n", err)
    		return
    	}
    	defer resp.Body.Close()
    
    	// Read response
    	body, err := io.ReadAll(resp.Body)
    	if err != nil {
    		fmt.Printf("Failed to read response: %v\n", err)
    		return
    	}
    
    	// Process response
    	if resp.StatusCode == http.StatusOK {
    		fmt.Println("Request successful:")
    		fmt.Println(string(body))
    	} else {
    		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
    		fmt.Println(string(body))
    	}
    }
    

    Sample response

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "fadbb4d1fe094ade88985620363506e6",
            "text": "Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan, which is very suitable for budgets under 3000 yuan. It features a lightweight 6.4-inch 1080 x 2340 pixel screen design, paired with 128GB storage and 6GB RAM, which can meet daily usage needs. At the same time, the 4000mAh battery ensures worry-free use throughout the day, while the 30× digital zoom lens can capture details from a distance, making it a very cost-effective choice."
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 119,
                    "model_id": "qwen-max",
                    "input_tokens": 1055
                }
            ]
        },
        "request_id": "3a755dd7-58a0-9a5e-8a07-b85b1db838a6"
    }
  2. Retrieve specified unstructured documents: Pass the knowledge base ID, document ID, tags, or metadata (key-value pairs) in rag_options.

    Document ID, tags, and metadata are only effective for unstructured documents.
    • How to get them:

      • Document ID (file_ids): You can find it on the Data Management page, or use the ID returned by the AddFile API when importing documents.

      • Document tags: You can find the tags on the Data Management page, or get them from the DescribeFile API.

      • Document metadata: On the Knowledge Base Index page, click View to enter a knowledge base. Then, click Metadata Information.

    • You can specify multiple document IDs, but the documents must have been included in knowledge indexes.

    • When specifying document IDs, you must also specify the knowledge base ID to which the documents belong.

    • Only the specified documents will be retrieved. For example, an Agent Application associates knowledge base A, but the API call specifies documents of knowledge base B. Then, documents from A will not be retrieved, only documents from B will be retrieved.

      Bailian Phones Specifications.docx is used in the following samples as an unstructured knowledge base.

      Python

      Sample request

      import os
      from http import HTTPStatus
      # Recommended dashscope SDK version >= 1.20.11
      from dashscope import Application
      import dashscope
      dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
      
      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 YOUR_APP_ID with application ID
          prompt='Please recommend a mobile phone under 3000 yuan',
          rag_options={
              "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"],  # Replace with actual knowledge base IDs, separate multiple with commas
              "file_ids": ["YOUR_FILE_ID1", "YOUR_FILE_ID2"],  # Replace with actual unstructured document IDs, separate multiple with commas
              "metadata_filter": {  # Document metadata key-value pairs, separate multiple with commas
                  "key1": "value1",
                  "key2": "value2"
              },
              "tags": ["tag1", "tag2"]  # Document tags, separate multiple with 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'Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
      else:
          print('%s\n' % (response.output))

      Sample response

      {
          "text": "Within a budget of under 3000 yuan, I recommend you consider the **Bailian Zephyr Z9**. This phone has the following features:
      
      - **Screen**: 6.4-inch 1080 x 2340 pixels, suitable for daily use and entertainment.
      - **Memory and storage**: 6GB RAM + 128GB storage space, which can meet most users' needs for smoothness and storage.
      - **Battery capacity**: 4000mAh, providing all-day usage guarantee.
      - **Camera function**: Equipped with a lens supporting 30× digital zoom, capable of capturing details from greater distances.
      - **Other features**: Lightweight and portable design, easy to carry.
      
      The reference price is between 2499 and 2799 yuan, which perfectly fits your budget requirements and offers good value for money. Hope these suggestions are helpful!",
          "finish_reason": "stop",
          "session_id": "10bdea3d1435406aad8750538b701bee",
          "thoughts": null,
          "doc_references": null
      }
      Java

      Sample request

      // Recommended dashscope SDK version >= 2.16.8;
      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.google.gson.JsonObject;
      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 {
              JsonObject metadataFilter = new JsonObject();
              metadataFilter.addProperty("key1", "value1"); // Metadata key-value pairs
              metadataFilter.addProperty("key2", "value2"); // For multiple, repeatedly call addProperty
              ApplicationParam param = ApplicationParam.builder()
                      // If environment variables are not configured, you can replace the following line with .apiKey("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.
                      .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                      .appId("YOUR_APP_ID") // Replace with the actual application ID
                      .prompt("Please recommend a mobile phone around 3000 yuan")
                      .ragOptions(RagOptions.builder()
                              .pipelineIds(List.of("PIPELINES_ID1","PIPELINES_ID2"))  // Replace with actual specified knowledge base IDs, separate multiple with commas
                              .fileIds(List.of("FILE_ID1", "FILE_ID2"))  // Replace with actual specified unstructured document IDs, separate multiple with commas
                              .tags(List.of("tags1", "tags2")) // Replace with specified document tag IDs, separate multiple with commas
                              .metadataFilter(metadataFilter)
                              .build())
                      .build();
      
              Application application = new Application();
              ApplicationResult result = application.call(param);
              System.out.printf("%s\n",
                      result.getOutput().getText());// Process text output only
          }
      
          public static void main(String[] args) {
              try {
                  streamCall();
              } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                  System.out.printf("Exception: %s", e.getMessage());
                  System.out.println("Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
              }
              System.exit(0);
          }
      }

      Sample response

      Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan, which fits perfectly within your budget range of around 3000 yuan.
      
      ### Bailian Zephyr Z9 Product Highlights:
      - **Screen**: 6.4-inch, 1080 x 2340 pixels, providing a clear and detailed visual experience.
      - **Storage and RAM**: 128GB storage space and 6GB RAM, sufficient to meet daily usage needs.
      - **Battery**: 4000mAh capacity battery can ensure normal use throughout the day.
      - **Camera**: Supports 30× digital zoom lens, capable of capturing distant details.
      - **Design**: Lightweight and portable, suitable for users who pursue fashion and convenience.
      
      This phone is not only moderately priced but also has balanced configurations and excellent appearance design, making it a very good choice in this price range. Hope these suggestions are helpful! If you have other requirements or questions, please feel free to let me know.
      HTTP
      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": "Please recommend a mobile phone around 3000 yuan"
          },
          "parameters":  {
                          "rag_options" : {
                          "pipeline_ids":["YOUR_PIPELINE_ID1"],
                          "file_ids":["YOUR_FILE_ID1"],
                          "metadata_filter":{
                          "name":"Zhang San"},
                          "tags":"mobile phone"
                          }
          },
          "debug": {}
      }'
      Replace YOUR_APP_ID with the actual application ID, YOUR_PIPELINE_ID1 with the specified knowledge base ID, YOUR_FILE_ID1 with the specified unstructured document ID, and the key-value pairs in metadata_filter with actual metadata.

      Sample response

      {"output":{"finish_reason":"stop","session_id":"f2f114864dd24a458f923aab0ec99a1d",
      "text":"Based on your budget, I recommend you consider the \"Tongyi Vivid 7\".
      It has a 6.5-inch 1080 x 2400 pixel full screen, with AI intelligent photography capabilities that allow you to take photos with professional-level color and detail.
      Its hardware configuration includes 8GB RAM and 128GB storage space, ensuring a smooth operating experience; the 4500mAh battery capacity also meets daily usage needs well.
      Additionally, the side fingerprint unlock design is both convenient and secure. The reference price is between 2999 and 3299 yuan, which fits your budget range."},
      "usage":{"models":[{"output_tokens":141,"model_id":"qwen-plus","input_tokens":1610}]},
      "request_id":"d815d3d1-8cef-95e2-b895-89fc8d0e0f84"}%      
      PHP

      Sample request

      <?php
      # If the environment variable is not configured, you can replace the next line with your API key: $api_key="sk-xxx". However, it is not recommended to hardcode the API key directly into the code in a production environment to reduce the risk of API key leakage.
      $api_key = getenv("DASHSCOPE_API_KEY");
      $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
      
      $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
      
      // Construct request data
      $data = [
          "input" => [
              'prompt' => 'Please help me recommend a smartphone under 3000 yuan.'
          ],
          "parameters" => [
              'rag_options' => [
                  'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'], // Replace with the specified knowledge base IDs; use commas to separate multiple IDs
                  'file_ids' => ['YOUR_FILE_ID1','YOUR_FILE_ID2'], // Replace with the actual document IDs; use commas to separate multiple IDs
                  "metadata_filter" => [ // Metadata key-value pairs
                      "key1" => "value1",
                      "key2" => "value2"
                  ],
                  "tags" => ["Tag1", "Tag2"] // Document tags
              ]
          ]
      ];
      
      // Encode data as JSON
      $dataString = json_encode($data);
      
      // Check if json_encode was successful
      if (json_last_error() !== JSON_ERROR_NONE) {
          die("JSON encoding failed with error: " . json_last_error_msg());
      }
      
      // Initialize curl session
      $ch = curl_init($url);
      
      // Set curl options
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
      curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, [
          'Content-Type: application/json',
          'Authorization: Bearer ' . $api_key
      ]);
      
      // Execute the request
      $response = curl_exec($ch);
      
      // Check if curl execution was successful
      if ($response === false) {
          die("curl Error: " . curl_error($ch));
      }
      
      // Get HTTP status code
      $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      // Close curl session
      curl_close($ch);
      
      // Decode response data
      $response_data = json_decode($response, true);
      
      // Handle response
      if ($status_code == 200) {
          if (isset($response_data['output']['text'])) {
              echo "{$response_data['output']['text']}\n";
          } else {
              echo "No text in response.\n";
          }
      } else {
          if (isset($response_data['request_id'])) {
              echo "request_id={$response_data['request_id']}\n";
          }
          echo "code={$status_code}\n";
          if (isset($response_data['message'])) {
              echo "message={$response_data['message']}\n";
          } else {
              echo "message=Unknown error\n";
          }
      }
      ?>
      

      Sample response

      Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone has a reference price between 2499-2799 yuan, which is perfect for requirements under 3000 yuan. It features a lightweight 6.4-inch 1080 x 2340 pixel design, paired with 128GB storage and 6GB RAM, which can meet your daily usage needs. Additionally, it is equipped with a 4000mAh battery to ensure worry-free use throughout the day, and has a 30× digital zoom lens to capture distant details, making it a thin yet powerful choice.
      Node.js

      Dependency:

      npm install axios

      Sample request

      const axios = require('axios');
      async function callDashScope() {
          // If environment variables are not configured, you can replace the following line with: apiKey='sk-xxx' using the Model Studio API Key. 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.
          const apiKey = process.env.DASHSCOPE_API_KEY;
          const appId = 'YOUR_APP_ID';//Replace with the actual application ID
      
          const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
      
          const data = {
              input: {
                  prompt: "Please recommend a mobile phone under 3000 yuan"
              },
              parameters: {
                  rag_options:{
                      pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'], // Replace with the specified knowledge base IDs, separate multiple IDs with commas
                      file_ids:['YOUR_FILE_ID1','YOUR_FILE_ID2'], // Replace with the specified file IDs, separate multiple IDs with commas
                      metadata_filter:{ // Metadata key-value pairs, separate multiple pairs with commas
                          'key1':'value1',
                          'key2':'value2'
                      },
                      tags: ['tag1', 'tag2'] // Document tags, separate multiple tags with commas
                  }
              },
              debug: {}
          };
      
          try {
              const response = await axios.post(url, data, {
                  headers: {
                      'Authorization': `Bearer ${apiKey}`,
                      'Content-Type': 'application/json'
                  }
              });
      
              if (response.status === 200) {
                  console.log(`${response.data.output.text}`);
              } else {
                  console.log(`request_id=${response.headers['request_id']}`);
                  console.log(`code=${response.status}`);
                  console.log(`message=${response.data.message}`);
              }
          } catch (error) {
              console.error(`Error calling DashScope: ${error.message}`);
              if (error.response) {
                  console.error(`Response status: ${error.response.status}`);
                  console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
              }
          }
      }
      
      callDashScope();

      Sample response

      Within a budget of under 3000 yuan, I recommend you consider the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan and features a slim, portable design with a 6.4-inch 1080 × 2340 pixel screen, 128GB storage, and 6GB RAM, which can meet your daily usage needs. Its 4000mAh battery ensures all-day usage, while the 30× digital zoom lens helps capture details from greater distances. Overall, this is a high-value option.
      C#

      Sample request

      using System.Text;
      
      class Program
      {
          static async Task Main(string[] args)
          {
              // If environment variables are not configured, you can replace the following line with apiKey="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.
              string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
              string appId = "YOUR_APP_ID";// Replace with the actual application ID
              // YOUR_PIPELINE_ID1 replace with specified knowledge base ID, YOUR_FILE_ID1 replace with specified unstructured document ID
              if (string.IsNullOrEmpty(apiKey))
              {
                  Console.WriteLine("Please make sure DASHSCOPE_API_KEY is set.");
                  return;
              }
      
              string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
              
              using (HttpClient client = new HttpClient())
              {
                  client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                  string jsonContent = $@"{{
                      ""input"": {{
                          ""prompt"": ""Please recommend a mobile phone under 3000 yuan""
                      }},
                      ""parameters"": {{
                          ""rag_options"" : {{
                              ""pipeline_ids"":[""YOUR_PIPELINE_ID1""],
                              ""file_ids"":[""YOUR_FILE_ID1""],
                              ""metadata_filter"":{{
                                  ""name"":""Zhang San""
                              }},
                      ""tags"":""mobile phone""
                          }}
                      }},
                      ""debug"": {{}}
                  }}";
      
                  HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
      
                  try
                  {
                      HttpResponseMessage response = await client.PostAsync(url, content);
      
                      if (response.IsSuccessStatusCode)
                      {
                          string responseBody = await response.Content.ReadAsStringAsync();
                          Console.WriteLine(responseBody);
                      }
                      else
                      {
                          Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                          string responseBody = await response.Content.ReadAsStringAsync();
                          Console.WriteLine(responseBody);
                      }
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine($"Error calling DashScope: {ex.Message}");
                  }
              }
          }
      }

      Sample response

      {
          "output": {
              "finish_reason": "stop",
              "session_id": "be9b5a1964fe41c9bbfd8674226bd238",
              "text": "Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan, which is very suitable for budgets under 3000 yuan.
      
      ### Product highlights
      - **Slim design**: Features a 6.4-inch screen with 1080 x 2340 pixel resolution, with an exquisite appearance that's easy to carry.
      - **Balanced performance**: Equipped with 6GB RAM and 128GB storage space, capable of meeting daily usage needs.
      - **Long-lasting battery**: Built-in 4000mAh battery ensures your normal usage throughout the day is not affected.
      - **Excellent photography**: Supports 30× digital zoom function, easily capturing distant scenery or details.
      
      If you're looking for a smartphone with good value for money that can meet basic needs while also having certain features, then the Bailian Zephyr Z9 would be a good choice."
          },
          "usage": {
              "models": [
                  {
                      "output_tokens": 180,
                      "model_id": "qwen-max",
                      "input_tokens": 1055
                  }
              ]
          },
          "request_id": "d0811195-0b3f-931e-90b8-323a65053d9c"
      }
      Go

      Sample request

      package main
      
      import (
      	"bytes"
      	"encoding/json"
      	"fmt"
      	"io"
      	"net/http"
      	"os"
      )
      
      func main() {
      	// If environment variables are not configured, you can replace the following line with apiKey := "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.
      	apiKey := os.Getenv("DASHSCOPE_API_KEY")
      	appId := "YOUR_APP_ID" // Replace with the actual application ID
      
      	if apiKey == "" {
      		fmt.Println("Please make sure DASHSCOPE_API_KEY is set.")
      		return
      	}
      
      	url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
      
      	// Create request body
      	requestBody := map[string]interface{}{
      		"input": map[string]string{
      			"prompt": "Please recommend a mobile phone under 3000 yuan",
      		},
      		"parameters": map[string]interface{}{
      			"rag_options": map[string]interface{}{
      				"pipeline_ids": []string{"YOUR_PIPELINE_ID1"}, // Replace with specified unstructured knowledge base ID
      				"file_ids":     []string{"YOUR_FILE_ID1"},     // Replace with specified unstructured document ID
      				"metadata_filter": map[string]string{
      					"name": "Zhang San", // Metadata key-value pairs
      				},
      				"tags": "mobile phone", // Unstructured data document tags
      			},
      		},
      		"debug": map[string]interface{}{},
      	}
      
      	jsonData, err := json.Marshal(requestBody)
      	if err != nil {
      		fmt.Printf("Failed to marshal JSON: %v\n", err)
      		return
      	}
      
      	// Create HTTP POST request
      	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
      	if err != nil {
      		fmt.Printf("Failed to create request: %v\n", err)
      		return
      	}
      
      	// Set request headers
      	req.Header.Set("Authorization", "Bearer "+apiKey)
      	req.Header.Set("Content-Type", "application/json")
      
      	// Send request
      	client := &http.Client{}
      	resp, err := client.Do(req)
      	if err != nil {
      		fmt.Printf("Failed to send request: %v\n", err)
      		return
      	}
      	defer resp.Body.Close()
      
      	// Read response
      	body, err := io.ReadAll(resp.Body)
      	if err != nil {
      		fmt.Printf("Failed to read response: %v\n", err)
      		return
      	}
      
      	// Process response
      	if resp.StatusCode == http.StatusOK {
      		fmt.Println("Request successful:")
      		fmt.Println(string(body))
      	} else {
      		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
      		fmt.Println(string(body))
      	}
      }
      

      Sample response

      {
          "output": {
              "finish_reason": "stop",
              "session_id": "9de268b3d84748b5ac6321aba72b6ecd",
              "text": "Based on your budget, I recommend you consider the **Bailian Zephyr Z9**. This phone has a reference price of 2499-2799 yuan, which is very suitable for needs under 3000 yuan. It has the following features:
      
      - Lightweight 6.4-inch 1080 x 2340 pixel screen design.
      - Paired with 128GB storage and 6GB RAM, capable of meeting daily usage needs.
      - Equipped with a 4000mAh battery, ensuring normal use throughout the day.
      - The rear camera supports 30× digital zoom lens, capable of capturing distant details.
      
      If you don't have particularly high requirements for photography or gaming, then the Bailian Zephyr Z9 should be a good choice."
          },
          "usage": {
              "models": [
                  {
                      "output_tokens": 156,
                      "model_id": "qwen-max",
                      "input_tokens": 1055
                  }
              ]
          },
          "request_id": "8940b597-92e1-9471-b4eb-896e563c479d"
      }
  3. Retrieve specified data from structured documents: Pass the knowledge base ID and "structured data header + value" key-value pairs in rag_options.

    Get structured data key-value pairs (structured_filter): On the Knowledge Base Index page, click View to enter a knowledge base. Then, click View Index.

    Python

    Sample request

    import os
    from http import HTTPStatus
    # Recommended dashscope SDK version >= 1.20.11
    from dashscope import Application
    import dashscope
    dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
    
    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 YOUR_APP_ID with application ID
        prompt='Please recommend a mobile phone under 3000 yuan',
        rag_options={
            "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"],  # Replace with actual knowledge base IDs, separate multiple with commas
             "structured_filter": {  # Structured data key-value pairs, corresponding to structured data, separate multiple with 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'Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output))

    Sample response

    {
        "text": "I recommend the \"Bailian\" phone, which is priced at 2999 yuan, fitting your budget requirement. If you need to know more information, such as performance, appearance, etc., please let me know.",
        "finish_reason": "stop",
        "session_id": "80a3b868b5ce42c8a12f01dccf8651e2",
        "thoughts": null,
        "doc_references": null
    }
    Java

    Sample request

    // Recommended dashscope SDK version >= 2.16.8;
    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.google.gson.JsonObject;
    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 {
            JsonObject structureFilter = new JsonObject();
            structureFilter.addProperty("key1", "value1"); // Structured data key-value pairs
            structureFilter.addProperty("key2", "value2"); // For multiple, repeatedly call addProperty
            ApplicationParam param = ApplicationParam.builder()
                    // If environment variables are not configured, you can replace the following line with .apiKey("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.
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID") // Replace with the actual application ID
                    .prompt("Please recommend a mobile phone around 3000 yuan")
                    .ragOptions(RagOptions.builder()
                            .pipelineIds(List.of("PIPELINE_ID1","PIPELINE_ID2"))  // Replace with actual specified knowledge base IDs, separate multiple with commas
                            .structuredFilter(structureFilter)
                            .build())
                    .build();
    
            Application application = new Application();
            ApplicationResult result = application.call(param);
            System.out.printf("%s\n",
                    result.getOutput().getText());// Process text output only
        }
    
        public static void main(String[] args) {
            try {
                streamCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }

    Sample response

    I recommend the "Bailian" phone, which is priced at 2999.0 yuan, fitting your budget requirement. If you need to know more information about this phone, such as configuration, performance, etc., please let me know, and I will provide you with more detailed information.
    HTTP
    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": "Please recommend a mobile phone around 3000 yuan"
        },
        "parameters":  {
                        "rag_options" : {
                        "pipeline_ids":["YOUR_PIPELINE_ID1"],
                        "structured_filter":{
                        "price":"2999"}
                        }
        },
        "debug": {}
    }'
    Replace YOUR_APP_ID with the actual application ID, YOUR_PIPELINE_ID1 with the specified knowledge base ID.

    Sample response

    {"output":{"finish_reason":"stop","session_id":"d6bc4206f9cc4d368d534f8aa4e502bc",
    "text":"I recommend a mobile phone priced close to 3000 yuan:\n\n- **Bailian phone**, priced at 2999 yuan.
    \n\nThis phone offers good value for money and meets your budget requirements.
    If you need more detailed information about this phone or have other specific requirements (such as camera performance, processor model, etc.), please let me know, and I will try to provide more comprehensive information."},
    "usage":{"models":[{"output_tokens":73,"model_id":"qwen-max","input_tokens":235}]},"request_id":"934e1258-219c-9ef1-8982-fc1bcefb8f11"}%  
    PHP

    Sample request

    <?php
    # If the environment variable is not configured, you can replace the next line with your API key: $api_key="sk-xxx". However, it is not recommended to hardcode the API key directly into the code in a production environment to reduce the risk of API key leakage.
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
    
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    
    // Construct request data
    $data = [
        "input" => [
            'prompt' => 'Please help me recommend a smartphone under 3000 yuan.'
        ],
        "parameters" => [
            'rag_options' => [
                'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'], // Replace with the specified knowledge base IDs; use commas to separate multiple IDs
                "structured_filter" => [ // Structured data key-value pairs; use commas to separate multiple entries
                    "key1" => "value1",
                    "key2" => "value2"
                ]
            ]
        ]
    ];
    
    // Encode data as JSON
    $dataString = json_encode($data);
    
    // Check if json_encode was successful
    if (json_last_error() !== JSON_ERROR_NONE) {
        die("JSON encoding failed with error: " . json_last_error_msg());
    }
    
    // Initialize curl session
    $ch = curl_init($url);
    
    // Set curl options
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key
    ]);
    
    // Execute the request
    $response = curl_exec($ch);
    
    // Check if curl execution was successful
    if ($response === false) {
        die("curl Error: " . curl_error($ch));
    }
    
    // Get HTTP status code
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    // Close curl session
    curl_close($ch);
    
    // Decode response data
    $response_data = json_decode($response, true);
    
    // Handle response
    if ($status_code == 200) {
        if (isset($response_data['output']['text'])) {
            echo "{$response_data['output']['text']}\n";
        } else {
            echo "No text in response.\n";
        }
    } else {
        if (isset($response_data['request_id'])) {
            echo "request_id={$response_data['request_id']}\n";
        }
        echo "code={$status_code}\n";
        if (isset($response_data['message'])) {
            echo "message={$response_data['message']}\n";
        } else {
            echo "message=Unknown error\n";
        }
    }
    ?>
    

    Sample response

    I recommend the "Bailian" phone, which is priced at 2999 yuan, fitting your budget requirement. If you need to know more information about this phone, please let me know.
    Node.js

    Dependency:

    npm install axios

    Sample request

    const axios = require('axios');
    async function callDashScope() {
        // If environment variables are not configured, you can replace the following line with apiKey='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.
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID';  // Replace with the actual application ID
        // YOUR_PIPELINE_ID1 replace with specified knowledge base ID, separate multiple knowledge base IDs with commas
        const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    
        const data = {
            input: {
                prompt: "Please recommend a mobile phone under 3000 yuan"
            },
            parameters: {
                rag_options:{
                    pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'],
                    structured_filter:{
                        'key1':'value1',
                        'key2':'value2'
                    }
                }
            },
            debug: {}
        };
    
        try {
            const response = await axios.post(url, data, {
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json'
                }
            });
    
            if (response.status === 200) {
                console.log(`${response.data.output.text}`);
            } else {
                console.log(`request_id=${response.headers['request_id']}`);
                console.log(`code=${response.status}`);
                console.log(`message=${response.data.message}`);
            }
        } catch (error) {
            console.error(`Error calling DashScope: ${error.message}`);
            if (error.response) {
                console.error(`Response status: ${error.response.status}`);
                console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
            }
        }
    }
    
    callDashScope();

    Sample response

    I recommend the "Bailian" phone, which is priced at 2999 yuan, fitting your budget requirement. If you need to know more details or have other specific requirements, please let me know!
    C#

    Sample request

    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // If environment variables are not configured, you can replace the following line with apiKey="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.
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
            string appId = "YOUR_APP_ID";// Replace with the actual application ID
            // YOUR_PIPELINE_ID1 replace with specified knowledge base ID
            if (string.IsNullOrEmpty(apiKey))
            {
                Console.WriteLine("Please make sure DASHSCOPE_API_KEY is set.");
                return;
            }
    
            string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
            
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                string jsonContent = $@"{{
                    ""input"": {{
                        ""prompt"": ""Please recommend a mobile phone under 3000 yuan""
                    }},
                    ""parameters"": {{
                        ""rag_options"" : {{
                            ""pipeline_ids"":[""YOUR_PIPELINE_ID1""],
                            ""structured_filter"":{{
                                ""price"":""2999""
                            }}
                        }}
                    }},
                    ""debug"": {{}}
                }}";
    
                HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    
                try
                {
                    HttpResponseMessage response = await client.PostAsync(url, content);
    
                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                    else
                    {
                        Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error calling DashScope: {ex.Message}");
                }
            }
        }
    }

    Sample response

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "108e9104568e44f1915fb3d3d44fdc92",
            "text": "I recommend the \"Bailian\" phone, which is priced at 2999.0 yuan, fitting your budget requirement. If you need more information about this phone or other suggestions, please let me know."
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 38,
                    "model_id": "qwen-max",
                    "input_tokens": 104
                }
            ]
        },
        "request_id": "d6d103f4-5c22-9782-9682-45d51a5607f9"
    }
    Go

    Sample request

    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"io"
    	"net/http"
    	"os"
    )
    
    func main() {
    	// If environment variables are not configured, you can replace the following line with apiKey := "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.
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID" // Replace with the actual application ID
    
    	if apiKey == "" {
    		fmt.Println("Please make sure DASHSCOPE_API_KEY is set.")
    		return
    	}
    
    	url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
    
    	// Create request body
    	requestBody := map[string]interface{}{
    		"input": map[string]string{
    			"prompt": "Please recommend a mobile phone under 3000 yuan",
    		},
    		"parameters": map[string]interface{}{
    			"rag_options": map[string]interface{}{
    				"pipeline_ids": []string{"YOUR_PIPELINE_ID1"}, // Replace with specified structured knowledge base ID
    				"structured_filter": map[string]string{
    					"price": "2999", // Structured data key-value pairs
    				},
    			},
    		},
    		"debug": map[string]interface{}{},
    	}
    
    	jsonData, err := json.Marshal(requestBody)
    	if err != nil {
    		fmt.Printf("Failed to marshal JSON: %v\n", err)
    		return
    	}
    
    	// Create HTTP POST request
    	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    	if err != nil {
    		fmt.Printf("Failed to create request: %v\n", err)
    		return
    	}
    
    	// Set request headers
    	req.Header.Set("Authorization", "Bearer "+apiKey)
    	req.Header.Set("Content-Type", "application/json")
    
    	// Send request
    	client := &http.Client{}
    	resp, err := client.Do(req)
    	if err != nil {
    		fmt.Printf("Failed to send request: %v\n", err)
    		return
    	}
    	defer resp.Body.Close()
    
    	// Read response
    	body, err := io.ReadAll(resp.Body)
    	if err != nil {
    		fmt.Printf("Failed to read response: %v\n", err)
    		return
    	}
    
    	// Process response
    	if resp.StatusCode == http.StatusOK {
    		fmt.Println("Request successful:")
    		fmt.Println(string(body))
    	} else {
    		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
    		fmt.Println(string(body))
    	}
    }
    

    Sample response

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "9e0a031b51d1492e8b613ca391b445b0",
            "text": "I recommend you consider the \"Bailian\" phone, which is priced at 2999.0 yuan, fitting your budget requirement. If you need more information about this phone or other recommendations, please let me know."
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 39,
                    "model_id": "qwen-max",
                    "input_tokens": 104
                }
            ]
        },
        "request_id": "036abd4f-10c8-9709-881d-8cc9f8095d54"
    }
View information
  • View retrieval process: When making a call, add has_thoughts to the code and set it to True. The retrieval process will be returned in the thoughts field of output.

  • View answer source: Turn on Show Source in the Retrieval Configuration of the Agent Application and publish the application. image

API references

For a complete list of parameters, see Application calling API.

References

FAQ

When I run a Java code sample, the java: package com.alibaba.dashscope.app does not exist error occured.

  1. Check whether the class names and package names in the import statements are correct.

  2. Add dependencies: If you are using Maven or Gradle for project management, make sure that the DashScope Java SDK dependency library has been added to pom.xml or build.gradle, and is the latest version. You can visit Maven to get the latest version number of DashScope Java SDK.

    <!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>dashscope-sdk-java</artifactId>
        <version>Fill in the latest version number here, 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: 'Fill in the latest version number here, such as 2.16.4'
  3. Upgrade SDK: Older versions of DashScope Java SDK may not include the features or classes you need. If you have already added the DashScope Java SDK dependency library, check whether it is the latest version. If not, upgrade it to the latest version. You can modify the version of DashScope Java SDK to the latest version in the pom.xml or build.gradle file.

    <!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>dashscope-sdk-java</artifactId>
        <version>Please modify the version number here to the latest version</version>
    </dependency>
    // https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
    implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: 'Please modify the version number here to the latest version'
  4. Reload the project for the changes take effect.

  5. Run the code sample again.

    If the problem persists, submit a ticket for further assistance.