Todos los productos
Search
Centro de documentos

Alibaba Cloud Model Studio:Llamada a aplicaciones

Última actualización: Oct 12, 2026

Puede integrar aplicaciones de Model Studio, como agentes, flujos de trabajo u orquestaciones de agentes, en sus sistemas empresariales mediante el SDK de DashScope o HTTP.

Requisitos previos

Puede usar el SDK de DashScope o una interfaz HTTP para llamar a una aplicación de Model Studio.

Independientemente del método de llamada, debe configurar la clave API como una variable de entorno. Si utiliza el SDK de DashScope, también debe instalar el SDK de DashScope.

Uso

Conversación de una sola ronda

Código de ejemplo para el SDK de DashScope o el método HTTP para implementar una conversación de una sola ronda.

Python

Solicitud de ejemplo
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/model-studio/developer-reference/error-code')
else:
    print(response.output.text)
Respuesta de ejemplo
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

Solicitud de ejemplo
// 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/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}
Respuesta de ejemplo
text: I am a large language model developed by Alibaba Cloud, named Qwen.

HTTP

curl

Solicitud de ejemplo
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": {}
}'

Reemplace YOUR_APP_ID con el ID real de la aplicación.

Respuesta de ejemplo
{"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

Solicitud de ejemplo
<?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";}
}
?>
Respuesta de ejemplo
I am a super-large-scale language model developed by Alibaba Cloud, and my name is Qwen.

Node.js

Dependencia:
npm install axios
Solicitud de ejemplo
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();
Respuesta de ejemplo
I am a large-scale language model developed by Alibaba Cloud, and my name is Qwen.

C#

Solicitud de ejemplo
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}");
            }
        }
    }
}
Respuesta de ejemplo
{
    "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

Solicitud de ejemplo
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))
	}
}
Respuesta de ejemplo
{
    "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"
}

Conversación de múltiples rondas

En las conversaciones de múltiples rondas, el LLM puede hacer referencia al historial de conversaciones, lo que lo hace más similar a los escenarios de comunicación cotidiana.

Actualmente, solo las aplicaciones de agente y las aplicaciones de flujo de trabajo de diálogo admiten conversaciones de múltiples rondas.

  • Cuando pasa session_id, la solicitud lleva automáticamente el historial de conversaciones almacenado en la nube.

    Al pasar session_id, se requiere prompt.

  • También puede optar por mantener un arreglo messages. Agregue cada ronda del historial de conversaciones y las nuevas instrucciones al arreglo messages. Luego, pase el historial a través de messages.

    Al pasar messages, prompt es opcional. Si se pasan ambos, prompt se agregará al final de messages como información complementaria.

Si se pasan tanto session_id como messages, se utilizará preferentemente messages.

Almacenamiento en la nube (session_id)

Python

Solicitud de ejemplo
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/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/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()
Respuesta de ejemplo
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

Solicitud de ejemplo
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/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}
Respuesta de ejemplo
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

Solicitud de ejemplo (ronda 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": {}
}'
Respuesta de ejemplo
{
    "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"
}
Solicitud de ejemplo (ronda 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": {}
}'
Respuesta de ejemplo
{
    "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

Solicitud de ejemplo (ronda 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";
    }
}
?>
Respuesta de ejemplo
I am a large-scale language model from Alibaba Cloud, my name is Qwen.
session_id=2e658bcb514f4d30ab7500b4766a8d43
Solicitud de ejemplo (ronda 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";
    }
}
?>
Respuesta de ejemplo
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

Dependencia:
npm install axios
Solicitud de ejemplo (ronda 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();
Respuesta de ejemplo
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
Solicitud de ejemplo (ronda 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();
Respuesta de ejemplo
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#

Solicitud de ejemplo (ronda 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}");
            }
        }
    }
}
Respuesta de ejemplo
{
    "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"
}
Solicitud de ejemplo (ronda 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}");
            }
        }
    }
}
Respuesta de ejemplo
{
    "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

Solicitud de ejemplo (ronda 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))
	}
}
Respuesta de ejemplo
{
    "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"
}
Solicitud de ejemplo (ronda 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))
	}
}
Respuesta de ejemplo
{
    "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"
}

