Todos los productos
Search
Centro de documentos

Alibaba Cloud Model Studio:Referencia de la API DashScope para aplicaciones

Última actualización: Oct 12, 2026

Parámetros de entrada y salida para llamar a aplicaciones de Model Studio (Agente, Flujo de Trabajo) a través de la API DashScope, con ejemplos para escenarios típicos.

ImportanteEste tema es aplicable únicamente a la región de Singapur.

Guías relacionadas

Invocación de aplicación.

Requisitos previos

Complete las siguientes tareas:

  1. Crear una aplicación: Vaya a Gestión de Aplicaciones para crear una aplicación de Model Studio y obtener su ID de aplicación.
  2. Obtener una clave de API: Obtenga su clave de API en Gestión de Claves y configure la clave de API como variable de entorno.
  3. Instalar el SDK (opcional): Si utiliza un SDK para realizar llamadas, instale el SDK de DashScope para su lenguaje de programación.

Métodos de invocación

  • Llamada de API HTTP

    URL de solicitud: POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion

    Reemplace APP_ID con su ID de aplicación real.

  • Llamada de SDK

    SDK de Python/Java: El endpoint correcto está configurado de forma predeterminada.

    Endpoint personalizado: Configúrelo mediante el parámetro base_url.

Cuerpo de la solicitud

app_idstring(obligatorio)

ID de aplicación.

Obtenga el ID de la aplicación desde la tarjeta de la aplicación en la página de Gestión de Aplicaciones.

En el SDK de Java, esto es appId. Al llamar mediante HTTP, coloque su ID de aplicación real en la URL, reemplazando APP_ID.

promptstring(obligatorio)

Entrada del usuario que guía a la aplicación para generar una respuesta.

Al llamar mediante HTTP, coloque prompt en el objeto input.

session_idstring (opcional)

Identificador del historial de conversación.

Pase session_id para incluir automáticamente el historial de conversaciones almacenado en la nube. Requiere prompt.

Caduca después de 1 hora de inactividad.

En el SDK de Java, esto es setSessionId. Al llamar mediante HTTP, coloque session_id en el objeto input.

mensajesarray(opcional)

Contexto de conversación pasado al modelo, organizado en orden cronológico.

Para conversaciones de múltiples turnos, pase messages en lugar de prompt o session_id.

Si pasa tanto session_id como messages, el modelo utiliza el contenido en messages e ignora session_id y prompt.

Al llamar mediante HTTP, coloque messages en el objeto input.

Para utilizar este parámetro, su versión del SDK de Python Dashscope debe ser al menos 1.20.14, y su versión del SDK de Java Dashscope debe ser al menos 2.17.0.

Tipos de mensajes

Mensaje del sistemaobject (opcional)

Mensaje del sistema que establece el rol del modelo, el tono, los objetivos de la tarea o las restricciones. Generalmente se coloca primero en el arreglo messages.

Propiedades

contenidostring(obligatorio)

Instrucción del sistema que define el rol del modelo, las pautas de comportamiento, el estilo de respuesta y las restricciones de la tarea.

rolstring(obligatorio)

Rol del mensaje del sistema, fijado como system.

Mensaje de usuarioobject(obligatorio)

Mensaje de usuario que pasa preguntas, instrucciones o contexto al modelo.

Propiedades

contenidostring(obligatorio)

Contenido del mensaje.

Propiedades

textostring(obligatorio)

Texto de entrada.

rolstring(obligatorio)

Rol del mensaje de usuario, fijado como user.

Mensaje del asistenteobject (opcional)

Respuesta del modelo. Normalmente se utiliza como contexto que se pasa de nuevo al modelo en conversaciones de múltiples turnos.

Propiedades

contenidostring(obligatorio)

Contenido de texto de la respuesta del modelo.

rolstring(obligatorio)

Rol del mensaje del asistente, fijado como assistant.

espacio de trabajo string (opcional)

Identificador del espacio de trabajo. Documentación relacionada: Obtener ID del espacio de trabajo.

Solo necesita pasar el workspace ID al invocar aplicaciones en un subespacio de trabajo.