Reemplace YOUR_APP_ID con el ID real de la aplicación. Para la ronda 2, reemplace el session_id con el session_id real devuelto en la ronda 1.

Autogestión (mensajes)

Python

Solicitud de ejemplo
# 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/model-studio/error-code')
else:
    print('%s\n' % (response.output.text))
Respuesta de ejemplo
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

Solicitud de ejemplo
// 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/model-studio/error-code");
        }
        System.exit(0);
    }
}
Respuesta de ejemplo
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

Solicitud de ejemplo
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": {}
}'
Respuesta de ejemplo
{"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

Solicitud de ejemplo
<?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";
    }
}
?>
Respuesta de ejemplo
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

Dependencia:
npm install axios
Solicitud de ejemplo
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();
Respuesta de ejemplo
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#

Solicitud de ejemplo
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}");
            }
        }
    }
}
Respuesta de ejemplo
{
    "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

Solicitud de ejemplo
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))
	}
}
Respuesta de ejemplo
{
    "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"
}

Pasar parámetros personalizados

Para adaptar el mismo agente o flujo de trabajo a diferentes escenarios empresariales, puede configurar parámetros personalizados para complementos o nodos, y pasar parámetros a través de biz_params al llamar a la aplicación. Para saber cómo configurar los parámetros, consulte Transferencia de parámetros de aplicación. Código de ejemplo:

  1. Complementos personalizados parámetros: Páselos a través de la Aplicación de Agente asociada o a través del Nodo de Complemento de la Aplicación de Flujo de Trabajo asociada.

    Puede pasar parámetros e información de autenticación a nivel de usuario para complementos personalizados:

    • Parámetros: user_defined_params.
    • Autenticación a nivel de usuario: user_defined_tokens. user_token es la información de autenticación requerida por el complemento, como la DASHSCOPE_API_KEY.

    El siguiente ejemplo es una Aplicación de Agente que requiere el parámetro index y la información de autenticación a nivel de usuario del complemento asociado.

    Las herramientas de complemento solo se pueden asociar con Aplicaciones de Agente en el mismo espacio de trabajo.

    Reemplace your_plugin_code con el ID de la herramienta de complemento asociada que se muestra en la tarjeta del complemento, y pase los pares clave-valor de los parámetros de entrada. En este ejemplo, article_index con un valor de 2.

    Paso de parámetros

    Python

    Solicitud de ejemplo
    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/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # Process text output only
        # print('%s\n' % (response.usage))
    
    Respuesta de ejemplo
    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

    Solicitud de ejemplo
    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/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }
    
    Respuesta de ejemplo
    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

    Solicitud de ejemplo
    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":{}
    }'
    

    Reemplace YOUR_APP_ID con el ID real de la aplicación.

    Respuesta de ejemplo
    {"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

    Solicitud de ejemplo
    <?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";}
    }
    ?>
    
    Respuesta de ejemplo
    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

    Dependencia:
    npm install axios
    
    Solicitud de ejemplo
    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();
    
    Respuesta de ejemplo
    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#

    Solicitud de ejemplo
    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}");
                }
            }
        }
    }
    
    Respuesta de ejemplo
    {
        "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

    Solicitud de ejemplo
    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))
     }
    }
    
    Respuesta de ejemplo
    {
        "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"
    }
    

    Autenticación a nivel de usuario

    Python

    Solicitud de ejemplo
    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/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # Process text output only
        # print('%s\n' % (response.usage))
    
    Respuesta de ejemplo
    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

    Solicitud de ejemplo
    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/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }
    
    Respuesta de ejemplo
    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

    Solicitud de ejemplo
    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":{}
    }'
    

    Reemplace YOUR_APP_ID con el ID real de la aplicación.

    Respuesta de ejemplo
    {"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

    Solicitud de ejemplo
    <?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";}
    }
    ?>
    
    Respuesta de ejemplo
    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

    Dependencia:
    npm install axios
    
    Solicitud de ejemplo
    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();
    
    Respuesta de ejemplo
    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#

    Solicitud de ejemplo
    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}");
                }
            }
        }
    }
    
    Respuesta de ejemplo
    {
        "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

    Solicitud de ejemplo
    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))
     }
    }
    
    Respuesta de ejemplo
    {
        "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. Parámetros de nodo personalizados: Páselos a través del Nodo de Inicio de la Aplicación de Flujo de Trabajo, o a través del Nodo de Aplicación de la Aplicación de Orquestación de Agentes.

    En el siguiente ejemplo, la Aplicación de Flujo de Trabajo define un parámetro city en el Nodo de Inicio. Inserte las variables city y query en el Prompt, y luego Publique la aplicación.

    imagen

    Al realizar la llamada, pase city a través de biz_params y pase query a través de prompt.

    Python

    Solicitud de ejemplo
    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/model-studio/developer-reference/error-code')
    else:
        print(f'{response.output.text}')  # Process text output only
    
    Respuesta de ejemplo
    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

    Solicitud de ejemplo
    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/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }
    
    Respuesta de ejemplo
    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

    Solicitud de ejemplo
    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":  {}
    }'
    

    Reemplace YOUR_APP_ID con el ID real de la aplicación.

    Respuesta de ejemplo
    {
      "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

    Solicitud de ejemplo
    <?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";
        }
    }
    
    Respuesta de ejemplo
    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

    Dependencia:
    npm install axios
    
    Solicitud de ejemplo
    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();
    
    Respuesta de ejemplo
    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#

    Solicitud de ejemplo
    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}");
                }
            }
        }
    }
    
    Respuesta de ejemplo
    {
        "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

    Solicitud de ejemplo
    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))
     }
    }
    
    Respuesta de ejemplo
    {
        "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"
    }
    