Al llamar mediante HTTP, especifique el encabezado X-DashScope-WorkSpace.

stream boolean (opcional) El valor predeterminado es False

Habilitar salida en streaming.

Establezca en True para mejorar la experiencia de lectura y reducir el riesgo de tiempo de espera.

Valores de parámetro:

  • False (predeterminado): El modelo devuelve todo el contenido de una sola vez después de que se completa la generación.
  • True (recomendado): El modelo transmite el contenido de forma incremental. Lea los fragmentos en tiempo real para ensamblar la respuesta completa.

Para implementar la salida de transmisión con el SDK de Java, utilice la interfaz streamCall. Para implementar la salida de transmisión mediante HTTP, configure el encabezado X-DashScope-SSE en enable.

incremental_output boolean (opcional) El valor predeterminado es False

Habilite la salida incremental en modo streaming.

Establezca en True para mejorar la experiencia de lectura.

Valores de parámetro:

  • False (predeterminado): Cada salida contiene la secuencia completa generada hasta el momento.
I
I like
I like apple
I like apple.
  • True (recomendado): Salida incremental. Cada fragmento contiene solo contenido nuevo. Lea los segmentos en tiempo real para ensamblar el resultado completo.
I
like
apple
.

En el SDK de Java, esto es incrementalOutput. Al llamar mediante HTTP, coloque incremental_output en el objeto parameters.

flow_stream_mode string (opcional) El valor predeterminado es full_thoughts

Modo de salida en streaming para la Aplicación de Flujo de Trabajo.

Valores de parámetro:

  • message_format (recomendado):

    Devuelve los resultados de nodos específicos (ya sea un nodo de Salida o un nodo Final) en el campo message.

    ImportanteEn la aplicación de consola, active el interruptor de Transmisión para el nodo objetivo a fin de devolver resultados en modo de transmisión. Si está desactivado, el resultado final del nodo se devuelve de una sola vez.

    En el SDK de Java, esto es FlowStreamMode.MESSAGE_FORMAT.

  • full_thoughts (predeterminado):

    Devuelve los resultados de todos los nodos en el campo thoughts.

    ImportanteAl usar este modo, también debe establecer el parámetro has_thoughts en True.

    En el SDK de Java, esto es FlowStreamMode.FULL_THOUGHTS.

  • agent_format:

    Devuelve los resultados de nodos especificados (nodos LLM o nodos finales) en el campo text.

    En la aplicación de consola, active el interruptor de Respuesta para el nodo objetivo a fin de devolver resultados en modo de transmisión.

    ImportanteNo utilice este modo con nodos paralelos, ya que puede causar mezcla de contenido. Asegúrese de que los nodos activados tengan un orden de ejecución claro.

    En el SDK de Java, esto es FlowStreamMode.AGENT_FORMAT.

Su versión del SDK de Python debe ser al menos 1.24.0, y su versión del SDK de Java debe ser al menos 2.21.0. Al llamar mediante HTTP, coloque flow_stream_mode en el objeto parameters.

biz_paramsobject (opcional)

Pase parámetros para variables personalizadas, nodos o complementos.

En el SDK de Java, esto es bizParams. Al llamar mediante HTTP, coloque biz_params en el objeto input.

Para la Aplicación de Flujo de Trabajo, pase las variables personalizadas para el nodo de inicio directamente, por ejemplo:

biz_params = {"city": "Hangzhou"}

Para la Aplicación Agente, pase las variables de prompt o las variables del complemento utilizando los siguientes campos:

Propiedades

user_defined_params object (opcional)

Parámetros de plugin personalizados.

Los complementos no pueden duplicarse. Máximo: 10.

Propiedades

tool_idstring (opcional)

ID del complemento, disponible en la tarjeta del complemento.

${plugin_params}string (opcional)

El objeto más interno contiene múltiples pares clave-valor. Cada par clave-valor representa un nombre de parámetro definido por el usuario y su valor especificado. Por ejemplo:

"article_index": 2

Pasos de uso:

  1. Asocie el complemento especificado con su aplicación y Publique la aplicación.
  2. Pase la información del complemento a través de este parámetro durante las llamadas a la API.

Puede proporcionar múltiples pares clave-valor, donde cada clave es el TOOL_ID del complemento y el valor es el objeto de parámetro requerido por ese complemento. Ejemplo:

"user_defined_params": {
        "<TOOL_ID>": {
            "article_index": 2},
        "<TOOL_ID>": {
            "article_index": 8}
        }

user_defined_tokens object (opcional)

Autenticación a nivel de usuario para complementos personalizados.

Los complementos no pueden duplicarse. Máximo: 10.

Propiedades

tool_idstring (opcional)

ID del complemento, disponible en la tarjeta del complemento. Pase a través del campo <TOOL_ID>.

user_token string (opcional)

Pase la información de autenticación de usuario requerida por este complemento, como el valor real de DASHSCOPE_API_KEY.

Pasos de uso:

  1. Asocie el complemento especificado con su aplicación y Publique la aplicación.
  2. Pase la información de autenticación a nivel de usuario del complemento a través de este parámetro durante las llamadas a la API.

Puede proporcionar múltiples pares clave-valor, donde cada clave es el TOOL_ID del complemento y el valor es el objeto user_token.

has_thoughts boolean (opcional) El valor predeterminado es False

Controla si la invocación de complementos y la recuperación de conocimiento aparecen en el campo thoughts.

Valores de parámetro:

  • True: Salida incluida.
  • False (predeterminado): Salida no incluida.

En el SDK de Java, esto es hasThoughts. Al llamar mediante HTTP, coloque has_thoughts en el objeto parameters.

rag_options object (opcional)

Configure los parámetros de recuperación, incluida la recuperación de bases de conocimiento o documentos específicos.

NotaSolo la Aplicación Agente admite este parámetro.

En el SDK de Java, esto es ragOptions. Al llamar mediante HTTP, coloque rag_optionsen el objeto parameters.

Propiedades

pipeline_ids array(obligatorio)

Una lista que contiene uno o más IDs de base de conocimiento. Máximo de 5.

Recupera todos los documentos dentro de las bases de conocimiento especificadas.

Cómo obtenerlo:

  • Página de Base de Conocimiento para obtener el ID de la base de conocimiento;
  • O bien a través de la API CreateIndex (admite solo bases de conocimiento no estructuradas), que devuelve Data.Id.

En el SDK de Java, esto es pipelineIds.

file_idsarray(opcional)

Una lista que contiene uno o más IDs de documentos no estructurados. Máximo de 5.

Recupera documentos no estructurados dentro de las bases de conocimiento especificadas.

Al pasar IDs de documentos, también debe pasar el ID de la base de conocimiento a la que pertenecen estos documentos en el campo pipeline_ids.

Cómo obtenerlo:

En el SDK de Java, esto es fileIds.

metadata_filterobject (opcional)

Filtre documentos no estructurados especificando uno o más pares clave-valor de metadatos dentro de la base de conocimiento especificada.

Requisitos previos:

Al pasar metadatos, también debe pasar el ID de la base de conocimiento a la que pertenecen dichos metadatos en el campo pipeline_ids.

Cómo verlo:

  • Visite la página de Base de Conocimiento, haga clic en View DetailsMetadata Information en la tarjeta de la base de conocimiento para verlo.
  • O bien obtenerlo a través de la API ListChunks.

Este objeto consta de uno o más pares clave-valor:

  • Clave: tipo String, que representa el nombre de los metadatos.

  • Valor:

    • Coincidencia exacta: El valor es un String, lo que significa que solo se recuperan los documentos cuyo valor de campo coincide exactamente con esta cadena.

      • Ejemplo: "author": "John.Doe"
    • Coincidencia "OR" de valores múltiples: El valor es un Array (arreglo) o List (lista) que contiene múltiples Strings. Esto significa que se recuperan los documentos cuyo valor de campo coincide con cualquier valor en el arreglo (lógica OR).

      • Ejemplo: "source": ["internal_wiki", "public_docs"]