Salida por secuencias

En el modo de salida por secuencias, el modelo genera resultados intermedios, y el resultado final se forma concatenando estos resultados intermedios. Puede leer a medida que el modelo genera la salida, reduciendo así el tiempo de espera para la respuesta del modelo. Dependiendo del método de llamada, puede configurar parámetros para implementar la salida por secuencias:

  • SDK de Python: Establezca stream en True.
  • SDK de Java: Llame a través de la interfaz streamCall.
  • HTTP: Especifique X-DashScope-SSE como enable en el encabezado.

De forma predeterminada, la salida en streaming no es incremental, lo que significa que cada retorno incluye todo el contenido generado previamente. Para utilizar la salida en streaming incremental, establezca el parámetro incremental_output (incrementalOutput para Java) en true. Para HTTP, establezca incremental_output en true y colóquelo en el objeto de parámetros.

Ejemplos:

  • Para la Aplicación de Agente:

    Python

    Solicitud de ejemplo
    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/model-studio/developer-reference/error-code')
        else:
            print(f'{response.output.text}\n')  # Process to output only the text
    
    Respuesta de ejemplo
    I am
    
    Alibaba
    
    Cloud
    
    's large-scale language model
    
    , my name is
    
    Qwen.
    

    Java

    Solicitud de ejemplo
    // 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/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }
    
    Respuesta de ejemplo
    I am Alibaba
    Cloud
    's large-scale language
    model, my name is
    Qwen
    .
    

    HTTP

    curl

    Solicitud de ejemplo
    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": {}
    }'
    

    Reemplace YOUR_APP_ID con el ID real de la aplicación.

    Respuesta de ejemplo
    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

    Solicitud de ejemplo
    <?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";
    }
    ?>
    
    Respuesta de ejemplo
    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

    Dependencia:
    npm install axios
    
    Solicitud de ejemplo

    1. Generar respuesta completa

    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();
    

    Expanda el panel para ver el código de ejemplo:

    2. Generar solo el campo de texto

    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();
    
    Respuesta de ejemplo
    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"}
    
    I am
    Alibaba
    Cloud
    's large-scale
    language model, I
    am called
    Qwen.
    

    C#

    Solicitud de ejemplo
    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}");
                }
            }
        }
    }
    
    Respuesta de ejemplo
    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

    Solicitud de ejemplo
    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
          }
      }
    }
    
    Respuesta de ejemplo
    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"}
    
  • La Aplicación de flujo de trabajo proporciona dos modos de salida por secuencias, determinados por el valor de flow_stream_mode.

    Valores de parámetros y métodos de uso:

    • full_thoughts (valor predeterminado):

      • Descripción: Los resultados de transmisión de todos los nodos se generarán en el campo thoughts.
      • Requisito: También debe establecer has_thoughts en True.
    • agent_format:

      • Descripción: El mismo modo de salida que las aplicaciones de agente.
      • Efecto: En la consola, puede activar el interruptor de Respuesta para un nodo específico, y los resultados de transmisión de ese nodo se incluirán en el campo text de output.
      • Escenario: Adecuado para escenarios donde solo le interesa la salida de nodos intermedios específicos.

      El interruptor de Respuesta solo está disponible en nodos de Conversión de Texto, nodos LLM y nodos Final (el interruptor está activado de forma predeterminada para los nodos Final). Los nodos que no admiten salida por secuencias generarán su contenido todo a la vez.

    Ejemplo:

    full_thoughts

    Esta es una Aplicación de flujo de trabajo publicada con salida por secuencias.

    imagen

    Python

    Solicitud de ejemplo
    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/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
    
    Respuesta de ejemplo
    [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

    Solicitud de ejemplo
    // 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/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }
    
    Respuesta de ejemplo
    [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

    Solicitud de ejemplo
    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": {}
    }'
    

    Reemplace YOUR_APP_ID con el ID real de la aplicación.

    Respuesta de ejemplo
    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

    Solicitud de ejemplo
    <?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";
    }
    ?>
    
    Respuesta de ejemplo
    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

    Dependencia:

    npm install axios
    
    Solicitud de ejemplo
    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();
    
    Respuesta de ejemplo
    /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#

    Solicitud de ejemplo
    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}");
                }
            }
        }
    }
    
    Respuesta de ejemplo
    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

    Solicitud de ejemplo
    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)
      }
    }
    
    Respuesta de ejemplo
    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"}
    
    • Cada elemento en thoughts corresponde a los detalles de ejecución de un nodo. A continuación se muestra un ejemplo de resultado de un nodo LLM.
    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"
    }
    

    Si está interesado en los resultados de transmisión de un nodo LLM (usando LLM_j45e en el ejemplo anterior), puede centrarse en la salida del nodo con nodeId LLM_j45e en cada envío de thoughts.

    • Si un nodo falla, toda la tarea también fallará.

    agent_format

    Esta es una Aplicación de flujo de trabajo publicada. El interruptor de Respuesta está activado solo para el primer Nodo LLM, centrándose únicamente en los resultados de este nodo.

    imagen

    Python

    Solicitud de ejemplo
    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/model-studio/developer-reference/error-code')
        else:
            print(f'{response.output.text}\n')  # Process output text, results are returned in text
    
    Respuesta de ejemplo
    West Lake
    
    Fish in Vinegar Sauce,
    
    Longjing Shrimp
    
    ,Dongpo Pork
    
    ,Zhiwei Small
    
    Steamed Buns,Beggar's Chicken
    

    HTTP

    curl

    Solicitud de ejemplo
    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": {}
    }'
    
    Respuesta de ejemplo
    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

    Solicitud de ejemplo
    <?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";
    }
    ?>
    
    Respuesta de ejemplo
    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

    Dependencia:

    npm install axios
    
    Solicitud de ejemplo
    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();
    
    Respuesta de ejemplo
    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#

    Solicitud de ejemplo
    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}");
                }
            }
        }
    }
    
    Respuesta de ejemplo
    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

    Solicitud de ejemplo
    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)
      }
    }
    
    Respuesta de ejemplo
    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"}
    