Lógica de combinación: Las diferentes claves utilizan lógica "AND". Por ejemplo, "author": "John.Doe", "source": ["internal_wiki", "public_docs"] significa filtrar documentos escritos por "John.Doe" Y obtenidos de "internal_wiki" O "public_docs".

En el SDK de Java, esto es metadataFilter.

etiquetas array (opcional)

Una lista que contiene una o más etiquetas para documentos no estructurados.

Puede recuperar documentos no estructurados con esta etiqueta.

Cómo verlo:

Conversación de un solo turno

Python

Ejemplo de solicitud
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(
    # Configure API key: use environment variable or replace with your Model Studio API key (do not hard code in production).
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    app_id='APP_ID',# Replace with your actual application ID
    prompt='Who are you?')

if response.status_code != HTTPStatus.OK:
    print(f'request_id={response.request_id}')
    print(f'code={response.status_code}')
    print(f'message={response.message}')
    print(f'See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
else:
    print(response.output.text)

Java

Ejemplo de solicitud
// We recommend 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 you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("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("See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

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

Reemplace APP_ID con su ID de aplicación real.

PHP

Ejemplo de solicitud
<?php

# If you have not configured an environment variable, replace the following line with $api_key="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = '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 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";}
}
?>

Node.js

Instale las dependencias requeridas:
npm install axios
Ejemplo de solicitud
const axios = require('axios');

async function callDashScope() {
    // If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with your 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();

C#

Ejemplo de solicitud
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        //If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments 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 = "APP_ID"; // Replace with your 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}");
            }
        }
    }
}

Go

Ejemplo de solicitud
package main

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

func main() {
	// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with your actual application ID

	if apiKey == "" {
		fmt.Println("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
	}

	// Handle 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))
	}
}

Conversación de múltiples turnos

Habilite conversaciones de múltiples turnos mediante session_id o messages.

Python

Ejemplo de solicitud
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(
        # Configure API key: use environment variable or replace with your Model Studio API key (do not hard code in production).
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='APP_ID',  # Replace with your actual application ID
        prompt='Who are you?')

    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
        return response

    responseNext = Application.call(
                # Configure API key: use environment variable or replace with your Model Studio API key (do not hard code in production).
                api_key=os.getenv("DASHSCOPE_API_KEY"),
                app_id='APP_ID',  # Replace with your 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'See documentation: 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()

Java

Ejemplo de solicitud
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 you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // Replace with your actual application ID
                .appId("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("See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

Ejemplo de solicitud (ronda anterior de conversación)
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Who are you?"
    },
    "parameters":  {},
    "debug": {}
}'
Ejemplo de solicitud (siguiente turno)
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/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": {}
}'

PHP

Ejemplo de solicitud (ronda anterior de conversación)
<?php
# If you have not configured an environment variable, replace the following line with $api_key="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = '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 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";
    };
    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";}
}
?>
Ejemplo de solicitud (siguiente turno)
<?php
# If you have not configured an environment variable, replace the following line with $api_key="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = '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' => 'What skills do you have?',
        // Replace with the actual session_id returned from the previous conversation
        'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
    ]
];

// Encode 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";
    };
    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";}
}
?>

Node.js

Instale las dependencias requeridas:
npm install axios
Solicitud de ejemplo (conversación previa)
const axios = require('axios');

async function callDashScope() {
    // If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with your 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();
Ejemplo de solicitud (siguiente turno)
const axios = require('axios');

async function callDashScope() {
    // If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with your 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();

C#

Ejemplo de solicitud (primer turno)
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        //If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments 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 = "APP_ID"; // Replace with your 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}");
            }
        }
    }
}
Ejemplo de solicitud (siguiente turno)
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        //If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments 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 = "APP_ID"; // Replace with your 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}");
            }
        }
    }
}

Go

Ejemplo de solicitud (ronda anterior de conversación)
package main

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

func main() {
	// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with your actual application ID

	if apiKey == "" {
		fmt.Println("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
	}

	// Handle 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))
	}
}
Ejemplo de solicitud (siguiente turno)
package main

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

func main() {
	// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with your actual application ID

	if apiKey == "" {
		fmt.Println("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
	}

	// Handle 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))
	}
}

Reemplace APP_ID con su ID de aplicación real. Reemplace el valor de session_id en los parámetros de entrada del siguiente turno con el valor real de session_id devuelto de la conversación anterior.

Pasar parámetros

Pase parámetros personalizados mediante biz_params.

Python

Ejemplo de solicitud
import os
from http import HTTPStatus
# We recommend 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 = {
    # Pass custom plug-in input parameters for agent applications. Replace <TOOL_ID> with your custom plug-in ID.
    "user_defined_params": {
        "<TOOL_ID>": {
            "article_index": 2}}}
response = Application.call(
        # Configure API key: use environment variable or replace with your Model Studio API key (do not hard code in production).
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='APP_ID',
        prompt='Dormitory rules 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'See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
else:
    print('%s\n' % (response.output.text))  # Process to output only text
    # print('%s\n' % (response.usage))

Java

Ejemplo de solicitud
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 =
                // Pass custom plug-in input parameters for agent applications. Replace <TOOL_ID> with your custom plug-in ID.
                "{\"user_defined_params\":{\"<TOOL_ID>\":{\"article_index\":2}}}";
        ApplicationParam param = ApplicationParam.builder()
                // If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID")
                .prompt("Dormitory rules 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("See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

Ejemplo de solicitud
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Dormitory rules content",
        "biz_params":
        {
            "user_defined_params":
            {
                "<TOOL_ID>":
                    {
                    "article_index": 2
                    }
            }
        }
    },
    "parameters":  {},
    "debug":{}
}'

Reemplace APP_ID con su ID de aplicación real. Reemplace <TOOL_ID> con su ID de complemento.

PHP

Ejemplo de solicitud
<?php

# If you have not configured an environment variable, replace the following line with $api_key="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with your actual application ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
//Replace <TOOL_ID> with your actual plug-in ID
// Construct request data
$data = [
    "input" => [
        'prompt' => 'Dormitory rules content',
        'biz_params' => [
        'user_defined_params' => [
            '<TOOL_ID>' => [
                'article_index' => 2
                ]
            ]
        ]
    ],
];
// Encode 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";}
}
?>

Node.js

Instale las dependencias requeridas:
npm install axios
Ejemplo de solicitud
const axios = require('axios');

async function callDashScope() {
    // If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with your actual application ID
    const pluginCode = 'TOOL_ID';// Replace with your actual plug-in ID
    const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "Dormitory rules content",
            biz_params: {
                user_defined_params: {
                    [pluginCode]: {
                        // article_index is a variable for the custom plug-in. Replace it with your 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();

C#

Ejemplo de solicitud
using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        // If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments 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 = "APP_ID";// Replace with your actual application ID

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("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 pluginCode = "TOOL_ID"; // Replace TOOL_ID with your actual plug-in ID
            string jsonContent = $@"{{
                ""input"": {{
                    ""prompt"": ""Dormitory rules 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}");
            }
        }
    }
}

Go

Ejemplo de solicitud
package main

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

func main() {
	// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID"           // Replace with your actual application ID
	pluginCode := "TOOL_ID" // Replace with your actual plug-in ID

	if apiKey == "" {
		fmt.Println("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{}{
			"prompt": "Dormitory rules 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
	}

	// Handle 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))
	}
}

Salida de transmisión

Habilite la salida en streaming mediante stream.

Python

Ejemplo de solicitud
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(
            # Configure API key: use environment variable or replace with your Model Studio API key (do not hard code in production).
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            app_id='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'See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
    else:
        print(f'{response.output.text}\n')  # Process to output only text

Java

Ejemplo de solicitud
// We recommend 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
// Implement streaming output for agent application calls

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 you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // Replace with your actual application ID
                .appId("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("See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

Ejemplo de solicitud
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/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 APP_ID con su ID de aplicación real.

PHP

Ejemplo de solicitud
<?php

// If you have not configured an environment variable, replace the following line with $api_key="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = '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?'],
    "parameters" => [
        'incremental_output' => true]];// Incremental output
// Encode 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, false); // Do not return transfer data
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $string) {
    echo $string; // Handle 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 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);

if ($status_code != 200) {
    echo "HTTP Status Code: $status_code\n";
    echo "Request Failed.\n";
}
?>

Node.js

Instale las dependencias requeridas:
npm install axios
Ejemplo de solicitud

1. Generar respuesta completa

const axios = require('axios');

async function callDashScope() {
    //If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with your 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) {
            // Handle 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 plegable para ver el contenido específico:

2. Generar solo el contenido del campo de texto

const axios = require('axios');
const { Transform } = require('stream');

async function callDashScope() {
    //If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID'; // Replace with your 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) {
            // // Handle streaming response SSE protocol parsing transform stream
            const sseTransformer = new Transform({
                transform(chunk, encoding, callback) {
                    this.buffer += chunk.toString();

                    // Split by SSE events (two newlines)
                    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 newline and push
                            this.push(textContent + '\n');
                        }
                    });

                    callback();
                },
                flush(callback) {
                    if (this.buffer) {
                        this.push(this.buffer + '\n');
                    }
                    callback();
                }
            });
            sseTransformer.buffer = '';

            // Pipe processing
            response.data
                .pipe(sseTransformer)
                .on('data', (textWithNewline) => {
                    process.stdout.write(textWithNewline); // Auto-wrap output
                })
                .on('end', () => console.log(""))
                .on('error', err => console.error("Pipe 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();

C#

Ejemplo de solicitud
using System.Net;
using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        //If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments 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 = "APP_ID"; // Replace with your 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}");
            }
        }
    }
}