Recuperar base de conocimientos

La base de conocimientos es la capacidad RAG de Model Studio. Puede complementar eficazmente los modelos con conocimientos privados y actualizados. Puede especificar el alcance de recuperación al llamar a las Aplicaciones de Agente para mejorar la precisión de las respuestas.

Antes de comenzar

En la consola de Model Studio, active la Aumentación de Recuperación de Base de Conocimientos para su Aplicación de Agente. Luego, Publique la aplicación.

Omita este requisito previo para las Aplicaciones RAG.

Especificar alcance de recuperación

  1. Para recuperar una base de conocimientos específica, elija uno de los siguientes métodos:

    • En la consola, haga clic en Configure Knowledge Base en la aplicación y seleccione la base de conocimientos especificada. Luego, Publique la aplicación.

    • No asocie la base de conocimientos especificada en la consola. Pase el ID de la base de conocimientos a través de rag_options al realizar una llamada a la API;

    • Asocie la base de conocimientos especificada en la consola y pase el ID de la base de conocimientos a través de rag_options al realizar una llamada a la API.

      En este caso, solo se recuperará la base de conocimiento pasada durante la llamada. Por ejemplo, una Aplicación de Agente está asociada con la base de conocimiento A. Sin embargo, usted especifica la base de conocimiento B al realizar la llamada a la API. Entonces, la base de conocimiento A no se recuperará y solo se recuperará la base de conocimiento B.

    Para obtener el ID de la base de conocimiento (pipeline_ids): Puede obtenerlo en la página de Base de Conocimiento, o utilizar el Data.Id devuelto por la API CreateIndex. CreateIndex solo admite bases de conocimiento no estructuradas.

    Bailian Phones Specifications.docx se utiliza en los siguientes ejemplos como una base de conocimientos no estructurada.

    Python

    Solicitud de ejemplo
    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/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # Process text output only
        # print('%s\n' % (response.usage))
    
    Respuesta de ejemplo
    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

    Solicitud de ejemplo
    // 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/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }
    
    Respuesta de ejemplo
    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

    Solicitud de ejemplo
    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": {}
    }'
    

    Reemplace YOUR_APP_ID con el ID real de la aplicación, y YOUR_PIPELINE_ID1 con el ID de la base de conocimientos especificada.

    Respuesta de ejemplo
    {"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

    Solicitud de ejemplo
    <?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";
        }
    }
    ?>
    
    Respuesta de ejemplo
    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

    Dependencia:
    npm install axios
    
    Solicitud de ejemplo
    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();
    
    Respuesta de ejemplo
    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#

    Solicitud de ejemplo
    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}");
                }
            }
        }
    }
    
    Respuesta de ejemplo
    {
        "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

    Solicitud de ejemplo
    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))
     }
    }
    
    Respuesta de ejemplo
    {
        "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. Recuperar documentos no estructurados especificados: Pase el ID de la base de conocimientos, el ID del documento, las etiquetas o los metadatos (pares clave-valor) en rag_options.

    El ID del documento, las etiquetas y los metadatos solo son efectivos para documentos no estructurados.

    • Cómo obtenerlos:

      • ID de documento (file_ids): Puede encontrarlo en la página de Datos de la Aplicación, o usar el ID devuelto por la API AddFile al importar documentos.
      • Etiquetas de documentos: Puede encontrar las etiquetas en la página de Datos de la Aplicación, u obtenerlas de la API DescribeFile.
      • Metadatos del documento: En la página de Base de Conocimientos, haga clic en View para ingresar a una base de conocimientos. Luego, haga clic en Metadata Information.
    • Puede especificar varios ID de documento, pero los documentos deben haber sido incluidos en los índices de conocimiento.

    • Al especificar ID de documentos, también debe especificar el ID de la base de conocimientos a la que pertenecen dichos documentos.

    • Solo se recuperarán los documentos especificados. Por ejemplo, una Aplicación de Agente asocia la base de conocimientos A, pero la llamada a la API especifica documentos de la base de conocimientos B. Entonces, no se recuperarán documentos de A, solo se recuperarán documentos de B.

      Bailian Phones Specifications.docx se utiliza en los siguientes ejemplos como una base de conocimientos no estructurada.

      Python

      Solicitud de ejemplo
      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/model-studio/developer-reference/error-code')
      else:
          print('%s\n' % (response.output))
      
      Respuesta de ejemplo
      {
          "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

      Solicitud de ejemplo
      // 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/model-studio/developer-reference/error-code");
              }
              System.exit(0);
          }
      }
      
      Respuesta de ejemplo
      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

      Solicitud de ejemplo
      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":"Alice"},
                          "tags":"mobile phone"
                          }
          },
          "debug": {}
      }'
      

      Reemplace YOUR_APP_ID con el ID real de la aplicación, YOUR_PIPELINE_ID1 con el ID de la base de conocimientos especificada, YOUR_FILE_ID1 con el ID del documento no estructurado especificado, y los pares clave-valor en metadata_filter con los metadatos reales.

      Respuesta de ejemplo
      {"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

      Solicitud de ejemplo
      <?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";
          }
      }
      ?>
      
      Respuesta de ejemplo
      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

      Dependencia:
      npm install axios
      
      Solicitud de ejemplo
      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();
      
      Respuesta de ejemplo
      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#

      Solicitud de ejemplo
      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"":""Alice""
                              }},
                      ""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}");
                  }
              }
          }
      }
      
      Respuesta de ejemplo
      {
          "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

      Solicitud de ejemplo
      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": "Alice", // 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))
          }
      }
      
      Respuesta de ejemplo
      {
          "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. Recuperar datos especificados de documentos estructurados: Pase el ID de la base de conocimientos y los pares clave-valor de "encabezado de datos estructurados + valor" en rag_options.

    Obtener pares clave-valor de datos estructurados (structured_filter): En la página de Base de Conocimientos, haga clic en View para ingresar a una base de conocimientos. Luego, haga clic en View Index.

    Python

    Solicitud de ejemplo
    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/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output))
    
    Respuesta de ejemplo
    {
        "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

    Solicitud de ejemplo
    // 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/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }
    
    Respuesta de ejemplo
    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

    Solicitud de ejemplo
    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": {}
    }'
    

    Reemplace YOUR_APP_ID con el ID real de la aplicación, y YOUR_PIPELINE_ID1 con el ID de la base de conocimientos especificada.

    Respuesta de ejemplo
    {"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

    Solicitud de ejemplo
    <?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";
        }
    }
    ?>
    
    Respuesta de ejemplo
    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

    Dependencia:
    npm install axios
    
    Solicitud de ejemplo
    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();
    
    Respuesta de ejemplo
    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#

    Solicitud de ejemplo
    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}");
                }
            }
        }
    }
    
    Respuesta de ejemplo
    {
        "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

    Solicitud de ejemplo
    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))
     }
    }
    
    Respuesta de ejemplo
    {
        "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"
    }
    