Go

Ejemplo de solicitud
package main

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

func main() {
	// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with your actual application ID

	if apiKey == "" {
		fmt.Println("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, where incremental_output enables 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 is set to enable for 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
	}

	// Handle 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
		}
	}
}

Recuperación de base de conocimiento

Al llamar a una Aplicación Agente, utilice rag_options para habilitar la recuperación de la base de conocimiento.

Python

Ejemplo de solicitud
import os
from http import HTTPStatus
# We recommend 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(
    # Configure API key: use environment variable or replace with your Model Studio API key (do not hard code in production).
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    app_id='APP_ID',  # Replace APP_ID with your application ID
    prompt='Please recommend a phone under 3000 yuan',
    rag_options={
        "pipeline_ids": ["PIPELINE_ID1","PIPELINE_ID2"],  # Replace with your actual knowledge base IDs, separated by commas for multiple
    }
)

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'See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
else:
    print('%s\n' % (response.output.text))  # Process to output only text
    # print('%s\n' % (response.usage))

Java

Ejemplo de solicitud
// We recommend 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.Arrays;

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 you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // Replace with your actual application ID
                .prompt("Please recommend a phone around 3000 yuan")
                .ragOptions(RagOptions.builder()
                        // Replace with your actual specified knowledge base IDs, separated by commas for multiple
                        .pipelineIds(Arrays.asList("PIPELINES_ID1", "PIPELINES_ID2"))
                        .build())
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);
        System.out.printf("%s\n",
                result.getOutput().getText());// Process to output only text
    }

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

HTTP

curl

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

Reemplace APP_ID con su ID de aplicación real y PIPELINE_ID1 con su ID de base de conocimiento especificada.

PHP

Ejemplo de solicitud
<?php
# If you have not configured an environment variable, replace the following line with $api_key="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = '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' => 'Please recommend a phone under 3000 yuan'
    ],
    "parameters" => [
        'rag_options' => [
            'pipeline_ids' => ['PIPELINE_ID1','PIPELINE_ID2']//Replace with your specified knowledge base IDs, separated by commas for multiple
        ]
    ]
];
// Encode 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";}
}
?>

Node.js

Instale las dependencias requeridas:
npm install axios
Ejemplo de solicitud
const axios = require('axios');
async function callDashScope() {
    // If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';//Replace with your actual application ID

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

    const data = {
        input: {
            prompt: "Please recommend a phone under 3000 yuan"
        },
        parameters: {
            rag_options:{
                pipeline_ids:['PIPELINE_ID1','PIPELINE_ID2']  // Replace with your specified knowledge base IDs, separated by commas for multiple
            }
        },
        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();

C#

Ejemplo de solicitud
using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        // If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments 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 = "APP_ID";// Replace with your actual application ID
        // Replace PIPELINE_ID1 with your specified knowledge base ID
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("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 phone under 3000 yuan""
                }},
                ""parameters"": {{
                    ""rag_options"" : {{
                        ""pipeline_ids"":[""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}");
            }
        }
    }
}

Go

Ejemplo de solicitud
package main

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

func main() {
	// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with your actual application ID

	if apiKey == "" {
		fmt.Println("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 phone under 3000 yuan",
		},
		"parameters": map[string]interface{}{
			"rag_options": map[string]interface{}{
				"pipeline_ids": []string{"PIPELINE_ID1"}, // Replace with your 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
	}

	// Handle 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))
	}
}

Ver información del proceso de recuperación: Agregue has_thoughts a su código y configúrelo en True. La información del proceso de recuperación se devolverá en el campo thoughts del campo output.

Objeto de respuesta

status_code string

Código de estado HTTP.

200 indica éxito; otros códigos indican fallo.

En caso de fallo, revise code para el código de error y message para los detalles.

El SDK de Java no devuelve este parámetro. En caso de fallo, lanza una excepción que contiene el contenido de status_code y message.

request_id string

ID único para esta invocación.

El SDK de Java devuelve esto como requestId.

code string

Código de error. Vacío en caso de éxito.

Solo devuelto por el SDK de Python.

message string

Detalles del error. Vacío en caso de éxito.

Solo devuelto por el SDK de Python.

output object

Resultado de invocación.

propiedades de output

text string

Contenido de respuesta del modelo.

finish_reason string

Motivo por el que finalizó la respuesta.

stop significa finalización natural (se encontró un marcador preestablecido), null significa interrupción forzada (por ejemplo, se alcanzó el límite máximo de longitud o se detuvo manualmente).

session_idstring

ID único para la conversación actual.

Pase esto en solicitudes posteriores para llevar registros históricos de conversación.

pensamientosarray

Cuando configura el parámetro has_thoughts en True durante la invocación, puede ver la invocación de complementos, los procesos de recuperación de conocimiento o el proceso de pensamiento del modelo de pensamiento profundo en thoughts.

propiedades de thoughts

pensamiento string

Proceso de pensamiento del modelo.

Cuando selecciona un modelo de pensamiento profundo en la Aplicación Agente de su consola y la publica correctamente, si configura el parámetro has_thoughts en True durante la invocación de la API, el proceso de pensamiento del modelo se devolverá en este campo.

reasoningContentstring

Proceso de pensamiento del modelo.

Cuando selecciona un modelo de pensamiento profundo en la Aplicación de Flujo de Trabajo de su consola y la publica correctamente, si configura el parámetro has_thoughts en True durante la invocación de la API, el proceso de pensamiento del modelo se devolverá en este campo.

action_type string

Tipo de paso de ejecución devuelto por el modelo. Por ejemplo, API significa ejecutar un complemento de API, agentRag significa ejecutar recuperación de conocimiento, y reasoning significa ejecutar el proceso de pensamiento del modelo de pensamiento profundo.

action_name string

Nombre de la acción ejecutada, como recuperación de conocimiento, complemento de API o proceso de pensamiento.

acción string

Pasos de ejecución.

action_input_stream string

Resultado en streaming de los parámetros de entrada.

action_input string

Parámetros de entrada del plugin.

observación string

Proceso de recuperación o ejecución del complemento.

doc_references array

Documentos referenciados que el modelo citó.

En la Aplicación Agente de su consola de Model Studio, active el interruptor de Mostrar Fuente y Publique la aplicación para que doc_references pueda contener información válida.

Propiedades de doc_references

index_id string

Índice del documento referenciado, por ejemplo, [1].

title string

Título del segmento de texto referenciado.

doc_id string

ID del documento referenciado.

doc_name string

Nombre del documento referenciado.

text string

Contenido de texto específico referenciado por el modelo.

biz_id string

Identificador de asociación empresarial referenciado por el modelo.

images array

Lista de URL de imágenes referenciadas por el modelo.

usage object

Uso de tokens para esta solicitud.

propiedades de usage

modelsarray

Información del modelo para esta invocación.

propiedades de models

model_id string

ID del modelo utilizado por esta aplicación.

input_tokens integer

Recuento de tokens de entrada.

output_tokens integer

Recuento de tokens de salida.

Ejemplo de respuesta de conversación de un solo turno
{
    "output": {
        "finish_reason": "stop",
        "session_id": "6105c965c31b40958a43dc93c28c7a59",
        "text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I'm designed to answer various questions, provide information, and converse with users. How can I help you?"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 36,
                "model_id": "qwen-plus",
                "input_tokens": 74
            }
        ]
    },
    "request_id": "f97ee37d-0f9c-9b93-b6bf-bd263a232bf9"
}
Ejemplo de respuesta de base de conocimiento especificada