Ver información

Ver proceso de recuperación: Al realizar una llamada, agregue has_thoughts al código y establézcalo en True. El proceso de recuperación se devolverá en el campo thoughts de output.

Ver fuente de la respuesta: Active Mostrar Fuente en la Configuración de Recuperación de la Aplicación de Agente y publique la aplicación. imagen

Referencia de API

Para obtener una lista completa de parámetros, consulte Referencia de API de flujo de trabajo y aplicación de agente heredada para DashScope.

Códigos de error

Si una llamada falla, consulte Códigos de error para solucionar problemas.

Referencias

FAQ

¿Cómo soluciono la excepción "java: package com.alibaba.dashscope.app does not exist" al ejecutar un ejemplo de código Java?

  1. Asegúrese de que los nombres de clase y paquete en sus declaraciones de importación sean correctos.
  2. Agregue la dependencia: Si usa Maven o Gradle, asegúrese de que la dependencia del SDK de Java de DashScope esté en su archivo pom.xml o build.gradle y sea la versión más reciente. Puede encontrar el número de la última versión del SDK de Java de DashScope en Maven.
<!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dashscope-sdk-java</artifactId>
    <version>Enter the latest version, e.g., 2.16.4</version>
</dependency>
// https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: 'Enter the latest version, e.g., 2.16.4'
  1. Actualice el SDK: Una versión anterior del SDK de Java de DashScope podría carecer de las funciones o clases que necesita. Si su versión está desactualizada, actualícela modificando el número de versión en su archivo pom.xml o build.gradle.
<!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dashscope-sdk-java</artifactId>
    <version>Replace this with the latest version number</version>
</dependency>
// https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: 'Replace this with the latest version number'
  1. Recargue el proyecto para aplicar los cambios.

  2. Vuelva a ejecutar el ejemplo de código.

    Si el problema persiste, consulte el foro de desarrolladores para buscar problemas similares y sus soluciones, o envíe un ticket.