Para generar información de documentos referenciados a partir de documentos recuperados, abra la Aplicación Agente de su aplicación, haga clic en Retrieve Configuration, active Show Source y Publish la aplicación.

{
    "text": "Based on your budget, I recommend considering the Bailian Zephyr Z9. This phone is lightweight and portable, featuring a 6.4-inch screen with 1080 x 2340 pixel resolution, paired with 128GB storage and 6GB RAM, making it perfect for daily use<ref>[1]</ref>. Additionally, it comes with a 4000mAh battery and a 30x digital zoom lens to capture distant details, priced between 2499-2799 yuan, fully meeting your budget requirements<ref>[1]</ref>.",
    "finish_reason": "stop",
    "session_id": "6c1d47fa5eca46b2ad0668c04ccfbf13",
    "thoughts": null,
    "doc_references": [
        {
            "index_id": "1",
            "title": "Bailian Phone Product Introduction",
            "doc_id": "file_7c0e9abee4f142f386e488c9baa9cf38_10317360",
            "doc_name": "Bailian Series Phone Product Introduction",
            "doc_url": null,
            "text": "【Document Name】:Bailian Series Phone Product Introduction\n【Title】:Bailian Phone Product Introduction\n【Content】:Reference Price: 5999- 6499. Bailian Ace Ultra ——For Gamers: Equipped with a 6.67-inch 1080 x 2400 pixel screen, built-in 10GB RAM and 256GB storage, ensuring smooth gaming. Bailian Ace Ultra ——For Gamers: Equipped with a 6.67-inch 1080 x 2400 pixel screen, built-in 10GB RAM and 256GB storage, ensuring smooth gaming. 5500mAh battery with liquid cooling system keeps your device cool during extended gaming sessions. High-dynamic dual speakers enhance immersive audio for gaming. Reference Price: 3999- 4299. Bailian Zephyr Z9 ——Art of Slim Design: Lightweight 6.4-inch 1080 x 2340 pixel design, paired with 128GB storage and 6GB RAM, handles daily tasks effortlessly. 4000mAh battery ensures all-day usage, while the 30x digital zoom lens captures distant details without compromising on power. Reference Price: 2499- 2799. Bailian Flex Fold+ ——New Era of Foldable Phones: Combines innovation and luxury with a 7.6-inch 1800 x 2400 pixel main screen and 4.7-inch 1080 x 2400 pixel outer screen, supporting multi-angle free-stop design for different scenarios. 512GB storage, 12GB RAM, plus a 4700mAh battery and UTG ultra-thin flexible glass, ushering in a new chapter for foldable phones. Additionally, this phone supports Dual SIM Dual Standby and satellite calls, keeping you connected worldwide. Reference Retail Price: 9999- 10999.\n",
            "biz_id": null,
            "images": [

            ],
            "page_number": [
                0]
        }]
}
Ejemplo de respuesta de error

Cuando una solicitud falla, la respuesta incluye detalles del error a través de code y message.

Este ejemplo muestra una respuesta de error para una API-KEY no válida.

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

Límites de tasa

El QPM predeterminado (consultas por minuto) para una sola aplicación es 15,000.

Códigos de error

Si la invocación falla y devuelve un error, consulte Información de errores para ver las soluciones.